commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3 values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
9c7dda9f55369109831eb53f4ed1da5fe82cfc7b | Fix test for observation_aggregator | tests/chainermn_tests/extensions_tests/test_observation_aggregator.py | tests/chainermn_tests/extensions_tests/test_observation_aggregator.py | import unittest
import numpy as np
import chainer
import chainer.testing
from chainer.training import extension
import chainermn
from chainermn.extensions.observation_aggregator import observation_aggregator
class DummyChain(chainer.Chain):
def __init__(self):
super(DummyChain, self).__init__()
def forward(self, x):
return chainer.Variable(x, grad=np.array([0]))
class TestObservationAggregator(unittest.TestCase):
def setUp(self):
self.communicator = chainermn.create_communicator('naive')
def test_observation_aggregator(self):
model = DummyChain()
comm = self.communicator
optimizer = chainermn.create_multi_node_optimizer(
chainer.optimizers.Adam(), self.communicator)
optimizer.setup(model)
train = np.random.rand(10, 1)
train_iter = chainer.iterators.SerialIterator(train,
batch_size=1,
repeat=True,
shuffle=True)
updater = chainer.training.StandardUpdater(train_iter, optimizer)
trainer = chainer.training.Trainer(updater, (1, 'epoch'))
@extension.make_extension(
trigger=(2, 'iteration'), priority=extension.PRIORITY_WRITER)
def rank_reporter(trainer):
trainer.observation['rank'] = comm.rank
@extension.make_extension(
trigger=(2, 'iteration'), priority=extension.PRIORITY_READER)
def aggregated_rank_checker(trainer):
actual = trainer.observation['rank-aggregated']
expected = (comm.size - 1) / 2.0
chainer.testing.assert_allclose(actual,
expected)
trainer.extend(rank_reporter)
trainer.extend(observation_aggregator(comm, 'rank', 'rank-aggregated'))
trainer.extend(aggregated_rank_checker)
trainer.run()
| import unittest
import numpy as np
import chainer
import chainer.testing
from chainer.training import extension
import chainermn
from chainermn.extensions.observation_aggregator import observation_aggregator
class DummyChain(chainer.Chain):
def __init__(self):
super(DummyChain, self).__init__()
def forward(self, x):
return chainer.Variable(x, grad=np.array([0]))
class TestObservationAggregator(unittest.TestCase):
def setUp(self):
self.communicator = chainermn.create_communicator('naive')
def test_observation_aggregator(self):
model = DummyChain()
comm = self.communicator
optimizer = chainermn.create_multi_node_optimizer(
chainer.optimizers.Adam(), self.communicator)
optimizer.setup(model)
train = np.random.rand(10, 1)
train_iter = chainer.iterators.SerialIterator(train,
batch_size=1,
repeat=True,
shuffle=True)
updater = chainer.training.StandardUpdater(train_iter, optimizer)
trainer = chainer.training.Trainer(updater, (1, 'epoch'))
@extension.make_extension(
trigger=(2, 'iteration'), priority=extension.PRIORITY_WRITER)
def rank_reporter(trainer):
trainer.observation['rank'] = comm.rank
@extension.make_extension(
trigger=(2, 'iteration'), priority=extension.PRIORITY_READER)
def aggregated_rank_checker(trainer):
actual = trainer.observation['rank-aggregated']
expected = (comm.size - 1) / 2
chainer.testing.assert_allclose(actual,
expected)
trainer.extend(rank_reporter)
trainer.extend(observation_aggregator(comm, 'rank', 'rank-aggregated'))
trainer.extend(aggregated_rank_checker)
trainer.run()
| Python | 0.000002 |
88be8370e6ede34cb01240a6621923b1ddea370f | remove retval before starting the completion service job if it exists | studio/completion_service/completion_service_client.py | studio/completion_service/completion_service_client.py | import importlib
import shutil
import pickle
import os
import sys
import six
from studio import fs_tracker, model, logs
logger = logs.getLogger('completion_service_client')
try:
logger.setLevel(model.parse_verbosity(sys.argv[1]))
except BaseException:
logger.setLevel(10)
def main():
logger.debug('copying and importing client module')
logger.debug('getting file mappings')
artifacts = fs_tracker.get_artifacts()
files = {}
logger.debug("Artifacts = {}".format(artifacts))
for tag, path in six.iteritems(artifacts):
if tag not in {'workspace', 'modeldir', 'tb', '_runner'}:
if os.path.isfile(path):
files[tag] = path
elif os.path.isdir(path):
dirlist = os.listdir(path)
if any(dirlist):
files[tag] = os.path.join(
path,
dirlist[0]
)
logger.debug("Files = {}".format(files))
script_path = files['clientscript']
retval_path = fs_tracker.get_artifact('retval')
if os.path.exists(retval_path):
shutil.rmtree(retval_path)
# script_name = os.path.basename(script_path)
new_script_path = os.path.join(os.getcwd(), '_clientscript.py')
shutil.copy(script_path, new_script_path)
script_path = new_script_path
logger.debug("script path: " + script_path)
mypath = os.path.dirname(script_path)
sys.path.append(mypath)
# os.path.splitext(os.path.basename(script_path))[0]
module_name = '_clientscript'
client_module = importlib.import_module(module_name)
logger.debug('loading args')
args_path = files['args']
with open(args_path, 'rb') as f:
args = pickle.loads(f.read())
logger.debug('calling client function')
retval = client_module.clientFunction(args, files)
logger.debug('saving the return value')
if os.path.isdir(fs_tracker.get_artifact('clientscript')):
# on go runner:
logger.debug("Running in a go runner, creating {} for retval"
.format(retval_path))
try:
os.mkdir(retval_path)
except OSError:
logger.debug('retval dir present')
retval_path = os.path.join(retval_path, 'retval')
logger.debug("New retval_path is {}".format(retval_path))
logger.debug('Saving retval')
with open(retval_path, 'wb') as f:
f.write(pickle.dumps(retval, protocol=2))
logger.debug('Done')
if __name__ == "__main__":
main()
| import importlib
import shutil
import pickle
import os
import sys
import six
from studio import fs_tracker, model, logs
logger = logs.getLogger('completion_service_client')
try:
logger.setLevel(model.parse_verbosity(sys.argv[1]))
except BaseException:
logger.setLevel(10)
def main():
logger.debug('copying and importing client module')
logger.debug('getting file mappings')
artifacts = fs_tracker.get_artifacts()
files = {}
logger.debug("Artifacts = {}".format(artifacts))
for tag, path in six.iteritems(artifacts):
if tag not in {'workspace', 'modeldir', 'tb', '_runner'}:
if os.path.isfile(path):
files[tag] = path
elif os.path.isdir(path):
dirlist = os.listdir(path)
if any(dirlist):
files[tag] = os.path.join(
path,
dirlist[0]
)
logger.debug("Files = {}".format(files))
script_path = files['clientscript']
retval_path = fs_tracker.get_artifact('retval')
shutil.rmtree(retval_path)
# script_name = os.path.basename(script_path)
new_script_path = os.path.join(os.getcwd(), '_clientscript.py')
shutil.copy(script_path, new_script_path)
script_path = new_script_path
logger.debug("script path: " + script_path)
mypath = os.path.dirname(script_path)
sys.path.append(mypath)
# os.path.splitext(os.path.basename(script_path))[0]
module_name = '_clientscript'
client_module = importlib.import_module(module_name)
logger.debug('loading args')
args_path = files['args']
with open(args_path, 'rb') as f:
args = pickle.loads(f.read())
logger.debug('calling client function')
retval = client_module.clientFunction(args, files)
logger.debug('saving the return value')
if os.path.isdir(fs_tracker.get_artifact('clientscript')):
# on go runner:
logger.debug("Running in a go runner, creating {} for retval"
.format(retval_path))
try:
os.mkdir(retval_path)
except OSError:
logger.debug('retval dir present')
retval_path = os.path.join(retval_path, 'retval')
logger.debug("New retval_path is {}".format(retval_path))
logger.debug('Saving retval')
with open(retval_path, 'wb') as f:
f.write(pickle.dumps(retval, protocol=2))
logger.debug('Done')
if __name__ == "__main__":
main()
| Python | 0 |
c3a251588868ace81e8e4e0bbe29828495d759d9 | fix command line arguments | ThingThree/Code/Dotstar/strandtest.py | ThingThree/Code/Dotstar/strandtest.py | #!/usr/bin/python
import time, math, sys
from dotstar import Adafruit_DotStar
numPixels = 24
dataPin = 17
clockPin = 27
strip = Adafruit_DotStar(numPixels, dataPin, clockPin)
strip.begin()
strip.setBrightness(255)
def scale(color, brightness):
str_hex = hex(color)[2:].zfill(6)
r,g,b = (int(str_hex[2*x:2*x+2],16)*(brightness/255.0) for x in xrange(3))
return (int(r) << 8) + (int(g) << 16) + int(b)
def pulseFade(color):
for brightness in range(0,255):
for i in range(0,numPixels):
strip.setPixelColor(i, scale(color,brightness))
strip.show()
time.sleep(0.01)
for brightness in range(255,0,-1):
for i in range(0,numPixels):
strip.setPixelColor(i, scale(color,brightness))
strip.show()
time.sleep(0.001)
def pulseFromMiddle(color):
for i in range(0,numPixels/2):
strip.setPixelColor(numPixels/2 + i, color);
strip.setPixelColor(numPixels/2 - i, color);
strip.show();
time.sleep(0.02);
for i in range(0,numPixels/2):
strip.setPixelColor(i, 0);
strip.setPixelColor(numPixels-i, 0);
strip.show();
time.sleep(0.02);
def cycle(color=-1):
head = 0
tail = -10
curColor = 0xFF0000 if (color == -1) else color
while True:
strip.setPixelColor(head,curColor)
strip.setPixelColor(tail,0)
strip.show()
time.sleep(0.02)
head += 1
if (head >= numPixels):
head = 0
if (color == -1):
curColor >>= 8
if (curColor == 0): curColor = 0xFF0000
tail += 1
if (tail >= numPixels): tail = 0
def pulseCycle(color, cycles):
head = 0
tail = -10
iters = 0
while iters < cycles:
strip.setPixelColor(head,color)
strip.setPixelColor(tail,0)
strip.show()
time.sleep(0.02)
head += 1
if (head >= numPixels):
head = 0
iters += 1
tail += 1
if (tail >= numPixels): tail = 0
while tail <= numPixels:
strip.setPixelColor(tail,0)
strip.show()
time.sleep(0.02)
tail += 1
def breathe(color):
while True:
millis = int(round(time.time() * 1000))
brightness = (math.exp(math.sin(millis/2000.0*math.pi)) - 0.36787944)*108.0;
for i in range(0,numPixels):
strip.setPixelColor(i, scale(color,brightness))
strip.show()
time.sleep(0.02)
pulseCycle(int(sys.argv[1],0),int(sys.argv[2]))
| #!/usr/bin/python
import time, math, sys
from dotstar import Adafruit_DotStar
numPixels = 24
dataPin = 17
clockPin = 27
strip = Adafruit_DotStar(numPixels, dataPin, clockPin)
strip.begin()
strip.setBrightness(255)
def scale(color, brightness):
str_hex = hex(color)[2:].zfill(6)
r,g,b = (int(str_hex[2*x:2*x+2],16)*(brightness/255.0) for x in xrange(3))
return (int(r) << 8) + (int(g) << 16) + int(b)
def pulseFade(color):
for brightness in range(0,255):
for i in range(0,numPixels):
strip.setPixelColor(i, scale(color,brightness))
strip.show()
time.sleep(0.01)
for brightness in range(255,0,-1):
for i in range(0,numPixels):
strip.setPixelColor(i, scale(color,brightness))
strip.show()
time.sleep(0.001)
def pulseFromMiddle(color):
for i in range(0,numPixels/2):
strip.setPixelColor(numPixels/2 + i, color);
strip.setPixelColor(numPixels/2 - i, color);
strip.show();
time.sleep(0.02);
for i in range(0,numPixels/2):
strip.setPixelColor(i, 0);
strip.setPixelColor(numPixels-i, 0);
strip.show();
time.sleep(0.02);
def cycle(color=-1):
head = 0
tail = -10
curColor = 0xFF0000 if (color == -1) else color
while True:
strip.setPixelColor(head,curColor)
strip.setPixelColor(tail,0)
strip.show()
time.sleep(0.02)
head += 1
if (head >= numPixels):
head = 0
if (color == -1):
curColor >>= 8
if (curColor == 0): curColor = 0xFF0000
tail += 1
if (tail >= numPixels): tail = 0
def pulseCycle(color, cycles):
head = 0
tail = -10
iters = 0
while iters < cycles:
strip.setPixelColor(head,color)
strip.setPixelColor(tail,0)
strip.show()
time.sleep(0.02)
head += 1
if (head >= numPixels):
head = 0
iters += 1
tail += 1
if (tail >= numPixels): tail = 0
while tail <= numPixels:
strip.setPixelColor(tail,0)
strip.show()
time.sleep(0.02)
tail += 1
def breathe(color):
while True:
millis = int(round(time.time() * 1000))
brightness = (math.exp(math.sin(millis/2000.0*math.pi)) - 0.36787944)*108.0;
for i in range(0,numPixels):
strip.setPixelColor(i, scale(color,brightness))
strip.show()
time.sleep(0.02)
pulseCycle(int(sys.argv[0],0),int(sys.argv[1]))
| Python | 0.000803 |
a171595f029b43af27d14a125e68647e2206c6d5 | Update __init__.py | tendrl/commons/objects/node_alert_counters/__init__.py | tendrl/commons/objects/node_alert_counters/__init__.py | from tendrl.commons import objects
class NodeAlertCounters(objects.BaseObject):
def __init__(
self,
warn_count=0,
node_id=None,
*args,
**kwargs
):
super(NodeAlertCounters, self).__init__(*args, **kwargs)
self.warning_count = warn_count
self.node_id = node_id
self.value = '/nodes/{0}/alert_counters'
def render(self):
self.value = self.value.format(self.node_id or NS.node_context.node_id)
return super(NodeAlertCounters, self).render()
def save(self, *args, **kwargs):
NS.tendrl.objects.ClusterNodeAlertCounters(warn_count=self.warning_count,
node_id=self.node_id,
integration_id=NS.tendrl_context.integration_id).save()
super(NodeAlertCounters, self).save(*args, **kwargs)
| from tendrl.commons import objects
class NodeAlertCounters(objects.BaseObject):
def __init__(
self,
warn_count=0,
node_id=None,
*args,
**kwargs
):
super(NodeAlertCounters, self).__init__(*args, **kwargs)
self.warning_count = warn_count
self.node_id = node_id
self.value = '/nodes/{0}/alert_counters'
def render(self):
self.value = self.value.format(self.node_id or NS.node_context.node_id)
return super(NodeAlertCounters, self).render()
def save(self, *args, **kwargs):
NS.tendrl.objects.ClusterNodeAlertCounters(warn_count=self.warning_count,
node_id=self.node_id).save()
super(NodeAlertCounters, self).save(*args, **kwargs)
| Python | 0.000072 |
dd7e0d18a15195cf67af44af8c15918a5cf068e4 | add header information | douban_book_api.py | douban_book_api.py | from douban_client.api.error import DoubanAPIError
import requests
import simplejson
from douban_client import DoubanClient
__author__ = 'owen2785'
baseurl = 'https://api.douban.com/v2/book/isbn/'
def getbyisbn_without_auth(isbn):
r = requests.get(baseurl+str(isbn),headers=headers)
print r.headers
print r.request.headers
return r.json()
| from douban_client.api.error import DoubanAPIError
import requests
import simplejson
from douban_client import DoubanClient
__author__ = 'owen2785'
baseurl = 'https://api.douban.com/v2/book/isbn/'
def getbyisbn_without_auth(isbn):
r = requests.get(baseurl+str(isbn))
return r.json() | Python | 0 |
396ab20874a0c3492482a8ae03fd7d61980917a5 | Update closest match adapter docstring. | chatterbot/adapters/logic/closest_match.py | chatterbot/adapters/logic/closest_match.py | # -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter logic adapter selects a known response
to an input by searching for a known statement that most closely
matches the input based on the Levenshtein Distance between the text
of each statement.
"""
def get(self, input_statement):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
statement_list = self.context.storage.get_response_statements()
if not statement_list:
if self.has_storage_context:
# Use a randomly picked statement
self.logger.info(
u'No statements have known responses. ' +
u'Choosing a random response to return.'
)
return 0, self.context.storage.get_random()
else:
raise self.EmptyDatasetException()
confidence = -1
closest_match = input_statement
# Find the closest matching known statement
for statement in statement_list:
ratio = fuzz.ratio(input_statement.text.lower(), statement.text.lower())
if ratio > confidence:
confidence = ratio
closest_match = statement
# Convert the confidence integer to a percent
confidence /= 100.0
return confidence, closest_match
| # -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter logic adapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter selects a response to an
input statement by selecting the closest known matching
statement based on the Levenshtein Distance between the text
of each statement.
"""
def get(self, input_statement):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
statement_list = self.context.storage.get_response_statements()
if not statement_list:
if self.has_storage_context:
# Use a randomly picked statement
self.logger.info(
u'No statements have known responses. ' +
u'Choosing a random response to return.'
)
return 0, self.context.storage.get_random()
else:
raise self.EmptyDatasetException()
confidence = -1
closest_match = input_statement
# Find the closest matching known statement
for statement in statement_list:
ratio = fuzz.ratio(input_statement.text.lower(), statement.text.lower())
if ratio > confidence:
confidence = ratio
closest_match = statement
# Convert the confidence integer to a percent
confidence /= 100.0
return confidence, closest_match
| Python | 0 |
2947fe97d466872de05ada289d9172f41895969c | Update GOV.UK Frontend/Jinja lib test | tests/templates/components/test_radios_with_images.py | tests/templates/components/test_radios_with_images.py | import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
| import json
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
assert package_json["dependencies"]["govuk-frontend"].startswith("3."), (
"After upgrading the Design System, manually validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
| Python | 0 |
f4a80c720d0164eb8a942e3ad1b5244d30800e5a | Add --allow-nacl-socket-api for the chromoting functional test. | chrome/test/functional/chromoting_basic.py | chrome/test/functional/chromoting_basic.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import pyauto_functional # Must come before chromoting and pyauto.
import chromoting
import pyauto
class ChromotingBasic(chromoting.ChromotingMixIn, pyauto.PyUITest):
"""Basic tests for Chromoting."""
_EXTRA_CHROME_FLAGS = [
'--allow-nacl-socket-api=*',
]
def ExtraChromeFlags(self):
"""Ensures Chrome is launched with some custom flags.
Overrides the default list of extra flags passed to Chrome. See
ExtraChromeFlags() in pyauto.py.
"""
return pyauto.PyUITest.ExtraChromeFlags(self) + self._EXTRA_CHROME_FLAGS
def setUp(self):
"""Set up test for Chromoting on both local and remote machines.
Installs the Chromoting app, launches it, and authenticates
using the default Chromoting test account.
"""
super(ChromotingBasic, self).setUp()
self._app = self.InstallExtension(self.GetWebappPath())
self.LaunchApp(self._app)
account = self.GetPrivateInfo()['test_chromoting_account']
self.Authenticate(account['username'], account['password'])
def testChromoting(self):
"""Verify that we can start and disconnect from a Chromoting session."""
client_local = (self.remote == None)
host = self
client = self if client_local else self.remote
client_tab_index = 2 if client_local else 1
access_code = host.Share()
self.assertTrue(access_code,
msg='Host attempted to share, but it failed. '
'No access code was found.')
if client_local:
client.LaunchApp(self._app)
self.assertTrue(client.Connect(access_code, client_tab_index),
msg='The client attempted to connect to the host, '
'but the chromoting session did not start.')
host.CancelShare()
client.Disconnect(client_tab_index)
if __name__ == '__main__':
pyauto_functional.Main()
| #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import pyauto_functional # Must come before chromoting and pyauto.
import chromoting
import pyauto
class ChromotingBasic(chromoting.ChromotingMixIn, pyauto.PyUITest):
"""Basic tests for Chromoting."""
def setUp(self):
"""Set up test for Chromoting on both local and remote machines.
Installs the Chromoting app, launches it, and authenticates
using the default Chromoting test account.
"""
super(ChromotingBasic, self).setUp()
self._app = self.InstallExtension(self.GetWebappPath())
self.LaunchApp(self._app)
account = self.GetPrivateInfo()['test_chromoting_account']
self.Authenticate(account['username'], account['password'])
def testChromoting(self):
"""Verify that we can start and disconnect from a Chromoting session."""
client_local = (self.remote == None)
host = self
client = self if client_local else self.remote
client_tab_index = 2 if client_local else 1
access_code = host.Share()
self.assertTrue(access_code,
msg='Host attempted to share, but it failed. '
'No access code was found.')
if client_local:
client.LaunchApp(self._app)
self.assertTrue(client.Connect(access_code, client_tab_index),
msg='The client attempted to connect to the host, '
'but the chromoting session did not start.')
host.CancelShare()
client.Disconnect(client_tab_index)
if __name__ == '__main__':
pyauto_functional.Main()
| Python | 0.000047 |
0b366a3f4c23b644f885ed649edc577242ae90ee | Fix genreflex rootmap files to not contain stray spaces after "string" Corrsponds to v5-22-00-patches r27408 | cint/reflex/python/genreflex/genrootmap.py | cint/reflex/python/genreflex/genrootmap.py | # Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose is hereby granted without fee, provided that this copyright and
# permissions notice appear in all copies and derivatives.
#
# This software is provided "as is" without express or implied warranty.
import os, sys, string, re
model = """
# This file has been generated by genreflex with the --rootmap option
#--Final End
"""
#----------------------------------------------------------------------------------
def isRootmapVetoed(c) :
if c.has_key('extra') and 'rootmap' in c['extra'] :
rootmapsel = c['extra']['rootmap'].lower()
return (rootmapsel == 'false' or rootmapsel == '0')
return False
#----------------------------------------------------------------------------------
def genRootMap(mapfile, dicfile, libfile, cnames, classes) :
startmark = '#--Begin ' + dicfile + '\n'
endmark = '#--End ' + dicfile + '\n'
finalmark = '#--Final End\n'
transtable = string.maketrans(': ', '@-')
transtable = string.maketrans(': ', '@-')
for c in classes :
c['fullname'] = c.get('fullname', c['name'])
# filter out classes that were de-selected by rootmap attribute
cveto = filter( lambda c: isRootmapVetoed(c),classes)
for cv in cveto :
cvname = cv['fullname']
# not all cvname have to be in cnames, cname could have been excluded
if cvname in cnames:
cnames.remove(cvname)
new_lines = []
if libfile.rfind('/') != -1 : libfile = libfile[libfile.rfind('/')+1:]
for c in cnames :
nc = string.translate(str(c), transtable)
# also remove possible seperator ' ', or set<basic_string<char> > becomes set<string >
nc = re.sub(r"\bstd@@basic_string<char>-?", 'string', nc)
nc = re.sub(r"\bstd@@", '', nc)
nc = nc.replace(' ','')
new_lines += '%-45s %s\n' % ('Library.' + nc + ':', libfile )
if not os.path.exists(mapfile) :
lines = [ line+'\n' for line in model.split('\n')]
else :
f = open(mapfile,'r')
lines = [ line for line in f.readlines()]
f.close()
if startmark in lines and endmark in lines :
lines[lines.index(startmark)+1 : lines.index(endmark)] = new_lines
else :
lines[lines.index(finalmark):lines.index(finalmark)] = [startmark]+new_lines+[endmark]
f = open(mapfile,'w')
f.writelines(lines)
f.close()
| # Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose is hereby granted without fee, provided that this copyright and
# permissions notice appear in all copies and derivatives.
#
# This software is provided "as is" without express or implied warranty.
import os, sys, string, re
model = """
# This file has been generated by genreflex with the --rootmap option
#--Final End
"""
#----------------------------------------------------------------------------------
def isRootmapVetoed(c) :
if c.has_key('extra') and 'rootmap' in c['extra'] :
rootmapsel = c['extra']['rootmap'].lower()
return (rootmapsel == 'false' or rootmapsel == '0')
return False
#----------------------------------------------------------------------------------
def genRootMap(mapfile, dicfile, libfile, cnames, classes) :
startmark = '#--Begin ' + dicfile + '\n'
endmark = '#--End ' + dicfile + '\n'
finalmark = '#--Final End\n'
transtable = string.maketrans(': ', '@-')
transtable = string.maketrans(': ', '@-')
for c in classes :
c['fullname'] = c.get('fullname', c['name'])
# filter out classes that were de-selected by rootmap attribute
cveto = filter( lambda c: isRootmapVetoed(c),classes)
for cv in cveto :
cvname = cv['fullname']
# not all cvname have to be in cnames, cname could have been excluded
if cvname in cnames:
cnames.remove(cvname)
new_lines = []
if libfile.rfind('/') != -1 : libfile = libfile[libfile.rfind('/')+1:]
for c in cnames :
nc = string.translate(str(c), transtable)
nc = re.sub(r"\bstd@@basic_string<char>", 'string', nc)
nc = re.sub(r"\bstd@@", '', nc)
nc = nc.replace(' ','')
new_lines += '%-45s %s\n' % ('Library.' + nc + ':', libfile )
if not os.path.exists(mapfile) :
lines = [ line+'\n' for line in model.split('\n')]
else :
f = open(mapfile,'r')
lines = [ line for line in f.readlines()]
f.close()
if startmark in lines and endmark in lines :
lines[lines.index(startmark)+1 : lines.index(endmark)] = new_lines
else :
lines[lines.index(finalmark):lines.index(finalmark)] = [startmark]+new_lines+[endmark]
f = open(mapfile,'w')
f.writelines(lines)
f.close()
| Python | 0.000014 |
b2e6a7a8df1ede0118838ce494e1679eea0eb578 | Decrease cert expiration alerting threshold from 2 years to 1 year. (#1002) | scripts/check-bundled-ca-certs-expirations.py | scripts/check-bundled-ca-certs-expirations.py | #!/usr/bin/env python
# Copyright 2014-2020 Scalyr 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 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.
"""
Script which errors out if any of the bundled certs will expire in 24 months or sooner.
"""
from __future__ import absolute_import
from __future__ import print_function
if False:
from typing import List
import os
import glob
import datetime
from io import open
from cryptography import x509
from cryptography.hazmat.backends import default_backend
# By default we fail if any of the bundled cert expires in 1 year or sooner
DEFAULT_EXPIRE_THRESHOLD_TIMEDELTA = datetime.timedelta(days=(12 * 30 * 1))
def fail_if_cert_expires_in_timedelta(cert_path, expire_in_threshold_timedelta):
# type: (str, datetime.timedelta) -> None
"""
Fail and throw an exception if the provided certificate expires in the provided timedelta period
or sooner.
"""
with open(cert_path, "rb") as fp:
content = fp.read()
cert = x509.load_pem_x509_certificate(content, default_backend())
now_dt = datetime.datetime.utcnow()
expire_in_days = (cert.not_valid_after - now_dt).days
if now_dt + expire_in_threshold_timedelta >= cert.not_valid_after:
raise Exception(
(
"Certificate %s will expire in %s days (%s), please update!"
% (cert_path, expire_in_days, cert.not_valid_after)
)
)
else:
print(
"OK - certificate %s will expire in %s days (%s)"
% (cert_path, expire_in_days, cert.not_valid_after)
)
def get_bundled_cert_paths():
# type: () -> List[str]
"""
Return full absolute paths for all the bundled certs.
"""
cwd = os.path.abspath(os.getcwd())
result = []
for file_name in glob.glob("certs/*"):
file_path = os.path.join(cwd, file_name)
result.append(file_path)
return result
def main():
cert_paths = get_bundled_cert_paths()
for cert_path in cert_paths:
fail_if_cert_expires_in_timedelta(
cert_path, expire_in_threshold_timedelta=DEFAULT_EXPIRE_THRESHOLD_TIMEDELTA
)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# Copyright 2014-2020 Scalyr 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 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.
"""
Script which errors out if any of the bundled certs will expire in 24 months or sooner.
"""
from __future__ import absolute_import
from __future__ import print_function
if False:
from typing import List
import os
import glob
import datetime
from io import open
from cryptography import x509
from cryptography.hazmat.backends import default_backend
# By default we fail if any of the bundled cert expires in 2 years or sooner
DEFAULT_EXPIRE_THRESHOLD_TIMEDELTA = datetime.timedelta(days=(12 * 30 * 2))
def fail_if_cert_expires_in_timedelta(cert_path, expire_in_threshold_timedelta):
# type: (str, datetime.timedelta) -> None
"""
Fail and throw an exception if the provided certificate expires in the provided timedelta period
or sooner.
"""
with open(cert_path, "rb") as fp:
content = fp.read()
cert = x509.load_pem_x509_certificate(content, default_backend())
now_dt = datetime.datetime.utcnow()
expire_in_days = (cert.not_valid_after - now_dt).days
if now_dt + expire_in_threshold_timedelta >= cert.not_valid_after:
raise Exception(
(
"Certificate %s will expire in %s days (%s), please update!"
% (cert_path, expire_in_days, cert.not_valid_after)
)
)
else:
print(
"OK - certificate %s will expire in %s days (%s)"
% (cert_path, expire_in_days, cert.not_valid_after)
)
def get_bundled_cert_paths():
# type: () -> List[str]
"""
Return full absolute paths for all the bundled certs.
"""
cwd = os.path.abspath(os.getcwd())
result = []
for file_name in glob.glob("certs/*"):
file_path = os.path.join(cwd, file_name)
result.append(file_path)
return result
def main():
cert_paths = get_bundled_cert_paths()
for cert_path in cert_paths:
fail_if_cert_expires_in_timedelta(
cert_path, expire_in_threshold_timedelta=DEFAULT_EXPIRE_THRESHOLD_TIMEDELTA
)
if __name__ == "__main__":
main()
| Python | 0.000007 |
686f0e21de510a12ee3d6af410448eb405d3e7b6 | add 1.4.0 release and 1.5 stable branch (#16261) | var/spack/repos/builtin/packages/libunwind/package.py | var/spack/repos/builtin/packages/libunwind/package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libunwind(AutotoolsPackage):
"""A portable and efficient C programming interface (API) to determine
the call-chain of a program."""
homepage = "http://www.nongnu.org/libunwind/"
url = "http://download.savannah.gnu.org/releases/libunwind/libunwind-1.1.tar.gz"
git = "https://github.com/libunwind/libunwind"
maintainers = ['mwkrentel']
version('master', branch='master')
version('1.5-head', branch='v1.5-stable')
version('1.5-rc1', sha256='3e0cbc6dee326592097ef06e97cf76ef597987eddd0df8bea49b0594e587627a')
version('1.4-head', branch='v1.4-stable')
version('1.4.0', sha256='df59c931bd4d7ebfd83ee481c943edf015138089b8e50abed8d9c57ba9338435', preferred=True)
version('1.4-rc1', sha256='1928459139f048f9b4aca4bb5010540cb7718d44220835a2980b85429007fa9f')
version('1.3.1', sha256='43997a3939b6ccdf2f669b50fdb8a4d3205374728c2923ddc2354c65260214f8')
version('1.2.1', sha256='3f3ecb90e28cbe53fba7a4a27ccce7aad188d3210bb1964a923a731a27a75acb')
version('1.1', sha256='9dfe0fcae2a866de9d3942c66995e4b460230446887dbdab302d41a8aee8d09a')
variant('xz', default=False,
description='Support xz (lzma) compressed symbol tables.')
variant('zlib', default=False,
description='Support zlib compressed symbol tables '
'(1.5 and later).')
# The libunwind releases contain the autotools generated files,
# but the git repo snapshots do not.
depends_on('autoconf', type='build', when='@master,1.4-head,1.5-head')
depends_on('automake', type='build', when='@master,1.4-head,1.5-head')
depends_on('libtool', type='build', when='@master,1.4-head,1.5-head')
depends_on('m4', type='build', when='@master,1.4-head,1.5-head')
depends_on('xz', type='link', when='+xz')
depends_on('zlib', type='link', when='+zlib')
conflicts('platform=darwin',
msg='Non-GNU libunwind needs ELF libraries Darwin does not have')
provides('unwind')
flag_handler = AutotoolsPackage.build_system_flags
def configure_args(self):
spec = self.spec
args = []
if '+xz' in spec:
args.append('--enable-minidebuginfo')
else:
args.append('--disable-minidebuginfo')
# zlib support is available in 1.5.x and later
if spec.satisfies('@1.5:'):
if '+zlib' in spec:
args.append('--enable-zlibdebuginfo')
else:
args.append('--disable-zlibdebuginfo')
return args
| # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libunwind(AutotoolsPackage):
"""A portable and efficient C programming interface (API) to determine
the call-chain of a program."""
homepage = "http://www.nongnu.org/libunwind/"
url = "http://download.savannah.gnu.org/releases/libunwind/libunwind-1.1.tar.gz"
git = "https://github.com/libunwind/libunwind"
maintainers = ['mwkrentel']
version('master', branch='master')
version('1.4-head', branch='v1.4-stable')
version('1.4-rc1', sha256='1928459139f048f9b4aca4bb5010540cb7718d44220835a2980b85429007fa9f')
version('1.3.1', sha256='43997a3939b6ccdf2f669b50fdb8a4d3205374728c2923ddc2354c65260214f8', preferred=True)
version('1.2.1', sha256='3f3ecb90e28cbe53fba7a4a27ccce7aad188d3210bb1964a923a731a27a75acb')
version('1.1', sha256='9dfe0fcae2a866de9d3942c66995e4b460230446887dbdab302d41a8aee8d09a')
variant('xz', default=False,
description='Support xz (lzma) compressed symbol tables.')
variant('zlib', default=False,
description='Support zlib compressed symbol tables (master '
'branch only).')
# The libunwind releases contain the autotools generated files,
# but the git repo snapshots do not.
depends_on('autoconf', type='build', when='@master,1.4-head')
depends_on('automake', type='build', when='@master,1.4-head')
depends_on('libtool', type='build', when='@master,1.4-head')
depends_on('m4', type='build', when='@master,1.4-head')
depends_on('xz', type='link', when='+xz')
depends_on('zlib', type='link', when='+zlib')
conflicts('platform=darwin',
msg='Non-GNU libunwind needs ELF libraries Darwin does not have')
provides('unwind')
flag_handler = AutotoolsPackage.build_system_flags
def configure_args(self):
spec = self.spec
args = []
if '+xz' in spec:
args.append('--enable-minidebuginfo')
else:
args.append('--disable-minidebuginfo')
# zlib support is only in the master branch (for now).
if spec.satisfies('@master'):
if '+zlib' in spec:
args.append('--enable-zlibdebuginfo')
else:
args.append('--disable-zlibdebuginfo')
return args
| Python | 0 |
1be539f68019435b2d09b1a46e4786a09e59edf2 | Allow for multiple SEPA payment methods with different versions (#493) (#496) | account_banking_pain_base/models/account_payment_method.py | account_banking_pain_base/models/account_payment_method.py | # -*- coding: utf-8 -*-
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, fields, api, _
from odoo.exceptions import UserError
class AccountPaymentMethod(models.Model):
_inherit = 'account.payment.method'
pain_version = fields.Selection([], string='PAIN Version')
convert_to_ascii = fields.Boolean(
string='Convert to ASCII', default=True,
help="If active, Odoo will convert each accented character to "
"the corresponding unaccented character, so that only ASCII "
"characters are used in the generated PAIN file.")
@api.multi
def get_xsd_file_path(self):
"""This method is designed to be inherited in the SEPA modules"""
self.ensure_one()
raise UserError(_(
"No XSD file path found for payment method '%s'") % self.name)
_sql_constraints = [(
# Extending this constraint from account_payment_mode
'code_payment_type_unique',
'unique(code, payment_type, pain_version)',
'A payment method of the same type already exists with this code'
' and PAIN version'
)]
| # -*- coding: utf-8 -*-
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, fields, api, _
from odoo.exceptions import UserError
class AccountPaymentMethod(models.Model):
_inherit = 'account.payment.method'
pain_version = fields.Selection([], string='PAIN Version')
convert_to_ascii = fields.Boolean(
string='Convert to ASCII', default=True,
help="If active, Odoo will convert each accented character to "
"the corresponding unaccented character, so that only ASCII "
"characters are used in the generated PAIN file.")
@api.multi
def get_xsd_file_path(self):
"""This method is designed to be inherited in the SEPA modules"""
self.ensure_one()
raise UserError(_(
"No XSD file path found for payment method '%s'") % self.name)
| Python | 0 |
4697bb9bb7a3708f1c35b795c02db329d3142703 | Add script to collect metrics in samples of a case into a single vector | src/rgbd_benchmark_tools/h5_collectSamples.py | src/rgbd_benchmark_tools/h5_collectSamples.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 09:02:31 2015
@author: jesus
"""
import argparse
import numpy as np
import h5py
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''
This script collects the metrics and results from several samples of an experiment into its parent group.
''')
parser.add_argument('h5file', help='HDF5 file in which the metrics are stored in the group eval for each sample')
parser.add_argument('group', help='H5 path of the main group containing sample minor groups')
parser.add_argument('delta_unit', help='delta_unit of the metrics to collect')
args = parser.parse_args()
h5f = h5py.File(args.h5file,'a')
unit = args.delta_unit
# Save the evaluation metric values in the samples' parent group
main_group = h5f[args.group]
# Check if eval group already exists in the main group
if 'eval/'+unit in main_group:
print "Removing existing eval/"+unit + " group in" + main_group.name
del main_group['eval/'+unit]
numOfSamples = len(main_group)
# Create new eval group in the main group
samples = main_group.keys()
samples = [x for x in samples if x != 'eval']
eval_group = main_group.require_group('eval/'+unit)
names = ['rmse','median','mean','max']
for name in names:
# Preallocate arrays
t_arr = np.empty(numOfSamples)
r_arr = np.empty(numOfSamples)
# Store metrics in sample in an array
for i, sample in enumerate(samples):
t_arr[i] = main_group[sample+'/eval/'+unit+'/t_'+name][()]
r_arr[i] = main_group[sample+'/eval/'+unit+'/r_'+name][()]
# Check if dataset already exists in the group
if 't_'+name in eval_group:
print "Removing existing trans dataset in " + eval_group.name
del eval_group['t_'+name]
if 'r_'+name in eval_group:
print "Removing existing rot dataset in " + eval_group.name
del eval_group['r_'+name]
# Save as a new dataset in the main group
eval_group.create_dataset('t_'+name, data=t_arr)
eval_group.create_dataset('r_'+name, data=r_arr)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 09:02:31 2015
@author: jesus
"""
import argparse
import numpy as np
import h5py
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''
This script collects the metrics and results from several samples of an experiment into its parent group.
''')
parser.add_argument('h5file', help='HDF5 file in which the metrics are stored in the group eval for each sample')
parser.add_argument('group', help='H5 path of the main group containing sample minor groups')
parser.add_argument('delta_unit', help='delta_unit of the metrics to collect')
args = parser.parse_args()
h5f = h5py.File(args.h5file,'a')
unit = args.delta_unit
# Save the evaluation metric values in the samples' parent group
main_group = h5f[args.group]
# Check if eval group already exists in the main group
if 'eval' in main_group:
print "Removing existing eval group in" + main_group.name
del main_group['eval']
numOfSamples = len(main_group)
# Create new eval group in the main group
samples = main_group.keys()
eval_group = main_group.require_group('eval/'+args.delta_unit)
names = ['rmse','median','mean','max']
for name in names:
# Preallocate arrays
t_arr = np.empty(numOfSamples)
r_arr = np.empty(numOfSamples)
# Store metrics in sample in an array
for i, sample in enumerate(samples):
t_arr[i] = main_group[sample+'/eval/'+unit+'/t_'+name][()]
r_arr[i] = main_group[sample+'/eval/'+unit+'/r_'+name][()]
# Check if dataset already exists in the group
if 't_'+name in eval_group:
print "Removing existing trans dataset in " + eval_group.name
del eval_group['t_'+name]
if 'r_'+name in eval_group:
print "Removing existing rot dataset in " + eval_group.name
del eval_group['r_'+name]
# Save as a new dataset in the main group
eval_group.create_dataset('t_'+name, data=t_arr)
eval_group.create_dataset('r_'+name, data=r_arr)
| Python | 0 |
0f295d0ee8c29361bd4f80dbc947da65dd7fbbe6 | move raindrops | Exercism/python/raindrops/raindrops.py | Exercism/python/raindrops/raindrops.py | def convert(number):
raindrops = ((3, "Pling"), (5, "Plang"), (7, "Plong"))
raindrop_result = [raindrop[1] for raindrop in raindrops if number % raindrop[0] == 0]
return "".join(raindrop_result) or str(number) | raindrops = ((3, "Pling"), (5, "Plang"), (7, "Plong"))
def convert(number):
raindrop_result = [raindrop[1] for raindrop in raindrops if number % raindrop[0] == 0]
return "".join(raindrop_result) or str(number) | Python | 0.000759 |
15ae458f7cf1a8257967b2b3b0ceb812547c4766 | Test more edge cases of the highlighting parser | IPython/utils/tests/test_pycolorize.py | IPython/utils/tests/test_pycolorize.py | # coding: utf-8
"""Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# third party
import nose.tools as nt
# our own
from IPython.utils.PyColorize import Parser
import io
#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------------------------------------------------
sample = u"""
def function(arg, *args, kwarg=True, **kwargs):
'''
this is docs
'''
pass is True
False == None
with io.open(ru'unicode'):
raise ValueError("\n escape \r sequence")
print("wěird ünicoðe")
class Bar(Super):
def __init__(self):
super(Bar, self).__init__(1**2, 3^4, 5 or 6)
"""
def test_loop_colors():
for scheme in ('Linux', 'NoColor','LightBG'):
def test_unicode_colorize():
p = Parser()
f1 = p.format('1/0', 'str', scheme=scheme)
f2 = p.format(u'1/0', 'str', scheme=scheme)
nt.assert_equal(f1, f2)
def test_parse_sample():
"""and test writing to a buffer"""
buf = io.StringIO()
p = Parser()
p.format(sample, buf, scheme=scheme)
buf.seek(0)
f1 = buf.read()
nt.assert_not_in('ERROR', f1)
def test_parse_error():
p = Parser()
f1 = p.format(')', 'str', scheme=scheme)
if scheme != 'NoColor':
nt.assert_in('ERROR', f1)
yield test_unicode_colorize
yield test_parse_sample
yield test_parse_error
| """Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# third party
import nose.tools as nt
# our own
from IPython.utils.PyColorize import Parser
#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------------------------------------------------
def test_unicode_colorize():
p = Parser()
f1 = p.format('1/0', 'str')
f2 = p.format(u'1/0', 'str')
nt.assert_equal(f1, f2)
| Python | 0 |
2fd6a6a2ae61b6babbe873e4278984920d1d6cd1 | update plots for the temporal noise experiment | projects/sequence_prediction/discrete_sequences/plotNoiseExperiment.py | projects/sequence_prediction/discrete_sequences/plotNoiseExperiment.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, 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 program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Plot temporal noise experiment result
"""
import os
from matplotlib import pyplot
import matplotlib as mpl
from plot import plotAccuracy
from plot import computeAccuracy
from plot import readExperiment
mpl.rcParams['pdf.fonttype'] = 42
pyplot.ion()
pyplot.close('all')
if __name__ == '__main__':
experiments = [os.path.join("lstm/results", "high-order-noise",
"inject_noise_after0.0", "0.log"),
os.path.join("tm/results", "high-order-noise",
"inject_noise_after0.0", "0.log")]
for experiment in experiments:
data = readExperiment(experiment)
(accuracy, x) = computeAccuracy(data['predictions'],
data['truths'],
data['iterations'],
resets=data['resets'],
randoms=data['randoms'])
plotAccuracy((accuracy, x),
data['trains'],
window=100,
type=type,
label='NoiseExperiment',
hideTraining=True,
lineSize=1.0)
pyplot.xlim([10500, 14500])
pyplot.xlabel('Number of elements seen')
pyplot.ylabel(' Accuracy ')
pyplot.legend(['LSTM', 'HTM'])
pyplot.savefig('./result/temporal_noise_train_with_noise.pdf')
experiments = [os.path.join("lstm/results", "high-order-noise",
"inject_noise_after12000.0", "0.log"),
os.path.join("tm/results", "high-order-noise",
"inject_noise_after12000.0", "0.log")]
pyplot.close('all')
for experiment in experiments:
data = readExperiment(experiment)
(accuracy, x) = computeAccuracy(data['predictions'],
data['truths'],
data['iterations'],
resets=data['resets'],
randoms=data['randoms'])
# injectNoiseAt = data['sequenceCounter'][12000]
# x = numpy.array(x) - injectNoiseAt + 1400
plotAccuracy((accuracy, x),
data['trains'],
window=100,
type=type,
label='NoiseExperiment',
hideTraining=True,
lineSize=1.0)
pyplot.xlim([10500, 14500])
pyplot.xlabel('Number of elements seen')
pyplot.ylabel(' Accuracy ')
pyplot.axvline(x=12000, color='k')
pyplot.legend(['LSTM', 'HTM'])
pyplot.savefig('./result/temporal_noise_train_without_noise.pdf')
experiments = [
os.path.join("lstm/results", "high-order-noise-test-without-noise", "0.log"),
os.path.join("tm/results", "high-order-noise-test-without-noise", "0.log"),
]
pyplot.close('all')
for experiment in experiments:
data = readExperiment(experiment)
(accuracy, x) = computeAccuracy(data['predictions'],
data['truths'],
data['iterations'],
resets=data['resets'],
randoms=data['randoms'])
plotAccuracy((accuracy, x),
data['trains'],
window=100,
type=type,
label='NoiseExperiment',
hideTraining=True,
lineSize=1.0)
pyplot.xlim([10500, 15000])
pyplot.axvline(x=12000, color='k')
pyplot.xlabel('Number of elements seen')
pyplot.ylabel(' Accuracy ')
pyplot.legend(['LSTM', 'HTM'])
pyplot.savefig('./result/temporal_noise_test_without_noise.pdf') | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, 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 program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Plot temporal noise experiment result
"""
import os
from matplotlib import pyplot
import matplotlib as mpl
from plot import plotAccuracy
from plot import computeAccuracy
from plot import readExperiment
mpl.rcParams['pdf.fonttype'] = 42
pyplot.ion()
if __name__ == '__main__':
experiments = [os.path.join("lstm/results", "high-order-noise", "0.log"),
os.path.join("tm/results", "high-order-noise", "0.log")]
for experiment in experiments:
data = readExperiment(experiment)
(accuracy, x) = computeAccuracy(data['predictions'],
data['truths'],
data['iterations'],
resets=data['resets'],
randoms=data['randoms'],
sequenceCounter=data['sequenceCounter'])
injectNoiseAt = data['sequenceCounter'][12000]
plotAccuracy((accuracy, x),
data['trains'],
window=100,
type=type,
label='NoiseExperiment',
hideTraining=True,
lineSize=1.0)
pyplot.xlim([1200, 1750])
pyplot.savefig('./model_performance_after_temporal_noise.pdf')
pyplot.legend(['LSTM', 'HTM']) | Python | 0 |
1eee9dfa6f7ea359f0dc4d0bf7450b3c96d3731d | Remove unnecessary var | reunition/apps/reunions/management/commands/setalumniusersfromrsvps.py | reunition/apps/reunions/management/commands/setalumniusersfromrsvps.py | from django.core.management.base import NoArgsCommand
from django.db.models.fields import related
from reunition.apps.alumni import models as alumni_m
from reunition.apps.reunions import models as reunions_m
class Command(NoArgsCommand):
help = 'Associate reunions.Rsvp.created_by to alumni.Person.user when not yet set'
def handle_noargs(self, **options):
for rsvp in reunions_m.Rsvp.objects.all():
user = rsvp.created_by
try:
user.person
except alumni_m.Person.DoesNotExist:
first_alumni_added = rsvp.rsvpalumniattendee_set.order_by('created').first()
if first_alumni_added:
person = first_alumni_added.person
print 'Associating user', user, 'with person', person
person.user = user
person.save()
| from django.core.management.base import NoArgsCommand
from django.db.models.fields import related
from reunition.apps.alumni import models as alumni_m
from reunition.apps.reunions import models as reunions_m
class Command(NoArgsCommand):
help = 'Associate reunions.Rsvp.created_by to alumni.Person.user when not yet set'
def handle_noargs(self, **options):
for rsvp in reunions_m.Rsvp.objects.all():
user = rsvp.created_by
try:
user.person
except alumni_m.Person.DoesNotExist, e:
first_alumni_added = rsvp.rsvpalumniattendee_set.order_by('created').first()
if first_alumni_added:
person = first_alumni_added.person
print 'Associating user', user, 'with person', person
person.user = user
person.save()
| Python | 0.000007 |
5fc54a2120fbc9151073c9b247e3fd7e8e79a9fa | Remove premature attribute from migration script (Fixes #283) | src/adhocracy/migration/versions/054_add_hierachical_categorybadges.py | src/adhocracy/migration/versions/054_add_hierachical_categorybadges.py | from datetime import datetime
from sqlalchemy import Column, ForeignKey, MetaData, Table
from sqlalchemy import Boolean, Integer, DateTime, String, Unicode, LargeBinary
metadata = MetaData()
#table to update
badge_table = Table(
'badge', metadata,
#common attributes
Column('id', Integer, primary_key=True),
Column('type', String(40), nullable=False),
Column('create_time', DateTime, default=datetime.utcnow),
Column('title', Unicode(40), nullable=False),
Column('color', Unicode(7), nullable=False),
Column('description', Unicode(255), default=u'', nullable=False),
Column('instance_id', Integer, ForeignKey('instance.id',
ondelete="CASCADE",),
nullable=True),
# attributes for UserBadges
Column('group_id', Integer, ForeignKey('group.id', ondelete="CASCADE")),
Column('display_group', Boolean, default=False),
Column('visible', Boolean, default=True),
)
def upgrade(migrate_engine):
#use sqlalchemy-migrate database connection
metadata.bind = migrate_engine
#autoload needed tables
instance_table = Table('instance', metadata, autoload=True)
#add hierachical columns to the table
select_child_desc = Column('select_child_description', Unicode(255), default=u'', nullable=True)
parent = Column('parent_id', Integer, ForeignKey('badge.id', ondelete="CASCADE"),
nullable=True)
#create/recreate the table
select_child_desc.create(badge_table)
select_child_desc.alter(nullable=False)
parent.create(badge_table)
def downgrade(migrate_engine):
raise NotImplementedError()
| from datetime import datetime
from sqlalchemy import Column, ForeignKey, MetaData, Table
from sqlalchemy import Boolean, Integer, DateTime, String, Unicode, LargeBinary
metadata = MetaData()
#table to update
badge_table = Table(
'badge', metadata,
#common attributes
Column('id', Integer, primary_key=True),
Column('type', String(40), nullable=False),
Column('create_time', DateTime, default=datetime.utcnow),
Column('title', Unicode(40), nullable=False),
Column('color', Unicode(7), nullable=False),
Column('description', Unicode(255), default=u'', nullable=False),
Column('instance_id', Integer, ForeignKey('instance.id',
ondelete="CASCADE",),
nullable=True),
# attributes for UserBadges
Column('group_id', Integer, ForeignKey('group.id', ondelete="CASCADE")),
Column('display_group', Boolean, default=False),
Column('visible', Boolean, default=True),
# attributes for ThumbnailBadges
Column('thumbnail', LargeBinary, default=None, nullable=True)
)
def upgrade(migrate_engine):
#use sqlalchemy-migrate database connection
metadata.bind = migrate_engine
#autoload needed tables
instance_table = Table('instance', metadata, autoload=True)
#add hierachical columns to the table
select_child_desc = Column('select_child_description', Unicode(255), default=u'', nullable=True)
parent = Column('parent_id', Integer, ForeignKey('badge.id', ondelete="CASCADE"),
nullable=True)
#create/recreate the table
select_child_desc.create(badge_table)
select_child_desc.alter(nullable=False)
parent.create(badge_table)
def downgrade(migrate_engine):
raise NotImplementedError()
| Python | 0 |
a1bf5aaf3866eea7370c1a401a5e3d5791f97539 | Add exception for inline encoded images. | better_figures_and_images/better_figures_and_images.py | better_figures_and_images/better_figures_and_images.py | """
Better Figures & Images
------------------------
This plugin:
- Adds a style="width: ???px; height: auto;" to each image in the content
- Also adds the width of the contained image to any parent div.figures.
- If RESPONSIVE_IMAGES == True, also adds style="max-width: 100%;"
- Corrects alt text: if alt == image filename, set alt = ''
TODO: Need to add a test.py for this plugin.
"""
from __future__ import unicode_literals
from os import path, access, R_OK
from pelican import signals
from bs4 import BeautifulSoup
from PIL import Image
import logging
logger = logging.getLogger(__name__)
def content_object_init(instance):
if instance._content is not None:
content = instance._content
soup = BeautifulSoup(content, 'html.parser')
if 'img' in content:
for img in soup('img'):
logger.debug('Better Fig. PATH: %s', instance.settings['PATH'])
logger.debug('Better Fig. img.src: %s', img['src'])
img_path, img_filename = path.split(img['src'])
logger.debug('Better Fig. img_path: %s', img_path)
logger.debug('Better Fig. img_fname: %s', img_filename)
# Strip off {filename}, |filename| or /static
if img_path.startswith(('{filename}', '|filename|')):
img_path = img_path[10:]
elif img_path.startswith('/static'):
img_path = img_path[7:]
elif img_path.startswith('data:image'):
# Image is encoded in-line (not a file).
continue
else:
logger.warning('Better Fig. Error: img_path should start with either {filename}, |filename| or /static')
# Build the source image filename
src = instance.settings['PATH'] + img_path + '/' + img_filename
logger.debug('Better Fig. src: %s', src)
if not (path.isfile(src) and access(src, R_OK)):
logger.error('Better Fig. Error: image not found: %s', src)
# Open the source image and query dimensions; build style string
im = Image.open(src)
extra_style = 'width: {}px; height: auto;'.format(im.size[0])
if 'RESPONSIVE_IMAGES' in instance.settings and instance.settings['RESPONSIVE_IMAGES']:
extra_style += ' max-width: 100%;'
if img.get('style'):
img['style'] += extra_style
else:
img['style'] = extra_style
if img['alt'] == img['src']:
img['alt'] = ''
fig = img.find_parent('div', 'figure')
if fig:
if fig.get('style'):
fig['style'] += extra_style
else:
fig['style'] = extra_style
instance._content = soup.decode()
def register():
signals.content_object_init.connect(content_object_init)
| """
Better Figures & Images
------------------------
This plugin:
- Adds a style="width: ???px; height: auto;" to each image in the content
- Also adds the width of the contained image to any parent div.figures.
- If RESPONSIVE_IMAGES == True, also adds style="max-width: 100%;"
- Corrects alt text: if alt == image filename, set alt = ''
TODO: Need to add a test.py for this plugin.
"""
from __future__ import unicode_literals
from os import path, access, R_OK
from pelican import signals
from bs4 import BeautifulSoup
from PIL import Image
import logging
logger = logging.getLogger(__name__)
def content_object_init(instance):
if instance._content is not None:
content = instance._content
soup = BeautifulSoup(content, 'html.parser')
if 'img' in content:
for img in soup('img'):
logger.debug('Better Fig. PATH: %s', instance.settings['PATH'])
logger.debug('Better Fig. img.src: %s', img['src'])
img_path, img_filename = path.split(img['src'])
logger.debug('Better Fig. img_path: %s', img_path)
logger.debug('Better Fig. img_fname: %s', img_filename)
# Strip off {filename}, |filename| or /static
if img_path.startswith(('{filename}', '|filename|')):
img_path = img_path[10:]
elif img_path.startswith('/static'):
img_path = img_path[7:]
elif img_path.startswith('data:image'):
# Image is encoded in-line (not a file).
break
else:
logger.warning('Better Fig. Error: img_path should start with either {filename}, |filename| or /static')
# Build the source image filename
src = instance.settings['PATH'] + img_path + '/' + img_filename
logger.debug('Better Fig. src: %s', src)
if not (path.isfile(src) and access(src, R_OK)):
logger.error('Better Fig. Error: image not found: %s', src)
# Open the source image and query dimensions; build style string
im = Image.open(src)
extra_style = 'width: {}px; height: auto;'.format(im.size[0])
if 'RESPONSIVE_IMAGES' in instance.settings and instance.settings['RESPONSIVE_IMAGES']:
extra_style += ' max-width: 100%;'
if img.get('style'):
img['style'] += extra_style
else:
img['style'] = extra_style
if img['alt'] == img['src']:
img['alt'] = ''
fig = img.find_parent('div', 'figure')
if fig:
if fig.get('style'):
fig['style'] += extra_style
else:
fig['style'] = extra_style
instance._content = soup.decode()
def register():
signals.content_object_init.connect(content_object_init)
| Python | 0 |
b06687b1e78645a055a314be4b1af693e2c3be05 | remove obsolete arguments | RatS/filmaffinity/filmaffinity_site.py | RatS/filmaffinity/filmaffinity_site.py | import time
from RatS.base.base_site import Site
from selenium.webdriver.common.by import By
class FilmAffinity(Site):
def __init__(self, args):
login_form_selector = "//form[@id='login-form']"
self.LOGIN_USERNAME_SELECTOR = login_form_selector + "//input[@name='username']"
self.LOGIN_PASSWORD_SELECTOR = login_form_selector + "//input[@name='password']"
self.LOGIN_BUTTON_SELECTOR = login_form_selector + "//input[@type='submit']"
super(FilmAffinity, self).__init__(args)
self.MY_RATINGS_URL = "https://www.filmaffinity.com/en/myvotes.php"
def _get_login_page_url(self):
return "https://www.filmaffinity.com/en/login.php"
def _handle_cookie_notice_if_present(self):
cookie_notices = self.browser.find_elements(By.ID, "qc-cmp2-container")
if len(cookie_notices) == 0:
return
cookie_notice = cookie_notices[0]
if cookie_notice is not None:
# agree
cookie_accept_button = cookie_notice.find_elements(
By.CSS_SELECTOR, "div.qc-cmp2-summary-buttons button"
)
if cookie_accept_button is not None and len(cookie_accept_button) > 1:
cookie_accept_button[1].click()
time.sleep(2)
# agree all
cookie_accept_button = cookie_notice.find_elements(
By.CSS_SELECTOR,
"div.qc-cmp2-buttons-desktop button",
)
if cookie_accept_button is not None and len(cookie_accept_button) > 1:
cookie_accept_button[1].click()
time.sleep(2)
| import time
from RatS.base.base_site import Site
from selenium.webdriver.common.by import By
class FilmAffinity(Site):
def __init__(self, args):
login_form_selector = "//form[@id='login-form']"
self.LOGIN_USERNAME_SELECTOR = login_form_selector + "//input[@name='username']"
self.LOGIN_PASSWORD_SELECTOR = login_form_selector + "//input[@name='password']"
self.LOGIN_BUTTON_SELECTOR = login_form_selector + "//input[@type='submit']"
super(FilmAffinity, self).__init__(args)
self.MY_RATINGS_URL = "https://www.filmaffinity.com/en/myvotes.php"
def _get_login_page_url(self):
return "https://www.filmaffinity.com/en/login.php"
def _handle_cookie_notice_if_present(self):
cookie_notices = self.browser.find_elements(By.ID, "qc-cmp2-container")
if len(cookie_notices) == 0:
return
cookie_notice = cookie_notices[0]
if cookie_notice is not None:
# agree
cookie_accept_button = cookie_notice.find_elements(
By.CSS_SELECTOR, By.CSS_SELECTOR, "div.qc-cmp2-summary-buttons button"
)
if cookie_accept_button is not None and len(cookie_accept_button) > 1:
cookie_accept_button[1].click()
time.sleep(2)
# agree all
cookie_accept_button = cookie_notice.find_elements(
By.CSS_SELECTOR,
By.CSS_SELECTOR,
"div.qc-cmp2-buttons-desktop button",
)
if cookie_accept_button is not None and len(cookie_accept_button) > 1:
cookie_accept_button[1].click()
time.sleep(2)
| Python | 0.005914 |
cd17eba08cbb898b1cf6d0bb622315d851b4eeec | The main parameter object is a list | ocradmin/ocr/tools/manager.py | ocradmin/ocr/tools/manager.py | """
Plugin manager.
"""
import os
import sys
class PluginManager(object):
"""
Class for managing OCR tool plugins.
"""
def __init__(self):
pass
@classmethod
def get_plugins(cls):
"""
List available OCR plugins.
"""
engines = []
plugdir = os.path.join(os.path.dirname(__file__), "plugins")
for fname in os.listdir(plugdir):
if not fname.endswith("wrapper.py"):
continue
modname = os.path.splitext(os.path.basename(fname))[0]
pm = __import__(
modname,
fromlist=["main_class"])
if not hasattr(pm, "main_class"):
continue
mod = pm.main_class()
engines.append(dict(
name=mod.name,
type="list",
description=mod.description,
parameters=True,
))
return engines
@classmethod
def get_provider(cls, provides=None):
"""
Get a list of available OCR engines.
"""
engines = []
plugdir = os.path.join(os.path.dirname(__file__), "plugins")
for fname in os.listdir(plugdir):
if fname.endswith("wrapper.py"):
modname = os.path.splitext(os.path.basename(fname))[0]
pm = __import__(
modname,
fromlist=["main_class"])
if not hasattr(pm, "main_class"):
continue
mod = pm.main_class()
if provides is None:
engines.append(mod.name)
elif isinstance(provides, str) and provides in mod.capabilities:
engines.append(mod.name)
elif isinstance(provides, tuple):
for cap in provides:
if cap in mod.capabilities:
engines.append(mod.name)
break
return engines
@classmethod
def get(cls, name, *args, **kwargs):
"""
Get a plugin directly.
"""
return cls._main_class(name)
@classmethod
def get_info(cls, name, *args, **kwargs):
"""
Get info about a plugin.
"""
mc = cls._main_class(name)
if mc is not None:
return mc.get_info(*args, **kwargs)
@classmethod
def get_parameters(cls, name, *args, **kwargs):
"""
Get general options for an engine.
"""
print "Getting options: " + name
mc = cls._main_class(name)
if mc is not None:
return mc.get_parameters(*args, **kwargs)
@classmethod
def get_trainer(cls, name, *args, **kwargs):
"""
Fetch a given trainer class. Currently this is the
same as the converter.
"""
return cls.get_converter(name, *args, **kwargs)
@classmethod
def get_converter(cls, name, *args, **kwargs):
"""
Get a converter with a given name.
"""
mc = cls._main_class(name)
if mc is not None:
return mc(*args, **kwargs)
@classmethod
def get_components(cls, name, *args, **kwargs):
"""
Get available components of the given type for given plugin.
"""
mc = cls._main_class(name)
if mc is not None:
return mc.get_components(*args, **kwargs)
@classmethod
def _main_class(cls, name):
"""
Get the plugin class with a given name.
"""
plugdir = os.path.join(os.path.dirname(__file__), "plugins")
for fname in os.listdir(plugdir):
modname = "%s_wrapper.py" % name
if fname == modname:
# FIXME: Hard-coded module import path needs to change
# TODO: Generally find a better way of doing this...
pm = __import__("%s_wrapper" % name, fromlist=["main_class"])
return pm.main_class()
| """
Plugin manager.
"""
import os
import sys
class PluginManager(object):
"""
Class for managing OCR tool plugins.
"""
def __init__(self):
pass
@classmethod
def get_plugins(cls):
"""
List available OCR plugins.
"""
engines = []
plugdir = os.path.join(os.path.dirname(__file__), "plugins")
for fname in os.listdir(plugdir):
if not fname.endswith("wrapper.py"):
continue
modname = os.path.splitext(os.path.basename(fname))[0]
pm = __import__(
modname,
fromlist=["main_class"])
if not hasattr(pm, "main_class"):
continue
mod = pm.main_class()
engines.append(dict(
name=mod.name,
type="object",
description=mod.description,
parameters=True,
))
return engines
@classmethod
def get_provider(cls, provides=None):
"""
Get a list of available OCR engines.
"""
engines = []
plugdir = os.path.join(os.path.dirname(__file__), "plugins")
for fname in os.listdir(plugdir):
if fname.endswith("wrapper.py"):
modname = os.path.splitext(os.path.basename(fname))[0]
pm = __import__(
modname,
fromlist=["main_class"])
if not hasattr(pm, "main_class"):
continue
mod = pm.main_class()
if provides is None:
engines.append(mod.name)
elif isinstance(provides, str) and provides in mod.capabilities:
engines.append(mod.name)
elif isinstance(provides, tuple):
for cap in provides:
if cap in mod.capabilities:
engines.append(mod.name)
break
return engines
@classmethod
def get(cls, name, *args, **kwargs):
"""
Get a plugin directly.
"""
return cls._main_class(name)
@classmethod
def get_info(cls, name, *args, **kwargs):
"""
Get info about a plugin.
"""
mc = cls._main_class(name)
if mc is not None:
return mc.get_info(*args, **kwargs)
@classmethod
def get_parameters(cls, name, *args, **kwargs):
"""
Get general options for an engine.
"""
print "Getting options: " + name
mc = cls._main_class(name)
if mc is not None:
return mc.get_parameters(*args, **kwargs)
@classmethod
def get_trainer(cls, name, *args, **kwargs):
"""
Fetch a given trainer class. Currently this is the
same as the converter.
"""
return cls.get_converter(name, *args, **kwargs)
@classmethod
def get_converter(cls, name, *args, **kwargs):
"""
Get a converter with a given name.
"""
mc = cls._main_class(name)
if mc is not None:
return mc(*args, **kwargs)
@classmethod
def get_components(cls, name, *args, **kwargs):
"""
Get available components of the given type for given plugin.
"""
mc = cls._main_class(name)
if mc is not None:
return mc.get_components(*args, **kwargs)
@classmethod
def _main_class(cls, name):
"""
Get the plugin class with a given name.
"""
plugdir = os.path.join(os.path.dirname(__file__), "plugins")
for fname in os.listdir(plugdir):
modname = "%s_wrapper.py" % name
if fname == modname:
# FIXME: Hard-coded module import path needs to change
# TODO: Generally find a better way of doing this...
pm = __import__("%s_wrapper" % name, fromlist=["main_class"])
return pm.main_class()
| Python | 0.999856 |
c79c3b7f920f4bcf5fb69cf74b224e6ff37a709b | test triggering travis | fabre_test.py | fabre_test.py | #!/usr/bin/env python
# coding=UTF-8
import pytest
import sys
# content of test_assert1.py
def f():
return 3
def test_function():
assert f() == 4
test_function()
| #!/usr/bin/env python
# coding=UTF-8
import pytest
import sys
sys.exit(0)
| Python | 0.000001 |
0fb800cd42f1545e8d5e744af1ff81922c930448 | Add Google analytics ID | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from datetime import datetime
import os
import sys
BASE_DIR = os.path.dirname(__file__)
# Clone the official plugin repo to the `official_plugins` dir
# (https://github.com/getpelican/pelican-plugins)
sys.path.append(os.path.join(BASE_DIR, "official_plugins"))
AUTHOR = u'Leonardo Zhou'
SITENAME = u'翼图南'
SITE_DESCRIPTION = u'故九萬里,則風斯在下矣,而後乃今培風;背負青天而莫之夭閼者,而後乃今將圖南'
SITEURL = ''
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = u'zh'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Social widget
SOCIAL = (
('twitter', 'https://twitter.com/glasslion'),
('envelope', 'mailto:glasslion@gmail.com'),
('github', 'https://github.com/glasslion'),
('stack-overflow', 'http://stackoverflow.com/users/1093020/leonardo-z'),
)
GOOGLE_ANALYTICS = "UA-42951023-1"
LOCALE = ('usa', 'en_US.utf8')
DEFAULT_DATE_FORMAT = '%b %d, %Y'
# DIRECT_TEMPLATES = ('index', 'tags', 'categories', 'archives')
# PAGINATED_DIRECT_TEMPLATES = (('blog',))
PLUGINS = ['summary', 'assets', 'neighbors']
# Assets
ASSET_BUNDLES = ()
ASSET_CONFIG = (('sass_bin', 'sass'), )
SUMMARY_MAX_LENGTH = 20
DEFAULT_PAGINATION = 5
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
# Static content
STATIC_PATHS = ['images', 'extra/CNAME',]
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
# Url
ARTICLE_URL = '{slug}/'
ARTICLE_SAVE_AS = '{slug}/index.html'
# Archive
YEAR_ARCHIVE_SAVE_AS = 'archives/{date:%Y}/index.html'
MONTH_ARCHIVE_SAVE_AS = 'archives/{date:%Y}/{date:%m}/index.html'
# Custom theme
THEME = '../pelican-zha'
CURRENT_DATETIME = datetime.now()
QINIU_BUCKET_URL = 'http://wing2south.qiniudn.com'
CDN_URL = SITEURL | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from datetime import datetime
import os
import sys
BASE_DIR = os.path.dirname(__file__)
# Clone the official plugin repo to the `official_plugins` dir
# (https://github.com/getpelican/pelican-plugins)
sys.path.append(os.path.join(BASE_DIR, "official_plugins"))
AUTHOR = u'Leonardo Zhou'
SITENAME = u'翼图南'
SITE_DESCRIPTION = u'故九萬里,則風斯在下矣,而後乃今培風;背負青天而莫之夭閼者,而後乃今將圖南'
SITEURL = ''
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = u'zh'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Social widget
SOCIAL = (
('twitter', 'https://twitter.com/glasslion'),
('envelope', 'mailto:glasslion@gmail.com'),
('github', 'https://github.com/glasslion'),
('stack-overflow', 'http://stackoverflow.com/users/1093020/leonardo-z'),
)
LOCALE = ('usa', 'en_US.utf8')
DEFAULT_DATE_FORMAT = '%b %d, %Y'
# DIRECT_TEMPLATES = ('index', 'tags', 'categories', 'archives')
# PAGINATED_DIRECT_TEMPLATES = (('blog',))
PLUGINS = ['summary', 'assets', 'neighbors']
# Assets
ASSET_BUNDLES = ()
ASSET_CONFIG = (('sass_bin', 'sass'), )
SUMMARY_MAX_LENGTH = 20
DEFAULT_PAGINATION = 5
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
# Static content
STATIC_PATHS = ['images', 'extra/CNAME',]
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
# Url
ARTICLE_URL = '{slug}/'
ARTICLE_SAVE_AS = '{slug}/index.html'
# Archive
YEAR_ARCHIVE_SAVE_AS = 'archives/{date:%Y}/index.html'
MONTH_ARCHIVE_SAVE_AS = 'archives/{date:%Y}/{date:%m}/index.html'
# Custom theme
THEME = '../pelican-zha'
CURRENT_DATETIME = datetime.now()
QINIU_BUCKET_URL = 'http://wing2south.qiniudn.com'
CDN_URL = SITEURL | Python | 0.000002 |
6a1176d547694b535bc581d5a0af87230d533caf | set to version 3.305.533 | base/pythonvideoannotator/pythonvideoannotator/__init__.py | base/pythonvideoannotator/pythonvideoannotator/__init__.py | # !/usr/bin/python3
# -*- coding: utf-8 -*-
__version__ = "3.305.533"
__author__ = ["Ricardo Ribeiro", "Carlos Mao de Ferro", "Hugo Cachitas"]
__credits__ = ["Ricardo Ribeiro", "Carlos Mao de Ferro", "Hugo Cachitas"]
__license__ = "Attribution-NonCommercial-ShareAlike 4.0 International"
__maintainer__ = ["Ricardo Ribeiro", "Carlos Mao de Ferro"]
__email__ = ["ricardojvr at gmail.com", "cajomferro at gmail.com"]
__status__ = "Development"
from confapp import conf; conf += 'pythonvideoannotator.settings'
import logging
logger = logging.getLogger(__name__)
logger.setLevel(conf.APP_LOG_HANDLER_LEVEL)
if conf.APP_LOG_HANDLER_FILE:
logger = logging.getLogger()
loggers_formatter = logging.Formatter(conf.PYFORMS_LOG_FORMAT)
fh = logging.FileHandler(conf.APP_LOG_HANDLER_FILE)
fh.setLevel(conf.APP_LOG_HANDLER_FILE_LEVEL)
fh.setFormatter(loggers_formatter)
logger.addHandler(fh)
| # !/usr/bin/python3
# -*- coding: utf-8 -*-
__version__ = "3.305.532"
__author__ = ["Ricardo Ribeiro", "Carlos Mao de Ferro", "Hugo Cachitas"]
__credits__ = ["Ricardo Ribeiro", "Carlos Mao de Ferro", "Hugo Cachitas"]
__license__ = "Attribution-NonCommercial-ShareAlike 4.0 International"
__maintainer__ = ["Ricardo Ribeiro", "Carlos Mao de Ferro"]
__email__ = ["ricardojvr at gmail.com", "cajomferro at gmail.com"]
__status__ = "Development"
from confapp import conf; conf += 'pythonvideoannotator.settings'
import logging
logger = logging.getLogger(__name__)
logger.setLevel(conf.APP_LOG_HANDLER_LEVEL)
if conf.APP_LOG_HANDLER_FILE:
logger = logging.getLogger()
loggers_formatter = logging.Formatter(conf.PYFORMS_LOG_FORMAT)
fh = logging.FileHandler(conf.APP_LOG_HANDLER_FILE)
fh.setLevel(conf.APP_LOG_HANDLER_FILE_LEVEL)
fh.setFormatter(loggers_formatter)
logger.addHandler(fh)
| Python | 0.000001 |
4af80f4a72618482135f388c3bc424fa12e1ccc4 | refactor filter structure | shot_detector/filters/dsl/dsl_filter_mixin.py | shot_detector/filters/dsl/dsl_filter_mixin.py | # -*- coding: utf8 -*-
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function
import collections
import logging
from shot_detector.utils.dsl import BaseDslOperatorMixin
from shot_detector.utils.dsl.dsl_kwargs import dsl_kwargs_decorator
class DslFilterMixin(BaseDslOperatorMixin):
"""
Basic filter mixin to build Filter-DSL
"""
__logger = logging.getLogger(__name__)
@staticmethod
def dsl_kwargs_decorator(*dsl_rules):
"""
:param dsl_rules:
:return:
"""
return dsl_kwargs_decorator(*dsl_rules)
def __or__(self, other):
"""
:param Filter other:
:return:
"""
return self.sequential(other)
def __ror__(self, other):
"""
:param Filter other:
:return:
"""
return self.sequential(other)
def sequential(self, other):
"""
:param other:
:return:
"""
from .filter_cast_features import FilterCastFeatures
from .filter_sequence import FilterSequence
if not isinstance(other, DslFilterMixin):
other = FilterCastFeatures(
cast=other,
)
return FilterSequence(
sequential_filters=[
self, other
],
)
def apply_operator(self,
op_func=None,
others=None,
mode=None,
**kwargs):
"""
:param other:
:param op:
:param is_right:
:return:
"""
from .filter_operator import FilterOperator as Fo
other = others[0]
if not isinstance(other, DslFilterMixin):
other = self.scalar_to_filter(
value=other,
)
mode = Fo.LEFT
if mode is self.OPERATOR_RIGHT:
mode = Fo.RIGHT
return Fo(
parallel_filters=[self, other],
op_func=op_func,
mode=mode,
**kwargs
)
def to_filter(self, value):
"""
:param value:
:return:
"""
if isinstance(value, collections.Iterable):
return self.seq_to_filter(value)
return self.scalar_to_filter(value)
@staticmethod
def seq_to_filter(value):
"""
:param value:
:return:
"""
from .filter_cast_seq_value import FilterCastSeqValue
return FilterCastSeqValue(seq=value)
@staticmethod
def scalar_to_filter(value):
"""
:param value:
:return:
"""
from .filter_cast_scalar_value import FilterCastScalarValue
return FilterCastScalarValue(value=value)
def __contains__(self, item):
"""
:param Filter item:
:return:
"""
return self.intersect(item)
def i(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
return self.intersect(*args, **kwargs)
def intersect(self, other, threshold=0):
"""
:param other:
:param threshold:
:return:
"""
from .filter_intersection import FilterIntersection
return FilterIntersection(
parallel_filters=[self, other],
threshold=threshold
)
| # -*- coding: utf8 -*-
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function
import collections
import logging
from shot_detector.utils.dsl import BaseDslOperatorMixin
from shot_detector.utils.dsl.dsl_kwargs import dsl_kwargs_decorator
class DslFilterMixin(BaseDslOperatorMixin):
"""
Basic filter mixin to build Filter-DSL
"""
__logger = logging.getLogger(__name__)
@staticmethod
def dsl_kwargs_decorator(*args, **kwargs):
return dsl_kwargs_decorator(args, kwargs)
def __or__(self, other):
"""
:param Filter other:
:return:
"""
return self.sequential(other)
def __ror__(self, other):
"""
:param Filter other:
:return:
"""
return self.sequential(other)
def sequential(self, other):
"""
:param other:
:return:
"""
from .filter_cast_features import FilterCastFeatures
from .filter_sequence import FilterSequence
if not isinstance(other, DslFilterMixin):
other = FilterCastFeatures(
cast=other,
)
return FilterSequence(
sequential_filters=[
self, other
],
)
def apply_operator(self,
op_func=None,
others=None,
mode=None,
**kwargs):
"""
:param other:
:param op:
:param is_right:
:return:
"""
from .filter_operator import FilterOperator as Fo
other = others[0]
if not isinstance(other, DslFilterMixin):
other = self.scalar_to_filter(
value=other,
)
mode = Fo.LEFT
if mode is self.OPERATOR_RIGHT:
mode = Fo.RIGHT
return Fo(
parallel_filters=[self, other],
op_func=op_func,
mode=mode,
**kwargs
)
def to_filter(self, value):
"""
:param value:
:return:
"""
if isinstance(value, collections.Iterable):
return self.seq_to_filter(value)
return self.scalar_to_filter(value)
@staticmethod
def seq_to_filter(value):
"""
:param value:
:return:
"""
from .filter_cast_seq_value import FilterCastSeqValue
return FilterCastSeqValue(seq=value)
@staticmethod
def scalar_to_filter(value):
"""
:param value:
:return:
"""
from .filter_cast_scalar_value import FilterCastScalarValue
return FilterCastScalarValue(value=value)
def __contains__(self, item):
"""
:param Filter item:
:return:
"""
return self.intersect(item)
def i(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
return self.intersect(*args, **kwargs)
def intersect(self, other, threshold=0):
"""
:param other:
:param threshold:
:return:
"""
from .filter_intersection import FilterIntersection
return FilterIntersection(
parallel_filters=[self, other],
threshold=threshold
)
| Python | 0.000001 |
d82c37a85e3522f7cf7e26a220eb5946aec66ffe | Create docs from numpy | test/test_data_utils.py | test/test_data_utils.py | import numpy as np
from cStringIO import StringIO
from nose.tools import raises
from microscopes.lda import utils
def test_docs_from_document_term_matrix():
dtm = [[2, 1], [3, 2]]
docs = [[0, 0, 1], [0, 0, 0, 1, 1]]
assert utils.docs_from_document_term_matrix(dtm) == docs
def test_docs_from_numpy_dtp():
dtm = np.array([[2, 1], [3, 2]])
docs = [[0, 0, 1], [0, 0, 0, 1, 1]]
assert utils.docs_from_document_term_matrix(dtm) == docs
def test_docs_from_ldac_simple():
stream = StringIO()
stream.write("2 0:2 1:1\n2 0:3 1:2")
stream.seek(0) # rewind stream
docs = [[0, 0, 1], [0, 0, 0, 1, 1]]
assert utils.docs_from_ldac(stream) == docs
stream = StringIO()
stream.write("2 1:1 0:2\n3 2:1 0:3 1:1")
stream.seek(0) # rewind stream
docs = [[1, 0, 0], [2, 0, 0, 0, 1]]
assert utils.docs_from_ldac(stream) == docs
@raises(AssertionError)
def test_bad_ldac_data():
stream = StringIO()
stream.write("2 0:1")
stream.seek(0) # rewind stream
utils.docs_from_ldac(stream)
| from cStringIO import StringIO
from nose.tools import raises
from microscopes.lda import utils
def test_docs_from_document_term_matrix():
dtm = [[2, 1], [3, 2]]
docs = [[0, 0, 1], [0, 0, 0, 1, 1]]
assert utils.docs_from_document_term_matrix(dtm) == docs
def test_docs_from_ldac_simple():
stream = StringIO()
stream.write("2 0:2 1:1\n2 0:3 1:2")
stream.seek(0) # rewind stream
docs = [[0, 0, 1], [0, 0, 0, 1, 1]]
assert utils.docs_from_ldac(stream) == docs
stream = StringIO()
stream.write("2 1:1 0:2\n3 2:1 0:3 1:1")
stream.seek(0) # rewind stream
docs = [[1, 0, 0], [2, 0, 0, 0, 1]]
assert utils.docs_from_ldac(stream) == docs
@raises(AssertionError)
def test_bad_ldac_data():
stream = StringIO()
stream.write("2 0:1")
stream.seek(0) # rewind stream
utils.docs_from_ldac(stream)
| Python | 0 |
4cc3fe30e676c31cc6af9cb3a75de10b47ff2adc | Add % to date format | door/views.py | door/views.py | from django.shortcuts import render
from django.http import HttpResponse
from .models import DoorStatus, OpenData
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from website import settings
from datetime import datetime
import json
# Create your views here.
@csrf_exempt
def door_post(request):
if request.method == 'POST':
unico = request.body.decode('utf-8')
data = json.loads(unico)
if 'key' in data:
if data['key'] == settings.DOOR_KEY:
if 'status' in data:
status = data['status']
if DoorStatus.objects.filter(name='hackerspace').count():
door_status_object = DoorStatus.objects.get(name='hackerspace')
else:
door_status_object = DoorStatus(name='hackerspace')
if status == True:
door_status_object.status = status
door_status_object.save()
if 'timeStart' in data and 'dateStart' in data:
timeStart = data['timeStart']
dateStart = data['dateStart']
opened = datetime.strptime(dateStart+"."+timeStart,"%Y-%m-%d.%H:%i:%s")
door_status_object.datetime = opened
door_status_object.save()
elif status == False:
door_status_object.status = status
door_status_object.save()
if 'timeStart' in data and 'dateStart' in data and 'timeEnd' in data and 'dateEnd' in data and 'timeTotal' in data:
timeStart = data['timeStart']
dateStart = data['dateStart']
timeEnd = data['timeEnd']
dateEnd = data['dateEnd']
total = data['timeTotal']
opened = datetime.strptime(dateStart+"."+timeStart,"%Y-%m-%d.%H:%i:%s")
closed = datetime.strptime(dateEnd+"."+timeEnd,"%Y-%m-%d.%H:%i:%s")
openData = OpenData(opened=opened, closed=closed, total=total)
openData.save()
door_status_object.datetime = closed
door_status_object.save()
return HttpResponse(" ")
@csrf_exempt
def get_status(request):
if DoorStatus.objects.filter(name='hackerspace').count():
status = DoorStatus.objects.get(name='hackerspace').status
else:
status = True
return HttpResponse(status)
def door_data(request):
opendata_list = OpenData.objects.all()
if DoorStatus.objects.filter(name='hackerspace').count():
status = DoorStatus.objects.get(name='hackerspace')
else:
status = DoorStatus(name='hackerspace')
context = {
'opendata_list': opendata_list,
'status': status,
}
return render(request, 'door_data.html', context)
| from django.shortcuts import render
from django.http import HttpResponse
from .models import DoorStatus, OpenData
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from website import settings
from datetime import datetime
import json
# Create your views here.
@csrf_exempt
def door_post(request):
if request.method == 'POST':
unico = request.body.decode('utf-8')
data = json.loads(unico)
if 'key' in data:
if data['key'] == settings.DOOR_KEY:
if 'status' in data:
status = data['status']
if DoorStatus.objects.filter(name='hackerspace').count():
door_status_object = DoorStatus.objects.get(name='hackerspace')
else:
door_status_object = DoorStatus(name='hackerspace')
if status == True:
door_status_object.status = status
door_status_object.save()
if 'timeStart' in data and 'dateStart' in data:
timeStart = data['timeStart']
dateStart = data['dateStart']
opened = datetime.strptime(dateStart+"."+timeStart,"Y-m-d.H:i:s")
door_status_object.datetime = opened
door_status_object.save()
elif status == False:
door_status_object.status = status
door_status_object.save()
if 'timeStart' in data and 'dateStart' in data and 'timeEnd' in data and 'dateEnd' in data and 'timeTotal' in data:
timeStart = data['timeStart']
dateStart = data['dateStart']
timeEnd = data['timeEnd']
dateEnd = data['dateEnd']
total = data['timeTotal']
opened = datetime.strptime(dateStart+"."+timeStart,"Y-m-d.H:i:s")
closed = datetime.strptime(dateEnd+"."+timeEnd,"Y-m-d.H:i:s")
openData = OpenData(opened=opened, closed=closed, total=total)
openData.save()
door_status_object.datetime = closed
door_status_object.save()
return HttpResponse(" ")
@csrf_exempt
def get_status(request):
if DoorStatus.objects.filter(name='hackerspace').count():
status = DoorStatus.objects.get(name='hackerspace').status
else:
status = True
return HttpResponse(status)
def door_data(request):
opendata_list = OpenData.objects.all()
if DoorStatus.objects.filter(name='hackerspace').count():
status = DoorStatus.objects.get(name='hackerspace')
else:
status = DoorStatus(name='hackerspace')
context = {
'opendata_list': opendata_list,
'status': status,
}
return render(request, 'door_data.html', context)
| Python | 0.000007 |
36ed44e94916d6abe3458645c957dd9715cbc532 | set STATIC_ROOT | myproj/myproj/settings.py | myproj/myproj/settings.py | """
Django settings for myproj project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'unsecret_key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myproj.urls'
WSGI_APPLICATION = 'myproj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'web', 'static')
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'myproj', 'templates'),
)
try:
from local_settings import *
except ImportError:
pass
| """
Django settings for myproj project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'unsecret_key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myproj.urls'
WSGI_APPLICATION = 'myproj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'myproj', 'templates'),
)
try:
from local_settings import *
except ImportError:
pass
| Python | 0.000008 |
566ceb81a14685c201f3c92668dc0530a1a91176 | fix path | organization/projects/management/commands/project_inject_content.py | organization/projects/management/commands/project_inject_content.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2017 Ircam
# Copyright (c) 2016-2017 Guillaume Pellerin
# Copyright (c) 2016-2017 Emilie Zawadzki
# This file is part of mezzanine-organization.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import json
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from organization.projects.models import *
from django.utils.text import slugify
from django.contrib.sites.models import Site
from copy import deepcopy
class Command(BaseCommand):
help = """Retrieve content_fr of old mode Project
from database Tue Feb 5 14:26:55 2019 +0100
"""
def handle(self, *args, **options):
json_path = '/srv/lib/mezzanine-organization/organization/projects/management/commands/projects.json'
old_projects = self.read_json(json_path)
project_pages = ProjectPage.objects.all()
for project_page in project_pages:
print(project_page.site_id)
for old_project in old_projects:
if old_project['pk'] == project_page.project_id:
# inject _fr in _en (because _fr became _en)
if not project_page.content_en:
project_page.content_en = project_page.content_fr
project_page.content_fr = old_project['fields']['content_fr']
project_page.save()
def read_file(self, path):
file = open(path, "r")
data = file.read()
file.close()
return data
def read_json(self, path):
return json.loads(self.read_file(path))
| # -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2017 Ircam
# Copyright (c) 2016-2017 Guillaume Pellerin
# Copyright (c) 2016-2017 Emilie Zawadzki
# This file is part of mezzanine-organization.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import json
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from organization.projects.models import *
from django.utils.text import slugify
from django.contrib.sites.models import Site
from copy import deepcopy
class Command(BaseCommand):
help = """Retrieve content_fr of old mode Project
from database Tue Feb 5 14:26:55 2019 +0100
"""
def handle(self, *args, **options):
old_projects = self.read_json('projects.json')
project_pages = ProjectPage.objects.all()
for project_page in project_pages:
print(project_page.site_id)
for old_project in old_projects:
if old_project['pk'] == project_page.project_id:
# inject _fr in _en (because _fr became _en)
if not project_page.content_en:
project_page.content_en = project_page.content_fr
project_page.content_fr = old_project['fields']['content_fr']
project_page.save()
def read_file(self, path):
file = open(path, "r")
data = file.read()
file.close()
return data
def read_json(self, path):
return json.loads(self.read_file(path))
| Python | 0.000001 |
70004e7caf332e55d40b4f1f757138c4cd35a3fe | fix path | organization/projects/management/commands/project_inject_content.py | organization/projects/management/commands/project_inject_content.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2017 Ircam
# Copyright (c) 2016-2017 Guillaume Pellerin
# Copyright (c) 2016-2017 Emilie Zawadzki
# This file is part of mezzanine-organization.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import json
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from organization.projects.models import *
from django.utils.text import slugify
from django.contrib.sites.models import Site
from copy import deepcopy
class Command(BaseCommand):
help = """Retrieve content_fr of old mode Project
from database Tue Feb 5 14:26:55 2019 +0100
"""
def handle(self, *args, **options):
json_path = '/srv/lib/mezzanine-organization/organization/projects/management/commands/projects.json'
old_projects = self.read_json(json_path)
project_pages = ProjectPage.objects.all()
for project_page in project_pages:
print(project_page.site_id)
for old_project in old_projects:
if old_project['pk'] == project_page.project_id:
# inject _fr in _en (because _fr became _en)
if not project_page.content_en:
project_page.content_en = project_page.content_fr
project_page.content_fr = old_project['fields']['content_fr']
project_page.save()
def read_file(self, path):
file = open(path, "r")
data = file.read()
file.close()
return data
def read_json(self, path):
return json.loads(self.read_file(path))
| # -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2017 Ircam
# Copyright (c) 2016-2017 Guillaume Pellerin
# Copyright (c) 2016-2017 Emilie Zawadzki
# This file is part of mezzanine-organization.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import json
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from organization.projects.models import *
from django.utils.text import slugify
from django.contrib.sites.models import Site
from copy import deepcopy
class Command(BaseCommand):
help = """Retrieve content_fr of old mode Project
from database Tue Feb 5 14:26:55 2019 +0100
"""
def handle(self, *args, **options):
old_projects = self.read_json('projects.json')
project_pages = ProjectPage.objects.all()
for project_page in project_pages:
print(project_page.site_id)
for old_project in old_projects:
if old_project['pk'] == project_page.project_id:
# inject _fr in _en (because _fr became _en)
if not project_page.content_en:
project_page.content_en = project_page.content_fr
project_page.content_fr = old_project['fields']['content_fr']
project_page.save()
def read_file(self, path):
file = open(path, "r")
data = file.read()
file.close()
return data
def read_json(self, path):
return json.loads(self.read_file(path))
| Python | 0.000001 |
2e4ec0fea35722fbdbab36ce326e664249e3eaf7 | Add support jinja2 | nacho/controllers/base.py | nacho/controllers/base.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from tornado.web import RequestHandler
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
class ApplicationController(RequestHandler):
def render(self, template_name, **kwargs):
kwargs.update({
'settings': self.settings,
'STATIC_URL': self.settings.get('static_url_prefix', '/static/'),
'request': self.request,
'xsrf_token': self.xsrf_token,
'xsrf_form_html': self.xsrf_form_html,
})
self.write(self.render_template(template_name, **kwargs))
def render_template(self, template_name, **kwargs):
template_dirs = []
if self.settings.get('template_path', ''):
template_dirs.append(self.settings["template_path"])
env = Environment(loader=FileSystemLoader(template_dirs))
try:
template = env.get_template(template_name)
except TemplateNotFound:
raise TemplateNotFound(template_name)
return template.render(kwargs)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from cyclone.web import RequestHandler
class ApplicationController(RequestHandler):
pass
| Python | 0 |
7f3a93dea0eb683bf2d35110fbe921b88646c579 | debug spacy init time | nalaf/features/parsing.py | nalaf/features/parsing.py | from textblob import TextBlob
from textblob.en.taggers import NLTKTagger
from textblob.en.np_extractors import FastNPExtractor
from nalaf.features import FeatureGenerator
from spacy.en import English
from nalaf import print_debug
#import time
class SpacyPosTagger(FeatureGenerator):
"""
POS-tag a dataset using the Spacy Pos Tagger
"""
def __init__(self):
print_debug("SpacyPosTagger: INIT START")
self.nlp = English()
print_debug("SpacyPosTagger: INIT END")
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
for sentence in part.sentences:
text_tokens = list(map(lambda x: x.word, sentence))
spacy_doc = self.nlp.tokenizer.tokens_from_list(text_tokens)
self.nlp.tagger(spacy_doc)
for token, spacy_token in zip(sentence, spacy_doc):
token.features['pos'] = spacy_token.pos_
token.features['tag'] = spacy_token.tag_
class NLKTPosTagger(FeatureGenerator):
"""
POS-tag a dataset using the NLTK Pos Tagger
See: https://textblob.readthedocs.org/en/dev/_modules/textblob/en/taggers.html#NLTKTagger
"""
def __init__(self):
self.tagger = NLTKTagger()
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
for sentence in part.sentences:
text_tokens = list(map(lambda x : x.word, sentence))
tags = self.tagger.tag(text_tokens, tokenize=False)
for token, tag in zip(sentence, tags):
token.features['tag'] = tag[1]
class PosTagFeatureGenerator(FeatureGenerator):
"""
"""
def __init__(self):
self.punctuation = ['.', ',', ':', ';', '[', ']', '(', ')', '{', '}', '”', '“', '–', '"', '#', '?', '-']
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
tags = TextBlob(part.text).tags
tag_index = 0
for sentence in part.sentences:
for token in sentence:
if token.word in self.punctuation:
token.features['tag'] = 'PUN'
else:
remember_index = tag_index
for word, tag in tags[tag_index:]:
if token.word in word:
token.features['tag'] = tag
tag_index += 1
break
tag_index = remember_index
class NounPhraseFeatureGenerator(FeatureGenerator):
"""
"""
def __init__(self):
self.extractor = FastNPExtractor()
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
for sentence in part:
# get the chunk of text representing the sentence
joined_sentence = part.text[sentence[0].start:sentence[-1].start + len(sentence[-1].word)]
phrases = self.extractor.extract(joined_sentence)
for phrase in phrases:
# only consider real noun phrases that have more than 1 word
if ' ' in phrase:
# find the phrase offset in part text
phrase_start = part.text.find(phrase, sentence[0].start)
phrase_end = phrase_start + len(phrase)
# mark the tokens that are part of that phrase
for token in sentence:
if phrase_start <= token.start < token.end <= phrase_end:
token.features['is_nn'] = 1
| from textblob import TextBlob
from textblob.en.taggers import NLTKTagger
from textblob.en.np_extractors import FastNPExtractor
from nalaf.features import FeatureGenerator
from spacy.en import English
#import time
class SpacyPosTagger(FeatureGenerator):
"""
POS-tag a dataset using the Spacy Pos Tagger
"""
def __init__(self):
self.nlp = English()
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
for sentence in part.sentences:
text_tokens = list(map(lambda x: x.word, sentence))
spacy_doc = self.nlp.tokenizer.tokens_from_list(text_tokens)
self.nlp.tagger(spacy_doc)
for token, spacy_token in zip(sentence, spacy_doc):
token.features['pos'] = spacy_token.pos_
token.features['tag'] = spacy_token.tag_
class NLKTPosTagger(FeatureGenerator):
"""
POS-tag a dataset using the NLTK Pos Tagger
See: https://textblob.readthedocs.org/en/dev/_modules/textblob/en/taggers.html#NLTKTagger
"""
def __init__(self):
self.tagger = NLTKTagger()
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
for sentence in part.sentences:
text_tokens = list(map(lambda x : x.word, sentence))
tags = self.tagger.tag(text_tokens, tokenize=False)
for token, tag in zip(sentence, tags):
token.features['tag'] = tag[1]
class PosTagFeatureGenerator(FeatureGenerator):
"""
"""
def __init__(self):
self.punctuation = ['.', ',', ':', ';', '[', ']', '(', ')', '{', '}', '”', '“', '–', '"', '#', '?', '-']
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
tags = TextBlob(part.text).tags
tag_index = 0
for sentence in part.sentences:
for token in sentence:
if token.word in self.punctuation:
token.features['tag'] = 'PUN'
else:
remember_index = tag_index
for word, tag in tags[tag_index:]:
if token.word in word:
token.features['tag'] = tag
tag_index += 1
break
tag_index = remember_index
class NounPhraseFeatureGenerator(FeatureGenerator):
"""
"""
def __init__(self):
self.extractor = FastNPExtractor()
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for part in dataset.parts():
for sentence in part:
# get the chunk of text representing the sentence
joined_sentence = part.text[sentence[0].start:sentence[-1].start + len(sentence[-1].word)]
phrases = self.extractor.extract(joined_sentence)
for phrase in phrases:
# only consider real noun phrases that have more than 1 word
if ' ' in phrase:
# find the phrase offset in part text
phrase_start = part.text.find(phrase, sentence[0].start)
phrase_end = phrase_start + len(phrase)
# mark the tokens that are part of that phrase
for token in sentence:
if phrase_start <= token.start < token.end <= phrase_end:
token.features['is_nn'] = 1
| Python | 0 |
beec55986440c5c7a4afdd556c743dd0d6bc3aa9 | fix citation in random_expand | chainercv/transforms/image/random_expand.py | chainercv/transforms/image/random_expand.py | import numpy as np
import random
def random_expand(img, max_ratio=4, fill=0, return_param=False):
"""Expand an image randomly.
This method randomly place the input image on a larger canvas. The size of
the canvas is :math:`(rW, rH)`, where :math:`(W, H)` is the size of the
input image and :math:`r` is a random ratio drawn from
:math:`[1, max\_ratio]`. The canvas is filled by a value :obj:`fill`
except for the region where the original image is placed.
This data augmentation trick is used to create "zoom out" effect [#]_.
.. [#] Wei Liu, Dragomir Anguelov, Dumitru Erhan, Christian Szegedy, \
Scott Reed, Cheng-Yang Fu, Alexander C. Berg. \
SSD: Single Shot MultiBox Detector. ECCV 2016.
Args:
img (~numpy.ndarray): An image array to be augmented. This is in
CHW format.
max_ratio (float): The maximum ratio of expansion. In the original
paper, this value is 4.
fill (float, tuple or ~numpy.ndarray): The value of padded pixels.
In the original paper, this value is the mean of ImageNet.
return_param (bool): Returns random parameters.
Returns:
~numpy.ndarray or (~numpy.ndarray, dict):
If :obj:`return_param = False`,
returns an array :obj:`out_img` that is the result of expansion.
If :obj:`return_param = True`,
returns a tuple whose elements are :obj:`out_img, param`.
:obj:`param` is a dictionary of intermediate parameters whose
contents are listed below with key, value-type and the description
of the value.
* **ratio** (*float*): The sampled value used to make the canvas.
* **x_offset** (*int*): The x coordinate of the top left corner\
of the image after placing on the canvas.
* **y_offset** (*int*): The y coodinate of the top left corner of\
the image after placing on the canvas.
"""
if max_ratio <= 1:
if return_param:
return img, {'ratio': 1, 'x_offset': 0, 'y_offset': 0}
else:
return img
C, H, W = img.shape
ratio = random.uniform(1, max_ratio)
out_H, out_W = int(H * ratio), int(W * ratio)
x_offset = random.randint(0, out_W - W)
y_offset = random.randint(0, out_H - H)
out_img = np.empty((C, out_H, out_W), dtype=img.dtype)
out_img[:] = np.array(fill).reshape(-1, 1, 1)
out_img[:, y_offset:y_offset + H, x_offset:x_offset + W] = img
if return_param:
param = {'ratio': ratio, 'x_offset': x_offset, 'y_offset': y_offset}
return out_img, param
else:
return out_img
| import numpy as np
import random
def random_expand(img, max_ratio=4, fill=0, return_param=False):
"""Expand an image randomly.
This method randomly place the input image on a larger canvas. The size of
the canvas is :math:`(rW, rH)`, where :math:`(W, H)` is the size of the
input image and :math:`r` is a random ratio drawn from
:math:`[1, max\_ratio]`. The canvas is filled by a value :obj:`fill`
except for the region where the original image is placed.
This data augmentation trick is used to create "zoom out" effect [1].
.. [1] Wei Liu, Dragomir Anguelov, Dumitru Erhan, Christian Szegedy, \
Scott Reed, Cheng-Yang Fu, Alexander C. Berg. \
SSD: Single Shot MultiBox Detector. ECCV 2016.
Args:
img (~numpy.ndarray): An image array to be augmented. This is in
CHW format.
max_ratio (float): The maximum ratio of expansion. In the original
paper, this value is 4.
fill (float, tuple or ~numpy.ndarray): The value of padded pixels.
In the original paper, this value is the mean of ImageNet.
return_param (bool): Returns random parameters.
Returns:
~numpy.ndarray or (~numpy.ndarray, dict):
If :obj:`return_param = False`,
returns an array :obj:`out_img` that is the result of expansion.
If :obj:`return_param = True`,
returns a tuple whose elements are :obj:`out_img, param`.
:obj:`param` is a dictionary of intermediate parameters whose
contents are listed below with key, value-type and the description
of the value.
* **ratio** (*float*): The sampled value used to make the canvas.
* **x_offset** (*int*): The x coordinate of the top left corner\
of the image after placing on the canvas.
* **y_offset** (*int*): The y coodinate of the top left corner of\
the image after placing on the canvas.
"""
if max_ratio <= 1:
if return_param:
return img, {'ratio': 1, 'x_offset': 0, 'y_offset': 0}
else:
return img
C, H, W = img.shape
ratio = random.uniform(1, max_ratio)
out_H, out_W = int(H * ratio), int(W * ratio)
x_offset = random.randint(0, out_W - W)
y_offset = random.randint(0, out_H - H)
out_img = np.empty((C, out_H, out_W), dtype=img.dtype)
out_img[:] = np.array(fill).reshape(-1, 1, 1)
out_img[:, y_offset:y_offset + H, x_offset:x_offset + W] = img
if return_param:
param = {'ratio': ratio, 'x_offset': x_offset, 'y_offset': y_offset}
return out_img, param
else:
return out_img
| Python | 0.001224 |
45c86ade944d9afe7bc8e627e25fa861489cd4b6 | fix a typo so that email is sent to the correct host | crate_project/settings/production/gondor.py | crate_project/settings/production/gondor.py | import os
from .base import *
from local_settings import * # Instance specific settings (in deploy.settings_[INSTANCE_NAME]))
# Fix Email Settings
SERVER_EMAIL = "server@crate.io"
DEFAULT_FROM_EMAIL = "support@crate.io"
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": ":".join([GONDOR_REDIS_HOST, str(GONDOR_REDIS_PORT)]),
"KEY_PREFIX": "cache",
"OPTIONS": {
"DB": 0,
"PASSWORD": GONDOR_REDIS_PASSWORD,
}
}
}
PYPI_DATASTORE_CONFIG = {
"host": GONDOR_REDIS_HOST,
"port": GONDOR_REDIS_PORT,
"password": GONDOR_REDIS_PASSWORD,
}
LOCK_DATASTORE_CONFIG = PYPI_DATASTORE_CONFIG
# Configure Celery
BROKER_TRANSPORT = "redis"
BROKER_HOST = GONDOR_REDIS_HOST
BROKER_PORT = GONDOR_REDIS_PORT
BROKER_VHOST = "0"
BROKER_PASSWORD = GONDOR_REDIS_PASSWORD
BROKER_POOL_LIMIT = 10
CELERY_RESULT_BACKEND = "redis"
CELERY_REDIS_HOST = GONDOR_REDIS_HOST
CELERY_REDIS_PORT = GONDOR_REDIS_PORT
CELERY_REDIS_PASSWORD = GONDOR_REDIS_PASSWORD
SECRET_KEY = os.environ["SECRET_KEY"]
EMAIL_HOST = os.environ["EMAIL_HOST"]
EMAIL_PORT = int(os.environ["EMAIL_PORT"])
EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"]
EMAIL_HOST_PASSWORD = os.environ["EMAIL_HOST_PASSWORD"]
EMAIL_USE_TLS = True
AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY = os.environ["AWS_SECRET_ACCESS_KEY"]
HAYSTACK_CONNECTIONS = {
"default": {
"ENGINE": os.environ["HAYSTACK_DEFAULT_ENGINE"],
"URL": os.environ["HAYSTACK_DEFAULT_URL"],
"INDEX_NAME": os.environ["HAYSTACK_DEFAULT_INDEX_NAME"],
},
}
INTERCOM_USER_HASH_KEY = os.environ["INTERCOM_USER_HASH_KEY"]
| import os
from .base import *
from local_settings import * # Instance specific settings (in deploy.settings_[INSTANCE_NAME]))
# Fix Email Settings
SERVER_EMAIL = "server@crate.io"
DEFAULT_FROM_EMAIL = "support@crate.io"
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": ":".join([GONDOR_REDIS_HOST, str(GONDOR_REDIS_PORT)]),
"KEY_PREFIX": "cache",
"OPTIONS": {
"DB": 0,
"PASSWORD": GONDOR_REDIS_PASSWORD,
}
}
}
PYPI_DATASTORE_CONFIG = {
"host": GONDOR_REDIS_HOST,
"port": GONDOR_REDIS_PORT,
"password": GONDOR_REDIS_PASSWORD,
}
LOCK_DATASTORE_CONFIG = PYPI_DATASTORE_CONFIG
# Configure Celery
BROKER_TRANSPORT = "redis"
BROKER_HOST = GONDOR_REDIS_HOST
BROKER_PORT = GONDOR_REDIS_PORT
BROKER_VHOST = "0"
BROKER_PASSWORD = GONDOR_REDIS_PASSWORD
BROKER_POOL_LIMIT = 10
CELERY_RESULT_BACKEND = "redis"
CELERY_REDIS_HOST = GONDOR_REDIS_HOST
CELERY_REDIS_PORT = GONDOR_REDIS_PORT
CELERY_REDIS_PASSWORD = GONDOR_REDIS_PASSWORD
SECRET_KEY = os.environ["SECRET_KEY"]
EMAIL_HOST = os.environ["EMAIL_HOST_PASSWORD"]
EMAIL_PORT = int(os.environ["EMAIL_PORT"])
EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"]
EMAIL_HOST_PASSWORD = os.environ["EMAIL_HOST_PASSWORD"]
EMAIL_USE_TLS = True
AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY = os.environ["AWS_SECRET_ACCESS_KEY"]
HAYSTACK_CONNECTIONS = {
"default": {
"ENGINE": os.environ["HAYSTACK_DEFAULT_ENGINE"],
"URL": os.environ["HAYSTACK_DEFAULT_URL"],
"INDEX_NAME": os.environ["HAYSTACK_DEFAULT_INDEX_NAME"],
},
}
INTERCOM_USER_HASH_KEY = os.environ["INTERCOM_USER_HASH_KEY"]
| Python | 0.999541 |
490ff333d7410f284be36ec938146dc3f36aa7dc | Change ordering of subreddits | main/gen_features.py | main/gen_features.py | __author__ = 'sharvey'
import multiprocessing
from corpus.mysql.reddit import RedditMySQLCorpus
from feature import ngram
from feature import lexical
import cred
import pprint
import re
def gen_feature(atuple):
text = re.sub(r'https?://([a-zA-Z0-9\.\-_]+)[\w\-\._~:/\?#@!\$&\'\*\+,;=%%]*',
'\\1', atuple['text'], flags=re.MULTILINE)
aset = set()
bngram = ngram.get_byte_ngrams(text)
for n in bngram['ngram_byte']:
for k in bngram['ngram_byte'][n]:
aset.add(('nb%d' % n, k))
for n in bngram['ngram_byte_cs']:
for k in bngram['ngram_byte_cs'][n]:
aset.add(('nbcs%d' % n, k))
wngram = ngram.get_word_ngrams(text)
for n in wngram['ngram_word']:
for k in wngram['ngram_word'][n]:
aset.add(('nw%d' % n, ' '.join(k)))
for n in wngram['ngram_word_clean']:
for k in wngram['ngram_word_clean'][n]:
aset.add(('nwc%d' % n, ' '.join(k)))
words, clean_words = ngram.get_words(text)
for word in words:
aset.add(('w', word))
for word in clean_words:
aset.add(('cw', word))
lex = lexical.get_symbol_dist(text)
for k in lex['lex']:
aset.add(('l', k))
#pprint.pprint(aset)
return set(aset)
if __name__ == '__main__':
corpus = RedditMySQLCorpus()
corpus.setup(**(cred.kwargs))
corpus.create()
pool = multiprocessing.Pool(multiprocessing.cpu_count())
print('set up pool')
chunk = 100
j = 0
feature_set = set()
for reddit in ['worldnews', 'quantum', 'netsec', 'uwaterloo', 'gaming', 'news', 'AskReddit']:
while True:
print(j)
rows = corpus.run_sql('SELECT `body` AS `text` FROM `comment` '
'LEFT JOIN `submission` ON (`comment`.`submission_id`=`submission`.`id`) '
'LEFT JOIN `reddit` ON (`submission`.`reddit_id`=`reddit`.`id`) '
'WHERE `reddit`.`name`= \'%s\''
'LIMIT %d, %d' % (reddit, j, chunk), None)
if len(rows) == 0:
break
it = pool.imap_unordered(gen_feature, rows, 100)
new_feature_set = set()
while True:
try:
atuple = it.next()
new_feature_set = new_feature_set.union(atuple)
except StopIteration:
break
new_feature_set.difference_update(feature_set)
pprint.pprint(len(new_feature_set))
corpus.run_sqls('INSERT IGNORE INTO `feature_map` (`type`, `feature`) VALUES (%s, %s)', list(new_feature_set))
corpus.cnx.commit()
feature_set = feature_set.union(new_feature_set)
j += chunk | __author__ = 'sharvey'
import multiprocessing
from corpus.mysql.reddit import RedditMySQLCorpus
from feature import ngram
from feature import lexical
import cred
import pprint
import re
def gen_feature(atuple):
text = re.sub(r'https?://([a-zA-Z0-9\.\-_]+)[\w\-\._~:/\?#@!\$&\'\*\+,;=%%]*',
'\\1', atuple['text'], flags=re.MULTILINE)
aset = set()
bngram = ngram.get_byte_ngrams(text)
for n in bngram['ngram_byte']:
for k in bngram['ngram_byte'][n]:
aset.add(('nb%d' % n, k))
for n in bngram['ngram_byte_cs']:
for k in bngram['ngram_byte_cs'][n]:
aset.add(('nbcs%d' % n, k))
wngram = ngram.get_word_ngrams(text)
for n in wngram['ngram_word']:
for k in wngram['ngram_word'][n]:
aset.add(('nw%d' % n, ' '.join(k)))
for n in wngram['ngram_word_clean']:
for k in wngram['ngram_word_clean'][n]:
aset.add(('nwc%d' % n, ' '.join(k)))
words, clean_words = ngram.get_words(text)
for word in words:
aset.add(('w', word))
for word in clean_words:
aset.add(('cw', word))
lex = lexical.get_symbol_dist(text)
for k in lex['lex']:
aset.add(('l', k))
#pprint.pprint(aset)
return set(aset)
if __name__ == '__main__':
corpus = RedditMySQLCorpus()
corpus.setup(**(cred.kwargs))
corpus.create()
pool = multiprocessing.Pool(multiprocessing.cpu_count())
print('set up pool')
chunk = 100
j = 0
feature_set = set()
for reddit in ['worldnews', 'news', 'quantum', 'netsec', 'uwaterloo', 'gaming']:
while True:
print(j)
rows = corpus.run_sql('SELECT `body` AS `text` FROM `comment` '
'LEFT JOIN `submission` ON (`comment`.`submission_id`=`submission`.`id`) '
'LEFT JOIN `reddit` ON (`submission`.`reddit_id`=`reddit`.`id`) '
'WHERE `reddit`.`name`= \'%s\''
'LIMIT %d, %d' % (reddit, j, chunk), None)
if len(rows) == 0:
break
it = pool.imap_unordered(gen_feature, rows, 100)
new_feature_set = set()
while True:
try:
atuple = it.next()
new_feature_set = new_feature_set.union(atuple)
except StopIteration:
break
new_feature_set.difference_update(feature_set)
pprint.pprint(len(new_feature_set))
corpus.run_sqls('INSERT IGNORE INTO `feature_map` (`type`, `feature`) VALUES (%s, %s)', list(new_feature_set))
corpus.cnx.commit()
feature_set = feature_set.union(new_feature_set)
j += chunk | Python | 0.000002 |
b3bfc6e3949fcca58cbf84232432c966f5f5d8c6 | fix indentation | analyzer/darwin/lib/dtrace/apicalls.py | analyzer/darwin/lib/dtrace/apicalls.py | #!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This file is part of my GSoC'15 project for Cuckoo Sandbox:
# http://www.cuckoosandbox.org
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
import os
import json
from common import *
from getpass import getuser
from subprocess import Popen
from collections import namedtuple
from tempfile import NamedTemporaryFile
apicall = namedtuple("apicall", "api args retval timestamp pid ppid tid")
def apicalls(target, **kwargs):
"""
"""
if not target:
raise Exception("Invalid target for apicalls()")
output_file = NamedTemporaryFile()
cmd = ["sudo", "/usr/sbin/dtrace", "-C"]
if "timeout" in kwargs:
cmd += ["-DANALYSIS_TIMEOUT=%d" % kwargs["timeout"]]
cmd += ["-s", path_for_script("apicalls.d")]
cmd += ["-DROOT=1"]
cmd += ["-o", output_file.name]
cmd += ["-DOUTPUT_FILE=\"%s\"" % output_file.name]
if "run_as_root" in kwargs:
run_as_root = kwargs["run_as_root"]
else:
run_as_root = False
if "args" in kwargs:
target_cmd = "%s %s" % (sanitize_path(target), " ".join(kwargs["args"]))
else:
target_cmd = sanitize_path(target)
# When we don't want to run the target as root, we have to drop privileges
# with `sudo -u current_user` right before calling the target.
if not run_as_root:
target_cmd = "sudo -u %s %s" % (getuser(), target_cmd)
cmd += ["-c", target_cmd]
# The dtrace script will take care of timeout itself, so we just launch
# it asynchronously
with open(os.devnull, "w") as f:
handler = Popen(cmd, stdout=f, stderr=f, cwd=current_directory())
# When we're using `sudo -u` for dropping root privileges, we also have to
# exclude sudo's own output from the results
sudo_pid = None
for entry in filelines(output_file):
if "## apicalls.d done ##" in entry.strip():
break
if len(entry.strip()) == 0:
continue
call = _parse_entry(entry.strip())
if not run_as_root and sudo_pid is None:
sudo_pid = call.pid
elif call.pid != sudo_pid:
yield call
output_file.close()
def _parse_entry(entry):
entry = entry.replace("\\0", "")
parsed = json.loads(entry)
api = parsed['api']
args = parsed['args']
retval = parsed['retval']
timestamp = parsed['timestamp']
pid = parsed['pid']
ppid = parsed['ppid']
tid = parsed['tid']
return apicall(api, args, retval, timestamp, pid, ppid, tid)
| #!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This file is part of my GSoC'15 project for Cuckoo Sandbox:
# http://www.cuckoosandbox.org
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
import os
import json
from common import *
from getpass import getuser
from subprocess import Popen
from collections import namedtuple
from tempfile import NamedTemporaryFile
apicall = namedtuple("apicall", "api args retval timestamp pid ppid tid")
def apicalls(target, **kwargs):
"""
"""
if not target:
raise Exception("Invalid target for apicalls()")
output_file = NamedTemporaryFile()
cmd = ["sudo", "/usr/sbin/dtrace", "-C"]
if "timeout" in kwargs:
cmd += ["-DANALYSIS_TIMEOUT=%d" % kwargs["timeout"]]
cmd += ["-s", path_for_script("apicalls.d")]
cmd += ["-DROOT=1"]
cmd += ["-o", output_file.name]
cmd += ["-DOUTPUT_FILE=\"%s\"" % output_file.name]
if "run_as_root" in kwargs:
run_as_root = kwargs["run_as_root"]
else:
run_as_root = False
if "args" in kwargs:
target_cmd = "%s %s" % (sanitize_path(target), " ".join(kwargs["args"]))
else:
target_cmd = sanitize_path(target)
# When we don't want to run the target as root, we have to drop privileges
# with `sudo -u current_user` right before calling the target.
if not run_as_root:
target_cmd = "sudo -u %s %s" % (getuser(), target_cmd)
cmd += ["-c", target_cmd]
# The dtrace script will take care of timeout itself, so we just launch
# it asynchronously
with open(os.devnull, "w") as f:
handler = Popen(cmd, stdout=f, stderr=f, cwd=current_directory())
# If we use `sudo -u` for dropping root privileges, we also have to
# exclude it's output from the results
sudo_pid = None
for entry in filelines(output_file):
if "## apicalls.d done ##" in entry.strip():
break
if len(entry.strip()) == 0:
continue
call = _parse_entry(entry.strip())
if not run_as_root and sudo_pid is None:
sudo_pid = call.pid
elif call.pid != sudo_pid:
yield call
output_file.close()
def _parse_entry(entry):
entry = entry.replace("\\0", "")
parsed = json.loads(entry)
api = parsed['api']
args = parsed['args']
retval = parsed['retval']
timestamp = parsed['timestamp']
pid = parsed['pid']
ppid = parsed['ppid']
tid = parsed['tid']
return apicall(api, args, retval, timestamp, pid, ppid, tid)
| Python | 0.000005 |
2a1407b34187cfba6c968a7b95e58ec1c115a8f6 | Print functions | datacommons/examples/population_analysis.py | datacommons/examples/population_analysis.py | # Copyright 2017 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 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.
"""Example analysis with DataCommons Python API.
"""
import pandas as pd
import datacommons
def main():
dc = datacommons.Client()
# Build a table with a single US state
state_table = dc.get_states('United States', 'state', max_rows=1)
# Add the state name and the 5 counties contained in that state
state_table = dc.expand(
state_table, 'name', 'state', 'state_name', outgoing=True)
state_table = dc.expand(
state_table,
'containedInPlace',
'state',
'county',
outgoing=False,
max_rows=3)
state_table = dc.expand(
state_table, 'name', 'county', 'county_name', outgoing=True)
state_table = dc.get_populations(
state_table,
seed_col_name='county',
new_col_name='county_population',
population_type='Person',
max_rows=100)
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print(state_table)
state_table = dc.get_populations(
state_table,
seed_col_name='county',
new_col_name='county_18_24_years_population',
population_type='Person',
max_rows=100,
age='USC/18To24Years')
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print(state_table)
state_table = dc.get_populations(
state_table,
seed_col_name='county',
new_col_name='county_male_population',
population_type='Person',
max_rows=100,
gender='Male')
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print(state_table)
state_table = dc.get_observations(
state_table,
seed_col_name='county_population',
new_col_name='county_person_count',
start_date='2012-01-01',
end_date='2016-01-01',
measured_property='count',
stats_type='count')
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print(state_table)
if __name__ == '__main__':
main()
| # Copyright 2017 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 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.
"""Example analysis with DataCommons Python API.
"""
import pandas as pd
import datacommons
def main():
dc = datacommons.Client()
# Build a table with a single US state
state_table = dc.get_states('United States', 'state', max_rows=1)
# Add the state name and the 5 counties contained in that state
state_table = dc.expand(
state_table, 'name', 'state', 'state_name', outgoing=True)
state_table = dc.expand(
state_table,
'containedInPlace',
'state',
'county',
outgoing=False,
max_rows=2)
state_table = dc.expand(
state_table, 'name', 'county', 'county_name', outgoing=True)
state_table = dc.get_populations(
state_table,
seed_col_name='county',
new_col_name='county_population',
population_type='Person',
max_rows=100)
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print state_table
state_table = dc.get_populations(
state_table,
seed_col_name='county',
new_col_name='county_18_24_years_population',
population_type='Person',
max_rows=100,
age='USC/18To24Years')
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print state_table
state_table = dc.get_populations(
state_table,
seed_col_name='county',
new_col_name='county_male_population',
population_type='Person',
max_rows=100,
gender='Male')
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print state_table
state_table = dc.get_observations(
state_table,
seed_col_name='county_population',
new_col_name='county_person_count',
start_date='2012-01-01',
end_date='2016-01-01',
measured_property='count',
stats_type='count')
with pd.option_context('display.width', 400, 'display.max_rows', 100):
print state_table
if __name__ == '__main__':
main()
| Python | 0.00001 |
d74b15485a0756ac1702fafd640f616f022b3f58 | bump verions | equals/__init__.py | equals/__init__.py | from __future__ import absolute_import
__version__ = '0.0.21'
import numbers
import collections
from equals.equals import Equals as instance_of
from equals.constraints.anything_true import AnythingTrue
from equals.constraints.anything_false import AnythingFalse
anything = instance_of()
try:
any_string = instance_of(basestring)
except NameError:
any_string = instance_of(str)
any_number = instance_of(numbers.Number)
any_int = instance_of(int)
any_float = instance_of(float)
any_iterable = instance_of(collections.Iterable)
any_dict = instance_of(dict)
any_list = instance_of(list)
any_tuple = instance_of(tuple)
anything_false = AnythingFalse(anything)
anything_true = AnythingTrue(anything)
| from __future__ import absolute_import
__version__ = '0.0.2'
import numbers
import collections
from equals.equals import Equals as instance_of
from equals.constraints.anything_true import AnythingTrue
from equals.constraints.anything_false import AnythingFalse
anything = instance_of()
try:
any_string = instance_of(basestring)
except NameError:
any_string = instance_of(str)
any_number = instance_of(numbers.Number)
any_int = instance_of(int)
any_float = instance_of(float)
any_iterable = instance_of(collections.Iterable)
any_dict = instance_of(dict)
any_list = instance_of(list)
any_tuple = instance_of(tuple)
anything_false = AnythingFalse(anything)
anything_true = AnythingTrue(anything)
| Python | 0.000001 |
9c2d1e9e841014dbc986b6e509b19f7f881969c4 | Fix silly typo | openspending/lib/csvexport.py | openspending/lib/csvexport.py | import csv
import sys
from datetime import datetime
from openspending import model
from openspending.mongo import DBRef, ObjectId
def write_csv(entries, response):
response.content_type = 'text/csv'
# NOTE: this should be a streaming service but currently
# I see no way to know the full set of keys without going
# through the data twice.
keys = set()
rows = []
for entry in entries:
d = {}
for k, v in model.entry.to_query_dict(entry).items():
if isinstance(v, (list, tuple, dict, DBRef)):
continue
elif isinstance(v, ObjectId):
v = str(v)
elif isinstance(v, datetime):
v = v.isoformat()
d[unicode(k).encode('utf8')] = unicode(v).encode('utf8')
keys.update(d.keys())
rows.append(d)
fields = sorted(keys)
writer = csv.DictWriter(response, fields)
if sys.version_info < (2,7):
header = dict(zip(fields, fields))
writer.writerow(header)
else:
writer.writeheader()
writer.writerows(rows)
| import csv
import sys
from datetime import datetime
from openspending import model
from openspending.mongo import DBRef, ObjectId
def write_csv(entries, response):
response.content_type = 'text/csv'
# NOTE: this should be a streaming service but currently
# I see no way to know the full set of keys without going
# through the data twice.
keys = set()
rows = []
for entry in entries:
d = {}
for k, v in model.entry.to_query_dict(entry).items():
if isinstance(v, (list, tuple, dict, DBRef)):
continue
elif isinstance(v, ObjectId):
v = str(v)
elif isinstance(v, datetime):
v = v.isoformat()
d[unicode(k).encode('utf8')] = unicode(v).encode('utf8')
keys.update(d.keys())
rows.append(d)
fields = sorted(keys)
writer = csv.DictWriter(response, fields)
if sys.version_info < (2,7):
header = dict(zip(fields, fields))
self.writerow(header)
else:
writer.writeheader()
writer.writerows(rows)
| Python | 0.999999 |
ab35f508375c760770884882acaea79079a1a976 | remove unnesecary print | erlang/__init__.py | erlang/__init__.py | from __future__ import division
def extended_b_lines(usage, blocking):
'''
Uses the Extended Erlang B formula to calcluate the ideal number of lines
for the given usage in erlangs and the given blocking rate.
Usage:
extended_b_lines(usage, blocking)
'''
line_count = 1
while extended_b(usage, line_count) > blocking:
line_count += 1
return line_count
def extended_b(usage, lines, recall=0.5):
'''
Usage:
extended_b(usage, lines, recall=0.5)
'''
original_usage = usage
while True:
PB = b(usage, lines)
magic_number_1 = (1 - PB) * usage + (1 - recall) * PB * usage
magic_number_2 = 0.9999 * original_usage
if magic_number_1 >= magic_number_2:
return PB
usage = original_usage + recall * PB * usage
return -1
def b(usage, lines):
'''
Usage:
b(usage, lines)
'''
if usage > 0:
PBR = (1 + usage) / usage
for index in range(2, lines + 1):
PBR = index / usage * PBR + 1
if PBR > 10000:
return 0
return 1 / PBR
return 0
| from __future__ import division
def extended_b_lines(usage, blocking):
'''
Uses the Extended Erlang B formula to calcluate the ideal number of lines
for the given usage in erlangs and the given blocking rate.
Usage:
extended_b_lines(usage, blocking)
'''
line_count = 1
while extended_b(usage, line_count) > blocking:
line_count += 1
return line_count
def extended_b(usage, lines, recall=0.5):
'''
Usage:
extended_b(usage, lines, recall=0.5)
'''
original_usage = usage
while True:
PB = b(usage, lines)
magic_number_1 = (1 - PB) * usage + (1 - recall) * PB * usage
magic_number_2 = 0.9999 * original_usage
if magic_number_1 >= magic_number_2:
return PB
usage = original_usage + recall * PB * usage
return -1
def b(usage, lines):
'''
Usage:
b(usage, lines)
'''
if usage > 0:
PBR = (1 + usage) / usage
for index in range(2, lines + 1):
print(PBR)
PBR = index / usage * PBR + 1
if PBR > 10000:
return 0
return 1 / PBR
return 0
| Python | 0.999922 |
c40a07e4ba1bfefd977bc9eea71abe5fcaf97370 | Use custom exception in place of NotImplemented | manifestos/twitter.py | manifestos/twitter.py | import re
from django.conf import settings
import tweepy
TWITTER_CONSUMER_KEY = settings.TWITTER_CONSUMER_KEY
TWITTER_CONSUMER_SECRET = settings.TWITTER_CONSUMER_SECRET
TWITTER_ACCESS_KEY = settings.TWITTER_ACCESS_KEY
TWITTER_ACCESS_SECRET = settings.TWITTER_ACCESS_SECRET
class TwitterBotException(Exception):
pass
class TwitterBot(object):
"""
Creates tweets for the Digital Manifest Twitter Bot.
"""
def get_auth(self):
auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
auth.set_access_token(TWITTER_ACCESS_KEY, TWITTER_ACCESS_SECRET)
return auth
def get_api(self):
auth = self.get_auth()
return tweepy.API(auth)
def tweet(self, text):
# Make sure we have legitimate text to tweet
if not isinstance(text, str):
raise TwitterBotException('Can only tweet strings.')
text = text.strip()
if not text:
raise TwitterBotException('Text has no content.')
# Escape SMS commands
pattern = re.compile(
r'^(ON|OFF|FOLLOW|F|UNFOLLOW|LEAVE|L|STOP|QUIT|END|CANCEL|'
r'UNSBSCRIBE|ARRET|D|M|RETWEET|RT|SET|WHOIS|W|GET|G|FAV|FAVE|'
r'FAVORITE|FAVORITE|\*|STATS|SUGGEST|SUG|S|WTF|HELP|INFO|AIDE|'
r'BLOCK|BLK|REPORT|REP)(\W)(.*)', re.I)
text = re.sub(pattern, '\\1\u200B\\2\\3', text)
# Truncate to 140 characters
text = text[:140]
# Tweet
api = self.get_api()
api.update_status(status=text)
| import re
from django.conf import settings
import tweepy
TWITTER_CONSUMER_KEY = settings.TWITTER_CONSUMER_KEY
TWITTER_CONSUMER_SECRET = settings.TWITTER_CONSUMER_SECRET
TWITTER_ACCESS_KEY = settings.TWITTER_ACCESS_KEY
TWITTER_ACCESS_SECRET = settings.TWITTER_ACCESS_SECRET
class TwitterBot(object):
"""
Creates tweets for the Digital Manifest Twitter Bot.
"""
def get_auth(self):
auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
auth.set_access_token(TWITTER_ACCESS_KEY, TWITTER_ACCESS_SECRET)
return auth
def get_api(self):
auth = self.get_auth()
return tweepy.API(auth)
def tweet(self, text):
if not isinstance(text, str):
raise NotImplemented('Can only tweet strings.')
# Escape SMS commands
pattern = re.compile(
r'^(ON|OFF|FOLLOW|F|UNFOLLOW|LEAVE|L|STOP|QUIT|END|CANCEL|'
r'UNSBSCRIBE|ARRET|D|M|RETWEET|RT|SET|WHOIS|W|GET|G|FAV|FAVE|'
r'FAVORITE|FAVORITE|\*|STATS|SUGGEST|SUG|S|WTF|HELP|INFO|AIDE|'
r'BLOCK|BLK|REPORT|REP)(\W)(.*)', re.I)
text = re.sub(pattern, '\\1\u200B\\2\\3', text)
text = text[:140]
api = self.get_api()
api.update_status(status=text)
| Python | 0.000001 |
4b4b689463c0e6d0db783a10fcf74b21fea60a68 | Fix double repr. | pygments/formatters/other.py | pygments/formatters/other.py | # -*- coding: utf-8 -*-
"""
pygments.formatters.other
~~~~~~~~~~~~~~~~~~~~~~~~~
Other formatters: NullFormatter, RawTokenFormatter.
:copyright: 2006 by Georg Brandl, Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from pygments.formatter import Formatter
__all__ = ['NullFormatter', 'RawTokenFormatter']
class NullFormatter(Formatter):
"""
Output the text unchanged without any formatting.
"""
def format(self, tokensource, outfile):
for ttype, value in tokensource:
outfile.write(value.encode(self.encoding))
class RawTokenFormatter(Formatter):
"""
Output a raw token representation for storing token streams.
The format is ``tokentype<TAB>repr(tokenstring)``
Additional options accepted:
``compress``
If set to "gz" or "bz2", compress the token stream with
the given compression algorithm (default: '').
"""
def __init__(self, **options):
Formatter.__init__(self, **options)
self.compress = options.get('compress', '')
def format(self, tokensource, outfile):
if self.compress == 'gz':
import gzip
outfile = gzip.GzipFile('', 'wb', 9, outfile)
write = outfile.write
flush = outfile.flush
elif self.compress == 'bz2':
import bz2
compressor = bz2.BZ2Compressor(9)
def write(text):
outfile.write(compressor.compress(text))
def flush():
outfile.write(compressor.flush())
outfile.flush()
else:
write = outfile.write
flush = outfile.flush
lasttype = None
lastval = u''
for ttype, value in tokensource:
value = repr(value)
if ttype is lasttype:
lastval += value
else:
if lasttype:
write("%s\t%s\n" % (lasttype, lastval))
lastval = value
lasttype = ttype
write("%s\t%s\n" % (lasttype, lastval))
flush()
| # -*- coding: utf-8 -*-
"""
pygments.formatters.other
~~~~~~~~~~~~~~~~~~~~~~~~~
Other formatters: NullFormatter, RawTokenFormatter.
:copyright: 2006 by Georg Brandl, Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from pygments.formatter import Formatter
__all__ = ['NullFormatter', 'RawTokenFormatter']
class NullFormatter(Formatter):
"""
Output the text unchanged without any formatting.
"""
def format(self, tokensource, outfile):
for ttype, value in tokensource:
outfile.write(value.encode(self.encoding))
class RawTokenFormatter(Formatter):
"""
Output a raw token representation for storing token streams.
The format is ``tokentype<TAB>repr(tokenstring)``
Additional options accepted:
``compress``
If set to "gz" or "bz2", compress the token stream with
the given compression algorithm (default: '').
"""
def __init__(self, **options):
Formatter.__init__(self, **options)
self.compress = options.get('compress', '')
def format(self, tokensource, outfile):
if self.compress == 'gz':
import gzip
outfile = gzip.GzipFile('', 'wb', 9, outfile)
write = outfile.write
flush = outfile.flush
elif self.compress == 'bz2':
import bz2
compressor = bz2.BZ2Compressor(9)
def write(text):
outfile.write(compressor.compress(text))
def flush():
outfile.write(compressor.flush())
outfile.flush()
else:
write = outfile.write
flush = outfile.flush
lasttype = None
lastval = u''
for ttype, value in tokensource:
value = repr(value)
if ttype is lasttype:
lastval += value
else:
if lasttype:
write("%s\t%r\n" % (lasttype, lastval))
lastval = value
lasttype = ttype
write("%s\t%r\n" % (lasttype, lastval))
flush()
| Python | 0.000001 |
2a7aee189dff539fe3cf8049319a2b09c6a0fbb1 | add new filter to dataset config | pysaliency/dataset_config.py | pysaliency/dataset_config.py | from .datasets import read_hdf5
from .filter_datasets import (
filter_fixations_by_number,
filter_stimuli_by_number,
filter_stimuli_by_size,
train_split,
validation_split,
test_split
)
from schema import Schema, Optional
dataset_config_schema = Schema({
'stimuli': str,
'fixations': str,
Optional('filters', default=[]): [{
'type': str,
Optional('parameters', default={}): dict,
}],
})
def load_dataset_from_config(config):
config = dataset_config_schema.validate(config)
stimuli = read_hdf5(config['stimuli'])
fixations = read_hdf5(config['fixations'])
for filter_config in config['filters']:
stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config)
return stimuli, fixations
def apply_dataset_filter_config(stimuli, fixations, filter_config):
filter_dict = {
'filter_fixations_by_number': add_stimuli_argument(filter_fixations_by_number),
'filter_stimuli_by_number': filter_stimuli_by_number,
'filter_stimuli_by_size': filter_stimuli_by_size,
'train_split': train_split,
'validation_split': validation_split,
'test_split': test_split,
}
if filter_config['type'] not in filter_dict:
raise ValueError("Invalid filter name: {}".format(filter_config['type']))
filter_fn = filter_dict[filter_config['type']]
return filter_fn(stimuli, fixations, **filter_config['parameters'])
def add_stimuli_argument(fn):
def wrapped(stimuli, fixations, **kwargs):
new_fixations = fn(fixations, **kwargs)
return stimuli, new_fixations
return wrapped
| from .datasets import read_hdf5
from .filter_datasets import filter_fixations_by_number, filter_stimuli_by_number, train_split, validation_split, test_split
from schema import Schema, Optional
dataset_config_schema = Schema({
'stimuli': str,
'fixations': str,
Optional('filters', default=[]): [{
'type': str,
Optional('parameters', default={}): dict,
}],
})
def load_dataset_from_config(config):
config = dataset_config_schema.validate(config)
stimuli = read_hdf5(config['stimuli'])
fixations = read_hdf5(config['fixations'])
for filter_config in config['filters']:
stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config)
return stimuli, fixations
def apply_dataset_filter_config(stimuli, fixations, filter_config):
filter_dict = {
'filter_fixations_by_number': add_stimuli_argument(filter_fixations_by_number),
'filter_stimuli_by_number': filter_stimuli_by_number,
'train_split': train_split,
'validation_split': validation_split,
'test_split': test_split,
}
if filter_config['type'] not in filter_dict:
raise ValueError("Invalid filter name: {}".format(filter_config['type']))
filter_fn = filter_dict[filter_config['type']]
return filter_fn(stimuli, fixations, **filter_config['parameters'])
def add_stimuli_argument(fn):
def wrapped(stimuli, fixations, **kwargs):
new_fixations = fn(fixations, **kwargs)
return stimuli, new_fixations
return wrapped
| Python | 0 |
46e21ff57d47f1860d639972dc4eed1994a6cd50 | remove print statements | scholars/authentication/pipeline.py | scholars/authentication/pipeline.py | import hashlib
from social_core.exceptions import AuthAlreadyAssociated, AuthException
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def check_email_present(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
raise AuthException(backend, "Email wasn't provided by oauth provider")
def social_user(backend, uid, user=None, *args, **kwargs):
provider = backend.name
social = backend.strategy.storage.user.get_social_auth(provider, uid)
if social:
# can happen when user has multiple accounts with same email (apply email uniqueness strictly)
if user and social.user != user:
msg = 'This {0} account is already in use.'.format(provider)
raise AuthAlreadyAssociated(backend, msg)
elif not user:
user = social.user
return {'social': social,
'user': user,
'is_new': user is None,
'new_association': social is None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
avatar = None
if 'google-oauth2' in backend_name and response.get('image', {}).get('url'):
avatar = response['image']['url'].split('?')[0]
else:
avatar = 'http://www.gravatar.com/avatar/'
avatar += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
avatar += '?size=100'
if avatar and user.avatar != avatar:
user.avatar = avatar
strategy.storage.user.changed(user)
| import hashlib
from social_core.exceptions import AuthAlreadyAssociated, AuthException
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def check_email_present(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
raise AuthException(backend, "Email wasn't provided by oauth provider")
def social_user(backend, uid, user=None, *args, **kwargs):
provider = backend.name
social = backend.strategy.storage.user.get_social_auth(provider, uid)
if social:
# can happen when user has multiple accounts with same email (apply email uniqueness strictly)
print user
print social
if user and social.user != user:
msg = 'This {0} account is already in use.'.format(provider)
raise AuthAlreadyAssociated(backend, msg)
elif not user:
user = social.user
return {'social': social,
'user': user,
'is_new': user is None,
'new_association': social is None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
avatar = None
if 'google-oauth2' in backend_name and response.get('image', {}).get('url'):
avatar = response['image']['url'].split('?')[0]
else:
avatar = 'http://www.gravatar.com/avatar/'
avatar += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
avatar += '?size=100'
if avatar and user.avatar != avatar:
user.avatar = avatar
strategy.storage.user.changed(user)
| Python | 0.999999 |
28917935e5086ff6a03964babbb5c2e09957b582 | Bump version | pytablewriter/__version__.py | pytablewriter/__version__.py | # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.47.0"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.46.3"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| Python | 0 |
a1d88ff0da34300f0417a9c4679d65b6d38f8bd6 | 修复#64,task无法删除的bug | app/controller/backend/TasksController.py | app/controller/backend/TasksController.py | #!/usr/bin/env python2
# coding: utf-8
# file: TasksController.py
import datetime
from flask import redirect, render_template, request, jsonify
from sqlalchemy.exc import SQLAlchemyError
from . import ADMIN_URL
from app import web, db
from app.CommonClass.ValidateClass import ValidateClass, login_required
from app.models import CobraTaskInfo
from utils import config
__author__ = "lightless"
__email__ = "root@lightless.me"
# show all tasks
@web.route(ADMIN_URL + '/tasks/<int:page>', methods=['GET'])
@login_required
def tasks(page):
per_page = 10
tasks = CobraTaskInfo.query.order_by('id desc').limit(per_page).offset((page - 1) * per_page).all()
# replace data
for task in tasks:
task.scan_way = "Full Scan" if task.scan_way == 1 else "Diff Scan"
task.report = 'http://' + config.Config('cobra', 'domain').value + '/report/' + str(task.id)
data = {
'tasks': tasks,
}
return render_template('backend/task/tasks.html', data=data)
# del the special task
@web.route(ADMIN_URL + '/del_task', methods=['POST'])
@login_required
def del_task():
vc = ValidateClass(request, "id")
ret, msg = vc.check_args()
if not ret:
return jsonify(tag="danger", msg=msg)
task = CobraTaskInfo.query.filter_by(id=vc.vars.id).first()
try:
db.session.delete(task)
db.session.commit()
return jsonify(tag='success', msg='delete success.')
except SQLAlchemyError as e:
print e
return jsonify(tag='danger', msg='unknown error.')
# edit the special task
@web.route(ADMIN_URL + '/edit_task/<int:task_id>', methods=['GET', 'POST'])
@login_required
def edit_task(task_id):
if request.method == 'POST':
# vc = ValidateClass(request, "branch", "scan_way", "new_version", "old_version", "target")
# ret, msg = vc.check_args()
# if not ret:
# return jsonify(tag="danger", msg=msg)
# TODO: check new_version and old_version when scan_way == 2
branch = request.form.get('branch')
scan_way = request.form.get('scan_way')
new_version = request.form.get('new_version')
old_version = request.form.get('old_version')
target = request.form.get('target')
if not branch or branch == "":
return jsonify(tag='danger', msg='branch can not be empty')
if not scan_way or scan_way == "":
return jsonify(tag='danger', msg='scan way can not be empty')
if (scan_way == 2) and ((not new_version or new_version == "") or (not old_version or old_version == "")):
return jsonify(tag='danger', msg='In diff scan mode, new version and old version can not be empty')
if not target or target == "":
return jsonify(tag='danger', msg='Target can not be empty.')
task = CobraTaskInfo.query.filter_by(id=task_id).first()
task.branch = branch
task.scan_way = scan_way
task.new_version = new_version
task.old_version = old_version
task.target = target
task.updated_time = datetime.datetime.now()
try:
db.session.add(task)
db.session.commit()
return jsonify(tag='success', msg='save success.')
except SQLAlchemyError as e:
print e
return jsonify(tag='danger', msg='save failed. Try again later?')
else:
task = CobraTaskInfo.query.filter_by(id=task_id).first()
return render_template('backend/task/edit_task.html', data={
'task': task,
})
| #!/usr/bin/env python2
# coding: utf-8
# file: TasksController.py
import datetime
from flask import redirect, render_template, request, jsonify
from . import ADMIN_URL
from app import web, db
from app.CommonClass.ValidateClass import ValidateClass
from app.models import CobraTaskInfo
from utils import config
__author__ = "lightless"
__email__ = "root@lightless.me"
# show all tasks
@web.route(ADMIN_URL + '/tasks/<int:page>', methods=['GET'])
def tasks(page):
if not ValidateClass.check_login():
return redirect(ADMIN_URL + '/index')
per_page = 10
tasks = CobraTaskInfo.query.order_by('id desc').limit(per_page).offset((page - 1) * per_page).all()
# replace data
for task in tasks:
task.scan_way = "Full Scan" if task.scan_way == 1 else "Diff Scan"
task.report = 'http://' + config.Config('cobra', 'domain').value + '/report/' + str(task.id)
data = {
'tasks': tasks,
}
return render_template('backend/task/tasks.html', data=data)
# del the special task
@web.route(ADMIN_URL + '/del_task', methods=['POST'])
def del_task():
if not ValidateClass.check_login():
return redirect(ADMIN_URL + '/index')
vc = ValidateClass(request, "id")
ret, msg = vc.check_args()
if not ret:
return jsonify(tag="danger", msg=msg)
task = CobraTaskInfo.query.filter_by(id=vc.vars.task_id).first()
try:
db.session.delete(task)
db.session.commit()
return jsonify(tag='success', msg='delete success.')
except:
return jsonify(tag='danger', msg='unknown error.')
# edit the special task
@web.route(ADMIN_URL + '/edit_task/<int:task_id>', methods=['GET', 'POST'])
def edit_task(task_id):
if not ValidateClass.check_login():
return redirect(ADMIN_URL + '/index')
if request.method == 'POST':
# vc = ValidateClass(request, "branch", "scan_way", "new_version", "old_version", "target")
# ret, msg = vc.check_args()
# if not ret:
# return jsonify(tag="danger", msg=msg)
# TODO: check new_version and old_version when scan_way == 2
branch = request.form.get('branch')
scan_way = request.form.get('scan_way')
new_version = request.form.get('new_version')
old_version = request.form.get('old_version')
target = request.form.get('target')
if not branch or branch == "":
return jsonify(tag='danger', msg='branch can not be empty')
if not scan_way or scan_way == "":
return jsonify(tag='danger', msg='scan way can not be empty')
if (scan_way == 2) and ((not new_version or new_version == "") or (not old_version or old_version == "")):
return jsonify(tag='danger', msg='In diff scan mode, new version and old version can not be empty')
if not target or target == "":
return jsonify(tag='danger', msg='Target can not be empty.')
task = CobraTaskInfo.query.filter_by(id=task_id).first()
task.branch = branch
task.scan_way = scan_way
task.new_version = new_version
task.old_version = old_version
task.target = target
task.updated_time = datetime.datetime.now()
try:
db.session.add(task)
db.session.commit()
return jsonify(tag='success', msg='save success.')
except:
return jsonify(tag='danger', msg='save failed. Try again later?')
else:
task = CobraTaskInfo.query.filter_by(id=task_id).first()
return render_template('backend/task/edit_task.html', data={
'task': task,
})
| Python | 0 |
f5b8b4bafabc06504e2ee2e0571f2d8571db17bb | Update for v1.5.4 | maxminddb/__init__.py | maxminddb/__init__.py | # pylint:disable=C0111
import os
import maxminddb.reader
try:
import maxminddb.extension
except ImportError:
maxminddb.extension = None
from maxminddb.const import (
MODE_AUTO,
MODE_MMAP,
MODE_MMAP_EXT,
MODE_FILE,
MODE_MEMORY,
MODE_FD,
)
from maxminddb.decoder import InvalidDatabaseError
def open_database(database, mode=MODE_AUTO):
"""Open a Maxmind DB database
Arguments:
database -- A path to a valid MaxMind DB file such as a GeoIP2 database
file, or a file descriptor in the case of MODE_FD.
mode -- mode to open the database with. Valid mode are:
* MODE_MMAP_EXT - use the C extension with memory map.
* MODE_MMAP - read from memory map. Pure Python.
* MODE_FILE - read database as standard file. Pure Python.
* MODE_MEMORY - load database into memory. Pure Python.
* MODE_FD - the param passed via database is a file descriptor, not
a path. This mode implies MODE_MEMORY.
* MODE_AUTO - tries MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that
order. Default mode.
"""
has_extension = maxminddb.extension and hasattr(maxminddb.extension, "Reader")
if (mode == MODE_AUTO and has_extension) or mode == MODE_MMAP_EXT:
if not has_extension:
raise ValueError(
"MODE_MMAP_EXT requires the maxminddb.extension module to be available"
)
return maxminddb.extension.Reader(database)
if mode in (MODE_AUTO, MODE_MMAP, MODE_FILE, MODE_MEMORY, MODE_FD):
return maxminddb.reader.Reader(database, mode)
raise ValueError("Unsupported open mode: {0}".format(mode))
def Reader(database): # pylint: disable=invalid-name
"""This exists for backwards compatibility. Use open_database instead"""
return open_database(database)
__title__ = "maxminddb"
__version__ = "1.5.4"
__author__ = "Gregory Oschwald"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2013-2019 Maxmind, Inc."
| # pylint:disable=C0111
import os
import maxminddb.reader
try:
import maxminddb.extension
except ImportError:
maxminddb.extension = None
from maxminddb.const import (
MODE_AUTO,
MODE_MMAP,
MODE_MMAP_EXT,
MODE_FILE,
MODE_MEMORY,
MODE_FD,
)
from maxminddb.decoder import InvalidDatabaseError
def open_database(database, mode=MODE_AUTO):
"""Open a Maxmind DB database
Arguments:
database -- A path to a valid MaxMind DB file such as a GeoIP2 database
file, or a file descriptor in the case of MODE_FD.
mode -- mode to open the database with. Valid mode are:
* MODE_MMAP_EXT - use the C extension with memory map.
* MODE_MMAP - read from memory map. Pure Python.
* MODE_FILE - read database as standard file. Pure Python.
* MODE_MEMORY - load database into memory. Pure Python.
* MODE_FD - the param passed via database is a file descriptor, not
a path. This mode implies MODE_MEMORY.
* MODE_AUTO - tries MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that
order. Default mode.
"""
has_extension = maxminddb.extension and hasattr(maxminddb.extension, "Reader")
if (mode == MODE_AUTO and has_extension) or mode == MODE_MMAP_EXT:
if not has_extension:
raise ValueError(
"MODE_MMAP_EXT requires the maxminddb.extension module to be available"
)
return maxminddb.extension.Reader(database)
if mode in (MODE_AUTO, MODE_MMAP, MODE_FILE, MODE_MEMORY, MODE_FD):
return maxminddb.reader.Reader(database, mode)
raise ValueError("Unsupported open mode: {0}".format(mode))
def Reader(database): # pylint: disable=invalid-name
"""This exists for backwards compatibility. Use open_database instead"""
return open_database(database)
__title__ = "maxminddb"
__version__ = "1.5.3"
__author__ = "Gregory Oschwald"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2013-2019 Maxmind, Inc."
| Python | 0 |
5f9da62f28e61636f33495058f3ea4a98a9d3c19 | add invalid separators to test | tests/inside_worker_test/cast_to_float_or_null_test.py | tests/inside_worker_test/cast_to_float_or_null_test.py | import pytest
import sqlalchemy
from tests.inside_worker_test.conftest import slow
@pytest.fixture(params=[2, 2.2, 3.898986, 0.6, 0])
def valid_float_representation(request):
return request.param
@pytest.fixture(params=["a2", "10b", "3.898986c", "3d.898986", "e6.9", "f0,9" "0,g9" "0,9h", "0,6", "123'456", "1 290", None])
def invalid_floats(request):
return request.param
@slow
def test_cast_to_float_null_if_failed_returns_floats_with_valid_floats(osmaxx_functions, valid_float_representation):
engine = osmaxx_functions
result = engine.execute(
sqlalchemy.text(
"select cast_to_float_null_if_failed($${}$$) as float_value;".format(valid_float_representation)
).execution_options(autocommit=True)
)
assert result.rowcount == 1
results = result.fetchall()
assert len(results) == 1
assert results[0]['float_value'] == float(valid_float_representation)
@slow
def test_cast_to_float_null_if_failed_returns_null_with_invalid_floats(osmaxx_functions, invalid_floats):
engine = osmaxx_functions
result = engine.execute(
sqlalchemy.text(
"select cast_to_float_null_if_failed($${}$$) as float_value;".format(invalid_floats)
).execution_options(autocommit=True)
)
assert result.rowcount == 1
results = result.fetchall()
assert len(results) == 1
assert results[0]['float_value'] is None
| import pytest
import sqlalchemy
from tests.inside_worker_test.conftest import slow
@pytest.fixture(params=[2, 2.2, 3.898986, "3.898986", "6", "0.2", 0.6])
def valid_float_representation(request):
return request.param
@pytest.fixture(params=["a2", "10b", "3.898986k", "3k.898986", "l6.9"])
def invalid_floats(request):
return request.param
@slow
def test_cast_to_float_null_if_failed_returns_floats_with_valid_floats(osmaxx_functions, valid_float_representation):
engine = osmaxx_functions
result = engine.execute(
sqlalchemy.text(
"select cast_to_float_null_if_failed($${}$$) as float_value;".format(valid_float_representation)
).execution_options(autocommit=True)
)
assert result.rowcount == 1
results = result.fetchall()
assert len(results) == 1
assert results[0]['float_value'] == float(valid_float_representation)
@slow
def test_cast_to_float_null_if_failed_returns_null_with_invalid_floats(osmaxx_functions, invalid_floats):
engine = osmaxx_functions
result = engine.execute(
sqlalchemy.text(
"select cast_to_float_null_if_failed($${}$$) as float_value;".format(invalid_floats)
).execution_options(autocommit=True)
)
assert result.rowcount == 1
results = result.fetchall()
assert len(results) == 1
assert results[0]['float_value'] is None
| Python | 0.000002 |
b3e1b6bd9f79427142ebfe4b57892d1cf3a89e86 | Implement the latest test spec for update which requires most of the parameters found in an example usage of mlab-ns against npad. | mlab-ns-simulator/mlabsim/update.py | mlab-ns-simulator/mlabsim/update.py | """
This approximates the mlab-ns slice information gathering. The actual
system uses nagios and we're not certain about the details. This much
simplified version is just a web URL anyone may PUT data into.
Warning: This doesn't have any security properties! We need a way to
prevent the addition of malicious entries.
"""
import json
from twisted.web import resource
from twisted.web.server import NOT_DONE_YET
DBEntryNames = [
'city',
'country',
'fqdn',
'ip',
'port',
'site',
'tool_extra',
]
class UpdateResource (resource.Resource):
def __init__(self, db):
"""db is a dict which will be modified to map { fqdn -> other_details }"""
resource.Resource.__init__(self)
self._db = db
def render_PUT(self, request):
dbentry = {}
for name in DBEntryNames:
# BUG: Multiple values not handled nor tested:
[value] = request.args[name]
if name == 'tool_extra':
try:
value = json.loads(value)
except ValueError:
request.setResponseCode(400, 'invalid')
request.finish()
return NOT_DONE_YET
dbentry[name] = value
self._db[dbentry['fqdn']] = dbentry
request.setResponseCode(200, 'ok')
request.finish()
return NOT_DONE_YET
| """
This approximates the mlab-ns slice information gathering. The actual
system uses nagios and we're not certain about the details. This much
simplified version is just a web URL anyone may PUT data into.
Warning: This doesn't have any security properties! We need a way to
prevent the addition of malicious entries.
"""
import json
from twisted.web import resource
from twisted.web.server import NOT_DONE_YET
class UpdateResource (resource.Resource):
def __init__(self, db):
"""db is a dict which will be modified to map { fqdn -> other_details }"""
resource.Resource.__init__(self)
self._db = db
def render_PUT(self, request):
[fqdn, tool_extra_json] = self._parse_args(request.args)
try:
tool_extra = json.loads(tool_extra_json)
except ValueError:
request.setResponseCode(400, 'invalid')
request.finish()
else:
self._db[fqdn] = {'tool_extra': tool_extra}
request.setResponseCode(200, 'ok')
request.finish()
return NOT_DONE_YET
def _parse_args(self, args):
for name in ['fqdn', 'tool_extra']:
[val] = args[name]
yield val
| Python | 0 |
45a24fae9f5e1ee24c2e0283746224e51f718cc2 | Remove redundant test of permissions parameter | planex/tree.py | planex/tree.py | """
In-memory 'filesystem' library
"""
import os
class Tree(object):
"""
An in-memory 'filesystem' which accumulates file changes
to be written later.
"""
def __init__(self):
self.tree = {}
def append(self, filename, contents=None, permissions=None):
"""
Append contents to filename in the in-memory filesystem.
"""
node = self.tree.get(filename, {})
if contents:
node['contents'] = node.get('contents', '') + contents
if permissions:
if 'permissions' in node and \
node['permissions'] != permissions:
raise Exception("Inconsistent permissions for '%s'" % filename)
node['permissions'] = permissions
self.tree[filename] = node
def apply(self, basepath):
"""
Save in-memory filesystem to disk.
"""
for subpath, node in self.tree.items():
permissions = node.get("permissions", 0o644)
contents = node.get("contents", "")
fullpath = os.path.join(basepath, subpath)
if not os.path.isdir(os.path.dirname(fullpath)):
os.makedirs(os.path.dirname(fullpath))
out = os.open(os.path.join(basepath, subpath),
os.O_WRONLY | os.O_CREAT, permissions)
os.write(out, contents)
os.close(out)
def __repr__(self):
res = ""
for subpath, node in self.tree.items():
permissions = node.get("permissions", 0o644)
contents = node.get("contents", "")
res += "%s (0o%o):\n" % (subpath, permissions)
res += contents
res += "\n\n"
return res
| """
In-memory 'filesystem' library
"""
import os
class Tree(object):
"""
An in-memory 'filesystem' which accumulates file changes
to be written later.
"""
def __init__(self):
self.tree = {}
def append(self, filename, contents=None, permissions=None):
"""
Append contents to filename in the in-memory filesystem.
"""
node = self.tree.get(filename, {})
if contents:
node['contents'] = node.get('contents', '') + contents
if permissions:
if 'permissions' in node and \
node['permissions'] != permissions:
raise Exception("Inconsistent permissions for '%s'" % filename)
if permissions:
node['permissions'] = permissions
else:
node['permissions'] = 0o644
self.tree[filename] = node
def apply(self, basepath):
"""
Save in-memory filesystem to disk.
"""
for subpath, node in self.tree.items():
permissions = node.get("permissions", 0o644)
contents = node.get("contents", "")
fullpath = os.path.join(basepath, subpath)
if not os.path.isdir(os.path.dirname(fullpath)):
os.makedirs(os.path.dirname(fullpath))
out = os.open(os.path.join(basepath, subpath),
os.O_WRONLY | os.O_CREAT, permissions)
os.write(out, contents)
os.close(out)
def __repr__(self):
res = ""
for subpath, node in self.tree.items():
permissions = node.get("permissions", 0o644)
contents = node.get("contents", "")
res += "%s (0o%o):\n" % (subpath, permissions)
res += contents
res += "\n\n"
return res
| Python | 0 |
7ad7f0231bc50c58f9b606cbab36d6cd98e141ec | Make the error message clearer (#944) | pyvista/plotting/__init__.py | pyvista/plotting/__init__.py | """Plotting routines."""
from .colors import (color_char_to_word, get_cmap_safe, hex_to_rgb, hexcolors,
string_to_rgb, PARAVIEW_BACKGROUND)
from .export_vtkjs import export_plotter_vtkjs, get_vtkjs_url
from .helpers import plot, plot_arrows, plot_compare_four, plot_itk
from .itkplotter import PlotterITK
from .plotting import BasePlotter, Plotter, close_all
from .renderer import CameraPosition, Renderer, scale_point
from .theme import (DEFAULT_THEME, FONT_KEYS, MAX_N_COLOR_BARS,
parse_color, parse_font_family, rcParams, set_plot_theme)
from .tools import (create_axes_marker, create_axes_orientation_box,
opacity_transfer_function, system_supports_plotting)
from .widgets import WidgetHelper
class QtDeprecationError(Exception):
"""Depreciation Error for features that moved to `pyvistaqt`."""
message = """`{}` has moved to pyvistaqt.
You can install this from PyPI with: `pip install pyvistaqt`
Then import it via: `from pyvistaqt import {}`
`{}` is no longer accessible by `pyvista.{}`
See https://github.com/pyvista/pyvistaqt
"""
def __init__(self, feature_name):
"""Empty init."""
Exception.__init__(self, self.message.format(*[feature_name] * 4))
class BackgroundPlotter():
"""This class has been moved to pyvistaqt."""
def __init__(self, *args, **kwargs):
"""Empty init."""
raise QtDeprecationError('BackgroundPlotter')
class QtInteractor():
"""This class has been moved to pyvistaqt."""
def __init__(self, *args, **kwargs):
"""Empty init."""
raise QtDeprecationError('QtInteractor')
| """Plotting routines."""
from .colors import (color_char_to_word, get_cmap_safe, hex_to_rgb, hexcolors,
string_to_rgb, PARAVIEW_BACKGROUND)
from .export_vtkjs import export_plotter_vtkjs, get_vtkjs_url
from .helpers import plot, plot_arrows, plot_compare_four, plot_itk
from .itkplotter import PlotterITK
from .plotting import BasePlotter, Plotter, close_all
from .renderer import CameraPosition, Renderer, scale_point
from .theme import (DEFAULT_THEME, FONT_KEYS, MAX_N_COLOR_BARS,
parse_color, parse_font_family, rcParams, set_plot_theme)
from .tools import (create_axes_marker, create_axes_orientation_box,
opacity_transfer_function, system_supports_plotting)
from .widgets import WidgetHelper
class QtDeprecationError(Exception):
"""Depreciation Error for features that moved to `pyvistaqt`."""
message = """`{}` has moved to pyvistaqt.
You can install this from PyPI with: `pip install pyvistaqt`
See https://github.com/pyvista/pyvistaqt
"""
def __init__(self, feature_name):
"""Empty init."""
Exception.__init__(self, self.message.format(feature_name))
class BackgroundPlotter():
"""This class has been moved to pyvistaqt."""
def __init__(self, *args, **kwargs):
"""Empty init."""
raise QtDeprecationError('BackgroundPlotter')
class QtInteractor():
"""This class has been moved to pyvistaqt."""
def __init__(self, *args, **kwargs):
"""Empty init."""
raise QtDeprecationError('QtInteractor')
| Python | 0.003492 |
f53e7452676e6ee903a4d8c350fa356a718a5fcc | Add a test for file: and path: searches for non-ASCII things. | tests/test_path_file_filters/test_path_file_filters.py | tests/test_path_file_filters/test_path_file_filters.py | # -*- coding: utf-8 -*-
from nose.tools import raises
from dxr.testing import DxrInstanceTestCase
class PathAndFileFilterTests(DxrInstanceTestCase):
"""Basic tests for functionality of the 'path:' and 'file:' filters"""
def test_basic_path_results(self):
"""Check that a 'path:' result includes both file and folder matches."""
self.found_files_eq('path:fish', ['fish1', 'fishy_folder/fish2',
'fishy_folder/gill', 'folder/fish3',
'folder/fish4'])
def test_basic_file_results(self):
"""Check that a 'file:' result includes only file matches."""
self.found_files_eq('file:fish', ['fish1', 'fishy_folder/fish2',
'folder/fish3', 'folder/fish4'])
def test_path_and_file_line_promotion(self):
"""Make sure promotion of a 'path:' or 'file:' filter to a LINE query
works.
"""
self.found_files_eq('path:fish fins', ['folder/fish3'])
self.found_files_eq('file:fish fins', ['folder/fish3'])
# This fails because we currently intentionally exclude folder paths from
# FILE query results - remove the @raises line when that's changed. (Of
# course then other tests here will need to be updated as well.)
@raises(AssertionError)
def test_empty_folder_path_results(self):
"""Check that 'path:' results include empty folders."""
self.found_files_eq('path:empty_folder', ['empty_folder'])
def test_basic_wildcard(self):
"""Test basic wildcard functionality."""
# 'path:' and 'file:' currently have the same underlying wildcard
# support, so we're spreading out the basic wildcard testing over both.
self.found_files_eq('path:fish?_fo*er',
['fishy_folder/fish2', 'fishy_folder/gill'])
self.found_files_eq('file:fish[14]', ['fish1', 'folder/fish4'])
def test_unicode(self):
"""Make sure searching for non-ASCII names works."""
self.found_files_eq(u'file:fre\u0301mium*', [u'fre\u0301mium.txt'])
# This one fails because é is normalized differently in ES than here:
# self.found_files_eq(u'file:frémium*', [u'frémium.txt'])
| from nose.tools import raises
from dxr.testing import DxrInstanceTestCase
class PathAndFileFilterTests(DxrInstanceTestCase):
"""Basic tests for functionality of the 'path:' and 'file:' filters"""
def test_basic_path_results(self):
"""Check that a 'path:' result includes both file and folder matches."""
self.found_files_eq('path:fish', ['fish1', 'fishy_folder/fish2',
'fishy_folder/gill', 'folder/fish3',
'folder/fish4'])
def test_basic_file_results(self):
"""Check that a 'file:' result includes only file matches."""
self.found_files_eq('file:fish', ['fish1', 'fishy_folder/fish2',
'folder/fish3', 'folder/fish4'])
def test_path_and_file_line_promotion(self):
"""Make sure promotion of a 'path:' or 'file:' filter to a LINE query
works.
"""
self.found_files_eq('path:fish fins', ['folder/fish3'])
self.found_files_eq('file:fish fins', ['folder/fish3'])
# This fails because we currently intentionally exclude folder paths from
# FILE query results - remove the @raises line when that's changed. (Of
# course then other tests here will need to be updated as well.)
@raises(AssertionError)
def test_empty_folder_path_results(self):
"""Check that 'path:' results include empty folders."""
self.found_files_eq('path:empty_folder', ['empty_folder'])
def test_basic_wildcard(self):
"""Test basic wildcard functionality."""
# 'path:' and 'file:' currently have the same underlying wildcard
# support, so we're spreading out the basic wildcard testing over both.
self.found_files_eq('path:fish?_fo*er',
['fishy_folder/fish2', 'fishy_folder/gill'])
self.found_files_eq('file:fish[14]', ['fish1', 'folder/fish4'])
| Python | 0.000001 |
d22bd8970b973fb58f1358b62cf8c27f826aa407 | update example | example/gravity.py | example/gravity.py | from pgmagick import Image, Geometry, Color, TypeMetric, \
DrawableText, DrawableList, DrawableGravity, GravityType
im = Image(Geometry(600, 600), Color("transparent"))
im.fontPointsize(30)
im.fillColor(Color("#f010f0"))
im.strokeColor(Color("transparent"))
im.font("Vera.ttf")
dl = DrawableList()
dl.append(DrawableGravity(GravityType.CenterGravity))
dl.append(DrawableText(0, 0, "center"))
tm = TypeMetric()
im.fontTypeMetrics("northn", tm)
font_height = tm.textHeight()
dl.append(DrawableGravity(GravityType.NorthGravity))
dl.append(DrawableText(0, font_height / 2., "north"))
dl.append(DrawableGravity(GravityType.WestGravity))
dl.append(DrawableText(0, 0, "west"))
dl.append(DrawableGravity(GravityType.EastGravity))
dl.append(DrawableText(0, 0, "east"))
dl.append(DrawableText(0, 20, "east-long"))
dl.append(DrawableGravity(GravityType.SouthGravity))
dl.append(DrawableText(0, 0, "south"))
dl.append(DrawableGravity(GravityType.NorthWestGravity))
dl.append(DrawableText(0, font_height / 2., "north-west"))
dl.append(DrawableGravity(GravityType.NorthEastGravity))
dl.append(DrawableText(0, font_height / 2., "north-east"))
dl.append(DrawableGravity(GravityType.SouthWestGravity))
dl.append(DrawableText(0, 0, "south-west"))
dl.append(DrawableGravity(GravityType.SouthEastGravity))
dl.append(DrawableText(0, 0, "south-east"))
im.draw(dl)
im.write("test.png")
| from pgmagick import Image, Geometry, Color, TypeMetric, \
DrawableText, DrawableList, DrawableGravity, GravityType
im = Image(Geometry(600, 600), Color("transparent"))
im.fontPointsize(30)
im.fillColor(Color("#f010f0"))
im.strokeColor(Color("transparent"))
im.font("Vera.ttf")
dl = DrawableList()
dl.append(DrawableGravity(GravityType.CenterGravity))
dl.append(DrawableText(0, 0, "center"))
tm = TypeMetric()
im.fontTypeMetrics("northn", tm)
font_height = tm.textHeight()
dl.append(DrawableGravity(GravityType.NorthGravity))
dl.append(DrawableText(0, font_height / 2., "north"))
dl.append(DrawableGravity(GravityType.WestGravity))
dl.append(DrawableText(0, 0, "west"))
dl.append(DrawableGravity(GravityType.EastGravity))
dl.append(DrawableText(0, 0, "east"))
dl.append(DrawableGravity(GravityType.SouthGravity))
dl.append(DrawableText(0, 0, "south"))
dl.append(DrawableGravity(GravityType.NorthWestGravity))
dl.append(DrawableText(0, font_height / 2., "north-west"))
dl.append(DrawableGravity(GravityType.NorthEastGravity))
dl.append(DrawableText(0, font_height / 2., "north-east"))
dl.append(DrawableGravity(GravityType.SouthWestGravity))
dl.append(DrawableText(0, 0, "south-west"))
dl.append(DrawableGravity(GravityType.SouthEastGravity))
dl.append(DrawableText(0, 0, "south-east"))
im.draw(dl)
im.write("test.png")
| Python | 0.000001 |
73e99078b3bce587e059b1a15dbb7f94be70dd8d | enable the possibility of success | testcases/OpalMsglog.py | testcases/OpalMsglog.py | #!/usr/bin/python2
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2017
# [+] International Business Machines Corp.
#
#
# 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.
#
import unittest
import OpTestConfiguration
from common.OpTestSystem import OpSystemState
from common.OpTestConstants import OpTestConstants as BMC_CONST
from common.Exceptions import CommandFailed
class OpalMsglog():
def setUp(self):
conf = OpTestConfiguration.conf
self.cv_HOST = conf.host()
self.cv_IPMI = conf.ipmi()
self.cv_SYSTEM = conf.system()
def runTest(self):
self.setup_test()
try:
log_entries = self.c.run_command("grep ',[0-4]\]' /sys/firmware/opal/msglog")
msg = '\n'.join(filter(None, log_entries))
self.assertTrue( len(log_entries) == 0, "Warnings/Errors in OPAL log:\n%s" % msg)
except CommandFailed as cf:
if cf.exitcode is 1 and len(cf.output) is 0:
pass
else:
raise cf
class Skiroot(OpalMsglog, unittest.TestCase):
def setup_test(self):
self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)
self.c = self.cv_SYSTEM.sys_get_ipmi_console()
self.cv_SYSTEM.host_console_unique_prompt()
class Host(OpalMsglog, unittest.TestCase):
def setup_test(self):
self.cv_SYSTEM.goto_state(OpSystemState.OS)
self.c = self.cv_SYSTEM.host().get_ssh_connection()
| #!/usr/bin/python2
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2017
# [+] International Business Machines Corp.
#
#
# 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.
#
import unittest
import OpTestConfiguration
from common.OpTestSystem import OpSystemState
from common.OpTestConstants import OpTestConstants as BMC_CONST
class OpalMsglog():
def setUp(self):
conf = OpTestConfiguration.conf
self.cv_HOST = conf.host()
self.cv_IPMI = conf.ipmi()
self.cv_SYSTEM = conf.system()
def runTest(self):
self.setup_test()
log_entries = self.c.run_command("grep ',[0-4]\]' /sys/firmware/opal/msglog")
msg = '\n'.join(filter(None, log_entries))
self.assertTrue( len(log_entries) == 0, "Warnings/Errors in OPAL log:\n%s" % msg)
class Skiroot(OpalMsglog, unittest.TestCase):
def setup_test(self):
self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)
self.c = self.cv_SYSTEM.sys_get_ipmi_console()
self.cv_SYSTEM.host_console_unique_prompt()
class Host(OpalMsglog, unittest.TestCase):
def setup_test(self):
self.cv_SYSTEM.goto_state(OpSystemState.OS)
self.c = self.cv_SYSTEM.host().get_ssh_connection()
| Python | 0 |
6cb0822aade07999d54e5fcd19eb2c7322abc80a | Improve performance @ Measurement Admin | measurement/admin.py | measurement/admin.py | from django.contrib import admin
from .models import Measurement
class MeasurementAdmin(admin.ModelAdmin):
model = Measurement
def get_queryset(self, request):
return super(MeasurementAdmin, self).get_queryset(request).select_related('patient__user')
admin.site.register(Measurement, MeasurementAdmin)
| from django.contrib import admin
from .models import Measurement
admin.site.register(Measurement)
| Python | 0 |
24b2509b1605dfd6d3eb325ed946c3d23441b969 | use Python's QT stuff | demo/quicktime.py | demo/quicktime.py | #!/usr/bin/env python
"""Display quicktime movie."""
import os, sys
import VisionEgg
from VisionEgg.Core import *
from VisionEgg.Text import *
from VisionEgg.Textures import *
from VisionEgg.QuickTime import new_movie_from_filename, MovieTexture
screen = get_default_screen()
screen.set(bgcolor=(0,0,0))
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = os.path.join(VisionEgg.config.VISIONEGG_SYSTEM_DIR,"data","water.mov")
movie = new_movie_from_filename(filename) # movie is type Carbon.Qt.Movie
bounds = movie.GetMovieBox()
width = bounds[2]-bounds[0]
height = bounds[3]-bounds[1]
scale_x = screen.size[0]/float(width)
scale_y = screen.size[1]/float(height)
scale = min(scale_x,scale_y) # maintain aspect ratio
movie_texture = MovieTexture(movie=movie)
stimulus = TextureStimulus(
texture=movie_texture,
position = (screen.size[0]/2.0,screen.size[1]/2.0),
anchor = 'center',
mipmaps_enabled = False, # can't do mipmaps with QuickTime movies
shrink_texture_ok = True,
size = (width*scale, height*scale),
)
text = Text( text = "Vision Egg QuickTime movie demo - Press any key to quit",
position = (screen.size[0]/2,screen.size[1]),
anchor = 'top',
color = (1.0, 1.0, 1.0),
)
viewport = Viewport(screen=screen,
stimuli=[stimulus, text])
movie.StartMovie()
frame_timer = FrameTimer()
while not pygame.event.peek((pygame.locals.QUIT,
pygame.locals.KEYDOWN,
pygame.locals.MOUSEBUTTONDOWN)):
movie.MoviesTask(0)
screen.clear()
viewport.draw()
swap_buffers() # display the frame we've drawn in back buffer
frame_timer.tick()
if movie.IsMovieDone():
movie.GoToBeginningOfMovie()
frame_timer.print_histogram()
| #!/usr/bin/env python
"""Display quicktime movie."""
import os
import VisionEgg
from VisionEgg.Core import *
from VisionEgg.Text import *
from VisionEgg.Textures import *
from VisionEgg.QuickTime import *
screen = get_default_screen()
screen.set(bgcolor=(0,0,0))
filename = os.path.join(VisionEgg.config.VISIONEGG_SYSTEM_DIR,"data","water.mov")
movie = Movie(filename)
left, bottom, right, top = movie.get_box()
width,height = abs(right-left), abs(top-bottom)
scale_x = screen.size[0]/float(width)
scale_y = screen.size[1]/float(height)
scale = min(scale_x,scale_y) # maintain aspect ratio
movie_texture = MovieTexture(movie=movie)
stimulus = TextureStimulus(
texture=movie_texture,
position = (screen.size[0]/2.0,screen.size[1]/2.0),
anchor = 'center',
mipmaps_enabled = False, # can't do mipmaps with QuickTime movies
shrink_texture_ok = True,
size = (width*scale, height*scale),
)
text = Text( text = "Vision Egg QuickTime movie demo - Press any key to quit",
position = (screen.size[0]/2,screen.size[1]),
anchor = 'top',
color = (1.0, 1.0, 1.0),
)
viewport = Viewport(screen=screen,
stimuli=[stimulus, text])
movie.start()
frame_timer = FrameTimer()
while not pygame.event.peek((pygame.locals.QUIT,
pygame.locals.KEYDOWN,
pygame.locals.MOUSEBUTTONDOWN)):
movie.task()
screen.clear()
viewport.draw()
swap_buffers() # display the frame we've drawn in back buffer
frame_timer.tick()
if movie.is_done():
movie.go_to_beginning()
frame_timer.print_histogram()
| Python | 0.000002 |
c92caa1f00c984cf839ccf7c645d207e100eb874 | Add test_invalid_image to test_image_validation module | test/server/test_image_validation.py | test/server/test_image_validation.py | from urlparse import urljoin
from clientlib import (
make_example_shot,
make_random_id,
screenshots_session,
example_images
)
import random, string
# Hack to make this predictable:
random.seed(0)
def test_invalid_image_url():
with screenshots_session() as user:
shot_id = make_random_id() + "/test.com"
shot_data = urljoin(user.backend, "data/" + shot_id)
shot_json = make_example_shot(user.deviceId)
invalid_url = "https://example.com/?aaA=bbb=\"); background-color: red;"
for clip_id in shot_json['clips']:
shot_json['clips'][clip_id]['image']['url'] = invalid_url
break
resp = user.session.put(
shot_data,
json=shot_json,
)
print(resp.text)
assert resp.status_code == 500 # assertion failure on clip image url
def test_invalid_data_image():
with screenshots_session() as user:
shot_id = make_random_id() + "/test.com"
shot_data = urljoin(user.backend, "data/" + shot_id)
shot_json = make_example_shot(user.deviceId)
valid_data_image = example_images['url']
if "iVBORw0KGgo" in valid_data_image:
print(valid_data_image)
def test_invalid_data_image_decoded():
pass
def test_invalid_data_url():
pass
if __name__ == "__main__":
test_invalid_data_image()
test_invalid_data_image_decoded()
test_invalid_data_url()
| from urlparse import urljoin
from clientlib import (
make_example_shot,
make_random_id,
screenshots_session,
example_images
)
import random
# Hack to make this predictable:
random.seed(0)
def test_invalid_image_url():
with screenshots_session() as user:
shot_id = make_random_id() + "/test.com"
shot_data = urljoin(user.backend, "data/" + shot_id)
shot_json = make_example_shot(user.deviceId)
invalid_url = "https://example.com/?aaA=bbb=\"); background-color: red;"
for clip_id in shot_json['clips']:
shot_json['clips'][clip_id]['image']['url'] = invalid_url
break
resp = user.session.put(
shot_data,
json=shot_json,
)
print(resp.text)
assert resp.status_code == 500 # assertion failure on clip image url
def test_invalid_data_image():
with screenshots_session() as user:
shot_url = user.create_shot(docTitle="TEST_JPEG", image_content_type="application/pdf", image_index=0)
shot_page = user.read_shot(shot_url)
assert shot_page["clip_content_type"] != "image/jpeg"
def test_invalid_data_image_decoded():
pass
def test_invalid_data_url():
pass
if __name__ == "__main__":
test_invalid_data_image()
test_invalid_data_image_decoded()
test_invalid_data_url()
| Python | 0.000001 |
2942f39534ca7b309e32268697350afaacad7274 | TEST : Added small integrity test for sct_get_centerline | testing/test_sct_get_centerline.py | testing/test_sct_get_centerline.py | #!/usr/bin/env python
#########################################################################################
#
# Test function for sct_get_centerline script
#
# replace the shell test script in sct 1.0
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Augustin Roux
# modified: 2014/09/28
#
# About the license: see the file LICENSE.TXT
#########################################################################################
import commands
from msct_image import Image
from sct_get_centerline import ind2sub
import math
import sct_utils as sct
import numpy as np
def test(path_data):
# parameters
folder_data = 't2/'
file_data = ['t2.nii.gz', 't2_centerline_init.nii.gz', 't2_centerline_labels.nii.gz', 't2_seg_manual.nii.gz']
output = ''
status = 0
# define command
cmd = 'sct_get_centerline -i ' + path_data + folder_data + file_data[0] \
+ ' -method auto' \
+ ' -t t2 ' \
+ ' -v 1'
output += '\n====================================================================================================\n'+cmd+'\n====================================================================================================\n\n' # copy command
s, o = commands.getstatusoutput(cmd)
status += s
output += o
# small integrity test on scad
try :
if status == 0:
manual_seg = Image(path_data + folder_data + file_data[3])
centerline_scad = Image(path_data + folder_data + file_data[0])
centerline_scad.change_orientation()
manual_seg.change_orientation()
from scipy.ndimage.measurements import center_of_mass
# find COM
iterator = range(manual_seg.data.shape[2])
com_x = [0 for ix in iterator]
com_y = [0 for iy in iterator]
for iz in iterator:
com_x[iz], com_y[iz] = center_of_mass(manual_seg.data[:, :, iz])
max_distance = {}
distance = {}
for iz in range(1, centerline_scad.data.shape[2]-1):
ind1 = np.argmax(centerline_scad.data[:, :, iz])
X,Y = ind2sub(centerline_scad.data[:, :, iz].shape,ind1)
com_phys = np.array(manual_seg.transfo_pix2phys([[com_x[iz], com_y[iz], iz]]))
scad_phys = np.array(centerline_scad.transfo_pix2phys([[X, Y, iz]]))
distance_magnitude = np.linalg.norm([com_phys[0][0]-scad_phys[0][0], com_phys[0][1]-scad_phys[0][1], 0])
if math.isnan(distance_magnitude):
print "Value is nan"
else:
distance[iz] = distance_magnitude
max_distance = max(distance.values())
#if max_distance > 5:
#sct.printv("Max distance between scad and manual centerline is greater than 5 mm", type="warning")
except Exception, e:
sct.printv("Exception found while testing scad integrity")
sct.printv(e.message, type="error")
# define command: DOES NOT RUN IT BECAUSE REQUIRES FSL FLIRT
# cmd = 'sct_get_centerline -i ' + path_data + folder_data + file_data[0] \
# + ' -method point' \
# + ' -p ' + path_data + folder_data + file_data[1] \
# + ' -g 1'\
# + ' -k 4'
# output += '\n====================================================================================================\n'+cmd+'\n====================================================================================================\n\n' # copy command
# s, o = commands.getstatusoutput(cmd)
# status += s
# output += o
# define command
cmd = 'sct_get_centerline -i ' + path_data + folder_data + file_data[0] \
+ ' -method labels ' \
+ ' -l ' + path_data + folder_data + file_data[2] \
+ ' -v 1'
output += '\n====================================================================================================\n'+cmd+'\n====================================================================================================\n\n' # copy command
s, o = commands.getstatusoutput(cmd)
status += s
output += o
return status, output
if __name__ == "__main__":
# call main function
test() | #!/usr/bin/env python
#########################################################################################
#
# Test function for sct_get_centerline script
#
# replace the shell test script in sct 1.0
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Augustin Roux
# modified: 2014/09/28
#
# About the license: see the file LICENSE.TXT
#########################################################################################
import commands
def test(path_data):
# parameters
folder_data = 't2/'
file_data = ['t2.nii.gz', 't2_centerline_init.nii.gz', 't2_centerline_labels.nii.gz']
output = ''
status = 0
# define command
cmd = 'sct_get_centerline -i ' + path_data + folder_data + file_data[0] \
+ ' -method auto' \
+ ' -t t2 ' \
+ ' -v 1'
output += '\n====================================================================================================\n'+cmd+'\n====================================================================================================\n\n' # copy command
s, o = commands.getstatusoutput(cmd)
status += s
output += o
# define command: DOES NOT RUN IT BECAUSE REQUIRES FSL FLIRT
# cmd = 'sct_get_centerline -i ' + path_data + folder_data + file_data[0] \
# + ' -method point' \
# + ' -p ' + path_data + folder_data + file_data[1] \
# + ' -g 1'\
# + ' -k 4'
# output += '\n====================================================================================================\n'+cmd+'\n====================================================================================================\n\n' # copy command
# s, o = commands.getstatusoutput(cmd)
# status += s
# output += o
# define command
cmd = 'sct_get_centerline -i ' + path_data + folder_data + file_data[0] \
+ ' -method labels ' \
+ ' -l ' + path_data + folder_data + file_data[2] \
+ ' -v 1'
output += '\n====================================================================================================\n'+cmd+'\n====================================================================================================\n\n' # copy command
s, o = commands.getstatusoutput(cmd)
status += s
output += o
return status, output
if __name__ == "__main__":
# call main function
test() | Python | 0 |
fcc5f3a8847dbbb7fc4f9b939dacacd340a314a2 | Load top level dicts in init | medleydb/__init__.py | medleydb/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Python tools for using MedleyDB """
import logging
from os import path
from os import environ
import warnings
import yaml
import json
from medleydb.version import __version__
__all__ = ["__version__", "sql"]
logging.basicConfig(level=logging.CRITICAL)
if "MEDLEYDB_PATH" in environ and path.exists(environ["MEDLEYDB_PATH"]):
MEDLEYDB_PATH = environ["MEDLEYDB_PATH"]
AUDIO_AVAILABLE = True
elif "MEDLEYDB_PATH" not in environ:
warnings.warn(
"The environment variable MEDLEYDB_PATH is not set. "
"As a result, any part of the code that requires the audio won't work. "
"If you don't need to access the audio, disregard this warning. "
"If you do, set the environment variable MEDLEYDB_PATH to your "
"local copy of MedeleyDB.",
UserWarning
)
MEDLEYDB_PATH = ""
AUDIO_AVAILABLE = False
else:
MEDLEYDB_PATH = environ["MEDLEYDB_PATH"]
warnings.warn(
"The value set for MEDLEYDB_PATH: %s does not exist. "
"As a result, any part of the code that requires the audio won't work. "
"If you don't need to access the audio, disregard this warning. "
"If you do, set the environment variable MEDLEYDB_PATH to your local "
"copy of MedeleyDB." % MEDLEYDB_PATH,
UserWarning
)
AUDIO_AVAILABLE = False
# The taxonomy, tracklist, annotations and metadata are version controlled and
# stored inside the repository
ANNOT_PATH = path.join(path.dirname(__file__), '../', 'Annotations')
METADATA_PATH = path.join(path.dirname(__file__), '../', 'Metadata')
TRACK_LIST = []
with open(path.join(path.dirname(__file__),
'tracklist_v1.txt'), 'r') as fhandle:
for line in fhandle.readlines():
TRACK_LIST.append(line.strip('\n'))
with open(path.join(path.dirname(__file__), 'taxonomy.yaml'), 'r') as f_handle:
INST_TAXONOMY = yaml.load(f_handle)
with open(path.join(path.dirname(__file__),
'instrument_f0_type.json'), 'r') as f_handle:
INST_F0_TYPE = json.load(f_handle)
with open(path.join(path.dirname(__file__),
'mixing_coefficients.yaml'), 'r') as fhandle:
MIXING_COEFFICIENTS = yaml.load(fhandle)
# Audio is downloaded separately and is not version controlled :'(.
# This is the motivation for requesting the user to set the MEDLEYDB_PATH
if AUDIO_AVAILABLE:
AUDIO_PATH = path.join(MEDLEYDB_PATH, 'Audio')
if not path.exists(AUDIO_PATH):
AUDIO_PATH = None
warnings.warn(
"The medleydb audio was not found at the expected path: %s "
"This module will still function, but without the "
"ability to access any of the audio." % AUDIO_PATH,
UserWarning
)
else:
AUDIO_PATH = None
from .utils import (
load_melody_multitracks,
load_all_multitracks,
load_multitracks,
get_files_for_instrument,
preview_audio
)
from .multitrack import (
MultiTrack,
Track,
get_duration,
read_annotation_file,
get_valid_instrument_labels,
is_valid_instrument
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Python tools for using MedleyDB """
import logging
from os import path
from os import environ
import warnings
from medleydb.version import __version__
__all__ = ["__version__", "sql"]
logging.basicConfig(level=logging.CRITICAL)
if "MEDLEYDB_PATH" in environ and path.exists(environ["MEDLEYDB_PATH"]):
MEDLEYDB_PATH = environ["MEDLEYDB_PATH"]
AUDIO_AVAILABLE = True
elif "MEDLEYDB_PATH" not in environ:
warnings.warn(
"The environment variable MEDLEYDB_PATH is not set. "
"As a result, any part of the code that requires the audio won't work. "
"If you don't need to access the audio, disregard this warning. "
"If you do, set the environment variable MEDLEYDB_PATH to your "
"local copy of MedeleyDB.",
UserWarning
)
MEDLEYDB_PATH = ""
AUDIO_AVAILABLE = False
else:
MEDLEYDB_PATH = environ["MEDLEYDB_PATH"]
warnings.warn(
"The value set for MEDLEYDB_PATH: %s does not exist. "
"As a result, any part of the code that requires the audio won't work. "
"If you don't need to access the audio, disregard this warning. "
"If you do, set the environment variable MEDLEYDB_PATH to your local "
"copy of MedeleyDB." % MEDLEYDB_PATH,
UserWarning
)
AUDIO_AVAILABLE = False
# The taxonomy, tracklist, annotations and metadata are version controlled and
# stored inside the repository
INST_TAXONOMY = path.join(path.dirname(__file__), 'taxonomy.yaml')
TRACK_LIST = path.join(path.dirname(__file__), 'tracklist_v1.txt')
ANNOT_PATH = path.join(path.dirname(__file__), '../', 'Annotations')
METADATA_PATH = path.join(path.dirname(__file__), '../', 'Metadata')
INST_F0_TYPE = path.join(path.dirname(__file__), 'instrument_f0_type.json')
# Audio is downloaded separately and is not version controlled :'(.
# This is the motivation for requesting the user to set the MEDLEYDB_PATH
if AUDIO_AVAILABLE:
AUDIO_PATH = path.join(MEDLEYDB_PATH, 'Audio')
if not path.exists(AUDIO_PATH):
AUDIO_PATH = None
warnings.warn(
"The medleydb audio was not found at the expected path: %s "
"This module will still function, but without the "
"ability to access any of the audio." % AUDIO_PATH,
UserWarning
)
else:
AUDIO_PATH = None
from .utils import (
load_melody_multitracks,
load_all_multitracks,
load_multitracks,
get_files_for_instrument,
preview_audio
)
from .multitrack import (
MultiTrack,
Track,
get_duration,
read_annotation_file,
get_valid_instrument_labels,
is_valid_instrument
)
| Python | 0 |
33121b74419e9913e46e183914805d4a9db8f742 | fix test to look for email instead of username | meetuppizza/tests.py | meetuppizza/tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.test import Client
from meetuppizza.forms import RegistrationForm
import pdb
class Test(TestCase):
def setUp(self):
self.params = {
'username':'Bjorn',
'email':'bjorn@bjorn.com',
'password1':'bjornbjorn',
'password2':'bjornbjorn'
}
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_page_contains_pizza(self):
response = self.client.get('/')
self.assertContains(response, "pizza")
def test_signup_redirects(self):
response = self.client.post('/sign_up', self.params, follow=True)
self.assertRedirects(response, '/welcome')
def test_user_is_created(self):
c = Client()
c.post('/sign_up', self.params)
self.assertEqual(1, len(User.objects.all()))
def test_user_is_logged_in_after_signup(self):
c = Client()
c.post('/sign_up', self.params)
user = User.objects.get(username='Bjorn')
self.assertTrue(user.is_authenticated())
def test_email_displayed_on_welcome_page(self):
c = Client()
c.post('/sign_up', self.params)
response = c.get('/welcome')
self.assertContains(response, "bjorn@bjorn.com")
| from django.test import TestCase
from django.contrib.auth.models import User
from django.test import Client
from meetuppizza.forms import RegistrationForm
import pdb
class Test(TestCase):
def setUp(self):
self.params = {
'username':'Bjorn',
'email':'bjorn@bjorn.com',
'password1':'bjornbjorn',
'password2':'bjornbjorn'
}
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_page_contains_pizza(self):
response = self.client.get('/')
self.assertContains(response, "pizza")
def test_signup_redirects(self):
response = self.client.post('/sign_up', self.params, follow=True)
self.assertRedirects(response, '/welcome')
def test_user_is_created(self):
c = Client()
c.post('/sign_up', self.params)
self.assertEqual(1, len(User.objects.all()))
def test_user_is_logged_in_after_signup(self):
c = Client()
c.post('/sign_up', self.params)
user = User.objects.get(username='Bjorn')
self.assertTrue(user.is_authenticated())
def test_email_displayed_on_welcome_page(self):
c = Client()
c.post('/sign_up', self.params)
response = c.get('/welcome')
self.assertContains(response, "Bjorn")
| Python | 0 |
9e202e78a5737d8609dfc193b35797b2f5f4a7bb | Corrige le groupage des fichiers statiques saisies plusieurs fois. | static_grouper/templatetags/static_grouper.py | static_grouper/templatetags/static_grouper.py | from collections import defaultdict
from compressor.templatetags.compress import CompressorNode
from django.template import Library, Node, Template, TemplateSyntaxError
register = Library()
CONTEXT_VARIABLE_NAME = 'static_grouper_dict'
class AddStaticNode(Node):
def __init__(self, parser, token):
contents = token.split_contents()
if len(contents) not in (2, 3):
raise TemplateSyntaxError
if len(contents) == 3:
assert contents[2] == 'nocompress'
self.compress = False
else:
self.compress = True
self.static_type = contents[1]
self.nodelist = parser.parse(('endaddstatic',))
parser.delete_first_token()
def render(self, context):
output = self.nodelist.render(context).strip()
static_grouper_dict = context.get(CONTEXT_VARIABLE_NAME)
if static_grouper_dict is None:
root_context = context.dicts[0]
root_context[CONTEXT_VARIABLE_NAME] = \
static_grouper_dict = defaultdict(list)
item = (self.compress, output)
if item not in static_grouper_dict[self.static_type]:
static_grouper_dict[self.static_type].append(item)
return ''
register.tag('addstatic', AddStaticNode)
class StaticListNode(Node):
def __init__(self, parser, token):
contents = token.split_contents()
if len(contents) not in (2, 3):
raise TemplateSyntaxError
self.static_type = contents[1]
if len(contents) == 3:
assert contents[2] == 'compress'
self.compress = True
else:
self.compress = False
self.following_nodelist = parser.parse()
def groups_iterator(self, static_grouper_dict):
compressed_group = []
for compress, output in static_grouper_dict[self.static_type]:
if compress:
compressed_group.append(output)
else:
if compressed_group:
yield True, ''.join(compressed_group)
compressed_group = []
yield False, output
if compressed_group:
yield True, ''.join(compressed_group)
def render(self, context):
static_grouper_dict = context.get(CONTEXT_VARIABLE_NAME, defaultdict(list))
following = self.following_nodelist.render(context)
inner = ''
for compress, output in self.groups_iterator(static_grouper_dict):
if compress and self.compress:
inner += CompressorNode(
nodelist=Template(output).nodelist, kind=self.static_type,
mode='file').render(context=context)
else:
inner += output
return inner + following
register.tag('static_list', StaticListNode)
| from collections import defaultdict
from compressor.templatetags.compress import CompressorNode
from django.template import Library, Node, Template, TemplateSyntaxError
register = Library()
CONTEXT_VARIABLE_NAME = 'static_grouper_dict'
class AddStaticNode(Node):
def __init__(self, parser, token):
contents = token.split_contents()
if len(contents) not in (2, 3):
raise TemplateSyntaxError
if len(contents) == 3:
assert contents[2] == 'nocompress'
self.compress = False
else:
self.compress = True
self.static_type = contents[1]
self.nodelist = parser.parse(('endaddstatic',))
parser.delete_first_token()
def render(self, context):
output = self.nodelist.render(context).strip()
static_grouper_dict = context.get(CONTEXT_VARIABLE_NAME)
if static_grouper_dict is None:
root_context = context.dicts[0]
root_context[CONTEXT_VARIABLE_NAME] = \
static_grouper_dict = defaultdict(list)
if output not in static_grouper_dict[self.static_type]:
static_grouper_dict[self.static_type].append(
(self.compress, output))
return ''
register.tag('addstatic', AddStaticNode)
class StaticListNode(Node):
def __init__(self, parser, token):
contents = token.split_contents()
if len(contents) not in (2, 3):
raise TemplateSyntaxError
self.static_type = contents[1]
if len(contents) == 3:
assert contents[2] == 'compress'
self.compress = True
else:
self.compress = False
self.following_nodelist = parser.parse()
def groups_iterator(self, static_grouper_dict):
compressed_group = []
for compress, output in static_grouper_dict[self.static_type]:
if compress:
compressed_group.append(output)
else:
if compressed_group:
yield True, ''.join(compressed_group)
compressed_group = []
yield False, output
if compressed_group:
yield True, ''.join(compressed_group)
def render(self, context):
static_grouper_dict = context.get(CONTEXT_VARIABLE_NAME, defaultdict(list))
following = self.following_nodelist.render(context)
inner = ''
for compress, output in self.groups_iterator(static_grouper_dict):
if compress and self.compress:
inner += CompressorNode(
nodelist=Template(output).nodelist, kind=self.static_type,
mode='file').render(context=context)
else:
inner += output
return inner + following
register.tag('static_list', StaticListNode)
| Python | 0 |
bf4cf008fb8eadd5a0b8b23a330a49fdea272314 | Convert exception to string | tests/cases/cloud_provider_test.py | tests/cases/cloud_provider_test.py | import unittest
import os
from cumulus.ansible.tasks.providers import CloudProvider, EC2Provider
class CloudProviderTestCase(unittest.TestCase):
def setup(self):
pass
def tearDown(self):
pass
def test_empty_profile(self):
with self.assertRaises(AssertionError) as context:
p = CloudProvider({})
self.assertTrue('Profile does not have a "cloudProvider" attribute'
in str(context.exception))
def test_ec2_profile(self):
p = CloudProvider({'cloudProvider': 'ec2'})
self.assertTrue(isinstance(p, EC2Provider))
| import unittest
import os
from cumulus.ansible.tasks.providers import CloudProvider, EC2Provider
class CloudProviderTestCase(unittest.TestCase):
def setup(self):
pass
def tearDown(self):
pass
def test_empty_profile(self):
with self.assertRaises(AssertionError) as context:
p = CloudProvider({})
self.assertTrue('Profile does not have a "cloudProvider" attribute'
in context.exception)
def test_ec2_profile(self):
p = CloudProvider({'cloudProvider': 'ec2'})
self.assertTrue(isinstance(p, EC2Provider))
| Python | 0.999979 |
0ac1cdfd59199d3c36ddbccc7c5004261b57f7be | Add api.python.failing_step | recipe_modules/python/api.py | recipe_modules/python/api.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from slave import recipe_api
from slave import recipe_util
import textwrap
class PythonApi(recipe_api.RecipeApi):
def __call__(self, name, script, args=None, unbuffered=True, **kwargs):
"""Return a step to run a python script with arguments."""
cmd = ['python']
if unbuffered:
cmd.append('-u')
cmd.append(script)
return self.m.step(name, cmd + list(args or []), **kwargs)
def inline(self, name, program, add_python_log=True, **kwargs):
"""Run an inline python program as a step.
Program is output to a temp file and run when this step executes.
"""
program = textwrap.dedent(program)
compile(program, '<string>', 'exec', dont_inherit=1)
try:
self(name, self.m.raw_io.input(program, '.py'), **kwargs)
finally:
result = self.m.step.active_result
if add_python_log:
result.presentation.logs['python.inline'] = program.splitlines()
return result
def failing_step(self, name, text):
"""Return a failng step (correctly recognized in expectations)."""
try:
self.inline(name,
'import sys; sys.exit(1)',
add_python_log=False,
step_test_data=lambda: self.m.raw_io.test_api.output(
text, retcode=1))
finally:
self.m.step.active_result.presentation.step_text = text
| # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from slave import recipe_api
from slave import recipe_util
import textwrap
class PythonApi(recipe_api.RecipeApi):
def __call__(self, name, script, args=None, unbuffered=True, **kwargs):
"""Return a step to run a python script with arguments."""
cmd = ['python']
if unbuffered:
cmd.append('-u')
cmd.append(script)
return self.m.step(name, cmd + list(args or []), **kwargs)
def inline(self, name, program, add_python_log=True, **kwargs):
"""Run an inline python program as a step.
Program is output to a temp file and run when this step executes.
"""
program = textwrap.dedent(program)
compile(program, '<string>', 'exec', dont_inherit=1)
try:
self(name, self.m.raw_io.input(program, '.py'), **kwargs)
finally:
result = self.m.step.active_result
if add_python_log:
result.presentation.logs['python.inline'] = program.splitlines()
return result
| Python | 0.000053 |
b1653d7a9589766a86141034865d9023b1f75fad | Fix as_tensor_test | tests/as_tensor_test.py | tests/as_tensor_test.py | import unittest
from tfi.as_tensor import as_tensor
from functools import partialmethod
class AsTensorTest(unittest.TestCase):
pass
_FIXTURES = [
('string', 'string', [], str, 'string'),
('list', ['string'], [None], str, ['string']),
('list', ['string'], [1], str, ['string']),
('generator', (s for s in ['string']), [1], str, ['string']),
('emptylist', [], [None], float, []),
('emptylist', [], [0], float, []),
('nested_list', [['string'], ['foo']], [2,1], str, [['string'], ['foo']]),
]
for (name, *rest) in _FIXTURES:
def do_test(self, expect, shape, dtype, data):
result = as_tensor(data, shape, dtype)
self.assertEqual(expect, result)
setattr(AsTensorTest,
'test_%s' % name,
partialmethod(do_test, *rest))
if __name__ == '__main__':
unittest.main()
| import unittest
from as_tensor import as_tensor
class AsTensorTest(unittest.TestCase):
pass
_FIXTURES = [
('string', 'string', [], 'string'),
('list', ['string'], [None], ['string']),
('list', ['string'], [1], ['string']),
('generator', (s for s in ['string']), [1], ['string']),
('emptylist', [], [None], []),
('emptylist', [], [0], []),
('nested_list', [['string'], ['foo']], [2,1], [['string'], ['foo']]),
]
for (name, expect, shape, data) in _FIXTURES:
def do_test(self):
result = as_tensor(data, shape)
self.assertEqual(expect, result)
setattr(AsTensorTest, 'test_%s' % name, do_test)
if __name__ == '__main__':
unittest.main()
| Python | 0.999412 |
55726db079313570fb9889ae91a4664f2e2daa98 | add buttons to choose task | methods/homeworks.py | methods/homeworks.py | from enum import Enum, auto
from telegram.ext import CommandHandler, MessageHandler, Filters
from telegram.ext.conversationhandler import ConversationHandler
from telegram.message import Message
from telegram.replykeyboardmarkup import ReplyKeyboardMarkup
from telegram.update import Update
from lyceum_api import get_check_queue
from lyceum_api.issue import QueueTask
from methods.auth import get_user
class State(Enum):
not_logged_in = auto()
def handle_hw(bot, update: Update):
user = get_user(update.message)
if not user:
update.message.reply_text('Not logged in')
return ConversationHandler.END
q = [QueueTask(t) for t in get_check_queue(user.sid)]
tasks = [['{} -- {}'.format(t.task_title, t.student_name)] for t in q]
markup = ReplyKeyboardMarkup(tasks, one_time_keyboard=True)
update.message.reply_text('Выберите задание на проверку',
reply_markup=markup)
return ConversationHandler.END
# def on_choose(bot, update):
# message: Message = update.message
conv_handler = ConversationHandler(
entry_points=[CommandHandler('hw', handle_hw, Filters.private)],
states={
# States.username: [MessageHandler(Filters.text,
# handle_username,
# pass_user_data=True)],
# States.password: [MessageHandler(Filters.text,
# handle_password,
# pass_user_data=True)]
},
fallbacks=[]
)
| from enum import Enum, auto
from telegram.ext import CommandHandler, MessageHandler, Filters
from telegram.ext.conversationhandler import ConversationHandler
from telegram.message import Message
from telegram.update import Update
from lyceum_api import get_check_queue
from lyceum_api.issue import QueueTask
from methods.auth import get_user
class State(Enum):
not_logged_in = auto()
def handle_hw(bot, update: Update):
user = get_user(update.message)
if not user:
update.message.reply_text('Not logged in')
return ConversationHandler.END
q = [QueueTask(t) for t in get_check_queue(user.sid)]
tasks = ('Задания на проверку:\n' +
'\n'.join('{} -- {}'.format(t.task_title, t.student_name) for t in q))
update.message.reply_text(tasks)
return ConversationHandler.END
# def on_choose(bot, update):
# message: Message = update.message
conv_handler = ConversationHandler(
entry_points=[CommandHandler('hw', handle_hw, Filters.private)],
states={
# States.username: [MessageHandler(Filters.text,
# handle_username,
# pass_user_data=True)],
# States.password: [MessageHandler(Filters.text,
# handle_password,
# pass_user_data=True)]
},
fallbacks=[]
)
| Python | 0.000017 |
fd61f3cfbcd520b1b5fc9208c553ee946cced517 | Remove duplicates from compression levels tests | tests/frame/conftest.py | tests/frame/conftest.py | import pytest
# import random
import lz4.frame as lz4frame
@pytest.fixture(
params=[
(lz4frame.BLOCKSIZE_DEFAULT),
(lz4frame.BLOCKSIZE_MAX64KB),
(lz4frame.BLOCKSIZE_MAX256KB),
(lz4frame.BLOCKSIZE_MAX1MB),
(lz4frame.BLOCKSIZE_MAX4MB),
]
)
def block_size(request):
return request.param
@pytest.fixture(
params=[
(lz4frame.BLOCKMODE_LINKED),
(lz4frame.BLOCKMODE_INDEPENDENT),
]
)
def block_mode(request):
return request.param
@pytest.fixture(
params=[
(lz4frame.CONTENTCHECKSUM_DISABLED),
(lz4frame.CONTENTCHECKSUM_ENABLED),
]
)
def content_checksum(request):
return request.param
compression_levels = list(range(-5, 13)) + [
lz4frame.COMPRESSIONLEVEL_MIN,
lz4frame.COMPRESSIONLEVEL_MINHC,
lz4frame.COMPRESSIONLEVEL_MAX,
]
compression_levels = [
# Although testing with all compression levels is desirable, the number of
# tests becomes too large. So, we'll select some compression levels at
# random.
# (i) for i in random.sample(set(compression_levels), k=2)
(i) for i in set(compression_levels)
]
@pytest.fixture(
params=compression_levels
)
def compression_level(request):
return request.param
@pytest.fixture(
params=[
(True),
(False)
]
)
def auto_flush(request):
return request.param
@pytest.fixture(
params=[
(True),
(False)
]
)
def store_size(request):
return request.param
| import pytest
# import random
import lz4.frame as lz4frame
@pytest.fixture(
params=[
(lz4frame.BLOCKSIZE_DEFAULT),
(lz4frame.BLOCKSIZE_MAX64KB),
(lz4frame.BLOCKSIZE_MAX256KB),
(lz4frame.BLOCKSIZE_MAX1MB),
(lz4frame.BLOCKSIZE_MAX4MB),
]
)
def block_size(request):
return request.param
@pytest.fixture(
params=[
(lz4frame.BLOCKMODE_LINKED),
(lz4frame.BLOCKMODE_INDEPENDENT),
]
)
def block_mode(request):
return request.param
@pytest.fixture(
params=[
(lz4frame.CONTENTCHECKSUM_DISABLED),
(lz4frame.CONTENTCHECKSUM_ENABLED),
]
)
def content_checksum(request):
return request.param
compression_levels = list(range(-5, 13)) + [
lz4frame.COMPRESSIONLEVEL_MIN,
lz4frame.COMPRESSIONLEVEL_MINHC,
lz4frame.COMPRESSIONLEVEL_MAX,
]
compression_levels = [
# Although testing with all compression levels is desirable, the number of
# tests becomes too large. So, we'll select some compression levels at
# random.
# (i) for i in random.sample(set(compression_levels), k=2)
(i) for i in compression_levels
]
@pytest.fixture(
params=compression_levels
)
def compression_level(request):
return request.param
@pytest.fixture(
params=[
(True),
(False)
]
)
def auto_flush(request):
return request.param
@pytest.fixture(
params=[
(True),
(False)
]
)
def store_size(request):
return request.param
| Python | 0.000001 |
f6861a57069306046f4d9b40daaede06d3618a53 | Lowercase for consistency | tests/generate_tests.py | tests/generate_tests.py |
from __future__ import print_function
from subprocess import check_output
from os import listdir
from os.path import join
from time import sleep
from utils import Colour, FoundError, getCurrentAbsolutePath, existsIn, EXEC, WHITE_LISTED_EXTENSIONS
dir_path = getCurrentAbsolutePath(__file__)
# (path/to/tests, infrared_command)
LEXER_TESTS = (join(dir_path, "lexer"), "tokenize")
PARSER_TESTS = (join(dir_path, "parser"), "parse")
jobs = [
LEXER_TESTS,
PARSER_TESTS
]
for job in jobs:
print(Colour.BOLD + "\nGENERATING TESTS: " + Colour.END + job[0])
try:
# We don't want to check any dotfiles in these directories
directories = [f for f in listdir(job[0]) if f[0] != "."]
except:
print("Directory was not found: " + job[0])
continue
for path in directories:
real_path = join(job[0], path)
print(Colour.LIGHT_GRAY + u'\u25F4' + " BUILDING " + Colour.END + path, end="\r")
try:
# Find test file (we only expect 1 file at the moment)
files = listdir(real_path)
files_valid = [f for f in files if existsIn(WHITE_LISTED_EXTENSIONS, f[-3:])]
if len(files_valid) != 1: raise
file = join(real_path, files_valid[0])
output = check_output([EXEC, job[1], file])
# Check output for simple errors
if (output.find("Syntax_Error") != -1 or
output.find("Unknown_Token") != -1):
raise FoundError
# Create expected output file
file_exp_name = file[:-3] + ".exp"
file_exp = open(file_exp_name, "w")
file_exp.write(output)
file_exp.close()
print(Colour.GREEN + u'\u2714' + " done " + Colour.END + path + " ")
except FoundError:
print(Colour.RED + u'\u2715' + " fail " + Colour.END + path + ": " +
Colour.LIGHT_GRAY + "Syntax_Error or Unknown_Token encountered" + Colour.END)
except:
print(Colour.RED + u'\u2715' + " error " + Colour.END + path + " ")
|
from __future__ import print_function
from subprocess import check_output
from os import listdir
from os.path import join
from time import sleep
from utils import Colour, FoundError, getCurrentAbsolutePath, existsIn, EXEC, WHITE_LISTED_EXTENSIONS
dir_path = getCurrentAbsolutePath(__file__)
# (path/to/tests, infrared_command)
LEXER_TESTS = (join(dir_path, "lexer"), "tokenize")
PARSER_TESTS = (join(dir_path, "parser"), "parse")
jobs = [
LEXER_TESTS,
PARSER_TESTS
]
for job in jobs:
print(Colour.BOLD + "\nGENERATING TESTS: " + Colour.END + job[0])
try:
# We don't want to check any dotfiles in these directories
directories = [f for f in listdir(job[0]) if f[0] != "."]
except:
print("Directory was not found: " + job[0])
continue
for path in directories:
real_path = join(job[0], path)
print(Colour.LIGHT_GRAY + u'\u25F4' + " BUILDING " + Colour.END + path, end="\r")
try:
# Find test file (we only expect 1 file at the moment)
files = listdir(real_path)
files_valid = [f for f in files if existsIn(WHITE_LISTED_EXTENSIONS, f[-3:])]
if len(files_valid) != 1: raise
file = join(real_path, files_valid[0])
output = check_output([EXEC, job[1], file])
# Check output for simple errors
if (output.find("Syntax_Error") != -1 or
output.find("Unknown_Token") != -1):
raise FoundError
# Create expected output file
file_exp_name = file[:-3] + ".exp"
file_exp = open(file_exp_name, "w")
file_exp.write(output)
file_exp.close()
print(Colour.GREEN + u'\u2714' + " DONE " + Colour.END + path + " ")
except FoundError:
print(Colour.RED + u'\u2715' + " FAIL " + Colour.END + path + ": " +
Colour.LIGHT_GRAY + "Syntax_Error or Unknown_Token encountered" + Colour.END)
except:
print(Colour.RED + u'\u2715' + " ERROR " + Colour.END + path + " ")
| Python | 0.998717 |
1c6ed4130baacf0d0f662b6aa056630dd7fd383d | Fix vocab splitting | spraakbanken/s5/spr_local/make_recog_vocab.py | spraakbanken/s5/spr_local/make_recog_vocab.py | #!/usr/bin/env python3
import sys
import collections
def main(in_vocab, size, out_vocab,):
counter = collections.Counter()
size = int(size)
for line in open(in_vocab, encoding='utf-8'):
word, count = line.rstrip("\n").split(" ")
if any(x.isdigit() for x in word):
continue
punctuation = "\\/?.,!;:\"\'()-=+[]%§*¤ïÐ$&<>#@{}"
if any(x in punctuation for x in word):
continue
counter[word] += int(count)
with open(out_vocab, 'w', encoding='utf-8') as out_f:
for w, c in counter.most_common(size):
print(w, file=out_f)
if __name__ == "__main__":
if len(sys.argv) != 4:
exit("3 arguments: in_vocab, desired_size, out_vocab")
main(*sys.argv[1:])
| #!/usr/bin/env python3
import sys
import collections
def main(in_vocab, size, out_vocab,):
counter = collections.Counter()
size = int(size)
for line in open(in_vocab, encoding='utf-8'):
word, count = line.strip().split()
if any(x.isdigit() for x in word):
continue
punctuation = "\\/?.,!;:\"\'()-=+[]%§*¤ïÐ$&<>#@{}"
if any(x in punctuation for x in word):
continue
counter[word] += int(count)
with open(out_vocab, 'w', encoding='utf-8') as out_f:
for w, c in counter.most_common(size):
print(w, file=out_f)
if __name__ == "__main__":
if len(sys.argv) != 4:
exit("3 arguments: in_vocab, desired_size, out_vocab")
main(*sys.argv[1:])
| Python | 0.003701 |
7be728d551d7d2becd70b575f95facbbd561e69b | Add latest version of libsigsegv (#3449) | var/spack/repos/builtin/packages/libsigsegv/package.py | var/spack/repos/builtin/packages/libsigsegv/package.py | ##############################################################################
# Copyright (c) 2013-2016, 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-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Libsigsegv(AutotoolsPackage):
"""GNU libsigsegv is a library for handling page faults in user mode."""
homepage = "https://www.gnu.org/software/libsigsegv/"
url = "https://ftp.gnu.org/gnu/libsigsegv/libsigsegv-2.11.tar.gz"
patch('patch.new_config_guess', when='@2.10')
version('2.11', 'a812d9481f6097f705599b218eea349f')
version('2.10', '7f96fb1f65b3b8cbc1582fb7be774f0f')
def configure_args(self):
return ['--enable-shared']
| ##############################################################################
# Copyright (c) 2013-2016, 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-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Libsigsegv(AutotoolsPackage):
"""GNU libsigsegv is a library for handling page faults in user mode."""
homepage = "https://www.gnu.org/software/libsigsegv/"
url = "https://ftp.gnu.org/gnu/libsigsegv/libsigsegv-2.10.tar.gz"
patch('patch.new_config_guess', when='@2.10')
version('2.10', '7f96fb1f65b3b8cbc1582fb7be774f0f')
def configure_args(self):
return ['--enable-shared']
| Python | 0 |
20a89ca326712058f3f22621eed725c0f510bee3 | Add branch with bugfix (#8355) | var/spack/repos/builtin/packages/meraculous/package.py | var/spack/repos/builtin/packages/meraculous/package.py | ##############################################################################
# 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-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Meraculous(CMakePackage):
"""Meraculous is a while genome assembler for Next Generation Sequencing
data geared for large genomes."""
homepage = "http://jgi.doe.gov/data-and-tools/meraculous/"
url = "https://downloads.sourceforge.net/project/meraculous20/Meraculous-v2.2.4.tar.gz"
version('2.2.5.1',
git="https://bitbucket.org/berkeleylab/genomics-meraculous2.git",
branch="release-2.2.5.1")
version('2.2.4', '349feb6cb178643a46e4b092c87bad3a')
depends_on('perl', type=('build', 'run'))
depends_on('boost@1.5.0:')
depends_on('gnuplot@3.7:')
depends_on('perl-log-log4perl', type=('build', 'run'))
conflicts('%gcc@6.0.0:', when='@2.2.4')
def patch(self):
edit = FileFilter('CMakeLists.txt')
edit.filter("-static-libstdc\+\+", "")
def setup_environment(self, spack_env, run_env):
run_env.set('MERACULOUS_ROOT', self.prefix)
run_env.prepend_path('PERL5LIB', self.prefix.lib)
| ##############################################################################
# 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-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Meraculous(CMakePackage):
"""Meraculous is a while genome assembler for Next Generation Sequencing
data geared for large genomes."""
homepage = "http://jgi.doe.gov/data-and-tools/meraculous/"
url = "https://downloads.sourceforge.net/project/meraculous20/Meraculous-v2.2.4.tar.gz"
version('2.2.4', '349feb6cb178643a46e4b092c87bad3a')
depends_on('perl', type=('build', 'run'))
depends_on('boost@1.5.0:')
depends_on('gnuplot@3.7:')
depends_on('perl-log-log4perl', type=('build', 'run'))
conflicts('%gcc@6.0.0:', when='@2.2.4')
def patch(self):
edit = FileFilter('CMakeLists.txt')
edit.filter("-static-libstdc\+\+", "")
def setup_environment(self, spack_env, run_env):
run_env.set('MERACULOUS_ROOT', self.prefix)
run_env.prepend_path('PERL5LIB', self.prefix.lib)
| Python | 0 |
5d608a855132f0a378e44b3c0c7dbba1f4f4dace | fix corehq.messaging.smsbackends.twilio.tests.test_log_call:TwilioLogCallTestCase.test_log_call | corehq/messaging/smsbackends/twilio/tests/test_log_call.py | corehq/messaging/smsbackends/twilio/tests/test_log_call.py | from __future__ import absolute_import
from __future__ import unicode_literals
import corehq.apps.ivr.tests.util as util
from corehq.apps.ivr.models import Call
from corehq.messaging.smsbackends.twilio.models import SQLTwilioBackend
from corehq.messaging.smsbackends.twilio.views import IVR_RESPONSE
from django.test import Client
class TwilioLogCallTestCase(util.LogCallTestCase):
def setUp(self):
super(TwilioLogCallTestCase, self).setUp()
self.backend = SQLTwilioBackend.objects.create(
name='TWILIO',
is_global=True,
hq_api_id=SQLTwilioBackend.get_api_id()
)
def tearDown(self):
self.backend.delete()
super(TwilioLogCallTestCase, self).tearDown()
def test_401_response(self):
with self.create_case():
start_count = Call.by_domain(self.domain).count()
response = Client().post('/twilio/ivr/xxxxx', {
'From': self.phone_number,
'CallSid': 'xyz',
})
self.assertEqual(response.status_code, 401)
end_count = Call.by_domain(self.domain).count()
self.assertEqual(start_count, end_count)
def simulate_inbound_call(self, phone_number):
url = '/twilio/ivr/%s' % self.backend.inbound_api_key
return Client().post(url, {
'From': phone_number,
'CallSid': 'xyz',
})
def check_response(self, response):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content.decode('utf-8'), IVR_RESPONSE)
| from __future__ import absolute_import
from __future__ import unicode_literals
import corehq.apps.ivr.tests.util as util
from corehq.apps.ivr.models import Call
from corehq.messaging.smsbackends.twilio.models import SQLTwilioBackend
from corehq.messaging.smsbackends.twilio.views import IVR_RESPONSE
from django.test import Client
class TwilioLogCallTestCase(util.LogCallTestCase):
def setUp(self):
super(TwilioLogCallTestCase, self).setUp()
self.backend = SQLTwilioBackend.objects.create(
name='TWILIO',
is_global=True,
hq_api_id=SQLTwilioBackend.get_api_id()
)
def tearDown(self):
self.backend.delete()
super(TwilioLogCallTestCase, self).tearDown()
def test_401_response(self):
with self.create_case():
start_count = Call.by_domain(self.domain).count()
response = Client().post('/twilio/ivr/xxxxx', {
'From': self.phone_number,
'CallSid': 'xyz',
})
self.assertEqual(response.status_code, 401)
end_count = Call.by_domain(self.domain).count()
self.assertEqual(start_count, end_count)
def simulate_inbound_call(self, phone_number):
url = '/twilio/ivr/%s' % self.backend.inbound_api_key
return Client().post(url, {
'From': phone_number,
'CallSid': 'xyz',
})
def check_response(self, response):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, IVR_RESPONSE)
| Python | 0.000002 |
968f0f3d41a546c4c6614d24be3e077ba1ee37b9 | Reorganiza imports de xml_utils | packtools/sps/utils/xml_utils.py | packtools/sps/utils/xml_utils.py | import logging
import re
from copy import deepcopy
from lxml import etree
from packtools.sps import exceptions
from packtools.sps.utils import file_utils
logger = logging.getLogger(__name__)
class LoadToXMLError(Exception):
...
def fix_xml(xml_str):
return fix_namespace_prefix_w(xml_str)
def fix_namespace_prefix_w(content):
"""
Convert os textos cujo padrão é `w:st="` em `w-st="`
"""
pattern = r"\bw:[a-z]{1,}=\""
found_items = re.findall(pattern, content)
logger.debug("Found %i namespace prefix w", len(found_items))
for item in set(found_items):
new_namespace = item.replace(":", "-")
logger.debug("%s -> %s" % (item, new_namespace))
content = content.replace(item, new_namespace)
return content
def _get_xml_content(xml):
if isinstance(xml, str):
try:
content = read_file(xml)
except (FileNotFoundError, OSError):
content = xml
content = fix_xml(content)
return content.encode("utf-8")
return xml
def get_xml_tree(content):
parser = etree.XMLParser(remove_blank_text=True, no_network=True)
try:
content = _get_xml_content(content)
xml_tree = etree.XML(content, parser)
# if isinstance(content, str):
# # xml_tree = etree.parse(BytesIO(content.encode("utf-8")), parser)
# xml_tree = etree.parse(StringIO(content), parser)
# else:
# # content == zipfile.read(sps_xml_file)
# except ValueError as exc:
# xml_tree = etree.XML(content, parser)
except etree.XMLSyntaxError as exc:
raise LoadToXMLError(str(exc)) from None
else:
return xml_tree
def tostring(node, doctype=None, pretty_print=False):
return etree.tostring(
node,
doctype=doctype,
xml_declaration=True,
method="xml",
encoding="utf-8",
pretty_print=pretty_print,
).decode("utf-8")
def node_text(node, doctype=None, pretty_print=False):
items = [node.text or ""]
for child in node.getchildren():
items.append(
etree.tostring(child, encoding="utf-8").decode("utf-8")
)
return "".join(items)
| import logging
import re
from lxml import etree
from dsm.utils.files import read_file
logger = logging.getLogger(__name__)
class LoadToXMLError(Exception):
...
def fix_xml(xml_str):
return fix_namespace_prefix_w(xml_str)
def fix_namespace_prefix_w(content):
"""
Convert os textos cujo padrão é `w:st="` em `w-st="`
"""
pattern = r"\bw:[a-z]{1,}=\""
found_items = re.findall(pattern, content)
logger.debug("Found %i namespace prefix w", len(found_items))
for item in set(found_items):
new_namespace = item.replace(":", "-")
logger.debug("%s -> %s" % (item, new_namespace))
content = content.replace(item, new_namespace)
return content
def _get_xml_content(xml):
if isinstance(xml, str):
try:
content = read_file(xml)
except (FileNotFoundError, OSError):
content = xml
content = fix_xml(content)
return content.encode("utf-8")
return xml
def get_xml_tree(content):
parser = etree.XMLParser(remove_blank_text=True, no_network=True)
try:
content = _get_xml_content(content)
xml_tree = etree.XML(content, parser)
# if isinstance(content, str):
# # xml_tree = etree.parse(BytesIO(content.encode("utf-8")), parser)
# xml_tree = etree.parse(StringIO(content), parser)
# else:
# # content == zipfile.read(sps_xml_file)
# except ValueError as exc:
# xml_tree = etree.XML(content, parser)
except etree.XMLSyntaxError as exc:
raise LoadToXMLError(str(exc)) from None
else:
return xml_tree
def tostring(node, doctype=None, pretty_print=False):
return etree.tostring(
node,
doctype=doctype,
xml_declaration=True,
method="xml",
encoding="utf-8",
pretty_print=pretty_print,
).decode("utf-8")
def node_text(node, doctype=None, pretty_print=False):
items = [node.text or ""]
for child in node.getchildren():
items.append(
etree.tostring(child, encoding="utf-8").decode("utf-8")
)
return "".join(items)
| Python | 0 |
4671e4a1f8f18ec26180a5b4093d70e7d3913302 | fix for mk language | plugins/tts.py | plugins/tts.py | import aiohttp
from plugin_system import Plugin
plugin = Plugin('Голос', usage="скажи [выражение] - бот сформирует "
"голосовое сообщение на основе текста")
try:
from gtts import gTTS
import langdetect
except ImportError:
plugin.log('gTTS или langdetect не установлены, плагин Голос не будет работать')
gTTS = None
langdetect = None
FAIL_MSG = 'Я не смог это произнести :('
@plugin.on_command('скажи')
async def say_text(msg, args):
if not gTTS or not langdetect:
return await msg.answer('Я не могу говорить, '
'так как у меня не хватает модулей :(')
text = ' '.join(args)
try:
# Используется Google Text To Speech и библиотека langdetect
lang = langdetect.detect(text)
if lang == 'mk':
# Иногда langdetect детектит русский как македонский
lang = 'ru'
tts = gTTS(text=text, lang=lang)
except Exception as ex:
# На самом деле не все языки, которых нет в gTTS, не поддерживаются
# Например, gTTS считает, что GTTS не поддерживает украинский, хотя он поддерживает
if 'Language' in ex:
return await msg.answer('Данный язык не поддерживается.'
'Если вы считаете, что он должен поддерживаться,'
'напишите администратору бота!')
raise # Если эта ошибка не связана с gTTS, бросаем её ещё раз
# Сохраняем файл с голосом
tts.save('audio.mp3')
# Получаем URL для загрузки аудио сообщения
upload_server = await msg.vk.method('docs.getUploadServer', {'type':'audio_message'})
url = upload_server.get('upload_url')
if not url:
return await msg.answer(FAIL_MSG)
# Загружаем аудио через aiohttp
form_data = aiohttp.FormData()
form_data.add_field('file', open('audio.mp3', 'rb'))
async with aiohttp.post(url, data=form_data) as resp:
file_url = await resp.json()
file = file_url.get('file')
if not file:
return await msg.answer(FAIL_MSG)
# Сохраняем файл в документы (чтобы можно было прикрепить к сообщению)
saved_data = await msg.vk.method('docs.save', {'file':file} )
# Получаем первый элемент, так как мы сохранили 1 файл
media = saved_data[0]
media_id, owner_id = media['id'], media['owner_id']
# Прикрепляем аудио к сообщению :)
await msg.answer('', attachment=f'doc{owner_id}_{media_id}')
| import aiohttp
from plugin_system import Plugin
plugin = Plugin('Голос', usage="скажи [выражение] - бот сформирует "
"голосовое сообщение на основе текста")
try:
from gtts import gTTS
import langdetect
except ImportError:
plugin.log('gTTS или langdetect не установлены, плагин Голос не будет работать')
gTTS = None
langdetect = None
FAIL_MSG = 'Я не смог это произнести :('
@plugin.on_command('скажи')
async def say_text(msg, args):
if not gTTS or not langdetect:
return await msg.answer('Я не могу говорить, '
'так как у меня не хватает модулей :(')
text = ' '.join(args)
try:
# Используется Google Text To Speech и библиотека langdetect
tts = gTTS(text=text, lang=langdetect.detect(text))
except Exception as ex:
# На самом деле не все языки, которых нет в gTTS, не поддерживаются
# Например, gTTS считает, что GTTS не поддерживает украинский, хотя он поддерживает
if 'Language' in ex:
return await msg.answer('Данный язык не поддерживается.'
'Если вы считаете, что он должен поддерживаться,'
'напишите администратору бота!')
raise # Если эта ошибка не связана с gTTS, бросаем её ещё раз
# Сохраняем файл с голосом
tts.save('audio.mp3')
# Получаем URL для загрузки аудио сообщения
upload_server = await msg.vk.method('docs.getUploadServer', {'type':'audio_message'})
url = upload_server.get('upload_url')
if not url:
return await msg.answer(FAIL_MSG)
# Загружаем аудио через aiohttp
form_data = aiohttp.FormData()
form_data.add_field('file', open('audio.mp3', 'rb'))
async with aiohttp.post(url, data=form_data) as resp:
file_url = await resp.json()
file = file_url.get('file')
if not file:
return await msg.answer(FAIL_MSG)
# Сохраняем файл в документы (чтобы можно было прикрепить к сообщению)
saved_data = await msg.vk.method('docs.save', {'file':file} )
# Получаем первый элемент, так как мы сохранили 1 файл
media = saved_data[0]
media_id, owner_id = media['id'], media['owner_id']
# Прикрепляем аудио к сообщению :)
await msg.answer('', attachment=f'doc{owner_id}_{media_id}')
| Python | 0.000001 |
713fd67b4aa0d3a614ca149f86deeb2d5e913d12 | fix installation on linux (#24706) | var/spack/repos/builtin/packages/py-keyring/package.py | var/spack/repos/builtin/packages/py-keyring/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyKeyring(PythonPackage):
"""The Python keyring library provides an easy way to access the system keyring
service from python. It can be used in any application that needs safe password
storage."""
homepage = "https://github.com/jaraco/keyring"
pypi = "keyring/keyring-23.0.1.tar.gz"
version('23.0.1', sha256='045703609dd3fccfcdb27da201684278823b72af515aedec1a8515719a038cb8')
depends_on('python@3.6:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-setuptools-scm@3.4.1:+toml', type='build')
depends_on('py-importlib-metadata@3.6:', type=('build', 'run'))
depends_on('py-secretstorage@3.2:', type=('build', 'run'), when='platform=linux')
depends_on('py-jeepney@0.4.2:', type=('build', 'run'), when='platform=linux')
# TODO: additional dependency on pywin32-ctypes required for Windows
| # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyKeyring(PythonPackage):
"""The Python keyring library provides an easy way to access the system keyring
service from python. It can be used in any application that needs safe password
storage."""
homepage = "https://github.com/jaraco/keyring"
pypi = "keyring/keyring-23.0.1.tar.gz"
version('23.0.1', sha256='045703609dd3fccfcdb27da201684278823b72af515aedec1a8515719a038cb8')
depends_on('python@3.6:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-setuptools-scm@3.4.1:+toml', type='build')
depends_on('py-importlib-metadata@3.6:', type=('build', 'run'))
# TODO: additional dependencies required for Windows/Linux
| Python | 0 |
e11f99e43ff9d909bf97f050c560663d38fb1388 | Add fixture/result subdirectory. | test/unit/staging/test_link_dicom.py | test/unit/staging/test_link_dicom.py | from nose.tools import *
import os, glob, shutil
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..'))
from qipipe.staging import link_dicom_files
# The test parent directory.
ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', 'link_dicom')
# The test results.
RESULTS = os.path.join(ROOT, 'results', 'staging', 'link_dicom')
# The test result target.
TARGET = os.path.join(RESULTS, 'data')
# The test result delta.
DELTA = os.path.join(RESULTS, 'delta')
class TestLinkDicom:
"""TCIA dicom link unit tests."""
def test_link_dicom_files(self):
shutil.rmtree(RESULTS, True)
src_pnt_dirs = glob.glob(FIXTURE + '/*')
opts = {'target': TARGET, 'include': '*concat*/*'}
args = src_pnt_dirs + [opts]
staging.link_dicom_files(*args)
# Verify that there are no broken links.
for root, dirs, files in os.walk(TARGET):
for f in files:
tgt_file = os.path.join(root, f)
assert_true(os.path.islink(tgt_file), "Missing source -> target target link: %s" % tgt_file)
assert_true(os.path.exists(tgt_file), "Broken source -> target link: %s" % tgt_file)
# Test incremental delta.
tgt = os.path.join(TARGET, 'patient01', 'visit02')
# Clean the partial result.
shutil.rmtree(tgt, True)
# Clean the delta tree.
shutil.rmtree(DELTA, True)
# Add the delta argument.
opts['delta'] = DELTA
# Rerun to capture the delta.
staging.link_dicom_files(*args)
delta = os.path.join(DELTA, 'patient01', 'visit02')
assert_true(os.path.islink(delta), "Missing delta -> target link: %s" % delta)
assert_true(os.path.exists(delta), "Broken delta -> target link: %s" % delta)
real_tgt = os.path.realpath(tgt)
real_delta = os.path.realpath(delta)
assert_equal(real_tgt, real_delta, "Delta does not reference the target: %s" % delta)
non_delta = os.path.join(DELTA, 'patient01', 'visit01')
assert_false(os.path.exists(non_delta), "Incorrectly added a target -> delta link in %s" % non_delta)
# Cleanup.
shutil.rmtree(RESULTS, True)
if __name__ == "__main__":
import nose
nose.main(defaultTest=__name__)
| from nose.tools import *
import os, glob, shutil
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..'))
from qipipe import staging
# The test parent directory.
ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging')
# The test results.
RESULTS = os.path.join(ROOT, 'results', 'staging')
# The test result target.
TARGET = os.path.join(RESULTS, 'data')
# The test result delta.
DELTA = os.path.join(RESULTS, 'delta')
class TestLinkDicom:
"""TCIA dicom link unit tests."""
def test_link_dicom_files(self):
shutil.rmtree(RESULTS, True)
src_pnt_dirs = glob.glob(FIXTURE + '/*')
opts = {'target': TARGET, 'include': '*concat*/*'}
args = src_pnt_dirs + [opts]
staging.link_dicom_files(*args)
# Verify that there are no broken links.
for root, dirs, files in os.walk(TARGET):
for f in files:
tgt_file = os.path.join(root, f)
assert_true(os.path.islink(tgt_file), "Missing source -> target target link: %s" % tgt_file)
assert_true(os.path.exists(tgt_file), "Broken source -> target link: %s" % tgt_file)
# Test incremental delta.
tgt = os.path.join(TARGET, 'patient01', 'visit02')
# Clean the partial result.
shutil.rmtree(tgt, True)
# Clean the delta tree.
shutil.rmtree(DELTA, True)
# Add the delta argument.
opts['delta'] = DELTA
# Rerun to capture the delta.
staging.link_dicom_files(*args)
delta = os.path.join(DELTA, 'patient01', 'visit02')
assert_true(os.path.islink(delta), "Missing delta -> target link: %s" % delta)
assert_true(os.path.exists(delta), "Broken delta -> target link: %s" % delta)
real_tgt = os.path.realpath(tgt)
real_delta = os.path.realpath(delta)
assert_equal(real_tgt, real_delta, "Delta does not reference the target: %s" % delta)
non_delta = os.path.join(DELTA, 'patient01', 'visit01')
assert_false(os.path.exists(non_delta), "Incorrectly added a target -> delta link in %s" % non_delta)
# Cleanup.
shutil.rmtree(RESULTS, True)
if __name__ == "__main__":
import nose
nose.main(defaultTest=__name__)
| Python | 0 |
f06a4689fab32d7d2f4c848019978665656a5cdf | Implement hexfile record types used by GNU ld | mikroeuhb/hexfile.py | mikroeuhb/hexfile.py | import struct, logging
from binascii import unhexlify
from util import bord
logger = logging.getLogger(__name__)
def load(f, devkit):
"""Load a Intel HEX File from a file object into a devkit.
The devkit must implement a write(address,data) method."""
lineno = 0
base_addr = 0
for line in f.xreadlines():
lineno += 1
line = line.strip()
if line == '':
continue
if bord(line[0]) != ord(':'):
raise IOError('line %d: malformed' % lineno)
line = unhexlify(line[1:])
byte_count, address, record_type = struct.unpack('>BHB', line[:4])
correct_len = byte_count + 5
if len(line) != correct_len:
logger.warn('line %d: should have %d bytes -- truncating' % (lineno, correct_len))
line = line[:correct_len]
if sum(map(bord,line)) & 0xFF != 0:
raise IOError('line %d: incorrect checksum' % lineno)
data = line[4:-1]
if record_type == 0x00: # data record
devkit.write(base_addr + address, data)
elif record_type == 0x01: # end of file record
break
elif record_type == 0x04: # extended linear address record
if byte_count != 2:
raise IOError('line %d: extended linear address record must have 2 bytes of data' % lineno)
base_addr, = struct.unpack('>H', data)
base_addr <<= 16
elif record_type == 0x02: # extended segment address record
base_addr, = struct.unpack('>H', data)
base_addr <<= 4
elif record_type not in [0x03, 0x05]: # used for the initial PC (ignored)
raise IOError('line %d: unsupported record type %d' % (lineno, record_type))
| import struct, logging
from binascii import unhexlify
from util import bord
logger = logging.getLogger(__name__)
def load(f, devkit):
"""Load a Intel HEX File from a file object into a devkit.
The devkit must implement a write(address,data) method."""
lineno = 0
base_addr = 0
for line in f.xreadlines():
lineno += 1
line = line.strip()
if line == '':
continue
if bord(line[0]) != ord(':'):
raise IOError('line %d: malformed' % lineno)
line = unhexlify(line[1:])
byte_count, address, record_type = struct.unpack('>BHB', line[:4])
correct_len = byte_count + 5
if len(line) != correct_len:
logger.warn('line %d: should have %d bytes -- truncating' % (lineno, correct_len))
line = line[:correct_len]
if sum(map(bord,line)) & 0xFF != 0:
raise IOError('line %d: incorrect checksum' % lineno)
data = line[4:-1]
if record_type == 0x00: # data record
devkit.write(base_addr + address, data)
elif record_type == 0x01: # end of file record
break
elif record_type == 0x04: # extended linear address record
if byte_count != 2:
raise IOError('line %d: extended linear address record must have 2 bytes of data' % lineno)
base_addr, = struct.unpack('>H', data)
base_addr <<= 16
else:
raise IOError('line %d: unsupported record type %d' % (lineno, record_type))
| Python | 0 |
b9b3837937341e6b1b052bbfdd979e3bb57d87c4 | Fix SSL security provider integration tests | tests/integration/test_with_ssl.py | tests/integration/test_with_ssl.py | import os
from pymco.test import ctxt
from . import base
FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures')
class SSLTestCase(base.IntegrationTestCase):
'''RabbitMQ integration test case.'''
CTXT = {
'plugin.activemq.pool.1.port': 61614,
'plugin.activemq.pool.1.password': 'marionette',
'plugin.ssl_server_public': 'tests/fixtures/server-public.pem',
'plugin.ssl_client_private': 'tests/fixtures/client-private.pem',
'plugin.ssl_client_public': 'tests/fixtures/client-public.pem',
'plugin.ssl_server_private': os.path.join(FIXTURES_PATH,
'server-private.pem'),
'securityprovider': 'ssl',
'plugin.ssl_client_cert_dir': FIXTURES_PATH,
}
class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase):
'''MCollective integration test case.'''
class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase):
'''MCollective integration test case.'''
class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase):
'''MCollective integration test case.'''
| from . import base
class SSLTestCase(base.IntegrationTestCase):
'''RabbitMQ integration test case.'''
CTXT = {
'plugin.activemq.pool.1.port': 61614,
'plugin.activemq.pool.1.password': 'marionette',
'plugin.ssl_server_public': 'tests/fixtures/server-public.pem',
'plugin.ssl_client_private': 'tests/fixtures/client-private.pem',
'plugin.ssl_client_public': 'tests/fixtures/client-public.pem',
}
class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase):
'''MCollective integration test case.'''
class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase):
'''MCollective integration test case.'''
class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase):
'''MCollective integration test case.'''
| Python | 0 |
30bd0a8b50545e24ec69ecc4c720c508c318e008 | Remove pdb | tests/mock_vws/utils.py | tests/mock_vws/utils.py | """
Utilities for tests for the VWS mock.
"""
from string import hexdigits
from typing import Optional
from urllib.parse import urljoin
from requests.models import Response
from common.constants import ResultCodes
class Endpoint:
"""
Details of endpoints to be called in tests.
"""
def __init__(self,
example_path: str,
method: str,
successful_headers_result_code: ResultCodes,
successful_headers_status_code: int,
content_type: Optional[str],
content: bytes,
) -> None:
"""
Args:
example_path: An example path for calling the endpoint.
method: The HTTP method for the endpoint.
successful_headers_result_code: The expected result code if the
example path is requested with the method.
successful_headers_status_code: The expected status code if the
example path is requested with the method.
content: The data to send with the request.
Attributes:
example_path: An example path for calling the endpoint.
method: The HTTP method for the endpoint.
content_type: The `Content-Type` header to send, or `None` if one
should not be sent.
content: The data to send with the request.
url: The URL to call the path with.
successful_headers_result_code: The expected result code if the
example path is requested with the method.
successful_headers_status_code: The expected status code if the
example path is requested with the method.
"""
self.example_path = example_path
self.method = method
self.content_type = content_type
self.content = content
self.url = urljoin('https://vws.vuforia.com/', example_path)
self.successful_headers_status_code = successful_headers_status_code
self.successful_headers_result_code = successful_headers_result_code
def assert_vws_failure(response: Response,
status_code: int,
result_code: ResultCodes) -> None:
"""
Assert that a VWS failure response is as expected.
Args:
response: The response returned by a request to VWS.
status_code: The expected status code of the response.
result_code: The expected result code of the response.
Raises:
AssertionError: The response is not in the expected VWS error format
for the given codes.
"""
assert response.json().keys() == {'transaction_id', 'result_code'}
assert_vws_response(
response=response,
status_code=status_code,
result_code=result_code,
)
def assert_vws_response(response: Response,
status_code: int,
result_code: ResultCodes,
) -> None:
"""
Assert that a VWS response is as expected, at least in part.
https://library.vuforia.com/articles/Solution/How-To-Interperete-VWS-API-Result-Codes
implies that the expected status code can be worked out from the result
code. However, this is not the case as the real results differ from the
documentation.
For example, it is possible to get a "Fail" result code and a 400 error.
Args:
response: The response returned by a request to VWS.
status_code: The expected status code of the response.
result_code: The expected result code of the response.
Raises:
AssertionError: The response is not in the expected VWS format for the
given codes.
"""
message = 'Expected {expected}, got {actual}.'
assert response.status_code == status_code, message.format(
expected=status_code,
actual=response.status_code,
)
assert response.json()['result_code'] == result_code.value
assert response.headers['Content-Type'] == 'application/json'
transaction_id = response.json()['transaction_id']
assert len(transaction_id) == 32
assert all(char in hexdigits for char in transaction_id)
| """
Utilities for tests for the VWS mock.
"""
from string import hexdigits
from typing import Optional
from urllib.parse import urljoin
from requests.models import Response
from common.constants import ResultCodes
class Endpoint:
"""
Details of endpoints to be called in tests.
"""
def __init__(self,
example_path: str,
method: str,
successful_headers_result_code: ResultCodes,
successful_headers_status_code: int,
content_type: Optional[str],
content: bytes,
) -> None:
"""
Args:
example_path: An example path for calling the endpoint.
method: The HTTP method for the endpoint.
successful_headers_result_code: The expected result code if the
example path is requested with the method.
successful_headers_status_code: The expected status code if the
example path is requested with the method.
content: The data to send with the request.
Attributes:
example_path: An example path for calling the endpoint.
method: The HTTP method for the endpoint.
content_type: The `Content-Type` header to send, or `None` if one
should not be sent.
content: The data to send with the request.
url: The URL to call the path with.
successful_headers_result_code: The expected result code if the
example path is requested with the method.
successful_headers_status_code: The expected status code if the
example path is requested with the method.
"""
self.example_path = example_path
self.method = method
self.content_type = content_type
self.content = content
self.url = urljoin('https://vws.vuforia.com/', example_path)
self.successful_headers_status_code = successful_headers_status_code
self.successful_headers_result_code = successful_headers_result_code
def assert_vws_failure(response: Response,
status_code: int,
result_code: ResultCodes) -> None:
"""
Assert that a VWS failure response is as expected.
Args:
response: The response returned by a request to VWS.
status_code: The expected status code of the response.
result_code: The expected result code of the response.
Raises:
AssertionError: The response is not in the expected VWS error format
for the given codes.
"""
# import pdb; pdb.set_trace()
assert response.json().keys() == {'transaction_id', 'result_code'}
assert_vws_response(
response=response,
status_code=status_code,
result_code=result_code,
)
def assert_vws_response(response: Response,
status_code: int,
result_code: ResultCodes,
) -> None:
"""
Assert that a VWS response is as expected, at least in part.
https://library.vuforia.com/articles/Solution/How-To-Interperete-VWS-API-Result-Codes
implies that the expected status code can be worked out from the result
code. However, this is not the case as the real results differ from the
documentation.
For example, it is possible to get a "Fail" result code and a 400 error.
Args:
response: The response returned by a request to VWS.
status_code: The expected status code of the response.
result_code: The expected result code of the response.
Raises:
AssertionError: The response is not in the expected VWS format for the
given codes.
"""
message = 'Expected {expected}, got {actual}.'
assert response.status_code == status_code, message.format(
expected=status_code,
actual=response.status_code,
)
assert response.json()['result_code'] == result_code.value
assert response.headers['Content-Type'] == 'application/json'
transaction_id = response.json()['transaction_id']
assert len(transaction_id) == 32
assert all(char in hexdigits for char in transaction_id)
| Python | 0.000004 |
dcc07355786f94da36d938239c5c60d5302e4d42 | test for identity link | testapp/tests/test_renderer_infer.py | testapp/tests/test_renderer_infer.py | #!/usr/bin/env python
# encoding: utf-8
from django.test import TestCase
from collection_json import Collection
from testapp.models import Person
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
class DictionaryTest(TestCase):
"""tests when the response contains a dictionary"""
def test_no_serializer_view(self):
with self.assertRaises(TypeError):
self.client.get("/infer/noserializer")
class PersonTest(TestCase):
def setUp(self):
self.num_people = 10
for i in range(self.num_people):
p = Person.objects.create(name="person{}".format(i),
address="address{}".format(i))
p.save()
self.url = "/infer/person"
response = self.client.get(self.url)
content = response.content.decode("utf-8")
self.collection = Collection.from_json(content)
def test_db_setup(self):
"""asserts that the database was properly initialized"""
self.assertEqual(self.num_people, len(Person.objects.all()))
def test_collection_items(self):
"""asserts that the right number of items was parsed"""
self.assertEqual(self.num_people, len(self.collection.items))
def test_collection_names(self):
"""tests that the given attribute was parsed correctly"""
for i, item in enumerate(self.collection.items):
expected = "person{}".format(i)
self.assertEqual(item.name.value, expected)
def test_collection_address(self):
"""tests that the given attribute was parsed correctly"""
for i, item in enumerate(self.collection.items):
expected = "address{}".format(i)
self.assertEqual(item.address.value, expected)
def test_collection_identity_link(self):
"""tests that the href for the collection is correct"""
actual = urlparse(self.collection.href).path
self.assertEqual(actual, self.url)
class ListTest(TestCase):
"""tests when the response contains a list"""
urls = "testapp.urls"
| #!/usr/bin/env python
# encoding: utf-8
from django.test import TestCase
from collection_json import Collection
from testapp.models import Person
class DictionaryTest(TestCase):
"""tests when the response contains a dictionary"""
def test_no_serializer_view(self):
with self.assertRaises(TypeError):
self.client.get("/infer/noserializer")
class PersonTest(TestCase):
def setUp(self):
self.num_people = 10
for i in range(self.num_people):
p = Person.objects.create(name="person{}".format(i),
address="address{}".format(i))
p.save()
response = self.client.get("/infer/person")
content = response.content.decode("utf-8")
self.collection = Collection.from_json(content)
def test_db_setup(self):
"""asserts that the database was properly initialized"""
self.assertEqual(self.num_people, len(Person.objects.all()))
def test_collection_items(self):
"""asserts that the right number of items was parsed"""
self.assertEqual(self.num_people, len(self.collection.items))
def test_collection_names(self):
"""tests that the given attribute was parsed correctly"""
for i, item in enumerate(self.collection.items):
expected = "person{}".format(i)
self.assertEqual(item.name.value, expected)
def test_collection_address(self):
"""tests that the given attribute was parsed correctly"""
for i, item in enumerate(self.collection.items):
expected = "address{}".format(i)
self.assertEqual(item.address.value, expected)
class ListTest(TestCase):
"""tests when the response contains a list"""
urls = "testapp.urls"
| Python | 0 |
943ecc39af2b152bc8d5fed55bdafe5332a33d75 | remove xfail (#4458) | testing/kfctl/endpoint_ready_test.py | testing/kfctl/endpoint_ready_test.py | import datetime
import json
import logging
import os
import subprocess
import tempfile
import uuid
from retrying import retry
import pytest
from kubeflow.testing import util
from testing import deploy_utils
from testing import gcp_util
# There's really no good reason to run test_endpoint during presubmits.
# We shouldn't need it to feel confident that kfctl is working.
@pytest.mark.skipif(os.getenv("JOB_TYPE") == "presubmit",
reason="test endpoint doesn't run in presubmits")
def test_endpoint_is_ready(record_xml_attribute, project, app_path, app_name, use_basic_auth):
"""Test that Kubeflow was successfully deployed.
Args:
project: The gcp project that we deployed kubeflow
app_name: The name of the kubeflow deployment
"""
util.set_pytest_junit(record_xml_attribute, "test_endpoint_is_ready")
url = "https://{}.endpoints.{}.cloud.goog".format(app_name, project)
if use_basic_auth:
with open(os.path.join(app_path, "login.json"), "r") as f:
login = json.load(f)
# Let it fail if login info cannot be found.
username = login["KUBEFLOW_USERNAME"]
password = login["KUBEFLOW_PASSWORD"]
if not gcp_util.basic_auth_is_ready(url, username, password):
raise Exception("Basic auth endpoint is not ready")
else:
# Owned by project kubeflow-ci-deployment.
os.environ["CLIENT_ID"] = "29647740582-7meo6c7a9a76jvg54j0g2lv8lrsb4l8g.apps.googleusercontent.com"
if not gcp_util.iap_is_ready(url):
raise Exception("IAP endpoint is not ready")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format=('%(levelname)s|%(asctime)s'
'|%(pathname)s|%(lineno)d| %(message)s'),
datefmt='%Y-%m-%dT%H:%M:%S',
)
logging.getLogger().setLevel(logging.INFO)
pytest.main()
| import datetime
import json
import logging
import os
import subprocess
import tempfile
import uuid
from retrying import retry
import pytest
from kubeflow.testing import util
from testing import deploy_utils
from testing import gcp_util
# TODO(https://github.com/kubeflow/kfctl/issues/42):
# Test is failing pretty consistently.
@pytest.mark.xfail
# There's really no good reason to run test_endpoint during presubmits.
# We shouldn't need it to feel confident that kfctl is working.
@pytest.mark.skipif(os.getenv("JOB_TYPE") == "presubmit",
reason="test endpoint doesn't run in presubmits")
def test_endpoint_is_ready(record_xml_attribute, project, app_path, app_name, use_basic_auth):
"""Test that Kubeflow was successfully deployed.
Args:
project: The gcp project that we deployed kubeflow
app_name: The name of the kubeflow deployment
"""
util.set_pytest_junit(record_xml_attribute, "test_endpoint_is_ready")
url = "https://{}.endpoints.{}.cloud.goog".format(app_name, project)
if use_basic_auth:
with open(os.path.join(app_path, "login.json"), "r") as f:
login = json.load(f)
# Let it fail if login info cannot be found.
username = login["KUBEFLOW_USERNAME"]
password = login["KUBEFLOW_PASSWORD"]
if not gcp_util.basic_auth_is_ready(url, username, password):
raise Exception("Basic auth endpoint is not ready")
else:
# Owned by project kubeflow-ci-deployment.
os.environ["CLIENT_ID"] = "29647740582-7meo6c7a9a76jvg54j0g2lv8lrsb4l8g.apps.googleusercontent.com"
if not gcp_util.iap_is_ready(url):
raise Exception("IAP endpoint is not ready")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format=('%(levelname)s|%(asctime)s'
'|%(pathname)s|%(lineno)d| %(message)s'),
datefmt='%Y-%m-%dT%H:%M:%S',
)
logging.getLogger().setLevel(logging.INFO)
pytest.main()
| Python | 0.000009 |
291681041f434a981a54371bb7f9f1fa9637afb7 | improve comment collapse | polls/admin.py | polls/admin.py | from django.contrib import admin
from polls.models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], #'classes': ['collapse']
}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date','question_text']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin) | from django.contrib import admin
from polls.models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], #'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date','question_text']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin) | Python | 0.000002 |
21ecd9a319c5e0dceed36fcf9cabdc864f735c2c | Write test for nearley include | tests/test_nearley/test_nearley.py | tests/test_nearley/test_nearley.py | from __future__ import absolute_import
import unittest
import logging
import os
import sys
logging.basicConfig(level=logging.INFO)
from lark.tools.nearley import create_code_for_nearley_grammar
NEARLEY_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'nearley'))
BUILTIN_PATH = os.path.join(NEARLEY_PATH, 'builtin')
class TestNearley(unittest.TestCase):
def test_css(self):
css_example_grammar = """
# http://www.w3.org/TR/css3-color/#colorunits
@builtin "whitespace.ne"
@builtin "number.ne"
@builtin "postprocessors.ne"
csscolor -> "#" hexdigit hexdigit hexdigit hexdigit hexdigit hexdigit {%
function(d) {
return {
"r": parseInt(d[1]+d[2], 16),
"g": parseInt(d[3]+d[4], 16),
"b": parseInt(d[5]+d[6], 16),
}
}
%}
| "#" hexdigit hexdigit hexdigit {%
function(d) {
return {
"r": parseInt(d[1]+d[1], 16),
"g": parseInt(d[2]+d[2], 16),
"b": parseInt(d[3]+d[3], 16),
}
}
%}
| "rgb" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")" {% $({"r": 4, "g": 8, "b": 12}) %}
| "hsl" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")" {% $({"h": 4, "s": 8, "l": 12}) %}
| "rgba" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")" {% $({"r": 4, "g": 8, "b": 12, "a": 16}) %}
| "hsla" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")" {% $({"h": 4, "s": 8, "l": 12, "a": 16}) %}
hexdigit -> [a-fA-F0-9]
colnum -> unsigned_int {% id %} | percentage {%
function(d) {return Math.floor(d[0]*255); }
%}
"""
code = create_code_for_nearley_grammar(css_example_grammar, 'csscolor', BUILTIN_PATH, './')
d = {}
exec (code, d)
parse = d['parse']
c = parse('#a199ff')
assert c['r'] == 161
assert c['g'] == 153
assert c['b'] == 255
c = parse('rgb(255, 70%, 3)')
assert c['r'] == 255
assert c['g'] == 178
assert c['b'] == 3
def test_include(self):
fn = os.path.join(NEARLEY_PATH, 'test/grammars/folder-test.ne')
with open(fn) as f:
grammar = f.read()
code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, os.path.dirname(fn))
d = {}
exec (code, d)
parse = d['parse']
parse('a')
parse('b')
if __name__ == '__main__':
unittest.main()
| from __future__ import absolute_import
import unittest
import logging
import os
import sys
logging.basicConfig(level=logging.INFO)
from lark.tools.nearley import create_code_for_nearley_grammar
NEARLEY_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'nearley'))
BUILTIN_PATH = os.path.join(NEARLEY_PATH, 'builtin')
class TestNearley(unittest.TestCase):
def test_css(self):
css_example_grammar = """
# http://www.w3.org/TR/css3-color/#colorunits
@builtin "whitespace.ne"
@builtin "number.ne"
@builtin "postprocessors.ne"
csscolor -> "#" hexdigit hexdigit hexdigit hexdigit hexdigit hexdigit {%
function(d) {
return {
"r": parseInt(d[1]+d[2], 16),
"g": parseInt(d[3]+d[4], 16),
"b": parseInt(d[5]+d[6], 16),
}
}
%}
| "#" hexdigit hexdigit hexdigit {%
function(d) {
return {
"r": parseInt(d[1]+d[1], 16),
"g": parseInt(d[2]+d[2], 16),
"b": parseInt(d[3]+d[3], 16),
}
}
%}
| "rgb" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")" {% $({"r": 4, "g": 8, "b": 12}) %}
| "hsl" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")" {% $({"h": 4, "s": 8, "l": 12}) %}
| "rgba" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")" {% $({"r": 4, "g": 8, "b": 12, "a": 16}) %}
| "hsla" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")" {% $({"h": 4, "s": 8, "l": 12, "a": 16}) %}
hexdigit -> [a-fA-F0-9]
colnum -> unsigned_int {% id %} | percentage {%
function(d) {return Math.floor(d[0]*255); }
%}
"""
code = create_code_for_nearley_grammar(css_example_grammar, 'csscolor', BUILTIN_PATH, './')
d = {}
exec (code, d)
parse = d['parse']
c = parse('#a199ff')
assert c['r'] == 161
assert c['g'] == 153
assert c['b'] == 255
c = parse('rgb(255, 70%, 3)')
assert c['r'] == 255
assert c['g'] == 178
assert c['b'] == 3
if __name__ == '__main__':
unittest.main()
| Python | 0 |
69770ecc4715788837f5f769e0d2f1e6690a153f | Allow test_core to run as a test program | tests/test_splauncher/test_core.py | tests/test_splauncher/test_core.py | from __future__ import print_function
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$May 18, 2015 22:08:21 EDT$"
import os
import shutil
import tempfile
import time
import unittest
from splauncher.core import main
class TestCore(unittest.TestCase):
def setUp(self):
self.cwd = os.getcwd()
self.tempdir = ""
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
print("tempdir = \"%s\"" % self.tempdir)
def tearDown(self):
os.chdir(self.cwd)
shutil.rmtree(self.tempdir)
self.tempdir = ""
self.cwd = ""
def test_main_0(self):
main("",
"python",
"-c",
"from __future__ import print_function;" +
"import sys;" +
"print(\"output\", file=sys.stdout)"
)
while len(os.listdir(self.tempdir)) < 2:
time.sleep(1)
time.sleep(1)
filenames = []
for each_filename in os.listdir(self.tempdir):
filenames.append(os.path.join(self.tempdir, each_filename))
filenames.sort()
assert ".err" in filenames[0]
assert ".out" in filenames[1]
with open(filenames[0], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == ""
with open(filenames[1], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == "output"
def test_main_1(self):
main("",
"python",
"-c",
"from __future__ import print_function;" +
"import sys;" +
"print(\"error\", file=sys.stderr)"
)
while len(os.listdir(self.tempdir)) < 2:
time.sleep(1)
time.sleep(1)
filenames = []
for each_filename in os.listdir(self.tempdir):
filenames.append(os.path.join(self.tempdir, each_filename))
filenames.sort()
assert ".err" in filenames[0]
assert ".out" in filenames[1]
with open(filenames[0], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == "error"
with open(filenames[1], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == ""
if __name__ == '__main__':
import sys
sys.exit(unittest.main())
| from __future__ import print_function
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$May 18, 2015 22:08:21 EDT$"
import os
import shutil
import tempfile
import time
import unittest
from splauncher.core import main
class TestCore(unittest.TestCase):
def setUp(self):
self.cwd = os.getcwd()
self.tempdir = ""
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
print("tempdir = \"%s\"" % self.tempdir)
def tearDown(self):
os.chdir(self.cwd)
shutil.rmtree(self.tempdir)
self.tempdir = ""
self.cwd = ""
def test_main_0(self):
main("",
"python",
"-c",
"from __future__ import print_function;" +
"import sys;" +
"print(\"output\", file=sys.stdout)"
)
while len(os.listdir(self.tempdir)) < 2:
time.sleep(1)
time.sleep(1)
filenames = []
for each_filename in os.listdir(self.tempdir):
filenames.append(os.path.join(self.tempdir, each_filename))
filenames.sort()
assert ".err" in filenames[0]
assert ".out" in filenames[1]
with open(filenames[0], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == ""
with open(filenames[1], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == "output"
def test_main_1(self):
main("",
"python",
"-c",
"from __future__ import print_function;" +
"import sys;" +
"print(\"error\", file=sys.stderr)"
)
while len(os.listdir(self.tempdir)) < 2:
time.sleep(1)
time.sleep(1)
filenames = []
for each_filename in os.listdir(self.tempdir):
filenames.append(os.path.join(self.tempdir, each_filename))
filenames.sort()
assert ".err" in filenames[0]
assert ".out" in filenames[1]
with open(filenames[0], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == "error"
with open(filenames[1], "r") as f:
s = f.read().strip()
print("File \"%s\" contains \"%s\"." % (f.name, s))
assert s == ""
| Python | 0.000002 |
534a21e8d664a4216af14db95415dafa0508b3b9 | Remove test | tests/integration/client/standard.py | tests/integration/client/standard.py | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import
import os
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
import salt.utils
class StdTest(integration.ModuleCase):
'''
Test standard client calls
'''
def test_cli(self):
'''
Test cli function
'''
cmd_iter = self.client.cmd_cli(
'minion',
'test.ping',
)
for ret in cmd_iter:
self.assertTrue(ret['minion'])
# make sure that the iter waits for long running jobs too
cmd_iter = self.client.cmd_cli(
'minion',
'test.sleep',
[6]
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret > 0
# ping a minion that doesn't exist, to make sure that it doesn't hang forever
# create fake minion
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'footest')
# touch the file
with salt.utils.fopen(key_file, 'a'):
pass
# ping that minion and ensure it times out
try:
cmd_iter = self.client.cmd_cli(
'footest',
'test.ping',
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret == 0
finally:
os.unlink(key_file)
def test_iter(self):
'''
test cmd_iter
'''
cmd_iter = self.client.cmd_iter(
'minion',
'test.ping',
)
for ret in cmd_iter:
self.assertTrue(ret['minion'])
def test_iter_no_block(self):
'''
test cmd_iter_no_block
'''
cmd_iter = self.client.cmd_iter_no_block(
'minion',
'test.ping',
)
for ret in cmd_iter:
if ret is None:
continue
self.assertTrue(ret['minion'])
def test_full_returns(self):
'''
test cmd_iter
'''
ret = self.client.cmd_full_return(
'minion',
'test.ping',
)
self.assertIn('minion', ret)
self.assertEqual({'ret': True, 'success': True}, ret['minion'])
def test_disconnected_return(self):
'''
Test return/messaging on a disconnected minion
'''
test_ret = {'ret': 'Minion did not return. [No response]', 'out': 'no_return'}
# Create a minion key, but do not start the "fake" minion. This mimics
# a disconnected minion.
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'disconnected')
with salt.utils.fopen(key_file, 'a'):
pass
# ping disconnected minion and ensure it times out and returns with correct message
try:
cmd_iter = self.client.cmd_cli(
'disconnected',
'test.ping',
show_timeout=True
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertEqual(ret['disconnected']['ret'], test_ret['ret'])
self.assertEqual(ret['disconnected']['out'], test_ret['out'])
# Ensure that we entered the loop above
self.assertEqual(num_ret, 1)
finally:
os.unlink(key_file)
if __name__ == '__main__':
from integration import run_tests
run_tests(StdTest)
| # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import
import os
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
import salt.utils
class StdTest(integration.ModuleCase):
'''
Test standard client calls
'''
def test_cli(self):
'''
Test cli function
'''
cmd_iter = self.client.cmd_cli(
'minion',
'test.ping',
)
for ret in cmd_iter:
self.assertTrue(ret['minion'])
# make sure that the iter waits for long running jobs too
cmd_iter = self.client.cmd_cli(
'minion',
'test.sleep',
[6]
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret > 0
# ping a minion that doesn't exist, to make sure that it doesn't hang forever
# create fake minion
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'footest')
# touch the file
with salt.utils.fopen(key_file, 'a'):
pass
# ping that minion and ensure it times out
try:
cmd_iter = self.client.cmd_cli(
'footest',
'test.ping',
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret == 0
finally:
os.unlink(key_file)
def test_iter(self):
'''
test cmd_iter
'''
cmd_iter = self.client.cmd_iter(
'minion',
'test.ping',
)
for ret in cmd_iter:
self.assertTrue(ret['minion'])
def test_iter_no_block(self):
'''
test cmd_iter_no_block
'''
cmd_iter = self.client.cmd_iter_no_block(
'minion',
'test.ping',
)
for ret in cmd_iter:
if ret is None:
continue
self.assertTrue(ret['minion'])
def test_full_returns(self):
'''
test cmd_iter
'''
ret = self.client.cmd_full_return(
'minion',
'test.ping',
)
self.assertIn('minion', ret)
self.assertEqual({'ret': True, 'success': True}, ret['minion'])
ret = self.client.cmd_full_return(
'minion',
'test.pong',
)
self.assertIn('minion', ret)
if self.master_opts['transport'] == 'zeromq':
self.assertEqual(
{
'out': 'nested',
'ret': '\'test.pong\' is not available.',
'success': False
},
ret['minion']
)
elif self.master_opts['transport'] == 'raet':
self.assertEqual(
{'success': False, 'ret': '\'test.pong\' is not available.'},
ret['minion']
)
def test_disconnected_return(self):
'''
Test return/messaging on a disconnected minion
'''
test_ret = {'ret': 'Minion did not return. [No response]', 'out': 'no_return'}
# Create a minion key, but do not start the "fake" minion. This mimics
# a disconnected minion.
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'disconnected')
with salt.utils.fopen(key_file, 'a'):
pass
# ping disconnected minion and ensure it times out and returns with correct message
try:
cmd_iter = self.client.cmd_cli(
'disconnected',
'test.ping',
show_timeout=True
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertEqual(ret['disconnected']['ret'], test_ret['ret'])
self.assertEqual(ret['disconnected']['out'], test_ret['out'])
# Ensure that we entered the loop above
self.assertEqual(num_ret, 1)
finally:
os.unlink(key_file)
if __name__ == '__main__':
from integration import run_tests
run_tests(StdTest)
| Python | 0 |
05e496de4f6ebbb9e77c6cb1796cc1050a41a181 | Adjust whitespace for pep8 | pratchett/__init__.py | pratchett/__init__.py | HEADER = ("X-Clacks-Overhead", "GNU Terry Pratchett")
class GNUTerryPratchett(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
def clacker(status, headers, *args, **kwargs):
if HEADER not in headers:
headers.append(HEADER)
return start_response(status, headers, *args, **kwargs)
return self.app(environ, clacker)
def make_filter(global_conf):
return GNUTerryPratchett
| HEADER = ("X-Clacks-Overhead", "GNU Terry Pratchett")
class GNUTerryPratchett(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
def clacker(status, headers, *args, **kwargs):
if HEADER not in headers:
headers.append(HEADER)
return start_response(status, headers, *args, **kwargs)
return self.app(environ, clacker)
def make_filter(global_conf):
return GNUTerryPratchett
| Python | 0.9998 |
ddb4ed6701808ed5c4e928d042b84e0c84490e58 | Bump version 0.0.4 | memsource/__init__.py | memsource/__init__.py | __author__ = 'Gengo'
__version__ = '0.0.4'
__license__ = 'MIT'
| __author__ = 'Gengo'
__version__ = '0.0.3'
__license__ = 'MIT'
| Python | 0 |
949c7b55e295b4d87f2d7a1bb98242cb055129d1 | Solve No.140 in Python with problems | 140.py | 140.py |
class Solution:
"""
@param a, b, n: 32bit integers
@return: An integer
"""
def fastPower(self, a, b, n):
ans = 1
while b > 0:
if b % 2==1:
ans = ans * a % n
a = a * a % n
b = b / 2
return ans % n
# WA because of lintcode
# AC |
class Solution:
"""
@param a, b, n: 32bit integers
@return: An integer
"""
def fastPower(self, a, b, n):
ans = 1
while b > 0:
if b % 2==1:
ans = ans * a % n
a = a * a % n
b = b / 2
return ans % n
# WA | Python | 0.005724 |
86f33d7c88c728bb5ce0c885543dd54d942e2962 | Fix strings broken by 1393650 | tests/steps/snapshot.py | tests/steps/snapshot.py | # -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from behave import step
from dogtail.rawinput import typeText, pressKey
from time import sleep
from utils import get_showing_node_name
@step('Add Snapshot named "{name}"')
def add_snapshot(context, name):
wait = 0
while len(context.app.findChildren(lambda x: x.roleName == 'push button' and x.showing and not x.name)) == 0:
sleep(0.25)
wait += 1
if wait == 20:
raise Exception("Timeout: Node %s wasn't found showing" %name)
context.app.findChildren(lambda x: x.roleName == 'push button' and x.showing and not x.name)[0].click()
wait = 0
while len(context.app.findChildren(lambda x: x.roleName == 'toggle button' and x.showing \
and x.sensitive and x.name == 'Menu')) == 0:
sleep(1)
wait += 1
if wait == 5:
raise Exception("Timeout: Node %s wasn't found showing" %name)
sleep(1)
context.app.findChildren(lambda x: x.roleName == 'toggle button' and x.showing \
and x.sensitive and x.name == 'Menu')[-1].click()
renames = context.app.findChildren(lambda x: x.name == 'Rename' and x.showing)
if not renames:
context.app.findChildren(lambda x: x.roleName == 'toggle button' and x.showing and x.sensitive \
and x.name == 'Menu')[-1].click()
renames = context.app.findChildren(lambda x: x.name == 'Rename' and x.showing)
renames[0].click()
sleep(0.5)
typeText(name)
context.app.findChildren(lambda x: x.showing and x.name == 'Done')[0].click()
@step('Create snapshot "{snap_name}" from machine "{vm_name}"')
def create_snapshot(context, snap_name, vm_name):
context.execute_steps(u"""
* Select "%s" box
* Press "Properties"
* Press "Snapshots"
* Add Snapshot named "%s"
* Press "Back"
""" %(vm_name, snap_name))
@step('Delete machines "{vm_name}" snapshot "{snap_name}"')
def delete_snapshot(context, vm_name, snap_name):
context.execute_steps(u"""
* Select "%s" box
* Press "Properties"
* Press "Snapshots"
""" % vm_name)
name = context.app.findChildren(lambda x: x.name == snap_name and x.showing)[0]
name.parent.child('Menu').click()
delete = context.app.findChildren(lambda x: x.name == "Delete" and x.showing)[0]
delete.click()
context.app.findChildren(lambda x: x.name == 'Undo' and x.showing)[0].grabFocus()
pressKey('Tab')
pressKey('Enter')
sleep(2)
get_showing_node_name('Back', context.app).click()
sleep(0.5)
@step('Revert machine "{vm_name}" to state "{snap_name}"')
def revert_snapshot(context, vm_name, snap_name):
context.execute_steps(u"""
* Select "%s" box
* Press "Properties"
* Press "Snapshots"
""" % vm_name)
name = context.app.findChildren(lambda x: x.name == snap_name and x.showing)[0]
name.parent.child('Menu').click()
revert = context.app.findChildren(lambda x: x.name == "Revert to this state" and x.showing)[0]
revert.click()
get_showing_node_name('Back', context.app).click()
sleep(0.5)
| # -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from behave import step
from dogtail.rawinput import typeText, pressKey
from time import sleep
from utils import get_showing_node_name
@step('Add Snapshot named "{name}"')
def add_snapshot(context, name):
wait = 0
while len(context.app.findChildren(lambda x: x.roleName == 'push button' and x.showing and not x.name)) == 0:
sleep(0.25)
wait += 1
if wait == 20:
raise Exception("Timeout: Node %s wasn't found showing" %name)
context.app.findChildren(lambda x: x.roleName == 'push button' and x.showing and not x.name)[0].click()
wait = 0
while len(context.app.findChildren(lambda x: x.roleName == 'toggle button' and x.showing \
and x.sensitive and x.name == 'Men')) == 0:
sleep(1)
wait += 1
if wait == 5:
raise Exception("Timeout: Node %s wasn't found showing" %name)
sleep(1)
context.app.findChildren(lambda x: x.roleName == 'toggle button' and x.showing \
and x.sensitive and x.name == 'Men')[-1].click()
renames = context.app.findChildren(lambda x: x.name == 'Rename' and x.showing)
if not renames:
context.app.findChildren(lambda x: x.roleName == 'toggle button' and x.showing and x.sensitive \
and x.name == 'Men')[-1].click()
renames = context.app.findChildren(lambda x: x.name == 'Rename' and x.showing)
renames[0].click()
sleep(0.5)
typeText(name)
context.app.findChildren(lambda x: x.showing and x.name == 'Done')[0].click()
@step('Create snapshot "{snap_name}" from machine "{vm_name}"')
def create_snapshot(context, snap_name, vm_name):
context.execute_steps(u"""
* Select "%s" box
* Press "Properties"
* Press "Snapshots"
* Add Snapshot named "%s"
* Press "Back"
""" %(vm_name, snap_name))
@step('Delete machines "{vm_name}" snapshot "{snap_name}"')
def delete_snapshot(context, vm_name, snap_name):
context.execute_steps(u"""
* Select "%s" box
* Press "Properties"
* Press "Snapshots"
""" % vm_name)
name = context.app.findChildren(lambda x: x.name == snap_name and x.showing)[0]
name.parent.child('Men').click()
delete = context.app.findChildren(lambda x: x.name == "Delete" and x.showing)[0]
delete.click()
context.app.findChildren(lambda x: x.name == 'Undo' and x.showing)[0].grabFocus()
pressKey('Tab')
pressKey('Enter')
sleep(2)
get_showing_node_name('Back', context.app).click()
sleep(0.5)
@step('Revert machine "{vm_name}" to state "{snap_name}"')
def revert_snapshot(context, vm_name, snap_name):
context.execute_steps(u"""
* Select "%s" box
* Press "Properties"
* Press "Snapshots"
""" % vm_name)
name = context.app.findChildren(lambda x: x.name == snap_name and x.showing)[0]
name.parent.child('Men').click()
revert = context.app.findChildren(lambda x: x.name == "Revert to this state" and x.showing)[0]
revert.click()
get_showing_node_name('Back', context.app).click()
sleep(0.5)
| Python | 0.004521 |
9221d42cda7ba7a44d1462de75c0c53412998fb4 | Remove unused code. | mysite/missions/tar/view_helpers.py | mysite/missions/tar/view_helpers.py | # This file is part of OpenHatch.
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2010 John Stumpo
# Copyright (C) 2010, 2011 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from mysite.missions.base.view_helpers import *
class IncorrectTarFile(Exception):
pass
class TarMission(object):
WRAPPER_DIR_NAME = 'myproject-0.1'
FILES = {
'hello.c': '''#include <stdio.h>
int main(void)
{
printf("Hello World\\n");
return 0;
}
''',
'Makefile': 'hello : hello.o\n'
}
class UntarMission(object):
TARBALL_DIR_NAME = 'ghello-0.4'
TARBALL_NAME = TARBALL_DIR_NAME + '.tar.gz'
FILE_WE_WANT = TARBALL_DIR_NAME + '/ghello.c'
@classmethod
def synthesize_tarball(cls):
tdata = StringIO()
tfile = tarfile.open(fileobj=tdata, mode='w:gz')
tfile.add(os.path.join(get_mission_data_path('tar'),
cls.TARBALL_DIR_NAME), cls.TARBALL_DIR_NAME)
tfile.close()
return tdata.getvalue()
@classmethod
def get_contents_we_want(cls):
'''Get the data for the file we want from the tarball.'''
return open(os.path.join(get_mission_data_path('tar'), cls.FILE_WE_WANT)).read()
| # This file is part of OpenHatch.
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2010 John Stumpo
# Copyright (C) 2010, 2011 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from mysite.missions.base.view_helpers import *
class IncorrectTarFile(Exception):
pass
class TarMission(object):
WRAPPER_DIR_NAME = 'myproject-0.1'
FILES = {
'hello.c': '''#include <stdio.h>
int main(void)
{
printf("Hello World\\n");
return 0;
}
''',
'Makefile': 'hello : hello.o\n'
}
@classmethod
def check_tarfile(cls, tardata):
"""
Validate that tardata is gzipped and contains the correct files in a wrapper directory.
"""
try:
tfile = tarfile.open(fileobj=StringIO(tardata), mode='r:gz')
except tarfile.ReadError:
raise IncorrectTarFile, 'Archive is not a valid gzipped tarball'
# Check the filename list.
filenames_wanted = [cls.WRAPPER_DIR_NAME] + \
[os.path.join(cls.WRAPPER_DIR_NAME, filename)
for filename in cls.FILES.keys()]
for member in tfile.getmembers():
if '/' not in member.name:
if member.name in cls.FILES.keys():
raise IncorrectTarFile, 'No wrapper directory is present'
elif member.isdir() and member.name != cls.WRAPPER_DIR_NAME:
raise IncorrectTarFile, 'Wrapper directory name is incorrect: "%s"' % member.name
if member.name not in filenames_wanted:
msg = 'An unexpected entry "%s" is present' % member.name
if '/._' in member.name:
# This is an Apple Double file.
msg += '. You can read about how to remove it <a href="/wiki/Tar_hints_for_Mac_OS_X_users">on our wiki</a>.'
raise IncorrectTarFile, msg
filenames_wanted.remove(member.name)
if member.name == cls.WRAPPER_DIR_NAME:
if not member.isdir():
raise IncorrectTarFile, '"%s" should be a directory but is not' % member.name
else:
if not member.isfile():
raise IncorrectTarFile, 'Entry "%s" is not a file' % member.name
if tfile.extractfile(member).read() != cls.FILES[member.name.split('/')[-1]]:
raise IncorrectTarFile, 'File "%s" has incorrect contents' % member.name
if len(filenames_wanted) != 0:
raise IncorrectTarFile, 'Archive does not contain all expected files (missing %s)' % (
', '.join('"%s"' % f for f in filenames_wanted))
class UntarMission(object):
TARBALL_DIR_NAME = 'ghello-0.4'
TARBALL_NAME = TARBALL_DIR_NAME + '.tar.gz'
FILE_WE_WANT = TARBALL_DIR_NAME + '/ghello.c'
@classmethod
def synthesize_tarball(cls):
tdata = StringIO()
tfile = tarfile.open(fileobj=tdata, mode='w:gz')
tfile.add(os.path.join(get_mission_data_path('tar'),
cls.TARBALL_DIR_NAME), cls.TARBALL_DIR_NAME)
tfile.close()
return tdata.getvalue()
@classmethod
def get_contents_we_want(cls):
'''Get the data for the file we want from the tarball.'''
return open(os.path.join(get_mission_data_path('tar'), cls.FILE_WE_WANT)).read()
| Python | 0 |
68eeda85605fa84d7bea69dfeab97b3b1278b4d4 | fix typo | examples/wordcloud_cn.py | examples/wordcloud_cn.py | # - * - coding: utf - 8 -*-
"""
create wordcloud with chinese
=============================
Wordcloud is a very good tool, but if you want to create
Chinese wordcloud only wordcloud is not enough. The file
shows how to use wordcloud with Chinese. First, you need a
Chinese word segmentation library jieba, jieba is now the
most elegant the most popular Chinese word segmentation tool in python.
You can use 'PIP install jieba'. To install it. As you can see,
at the same time using wordcloud with jieba very convenient
"""
import jieba
jieba.enable_parallel(4)
# Setting up parallel processes :4 ,but unable to run on Windows
from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
import os
# jieba.load_userdict("txt\userdict.txt")
# add userdict by load_userdict()
from wordcloud import WordCloud, ImageColorGenerator
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
stopwords_path = d + '/wc_cn/stopwords_cn_en.txt'
# Chinese fonts must be set
font_path = d + '/fonts/SourceHanSerif/SourceHanSerifK-Light.otf'
# the path to save worldcloud
imgname1 = d + '/wc_cn/LuXun.jpg'
imgname2 = d + '/wc_cn/LuXun_colored.jpg'
# read the mask / color image taken from
back_coloring = imread(path.join(d, d + '/wc_cn/LuXun_color.jpg'))
# Read the whole text.
text = open(path.join(d, d + '/wc_cn/CalltoArms.txt')).read()
# if you want use wordCloud,you need it
# add userdict by add_word()
userdict_list = ['阿Q', '孔乙己', '单四嫂子']
# The function for processing text with Jieba
def jieba_processing_txt(text):
for word in userdict_list:
jieba.add_word(word)
mywordlist = []
seg_list = jieba.cut(text, cut_all=False)
liststr = "/ ".join(seg_list)
with open(stopwords_path, encoding='utf-8') as f_stop:
f_stop_text = f_stop.read()
f_stop_seg_list = f_stop_text.splitlines()
for myword in liststr.split('/'):
if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:
mywordlist.append(myword)
return ' '.join(mywordlist)
wc = WordCloud(font_path=font_path, background_color="white", max_words=2000, mask=back_coloring,
max_font_size=100, random_state=42, width=1000, height=860, margin=2,)
wc.generate(jieba_processing_txt(text))
# create coloring from image
image_colors_default = ImageColorGenerator(back_coloring)
plt.figure()
# recolor wordcloud and show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
# save wordcloud
wc.to_file(path.join(d, imgname1))
# create coloring from image
image_colors_byImg = ImageColorGenerator(back_coloring)
# show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors_byImg), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(back_coloring, interpolation="bilinear")
plt.axis("off")
plt.show()
# save wordcloud
wc.to_file(path.join(d, imgname2))
| # - * - coding: utf - 8 -*-
"""
create wordcloud with chinese
=============================
Wordcloud is a very good tools, but if you want to create
Chinese wordcloud only wordcloud is not enough. The file
shows how to use wordcloud with Chinese. First, you need a
Chinese word segmentation library jieba, jieba is now the
most elegant the most popular Chinese word segmentation tool in python.
You can use 'PIP install jieba'. To install it. As you can see,
at the same time using wordcloud with jieba very convenient
"""
import jieba
jieba.enable_parallel(4)
# Setting up parallel processes :4 ,but unable to run on Windows
from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
import os
# jieba.load_userdict("txt\userdict.txt")
# add userdict by load_userdict()
from wordcloud import WordCloud, ImageColorGenerator
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
stopwords_path = d + '/wc_cn/stopwords_cn_en.txt'
# Chinese fonts must be set
font_path = d + '/fonts/SourceHanSerif/SourceHanSerifK-Light.otf'
# the path to save worldcloud
imgname1 = d + '/wc_cn/LuXun.jpg'
imgname2 = d + '/wc_cn/LuXun_colored.jpg'
# read the mask / color image taken from
back_coloring = imread(path.join(d, d + '/wc_cn/LuXun_color.jpg'))
# Read the whole text.
text = open(path.join(d, d + '/wc_cn/CalltoArms.txt')).read()
# if you want use wordCloud,you need it
# add userdict by add_word()
userdict_list = ['阿Q', '孔乙己', '单四嫂子']
# The function for processing text with Jieba
def jieba_processing_txt(text):
for word in userdict_list:
jieba.add_word(word)
mywordlist = []
seg_list = jieba.cut(text, cut_all=False)
liststr = "/ ".join(seg_list)
with open(stopwords_path, encoding='utf-8') as f_stop:
f_stop_text = f_stop.read()
f_stop_seg_list = f_stop_text.splitlines()
for myword in liststr.split('/'):
if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:
mywordlist.append(myword)
return ' '.join(mywordlist)
wc = WordCloud(font_path=font_path, background_color="white", max_words=2000, mask=back_coloring,
max_font_size=100, random_state=42, width=1000, height=860, margin=2,)
wc.generate(jieba_processing_txt(text))
# create coloring from image
image_colors_default = ImageColorGenerator(back_coloring)
plt.figure()
# recolor wordcloud and show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
# save wordcloud
wc.to_file(path.join(d, imgname1))
# create coloring from image
image_colors_byImg = ImageColorGenerator(back_coloring)
# show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors_byImg), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(back_coloring, interpolation="bilinear")
plt.axis("off")
plt.show()
# save wordcloud
wc.to_file(path.join(d, imgname2))
| Python | 0.999991 |
63667e0d492c16e0c3bc4a398044a60df695cc61 | Add more side effects | tests/unit/states/ssh_auth_test.py | tests/unit/states/ssh_auth_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import Salt Libs
from salt.states import ssh_auth
ssh_auth.__salt__ = {}
ssh_auth.__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class SshAuthTestCase(TestCase):
'''
Test cases for salt.states.ssh_auth
'''
# 'present' function tests: 1
def test_present(self):
'''
Test to verifies that the specified SSH key
is present for the specified user.
'''
name = 'sshkeys'
user = 'root'
source = 'salt://ssh_keys/id_rsa.pub'
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
mock = MagicMock(return_value='exists')
mock_data = MagicMock(side_effect=['replace', 'new'])
with patch.dict(ssh_auth.__salt__, {'ssh.check_key': mock,
'ssh.set_auth_key': mock_data}):
with patch.dict(ssh_auth.__opts__, {'test': True}):
comt = ('The authorized host key sshkeys is already '
'present for user root')
ret.update({'comment': comt})
self.assertDictEqual(ssh_auth.present(name, user, source), ret)
with patch.dict(ssh_auth.__opts__, {'test': False}):
comt = ('The authorized host key sshkeys '
'for user root was updated')
ret.update({'comment': comt, 'changes': {name: 'Updated'}})
self.assertDictEqual(ssh_auth.present(name, user, source), ret)
comt = ('The authorized host key sshkeys '
'for user root was added')
ret.update({'comment': comt, 'changes': {name: 'New'}})
self.assertDictEqual(ssh_auth.present(name, user, source), ret)
# 'absent' function tests: 1
def test_absent(self):
'''
Test to verifies that the specified SSH key is absent.
'''
name = 'sshkeys'
user = 'root'
source = 'salt://ssh_keys/id_rsa.pub'
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
mock = MagicMock(side_effect=['User authorized keys file not present',
'User authorized keys file not present',
'User authorized keys file not present',
'Key removed'])
mock_up = MagicMock(side_effect=['update', 'updated'])
with patch.dict(ssh_auth.__salt__, {'ssh.rm_auth_key': mock,
'ssh.check_key': mock_up}):
with patch.dict(ssh_auth.__opts__, {'test': True}):
comt = ('Key sshkeys for user root is set for removal')
ret.update({'comment': comt})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
comt = ('Key is already absent')
ret.update({'comment': comt, 'result': True})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
with patch.dict(ssh_auth.__opts__, {'test': False}):
comt = ('User authorized keys file not present')
ret.update({'comment': comt, 'result': False})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
comt = ('Key removed')
ret.update({'comment': comt, 'result': True,
'changes': {name: 'Removed'}})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
if __name__ == '__main__':
from integration import run_tests
run_tests(SshAuthTestCase, needs_daemon=False)
| # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import Salt Libs
from salt.states import ssh_auth
ssh_auth.__salt__ = {}
ssh_auth.__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class SshAuthTestCase(TestCase):
'''
Test cases for salt.states.ssh_auth
'''
# 'present' function tests: 1
def test_present(self):
'''
Test to verifies that the specified SSH key
is present for the specified user.
'''
name = 'sshkeys'
user = 'root'
source = 'salt://ssh_keys/id_rsa.pub'
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
mock = MagicMock(return_value='exists')
mock_data = MagicMock(side_effect=['replace', 'new'])
with patch.dict(ssh_auth.__salt__, {'ssh.check_key': mock,
'ssh.set_auth_key': mock_data}):
with patch.dict(ssh_auth.__opts__, {'test': True}):
comt = ('The authorized host key sshkeys is already '
'present for user root')
ret.update({'comment': comt})
self.assertDictEqual(ssh_auth.present(name, user, source), ret)
with patch.dict(ssh_auth.__opts__, {'test': False}):
comt = ('The authorized host key sshkeys '
'for user root was updated')
ret.update({'comment': comt, 'changes': {name: 'Updated'}})
self.assertDictEqual(ssh_auth.present(name, user, source), ret)
comt = ('The authorized host key sshkeys '
'for user root was added')
ret.update({'comment': comt, 'changes': {name: 'New'}})
self.assertDictEqual(ssh_auth.present(name, user, source), ret)
# 'absent' function tests: 1
def test_absent(self):
'''
Test to verifies that the specified SSH key is absent.
'''
name = 'sshkeys'
user = 'root'
source = 'salt://ssh_keys/id_rsa.pub'
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
mock = MagicMock(side_effect=['User authorized keys file not present',
'Key removed'])
mock_up = MagicMock(side_effect=['update', 'updated'])
with patch.dict(ssh_auth.__salt__, {'ssh.rm_auth_key': mock,
'ssh.check_key': mock_up}):
with patch.dict(ssh_auth.__opts__, {'test': True}):
comt = ('Key sshkeys for user root is set for removal')
ret.update({'comment': comt})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
comt = ('Key is already absent')
ret.update({'comment': comt, 'result': True})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
with patch.dict(ssh_auth.__opts__, {'test': False}):
comt = ('User authorized keys file not present')
ret.update({'comment': comt, 'result': False})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
comt = ('Key removed')
ret.update({'comment': comt, 'result': True,
'changes': {name: 'Removed'}})
self.assertDictEqual(ssh_auth.absent(name, user, source), ret)
if __name__ == '__main__':
from integration import run_tests
run_tests(SshAuthTestCase, needs_daemon=False)
| Python | 0 |
d10bb3695ee93ffd8b91d4d82adaf484de9e9bf1 | Rename NeuronNetwork to NeuralNetwork | ANN.py | ANN.py | from random import uniform
class Neuron:
def __init__(self, parents=[]):
self.parents = [{
'neuron': parent,
'weight': uniform(-1, 1),
'slope': uniform(-1, 1),
} for parent in parents]
def calculate(self, increment=0):
self.output = sum([parent['neuron'].output * (parent['weight'] + increment * parent['slope']) for parent in self.parents]) > 0
def mutate(self, increment):
for parent in self.parents:
parent['weight'] += increment * parent['slope']
parent['slope'] = uniform(-1, 1)
class NeuralNetwork:
def __init__(self, inputs, outputs, hidden, rows):
self.bias = Neuron()
self.neurons = []
for row in xrange(rows):
self.neurons.append([])
if row == 0:
for input_ in xrange(inputs):
self.neurons[row].append(Neuron(parents=[]))
elif row == rows - 1:
for output in xrange(outputs):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1] + [self.bias]))
else:
for column in xrange(hidden):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1] + [self.bias]))
self.bias.output = True
def calculate(self, inputs, increment=0):
for i, neuron_row in enumerate(self.neurons):
for j, neuron in enumerate(neuron_row):
if i == 0:
neuron.output = inputs[j]
else:
neuron.calculate(increment=increment)
return [neuron.output for neuron in self.neurons[-1]]
def mutate(self, increment):
for neuron_row in self.neurons:
for neuron in neuron_row:
neuron.mutate(increment=increment)
| from random import uniform
class Neuron:
def __init__(self, parents=[]):
self.parents = [{
'neuron': parent,
'weight': uniform(-1, 1),
'slope': uniform(-1, 1),
} for parent in parents]
def calculate(self, increment=0):
self.output = sum([parent['neuron'].output * (parent['weight'] + increment * parent['slope']) for parent in self.parents]) > 0
def mutate(self, increment):
for parent in self.parents:
parent['weight'] += increment * parent['slope']
parent['slope'] = uniform(-1, 1)
class NeuronNetwork:
def __init__(self, inputs, outputs, hidden, rows):
self.bias = Neuron()
self.neurons = []
for row in xrange(rows):
self.neurons.append([])
if row == 0:
for input_ in xrange(inputs):
self.neurons[row].append(Neuron(parents=[]))
elif row == rows - 1:
for output in xrange(outputs):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1] + [self.bias]))
else:
for column in xrange(hidden):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1] + [self.bias]))
self.bias.output = True
def calculate(self, inputs, increment=0):
for i, neuron_row in enumerate(self.neurons):
for j, neuron in enumerate(neuron_row):
if i == 0:
neuron.output = inputs[j]
else:
neuron.calculate(increment=increment)
return [neuron.output for neuron in self.neurons[-1]]
def mutate(self, increment):
for neuron_row in self.neurons:
for neuron in neuron_row:
neuron.mutate(increment=increment)
| Python | 0.99959 |
4f219c4a05a251d9958543d24891955d640bc07f | Add more realistic responses for audit logs in tests. | tests/test_audit_log.py | tests/test_audit_log.py | import httpretty
from fulcrum.exceptions import NotFoundException, InternalServerErrorException
from tests import FulcrumTestCase
from tests.valid_objects import form as valid_form
class AuditLogTest(FulcrumTestCase):
@httpretty.activate
def test_all(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/audit_logs',
body='{"audit_logs":[{"source_type":"authorization","source_id":"ec4a410f-0b76-4a65-ba58-b97eed023351","action":"create","description":"Levar Burton created API token Fulcrum Query Utility","data":{"note":"Fulcrum Query Utility","token_last_8":"f816b890","user_id":"reading-rainbow","user":"Levar Burton"},"ip":"1.1.1.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36","location":"Austin, Texas, United States","latitude":30.3085,"longitude":-97.6849,"admin_area":"TX","country":"US","locality":"Austin","postal_code":"78723","id":"def-456","created_at":"2019-01-16T15:14:58Z","updated_at":"2019-01-16T15:14:58Z","actor":"Levar Burton","actor_id":"8a11c2b4-79fc-4503-85e4-056671c41e6f","time":"2019-01-16T15:14:58Z"},{"source_type":"choice_list","source_id":"1c0b0ea3-66cd-4b69-9fe7-20a9e9f07556","action":"create","description":"Levar Burton created choice list New Choice List","data":null,"ip":"1.1.1.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36","location":"Tampa, Florida, United States","latitude":27.9987,"longitude":-82.5156,"admin_area":"FL","country":"US","locality":"Tampa","postal_code":"33614","id":"ghi-789","created_at":"2019-01-22T16:11:15Z","updated_at":"2019-01-22T16:11:15Z","actor":"Levar Burton","actor_id":"094ed10f-cd99-4a58-9b4b-65ab5b31b791","time":"2019-01-22T16:11:15Z"}],"current_page":1,"total_pages":30,"total_count":60,"per_page":2}',
status=200)
audit_logs = self.fulcrum_api.audit_logs.search()
self.assertIsInstance(audit_logs, dict)
self.assertEqual(len(audit_logs['audit_logs']), 2)
self.assertEqual(audit_logs['audit_logs'][0]['id'], 'def-456')
self.assertEqual(audit_logs['audit_logs'][1]['id'], 'ghi-789')
@httpretty.activate
def test_find(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/audit_logs/abc-123',
body='{"audit_log":{"source_type":"form","source_id":"zxy-987","action":"update","description":"Jason Sanford updated app GeoBooze - Changed:[Section:actions - YesNoField:post_to_slack];[RecordLinkField:beer_type];","data":null,"ip":"1.1.1.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36","location":"Ashburn, Virginia, United States","latitude":39.0481,"longitude":-77.4728,"admin_area":"VA","country":"US","locality":"Ashburn","postal_code":"20149","id":"abc-123","created_at":"2019-01-10T17:29:16Z","updated_at":"2019-01-10T17:29:16Z","actor":"George Costanza","actor_id":"abc123","time":"2019-01-10T17:29:16Z"}}',
status=200)
audit_log = self.fulcrum_api.audit_logs.find('abc-123')
self.assertIsInstance(audit_log, dict)
self.assertEqual(audit_log['audit_log']['id'], 'abc-123')
| import httpretty
from fulcrum.exceptions import NotFoundException, InternalServerErrorException
from tests import FulcrumTestCase
from tests.valid_objects import form as valid_form
class AuditLogTest(FulcrumTestCase):
@httpretty.activate
def test_all(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/audit_logs',
body='{"audit_logs": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "total_pages": 1, "per_page": 20000}',
status=200)
audit_logs = self.fulcrum_api.audit_logs.search()
self.assertIsInstance(audit_logs, dict)
self.assertEqual(len(audit_logs['audit_logs']), 2)
@httpretty.activate
def test_find(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/audit_logs/5b656cd8-f3ef-43e9-8d22-84d015052778',
body='{"record_count": 4, "description": "Food Carts and Trucks in Denver", "id": "5b656cd8-f3ef-43e9-8d22-84d015052778"}',
status=200)
audit_log = self.fulcrum_api.audit_logs.find('5b656cd8-f3ef-43e9-8d22-84d015052778')
self.assertIsInstance(audit_log, dict)
self.assertEqual(audit_log['id'], '5b656cd8-f3ef-43e9-8d22-84d015052778')
@httpretty.activate
def test_find_not_found(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/audit_logs/lobster', status=404)
try:
self.fulcrum_api.audit_logs.find('lobster')
except Exception as exc:
self.assertIsInstance(exc, NotFoundException) | Python | 0 |
74935550f886edfefa26298a98874e4c2dd2ab53 | Fold a line | extenteten/util.py | extenteten/util.py | import functools
import numpy
import tensorflow as tf
def static_shape(tensor):
return tf.convert_to_tensor(tensor).get_shape().as_list()
def static_shapes(*tensors):
return _map_to_list(static_shape, tensors)
def static_rank(tensor):
return len(static_shape(tf.convert_to_tensor(tensor)))
def static_ranks(*tensors):
return _map_to_list(static_rank, tensors)
def _map_to_list(func, xs):
return list(map(func, xs))
def dtypes(*tensors):
return [tensor.dtype for tensor in tensors]
def func_scope(name=None, initializer=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with tf.variable_scope(name or func.__name__,
initializer=initializer):
return func(*args, **kwargs)
return wrapper
return decorator
def on_device(device_name):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with tf.device(device_name):
return func(*args, **kwargs)
return wrapper
return decorator
def dimension_indices(tensor, start=0):
return [*range(static_rank(tensor))][start:]
@func_scope()
def dtype_min(dtype):
return tf.constant(_numpy_min(dtype.as_numpy_dtype))
def _numpy_min(dtype):
return numpy.finfo(dtype).min
@func_scope()
def dtype_epsilon(dtype):
return tf.constant(_numpy_epsilon(dtype.as_numpy_dtype))
def _numpy_epsilon(dtype):
return numpy.finfo(dtype).eps
def flatten(x):
return tf.reshape(x, [-1])
def rename(x, name):
return tf.identity(x, name)
| import functools
import numpy
import tensorflow as tf
def static_shape(tensor):
return tf.convert_to_tensor(tensor).get_shape().as_list()
def static_shapes(*tensors):
return _map_to_list(static_shape, tensors)
def static_rank(tensor):
return len(static_shape(tf.convert_to_tensor(tensor)))
def static_ranks(*tensors):
return _map_to_list(static_rank, tensors)
def _map_to_list(func, xs):
return list(map(func, xs))
def dtypes(*tensors):
return [tensor.dtype for tensor in tensors]
def func_scope(name=None, initializer=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with tf.variable_scope(name or func.__name__, initializer=initializer):
return func(*args, **kwargs)
return wrapper
return decorator
def on_device(device_name):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with tf.device(device_name):
return func(*args, **kwargs)
return wrapper
return decorator
def dimension_indices(tensor, start=0):
return [*range(static_rank(tensor))][start:]
@func_scope()
def dtype_min(dtype):
return tf.constant(_numpy_min(dtype.as_numpy_dtype))
def _numpy_min(dtype):
return numpy.finfo(dtype).min
@func_scope()
def dtype_epsilon(dtype):
return tf.constant(_numpy_epsilon(dtype.as_numpy_dtype))
def _numpy_epsilon(dtype):
return numpy.finfo(dtype).eps
def flatten(x):
return tf.reshape(x, [-1])
def rename(x, name):
return tf.identity(x, name)
| Python | 0.999989 |
952d70244f885dc194d83d5bb598fa9ebcdfceb2 | Add no store command-line option to trends util script | app/utils/insert/trendsCountryAndTowns.py | app/utils/insert/trendsCountryAndTowns.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Utility to get trend data and add to the database.
Expects a single country name and uses the country and child town
WOEIDs to get trend data.
Run file directly (not as a module) and with `--help` flag in order to see
usage instructions.
"""
import time
# Allow imports to be done when executing this file directly.
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
))
from lib import places, trends
from lib.query.place import countryReport
from lib.config import AppConf
appConf = AppConf()
def listCountries():
print u'See available countries below...\n'
countryReport.showTownCountByCountry(byName=True)
print u'Enter a country name from the above an argument.'
print u'Or, use `--default` flag to get the configured country, which ' \
u'is currently `{}`.'.format(appConf.get('TrendCron', 'countryName'))
def main(args):
"""
Provide help for the user or runs as a produce to get data from the
Twitter API for the selected country.
The max time is set in the app configuration file. If the duration of
the current iteration was less than the required max then we sleep for
the remaining number of seconds to make the iteration's total time close
to 12 seconds. If the duration was more, or the max was configured to
zero, no waiting is applied.
"""
if not args or set(args) & set(('-h', '--help')):
print u'Usage: ./app/utils/trendsCountryAndTowns.py'\
' [-d|--default|COUNTRYNAME] [-s|--show] [-f|--fast]' \
' [-n|--no-store] [-h|--help]'
elif set(args) & set(('-s', '--show')):
listCountries()
else:
print u'Starting job for trends by country and towns.'
if set(args) & set(('-d', '--default')):
# Use configured country name.
countryName = appConf.get('TrendCron', 'countryName')
else:
# Set country name string from arguments list, ignoring flags.
words = [word for word in args if not word.startswith('-')]
countryName = ' '.join(words)
assert countryName, ('Country name input is missing.')
if set(args) & set(('-f', '--fast')):
# User can override the waiting with a --fast flag, which
# means queries will be done quick succession, at least within
# each 15 min rate-limited window.
minSeconds = 0
else:
minSeconds = appConf.getint('TrendCron', 'minSeconds')
woeidIDs = places.countryAndTowns(countryName)
delete = bool(set(args) & set(('-n', '--no-store')))
for woeid in woeidIDs:
start = time.time()
trends.insertTrendsForWoeid(woeid, delete=delete)
duration = time.time() - start
print u" took {}s".format(int(duration))
diff = minSeconds - duration
if diff > 0:
time.sleep(diff)
main(sys.argv[1:])
| #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Utility to get trend data and add to the database.
Expects a single country name and uses the country and child town
WOEIDs to get trend data.
Run file directly (not as a module) and with `--help` flag in order to see
usage instructions.
"""
import time
# Allow imports to be done when executing this file directly.
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
))
from lib import places, trends
from lib.query.place import countryReport
from lib.config import AppConf
appConf = AppConf()
def listCountries():
print u'See available countries below...\n'
countryReport.showTownCountByCountry(byName=True)
print u'Enter a country name from the above an argument.'
print u'Or, use `--default` flag to get the configured country, which ' \
u'is currently `{}`.'.format(appConf.get('TrendCron', 'countryName'))
def main(args):
"""
Provide help for the user or runs as a produce to get data from the
Twitter API for the selected country.
The max time is set in the app configuration file. If the duration of
the current iteration was less than the required max then we sleep for
the remaining number of seconds to make the iteration's total time close
to 12 seconds. If the duration was more, or the max was configured to
zero, no waiting is applied.
"""
if not args or set(args) & set(('-h', '--help')):
print u'Usage: ./app/utils/trendsCountryAndTowns.py'\
' [-d|--default|COUNTRYNAME] [-s|--show] [-f|--fast] [-h|--help]'
elif set(args) & set(('-s', '--show')):
listCountries()
else:
print u'Starting job for trends by country and towns.'
if set(args) & set(('-d', '--default')):
# Use configured country name.
countryName = appConf.get('TrendCron', 'countryName')
else:
# Set country name string from arguments list, ignoring flags.
words = [word for word in args if not word.startswith('-')]
countryName = ' '.join(words)
assert countryName, ('Country name input is missing.')
if set(args) & set(('-f', '--fast')):
# User can override the waiting with a --fast flag, which
# means queries will be done quick succession, at least within
# each 15 min rate-limited window.
minSeconds = 0
else:
minSeconds = appConf.getint('TrendCron', 'minSeconds')
woeidIDs = places.countryAndTowns(countryName)
for woeid in woeidIDs:
start = time.time()
trends.insertTrendsForWoeid(woeid)
duration = time.time() - start
print u" took {}s".format(int(duration))
diff = minSeconds - duration
if diff > 0:
time.sleep(diff)
main(sys.argv[1:])
| Python | 0 |
14d1cbae9323e3ff7d80480b39a96b76cada94b0 | Add a clear_requested signal | pyqode/core/frontend/widgets/menu_recents.py | pyqode/core/frontend/widgets/menu_recents.py | """
Provides a menu that display the list of recent files and a RecentFilesManager
which use your application's QSettings to store the list of recent files.
"""
import os
from pyqode.qt import QtCore, QtWidgets
class RecentFilesManager:
"""
Manages a list of recent files. The list of files is stored in your
application QSettings.
"""
#: Maximum number of files kept in the list.
max_recent_files = 15
def __init__(self, organisation, application):
self._settings = QtCore.QSettings(organisation, application)
def clear(self):
""" Clears recent files in QSettings """
self._settings.setValue('recentFiles', [])
def get_recent_files(self):
"""
Gets the list of recent files. (files that do not exists anymore
are automatically filtered)
"""
ret_val = []
files = self._settings.value('recentFiles', [])
# empty list
if files is None:
files = []
# single file
if isinstance(files, str):
files = [files]
# filter files, remove files that do not exist anymore
for file in files:
if os.path.exists(file):
ret_val.append(file)
return ret_val
def open_file(self, file):
"""
Adds a file to the list (and move it to the top of the list if the
file already exists)
"""
files = self.get_recent_files()
try:
files.remove(file)
except ValueError:
pass
files.insert(0, file)
# discard old files
del files[self.max_recent_files:]
self._settings.setValue('recentFiles', files)
class MenuRecentFiles(QtWidgets.QMenu):
"""
Menu that manage the list of recent files.
To use the menu, simply pass connect to the open_requested signal.
"""
#: Signal emitted when the user clicked on a recent file action.
#: The parameter is the path of the file to open.
open_requested = QtCore.Signal(str)
clear_requested = QtCore.Signal()
def __init__(self, parent, recent_files_manager=None,
title='Recent files'):
"""
:param organisation: name of your organisation as used for your own
QSettings
:param application: name of your application as used for your own
QSettings
:param parent: parent object
"""
super().__init__(title, parent)
#: Recent files manager
self.manager = recent_files_manager
#: List of recent files actions
self.recent_files_actions = []
self.update_actions()
def update_actions(self):
"""
Updates the list of actions.
"""
self.clear()
self.recent_files_actions[:] = []
for file in self.manager.get_recent_files():
action = QtWidgets.QAction(self)
action.setText(os.path.split(file)[1])
action.setData(file)
action.triggered.connect(self._on_action_triggered)
self.addAction(action)
self.recent_files_actions.append(action)
self.addSeparator()
action_clear = QtWidgets.QAction('Clear list', self)
action_clear.triggered.connect(self.clear_recent_files)
self.addAction(action_clear)
def clear_recent_files(self):
""" Clear recent files and menu. """
self.manager.clear()
self.update_actions()
self.clear_requested.emit()
def _on_action_triggered(self):
"""
Emits open_requested when a recent file action has been triggered.
"""
action = self.sender()
assert isinstance(action, QtWidgets.QAction)
path = action.data()
self.open_requested.emit(path)
self.update_actions()
| """
Provides a menu that display the list of recent files and a RecentFilesManager
which use your application's QSettings to store the list of recent files.
"""
import os
from pyqode.qt import QtCore, QtWidgets
class RecentFilesManager:
"""
Manages a list of recent files. The list of files is stored in your
application QSettings.
"""
#: Maximum number of files kept in the list.
max_recent_files = 15
def __init__(self, organisation, application):
self._settings = QtCore.QSettings(organisation, application)
def clear(self):
""" Clears recent files in QSettings """
self._settings.setValue('recentFiles', [])
def get_recent_files(self):
"""
Gets the list of recent files. (files that do not exists anymore
are automatically filtered)
"""
ret_val = []
files = self._settings.value('recentFiles', [])
# empty list
if files is None:
files = []
# single file
if isinstance(files, str):
files = [files]
# filter files, remove files that do not exist anymore
for file in files:
if os.path.exists(file):
ret_val.append(file)
return ret_val
def open_file(self, file):
"""
Adds a file to the list (and move it to the top of the list if the
file already exists)
"""
files = self.get_recent_files()
try:
files.remove(file)
except ValueError:
pass
files.insert(0, file)
# discard old files
del files[self.max_recent_files:]
self._settings.setValue('recentFiles', files)
class MenuRecentFiles(QtWidgets.QMenu):
"""
Menu that manage the list of recent files.
To use the menu, simply pass connect to the open_requested signal.
"""
#: Signal emitted when the user clicked on a recent file action.
#: The parameter is the path of the file to open.
open_requested = QtCore.Signal(str)
def __init__(self, parent, recent_files_manager=None,
title='Recent files'):
"""
:param organisation: name of your organisation as used for your own
QSettings
:param application: name of your application as used for your own
QSettings
:param parent: parent object
"""
super().__init__(title, parent)
#: Recent files manager
self.manager = recent_files_manager
#: List of recent files actions
self.recent_files_actions = []
self.update_actions()
def update_actions(self):
"""
Updates the list of actions.
"""
self.clear()
self.recent_files_actions[:] = []
for file in self.manager.get_recent_files():
action = QtWidgets.QAction(self)
action.setText(os.path.split(file)[1])
action.setData(file)
action.triggered.connect(self._on_action_triggered)
self.addAction(action)
self.recent_files_actions.append(action)
self.addSeparator()
action_clear = QtWidgets.QAction('Clear list', self)
action_clear.triggered.connect(self.clear_recent_files)
self.addAction(action_clear)
def clear_recent_files(self):
""" Clear recent files and menu. """
self.manager.clear()
self.update_actions()
def _on_action_triggered(self):
"""
Emits open_requested when a recent file action has been triggered.
"""
action = self.sender()
assert isinstance(action, QtWidgets.QAction)
path = action.data()
self.open_requested.emit(path)
self.update_actions()
| Python | 0.000001 |
fdd8e33b58f8ffba50dff86931a47daf396903e8 | Revert tweak to TokenPermissions.has_permission() | netbox/netbox/api/authentication.py | netbox/netbox/api/authentication.py | from django.conf import settings
from rest_framework import authentication, exceptions
from rest_framework.permissions import BasePermission, DjangoObjectPermissions, SAFE_METHODS
from users.models import Token
class TokenAuthentication(authentication.TokenAuthentication):
"""
A custom authentication scheme which enforces Token expiration times.
"""
model = Token
def authenticate_credentials(self, key):
model = self.get_model()
try:
token = model.objects.prefetch_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed("Invalid token")
# Enforce the Token's expiration time, if one has been set.
if token.is_expired:
raise exceptions.AuthenticationFailed("Token expired")
if not token.user.is_active:
raise exceptions.AuthenticationFailed("User inactive")
return token.user, token
class TokenPermissions(DjangoObjectPermissions):
"""
Custom permissions handler which extends the built-in DjangoModelPermissions to validate a Token's write ability
for unsafe requests (POST/PUT/PATCH/DELETE).
"""
# Override the stock perm_map to enforce view permissions
perms_map = {
'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': [],
'HEAD': ['%(app_label)s.view_%(model_name)s'],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}
def __init__(self):
# LOGIN_REQUIRED determines whether read-only access is provided to anonymous users.
self.authenticated_users_only = settings.LOGIN_REQUIRED
super().__init__()
def _verify_write_permission(self, request):
# If token authentication is in use, verify that the token allows write operations (for unsafe methods).
if request.method in SAFE_METHODS or request.auth.write_enabled:
return True
def has_permission(self, request, view):
# Enforce Token write ability
if isinstance(request.auth, Token) and not self._verify_write_permission(request):
return False
return super().has_permission(request, view)
def has_object_permission(self, request, view, obj):
# Enforce Token write ability
if isinstance(request.auth, Token) and not self._verify_write_permission(request):
return False
return super().has_object_permission(request, view, obj)
class IsAuthenticatedOrLoginNotRequired(BasePermission):
"""
Returns True if the user is authenticated or LOGIN_REQUIRED is False.
"""
def has_permission(self, request, view):
if not settings.LOGIN_REQUIRED:
return True
return request.user.is_authenticated
| from django.conf import settings
from rest_framework import authentication, exceptions
from rest_framework.permissions import BasePermission, DjangoObjectPermissions, SAFE_METHODS
from users.models import Token
class TokenAuthentication(authentication.TokenAuthentication):
"""
A custom authentication scheme which enforces Token expiration times.
"""
model = Token
def authenticate_credentials(self, key):
model = self.get_model()
try:
token = model.objects.prefetch_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed("Invalid token")
# Enforce the Token's expiration time, if one has been set.
if token.is_expired:
raise exceptions.AuthenticationFailed("Token expired")
if not token.user.is_active:
raise exceptions.AuthenticationFailed("User inactive")
return token.user, token
class TokenPermissions(DjangoObjectPermissions):
"""
Custom permissions handler which extends the built-in DjangoModelPermissions to validate a Token's write ability
for unsafe requests (POST/PUT/PATCH/DELETE).
"""
# Override the stock perm_map to enforce view permissions
perms_map = {
'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': [],
'HEAD': ['%(app_label)s.view_%(model_name)s'],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}
def __init__(self):
# LOGIN_REQUIRED determines whether read-only access is provided to anonymous users.
self.authenticated_users_only = settings.LOGIN_REQUIRED
super().__init__()
def _verify_write_permission(self, request):
# If token authentication is in use, verify that the token allows write operations (for unsafe methods).
if request.method in SAFE_METHODS or request.auth.write_enabled:
return True
def has_permission(self, request, view):
# User must be authenticated
if not request.user.is_authenticated:
return False
# Enforce Token write ability
if isinstance(request.auth, Token) and not self._verify_write_permission(request):
return False
return super().has_permission(request, view)
def has_object_permission(self, request, view, obj):
# Enforce Token write ability
if isinstance(request.auth, Token) and not self._verify_write_permission(request):
return False
return super().has_object_permission(request, view, obj)
class IsAuthenticatedOrLoginNotRequired(BasePermission):
"""
Returns True if the user is authenticated or LOGIN_REQUIRED is False.
"""
def has_permission(self, request, view):
if not settings.LOGIN_REQUIRED:
return True
return request.user.is_authenticated
| Python | 0 |
f2cc74d79abf42c0f199c48ef9110bce6cec45b4 | Update alcatel_sros_ssh.py | netmiko/alcatel/alcatel_sros_ssh.py | netmiko/alcatel/alcatel_sros_ssh.py | '''
Alcatel-Lucent SROS support
'''
from netmiko.ssh_connection import SSHConnection
class AlcatelSrosSSH(SSHConnection):
'''
SROS support
'''
def session_preparation(self):
self.disable_paging(command="environment no more\n")
def enable(self):
pass
| '''
Alcatel-Lucent SROS support
'''
from netmiko.ssh_connection import SSHConnection
class AlcatelSrosSSH(SSHConnection):
'''
SROS support
'''
def session_preparation(self):
self.disable_paging(command="\environment no more\n")
def enable(self):
pass
| Python | 0 |
0824bfd48692d3ca7711171c0dea6868411db4ce | Fix window extraction convolution | thinc/neural/_classes/convolution.py | thinc/neural/_classes/convolution.py | from .model import Model
from ... import describe
from ...describe import Dimension
@describe.attributes(
nW=Dimension("Number of surrounding tokens on each side to extract")
)
class ExtractWindow(Model):
'''Add context to vectors in a sequence by concatenating n surrounding
vectors.
If the input is (10, 32) and n=1, the output will be (10, 96), with
output[i] made up of (input[i-1], input[i], input[i+1]).
'''
name = 'extract_window'
def __init__(self, nW=2):
Model.__init__(self)
self.nW = nW
def predict(self, X):
nr_feat = self.nW * 2 + 1
shape = (X.shape[0], nr_feat) + X.shape[1:]
output = self.ops.allocate(shape)
for i in range(1, self.nW+1):
output[:-i, self.nW-i] = X[i:]
# output[i, n] will be w[i]
output[:, self.nW] = X
for i in range(1, self.nW+1):
output[i:, self.nW + i] = X[:-i]
return output.reshape(shape[0], self.ops.xp.prod(shape[1:]))
def begin_update(self, X__bi, drop=0.0):
X__bo = self.predict(X__bi)
X__bo, bp_dropout = self.ops.dropout(X__bo, drop)
finish_update = self._get_finish_update()
return X__bo, bp_dropout(finish_update)
def _get_finish_update(self):
return lambda d, sgd=None: backprop_concatenate(self.ops, d, self.nW)
def backprop_concatenate(ops, dY__bo, nW):
nr_feat = nW * 2 + 1
bfi = (dY__bo.shape[0], nr_feat, int(dY__bo.shape[-1] / nr_feat))
dY__bfi = dY__bo.reshape(bfi)
dX__bi = ops.allocate((dY__bo.shape[0], bfi[-1]))
for f in range(1, nW+1):
dX__bi[f:] += dY__bfi[:-f, nW-f] # Words at start not used as rightward feats
dX__bi += dY__bfi[:, nW]
for f in range(1, nW+1):
dX__bi[:-f] += dY__bfi[f:, nW+f] # Words at end not used as leftward feats
return dX__bi
| from .model import Model
from ... import describe
from ...describe import Dimension
@describe.attributes(
nW=Dimension("Number of surrounding tokens on each side to extract")
)
class ExtractWindow(Model):
'''Add context to vectors in a sequence by concatenating n surrounding
vectors.
If the input is (10, 32) and n=1, the output will be (10, 96), with
output[i] made up of (input[i-1], input[i], input[i+1]).
'''
name = 'extract_window'
def __init__(self, nW=2):
Model.__init__(self)
self.nW = nW
def predict(self, X):
nr_feat = self.nW * 2 + 1
shape = (X.shape[0], nr_feat) + X.shape[1:]
output = self.ops.allocate(shape)
# Let L(w[i]) LL(w[i]), R(w[i]), RR(w[i])
# denote the words one and two to the left and right of word i.
# So L(w[i]) == w[i-1] for i >= 1 and {empty} otherwise.
# output[i, n-1] will be L(w[i]) so w[i-1] or empty
# output[i, n-2] will be LL(w[i]) so w[i-2] or empty
# etc
for i in range(self.nW):
output[i+1:, i] = X[:-(i+1)]
# output[i, n] will be w[i]
output[:, self.nW] = X
# Now R(w[i]), RR(w[i]) etc
for i in range(1, self.nW+1):
output[:-i, self.nW + i] = X[:-i]
return output.reshape(shape[0], self.ops.xp.prod(shape[1:]))
def begin_update(self, X, drop=0.0):
output = self.predict(X)
output, bp_dropout = self.ops.dropout(output, drop)
def finish_update(gradient, sgd=None, **kwargs):
nr_feat = self.nW * 2 + 1
shape = (gradient.shape[0], nr_feat, int(gradient.shape[-1] / nr_feat))
gradient = gradient.reshape(shape)
output = self.ops.allocate((gradient.shape[0], gradient.shape[-1]))
# Word w[i+1] is the R feature of w[i]. So
# grad(w[i+1]) += grad(R[i, n+1])
# output[:-1] += gradient[1:, self.nW+1]
for i in range(1, self.nW+1): # As rightward features
output[:-i] += gradient[i:, self.nW+i]
# Word w[i-1] is the L feature of w[i]. So
# grad(w[i-1]) += grad(L[i, n-1])
# output[1:] += gradient[:-1, self.nW-1]
for i in range(1, self.nW+1): # As leftward features
output[i:] += gradient[:-i, self.nW-i]
# Central column of gradient is the word's own feature
output += gradient[:, self.nW, :]
return output
return output, bp_dropout(finish_update)
| Python | 0.000002 |
91ff2ed96dc3ba197f71be935ac23796d40ef5dc | Update TFRT dependency to use revision http://github.com/tensorflow/runtime/commit/812a20bfa97f7b56eb3340c2f75358db58483974. | third_party/tf_runtime/workspace.bzl | third_party/tf_runtime/workspace.bzl | """Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "812a20bfa97f7b56eb3340c2f75358db58483974"
TFRT_SHA256 = "8235d34c674a842fb08f5fc7f7b6136a1af1dbb20a2ec7213dd99848b884878f"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT),
urls = [
"http://mirror.tensorflow.org/github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
"https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
],
)
| """Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "c442a283246c2060d139d4cadb0f8ff59ee7e7da"
TFRT_SHA256 = "649107aabf7a242678448c44d4a51d5355904222de7d454a376ad511c803cf0f"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT),
urls = [
"http://mirror.tensorflow.org/github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
"https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
],
)
| Python | 0.000002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.