commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
---|---|---|---|---|---|---|---|---|---|---|
5a82f76e3e95268fb1bbb297faa43e7f7cb59058 | tests/perf_concrete_execution.py | tests/perf_concrete_execution.py |
# Performance tests on concrete code execution without invoking Unicorn engine
import os
import time
import logging
import angr
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests'))
def test_tight_loop(arch):
b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False)
simgr = b.factory.simgr()
# logging.getLogger('angr.sim_manager').setLevel(logging.INFO)
start = time.time()
simgr.explore()
elapsed = time.time() - start
print("Elapsed %f sec" % elapsed)
print(simgr)
if __name__ == "__main__":
test_tight_loop("x86_64")
|
# Performance tests on concrete code execution without invoking Unicorn engine
import os
import time
import logging
import angr
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests'))
def test_tight_loop(arch):
b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False)
state = b.factory.full_init_state(plugins={'registers': angr.state_plugins.SimLightRegisters()},
remove_options={angr.sim_options.COPY_STATES})
simgr = b.factory.simgr(state)
# logging.getLogger('angr.sim_manager').setLevel(logging.INFO)
start = time.time()
simgr.explore()
elapsed = time.time() - start
print("Elapsed %f sec" % elapsed)
print(simgr)
if __name__ == "__main__":
test_tight_loop("x86_64")
| Enable SimLightRegisters and remove COPY_STATES for the performance test case. | Enable SimLightRegisters and remove COPY_STATES for the performance test case.
| Python | bsd-2-clause | angr/angr,schieb/angr,schieb/angr,iamahuman/angr,schieb/angr,iamahuman/angr,angr/angr,iamahuman/angr,angr/angr | ---
+++
@@ -13,7 +13,9 @@
def test_tight_loop(arch):
b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False)
- simgr = b.factory.simgr()
+ state = b.factory.full_init_state(plugins={'registers': angr.state_plugins.SimLightRegisters()},
+ remove_options={angr.sim_options.COPY_STATES})
+ simgr = b.factory.simgr(state)
# logging.getLogger('angr.sim_manager').setLevel(logging.INFO)
|
db981f7616283992fd1d17a3b1bf7d300b8ee34f | proper_parens.py | proper_parens.py | #!/usr/bin/env python
from __future__ import unicode_literals
<<<<<<< HEAD
def check_statement1(value):
output = 0
while output >= 0:
for item in value:
if item == ")":
output -= 1
if output == -1:
return -1
elif item == "(":
output += 1
if output == 0:
return 0
elif output > 1:
return 1
=======
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
index = 0
while index < len(value) and output >= 0:
# If the count is ever < 0, statement must be -1 (broken), end loop
# If the index is out of range, end loop
if value[index] == ")":
# Subtract 1 for every close paren
output -= 1
elif value[index] == "(":
# Add 1 for every close paren
output += 1
index += 1
if output == -1:
# Check if output is -1 (broken)
return output
elif not output:
# Check if output is 0 (balanced)
return output
else:
# Must be 1 (open) if it makes it to here
return 1
>>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08
| #!/usr/bin/env python
from __future__ import unicode_literals
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
index = 0
while index < len(value) and output >= 0:
# If the count is ever < 0, statement must be -1 (broken), end loop
# If the index is out of range, end loop
if value[index] == ")":
# Subtract 1 for every close paren
output -= 1
elif value[index] == "(":
# Add 1 for every close paren
output += 1
index += 1
if output == -1:
# Check if output is -1 (broken)
return output
elif not output:
# Check if output is 0 (balanced)
return output
else:
# Must be 1 (open) if it makes it to here
return 1
| Fix proper parens merge conflict | Fix proper parens merge conflict
| Python | mit | constanthatz/data-structures | ---
+++
@@ -2,22 +2,6 @@
from __future__ import unicode_literals
-<<<<<<< HEAD
-def check_statement1(value):
- output = 0
- while output >= 0:
- for item in value:
- if item == ")":
- output -= 1
- if output == -1:
- return -1
- elif item == "(":
- output += 1
- if output == 0:
- return 0
- elif output > 1:
- return 1
-=======
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
@@ -43,4 +27,3 @@
else:
# Must be 1 (open) if it makes it to here
return 1
->>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08 |
075b8ba1813360720fc8933dc5e167f92b4e3aaf | python/epidb/client/client.py | python/epidb/client/client.py |
import urllib
__version__ = '0.0~20090901.1'
__user_agent__ = 'EpiDBClient v%s/python' % __version__
class EpiDBClientOpener(urllib.FancyURLopener):
version = __user_agent__
class EpiDBClient:
version = __version__
user_agent = __user_agent__
server = 'https://egg.science.uva.nl:7443'
path_survey = '/survey/'
def __init__(self, api_key=None):
self.api_key = api_key
def __epidb_call(self, url, param):
data = urllib.urlencode(param)
opener = EpiDBClientOpener()
sock = opener.open(url, data)
res = sock.read()
sock.close()
return res
def survey_submit(self, data):
param = {
'data': data
}
url = self.server + self.path_survey
res = self.__epidb_call(url, param)
return res
|
import urllib
import urllib2
__version__ = '0.0~20090901.1'
__user_agent__ = 'EpiDBClient v%s/python' % __version__
class EpiDBClient:
version = __version__
user_agent = __user_agent__
server = 'https://egg.science.uva.nl:7443'
path_survey = '/survey/'
def __init__(self, api_key=None):
self.api_key = api_key
def __epidb_call(self, url, param):
data = urllib.urlencode(param)
req = urllib2.Request(url)
req.add_header('User-Agent', self.user_agent)
if self.api_key:
req.add_header('Cookie', 'epidb-apikey=%s' % self.api_key)
sock = urllib2.urlopen(req, data)
res = sock.read()
sock.close()
return res
def survey_submit(self, data):
param = {
'data': data
}
url = self.server + self.path_survey
res = self.__epidb_call(url, param)
return res
| Send api-key through HTTP cookie. | [python] Send api-key through HTTP cookie.
| Python | agpl-3.0 | ISIFoundation/influenzanet-epidb-client | ---
+++
@@ -1,11 +1,9 @@
import urllib
+import urllib2
__version__ = '0.0~20090901.1'
__user_agent__ = 'EpiDBClient v%s/python' % __version__
-
-class EpiDBClientOpener(urllib.FancyURLopener):
- version = __user_agent__
class EpiDBClient:
@@ -20,8 +18,12 @@
def __epidb_call(self, url, param):
data = urllib.urlencode(param)
- opener = EpiDBClientOpener()
- sock = opener.open(url, data)
+
+ req = urllib2.Request(url)
+ req.add_header('User-Agent', self.user_agent)
+ if self.api_key:
+ req.add_header('Cookie', 'epidb-apikey=%s' % self.api_key)
+ sock = urllib2.urlopen(req, data)
res = sock.read()
sock.close()
|
d3933d58b2ebcb0fb0c6301344335ae018973774 | n_pair_mc_loss.py | n_pair_mc_loss.py | from chainer import cuda
from chainer.functions import matmul
from chainer.functions import transpose
from chainer.functions import softmax_cross_entropy
from chainer.functions import batch_l2_norm_squared
def n_pair_mc_loss(f, f_p, l2_reg):
"""Multi-class N-pair loss (N-pair-mc loss) function.
Args:
f (~chainer.Variable): Feature vectors.
All examples must be different classes each other.
f_p (~chainer.Variable): Positive examples corresponding to f.
Each example must be the same class for each example in f.
l2_reg (~float): A weight of L2 regularization for feature vectors.
Returns:
~chainer.Variable: Loss value.
See: `Improved Deep Metric Learning with Multi-class N-pair Loss \
Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\
learning-with-multi-class-n-pair-loss-objective>`_
"""
logit = matmul(f, transpose(f_p))
N = len(logit.data)
xp = cuda.get_array_module(logit.data)
loss_sce = softmax_cross_entropy(logit, xp.arange(N))
l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p))
loss = loss_sce + l2_reg * l2_loss
return loss
| from chainer import cuda
from chainer.functions import matmul
from chainer.functions import transpose
from chainer.functions import softmax_cross_entropy
from chainer.functions import batch_l2_norm_squared
def n_pair_mc_loss(f, f_p, l2_reg):
"""Multi-class N-pair loss (N-pair-mc loss) function.
Args:
f (~chainer.Variable): Feature vectors.
All examples must be different classes each other.
f_p (~chainer.Variable): Positive examples corresponding to f.
Each example must be the same class for each example in f.
l2_reg (~float): A weight of L2 regularization for feature vectors.
Returns:
~chainer.Variable: Loss value.
See: `Improved Deep Metric Learning with Multi-class N-pair Loss \
Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\
learning-with-multi-class-n-pair-loss-objective>`_
"""
logit = matmul(f, transpose(f_p))
N = len(logit.data)
xp = cuda.get_array_module(logit.data)
loss_sce = softmax_cross_entropy(logit, xp.arange(N))
l2_loss = sum(batch_l2_norm_squared(f) +
batch_l2_norm_squared(f_p)) / (2.0 * N)
loss = loss_sce + l2_reg * l2_loss
return loss
| Modify to average the L2 norm loss of output vectors | Modify to average the L2 norm loss of output vectors
| Python | mit | ronekko/deep_metric_learning | ---
+++
@@ -27,6 +27,7 @@
N = len(logit.data)
xp = cuda.get_array_module(logit.data)
loss_sce = softmax_cross_entropy(logit, xp.arange(N))
- l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p))
+ l2_loss = sum(batch_l2_norm_squared(f) +
+ batch_l2_norm_squared(f_p)) / (2.0 * N)
loss = loss_sce + l2_reg * l2_loss
return loss |
0261930771864cc4cdba58ece3959020fb499cd1 | neupy/__init__.py | neupy/__init__.py | """
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.2.1'
| """
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0dev1'
| Set up version 0.3.0 dev 1. | Set up version 0.3.0 dev 1.
| Python | mit | itdxer/neupy,itdxer/neupy,itdxer/neupy,itdxer/neupy | ---
+++
@@ -3,4 +3,4 @@
"""
-__version__ = '0.2.1'
+__version__ = '0.3.0dev1' |
a094d29959243777fad47ea38b4497d891b9990e | data/data/models.py | data/data/models.py | from django.db import models
from uuid import uuid4
import hashlib
def _get_rand_hash():
uid = uuid4()
return hashlib.sha1(str(uid)).hexdigest()
def generate_token_secret():
return _get_rand_hash(), _get_rand_hash()
class User(models.Model):
username = models.CharField(max_length=200, unique=True)
password = models.CharField(max_length=200)
token = models.CharField(max_length=200, blank=True)
secret = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.username
def save(self, *args, **kwargs):
if not self.token:
self.token, self.secret = generate_token_secret()
return super(User, self).save(*args, **kwargs)
| from django.db import models
from uuid import uuid4
import hashlib
def get_rand_hash():
uid = uuid4()
return hashlib.sha1(str(uid)).hexdigest()
class User(models.Model):
username = models.CharField(max_length=200, unique=True)
password = models.CharField(max_length=200)
token = models.CharField(max_length=200, default=get_rand_hash)
secret = models.CharField(max_length=200, default=get_rand_hash)
def __unicode__(self):
return self.username
| Set token and secret by default | Set token and secret by default
| Python | bsd-2-clause | honza/oauth-service,honza/oauth-service | ---
+++
@@ -3,25 +3,16 @@
import hashlib
-def _get_rand_hash():
+def get_rand_hash():
uid = uuid4()
return hashlib.sha1(str(uid)).hexdigest()
-
-
-def generate_token_secret():
- return _get_rand_hash(), _get_rand_hash()
class User(models.Model):
username = models.CharField(max_length=200, unique=True)
password = models.CharField(max_length=200)
- token = models.CharField(max_length=200, blank=True)
- secret = models.CharField(max_length=200, blank=True)
+ token = models.CharField(max_length=200, default=get_rand_hash)
+ secret = models.CharField(max_length=200, default=get_rand_hash)
def __unicode__(self):
return self.username
-
- def save(self, *args, **kwargs):
- if not self.token:
- self.token, self.secret = generate_token_secret()
- return super(User, self).save(*args, **kwargs) |
d96b07d529ea7ced5cbe5f5accaa84485e14395a | Lib/test/test_tk.py | Lib/test/test_tk.py | from test import support
# Skip test if _tkinter wasn't built.
support.import_module('_tkinter')
import tkinter
from tkinter.test import runtktests
import unittest
import tkinter
try:
tkinter.Button()
except tkinter.TclError as msg:
# assuming tk is not available
raise unittest.SkipTest("tk not available: %s" % msg)
def test_main(enable_gui=False):
if enable_gui:
if support.use_resources is None:
support.use_resources = ['gui']
elif 'gui' not in support.use_resources:
support.use_resources.append('gui')
support.run_unittest(
*runtktests.get_tests(text=False, packages=['test_tkinter']))
if __name__ == '__main__':
test_main(enable_gui=True)
| from test import support
# Skip test if _tkinter wasn't built.
support.import_module('_tkinter')
import tkinter
from tkinter.test import runtktests
import unittest
try:
tkinter.Button()
except tkinter.TclError as msg:
# assuming tk is not available
raise unittest.SkipTest("tk not available: %s" % msg)
def test_main(enable_gui=False):
if enable_gui:
if support.use_resources is None:
support.use_resources = ['gui']
elif 'gui' not in support.use_resources:
support.use_resources.append('gui')
support.run_unittest(
*runtktests.get_tests(text=False, packages=['test_tkinter']))
if __name__ == '__main__':
test_main(enable_gui=True)
| Remove redundant import of tkinter. | Remove redundant import of tkinter.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -5,9 +5,6 @@
import tkinter
from tkinter.test import runtktests
import unittest
-
-
-import tkinter
try:
tkinter.Button() |
4d4de16969439c71f0e9e15b32b26bd4b7310e8f | Simulated_import.py | Simulated_import.py | #!/usr/bin/env python
# We're going to simulate how evolution_master should import things
from genes import golang
from genes import web_cli
# etc...
| #!/usr/bin/env python
# We're going to simulate how evolution_master should import things
from genes import docker
from genes import java
# etc...
| Change simulated around for existing modules | Change simulated around for existing modules | Python | mit | hatchery/Genepool2,hatchery/genepool | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# We're going to simulate how evolution_master should import things
-from genes import golang
-from genes import web_cli
+from genes import docker
+from genes import java
# etc... |
f29377a4f7208d75490e550a732a24cb6f471f18 | linked_list.py | linked_list.py | # -*- coding: utf-8 -*-
class Node(object):
""" """
def __init__(self, value, pointer=None):
self.value = value
self.pointer = pointer
class LinkedList(object):
""" """
def __init__(self):
self.length = 0
self.header = None
def push(self, value):
temp_node = self.header
new_node = Node(value, temp_node)
self.header = new_node
# self.set_init_list(*value)
# def set_init_list(self, *values):
# for value in values:
# self.length += 1
| # -*- coding: utf-8 -*-
class Node(object):
""" """
def __init__(self, value, pointer=None):
self.value = value
self.pointer = pointer
class LinkedList(object):
""" """
def __init__(self):
self.length = 0
self.header = None
def __len__(self):
return self.length
def push(self, value):
temp_node = self.header
new_node = Node(value, temp_node)
self.header = new_node
self.length += 1
def size(self):
return len(self)
# self.set_init_list(*value)
# def set_init_list(self, *values):
# for value in values:
# self.length += 1
| Add size and len finctions. | Add size and len finctions.
| Python | mit | jefferyrayrussell/data-structures | ---
+++
@@ -14,10 +14,17 @@
self.length = 0
self.header = None
+ def __len__(self):
+ return self.length
+
def push(self, value):
temp_node = self.header
new_node = Node(value, temp_node)
self.header = new_node
+ self.length += 1
+
+ def size(self):
+ return len(self)
# self.set_init_list(*value) |
3c1523f2fc3fec918f451a7dc361be9eb631524c | serrano/urls.py | serrano/urls.py | from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'', include(patterns('',
url(r'^$', include('serrano.resources')),
url(r'^fields/', include('serrano.resources.field')),
url(r'^concepts/', include('serrano.resources.concept')),
url(r'^contexts/', include('serrano.resources.context', namespace='contexts')),
url(r'^queries/', include('serrano.resources.query', namespace='queries')),
url(r'^views/', include('serrano.resources.view', namespace='views')),
url(r'^data/', include(patterns('',
url(r'^export/', include('serrano.resources.exporter')),
url(r'^preview/', include('serrano.resources.preview')),
), namespace='data')),
), namespace='serrano')),
)
| import time
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'', include(patterns('',
url(r'^$', include('serrano.resources')),
url(r'^fields/', include('serrano.resources.field')),
url(r'^concepts/', include('serrano.resources.concept')),
url(r'^contexts/', include('serrano.resources.context', namespace='contexts')),
url(r'^queries/', include('serrano.resources.query', namespace='queries')),
url(r'^views/', include('serrano.resources.view', namespace='views')),
url(r'^data/', include(patterns('',
url(r'^export/', include('serrano.resources.exporter')),
url(r'^preview/', include('serrano.resources.preview')),
), namespace='data')),
), namespace='serrano')),
)
| Insert unused import to test pyflakes in travis | Insert unused import to test pyflakes in travis
| Python | bsd-2-clause | chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night,chop-dbhi/serrano | ---
+++
@@ -1,3 +1,4 @@
+import time
from django.conf.urls import patterns, url, include
|
06e858fc86f8f34ccae521cb269c959569f53f97 | script/sample/submitpython.py | script/sample/submitpython.py | #!/usr/bin/env python
from __future__ import print_function
import multyvac
multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/v1')
def add(a, b):
return a + b
jid = multyvac.submit(add, 3, 4)
result = multyvac.get(jid).get_result()
print("result = {}".format(result))
| #!/usr/bin/env python
# CLOUDPIPE_URL=http://`echo $DOCKER_HOST | cut -d ":" -f2 | tr -d "/"`:8000/v1 python2 script/sample/submitpython.py
from __future__ import print_function
import multyvac
import os
# Grab from the CLOUDPIPE_URL environment variable, otherwise assume they have
# /etc/hosts configured to point to their docker
api_url = os.environ.get('CLOUDPIPE_URL', 'http://docker:8000/v1')
multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url=api_url)
def add(a, b):
return a + b
jid = multyvac.submit(add, 3, 4)
result = multyvac.get(jid).get_result()
print("added {} and {} to get {}... in the cloud!".format(3,4,result))
| Allow api_url in the script to be configurable | Allow api_url in the script to be configurable
| Python | bsd-3-clause | cloudpipe/cloudpipe,cloudpipe/cloudpipe,cloudpipe/cloudpipe | ---
+++
@@ -1,14 +1,21 @@
#!/usr/bin/env python
+
+# CLOUDPIPE_URL=http://`echo $DOCKER_HOST | cut -d ":" -f2 | tr -d "/"`:8000/v1 python2 script/sample/submitpython.py
from __future__ import print_function
import multyvac
-multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/v1')
+import os
+# Grab from the CLOUDPIPE_URL environment variable, otherwise assume they have
+# /etc/hosts configured to point to their docker
+api_url = os.environ.get('CLOUDPIPE_URL', 'http://docker:8000/v1')
+
+multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url=api_url)
def add(a, b):
return a + b
jid = multyvac.submit(add, 3, 4)
result = multyvac.get(jid).get_result()
-print("result = {}".format(result))
+print("added {} and {} to get {}... in the cloud!".format(3,4,result)) |
f33c66d4b1b439f6d4ede943812985783d961483 | Speech/processor.py | Speech/processor.py | # Retrieve file from Facebook
import urllib, convert, re, os
# from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve (audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
| # Retrieve file from Facebook
import urllib, convert, re, os
# from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
| Modify ffmpeg path heroku 2 | Modify ffmpeg path heroku 2
| Python | mit | hungtraan/FacebookBot,hungtraan/FacebookBot,hungtraan/FacebookBot | ---
+++
@@ -11,7 +11,7 @@
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
- urllib.urlretrieve (audio_url, './audio/retrieved_audio/{}'.format(file_name))
+ urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav")) |
5d3c6452f8efd0667948094693e90392abb99091 | statsmodels/tests/test_package.py | statsmodels/tests/test_package.py | import subprocess
import pytest
from statsmodels.compat.platform import PLATFORM_WIN
from statsmodels.compat.scipy import SCIPY_11
def test_lazy_imports():
# Check that when statsmodels.api is imported, matplotlib is _not_ imported
cmd = ("import statsmodels.api as sm; "
"import sys; "
"mods = [x for x in sys.modules if 'matplotlib.pyplot' in x]; "
"assert not mods, mods")
# TODO: is there a cleaner way to do this import in an isolated environment
pyexe = 'python3' if not PLATFORM_WIN else 'python'
p = subprocess.Popen(pyexe + ' -c "' + cmd + '"',
shell=True, close_fds=True)
p.wait()
rc = p.returncode
assert rc == 0
@pytest.mark.skipif(SCIPY_11, reason='SciPy raises on -OO')
def test_docstring_optimization_compat():
# GH#5235 check that importing with stripped docstrings doesn't raise
p = subprocess.Popen('python -OO -c "import statsmodels.api as sm"',
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate()
rc = p.returncode
assert rc == 0, out
| import subprocess
import pytest
from statsmodels.compat.platform import PLATFORM_WIN
from statsmodels.compat.scipy import SCIPY_11
def test_lazy_imports():
# Check that when statsmodels.api is imported, matplotlib is _not_ imported
cmd = ("import statsmodels.api as sm; "
"import sys; "
"mods = [x for x in sys.modules if 'matplotlib.pyplot' in x]; "
"assert not mods, mods")
# TODO: is there a cleaner way to do this import in an isolated environment
pyexe = 'python3' if not PLATFORM_WIN else 'python'
p = subprocess.Popen(pyexe + ' -c "' + cmd + '"',
shell=True, close_fds=True)
p.wait()
rc = p.returncode
assert rc == 0
@pytest.mark.skipif(SCIPY_11, reason='SciPy raises on -OO')
def test_docstring_optimization_compat():
# GH#5235 check that importing with stripped docstrings doesn't raise
pyexe = 'python3' if not PLATFORM_WIN else 'python'
p = subprocess.Popen(pyexe + ' -OO -c "import statsmodels.api as sm"',
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate()
rc = p.returncode
assert rc == 0, out
| Use python3 for test_docstring_optimization_compat subprocess | TST: Use python3 for test_docstring_optimization_compat subprocess
| Python | bsd-3-clause | jseabold/statsmodels,bashtage/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,jseabold/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,jseabold/statsmodels,statsmodels/statsmodels,jseabold/statsmodels,bashtage/statsmodels,jseabold/statsmodels | ---
+++
@@ -25,7 +25,8 @@
@pytest.mark.skipif(SCIPY_11, reason='SciPy raises on -OO')
def test_docstring_optimization_compat():
# GH#5235 check that importing with stripped docstrings doesn't raise
- p = subprocess.Popen('python -OO -c "import statsmodels.api as sm"',
+ pyexe = 'python3' if not PLATFORM_WIN else 'python'
+ p = subprocess.Popen(pyexe + ' -OO -c "import statsmodels.api as sm"',
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate() |
18ad742656f8ef0b47e4e8d810939ea93528aee4 | plugins/urlgrabber.py | plugins/urlgrabber.py | from plugins.categories import ISilentCommand
try:
import requests_pyopenssl
from requests.packages.urllib3 import connectionpool
connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket
except ImportError:
pass
import requests
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand):
triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-]+).*': "url"}
def trigger_url(self, context, user, channel, match):
if user == 'JustCommit':
return
try:
url = match.group(1)
response = requests.get(url)
except (requests.exceptions.ConnectionError) as e:
print "Failed to load URL: %s" % url
print "Message: %s" % e
else:
soup = BeautifulSoup(response.text)
if soup.title and soup.title.text:
title = soup.title.string
title = title.replace('\n', '') # remove newlines
title = title.replace('\x01', '') # remove dangerous control character \001
title = ' '.join(title.split()) # normalise all other whitespace
# Truncate length
if len(title) > 120:
title = title[:117] + "..."
return title
else:
print "URL has no title: %s" % url
| from plugins.categories import ISilentCommand
try:
import requests_pyopenssl
from requests.packages.urllib3 import connectionpool
connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket
except ImportError:
pass
import requests
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand):
triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"}
def trigger_url(self, context, user, channel, match):
if user == 'JustCommit':
return
try:
url = match.group(1)
response = requests.get(url)
except (requests.exceptions.ConnectionError) as e:
print "Failed to load URL: %s" % url
print "Message: %s" % e
else:
soup = BeautifulSoup(response.text)
if soup.title and soup.title.text:
title = soup.title.string
title = title.replace('\n', '') # remove newlines
title = title.replace('\x01', '') # remove dangerous control character \001
title = ' '.join(title.split()) # normalise all other whitespace
# Truncate length
if len(title) > 120:
title = title[:117] + "..."
return title
else:
print "URL has no title: %s" % url
| Include colons in URL matching | Include colons in URL matching | Python | isc | ComSSA/KhlavKalash | ---
+++
@@ -11,7 +11,7 @@
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand):
- triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-]+).*': "url"}
+ triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"}
def trigger_url(self, context, user, channel, match):
if user == 'JustCommit': |
1510d5657e6084cb94de514d1ba05e3b30f0ce5f | tools/python/frame_processor/frame_processor.py | tools/python/frame_processor/frame_processor.py | from frame_receiver.ipc_channel import IpcChannel, IpcChannelException
from frame_receiver.ipc_message import IpcMessage, IpcMessageException
from frame_processor_config import FrameProcessorConfig
import time
class FrameProcessor(object):
def __init__(self):
# Instantiate a configuration container object, which will be populated
# with sensible default values
self.config = FrameProcessorConfig("FrameProcessor - test harness to simulate operation of FrameProcessor application")
# Create the appropriate IPC channels
self.ctrl_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_REQ)
def run(self):
self.ctrl_channel.connect(self.config.ctrl_endpoint)
for i in range(10):
#msg = "HELLO " + str(i)
msg = IpcMessage(msg_type='cmd', msg_val='status')
print "Sending message", msg
self.ctrl_channel.send(msg.encode())
reply = self.ctrl_channel.recv()
print "Got reply:", reply
time.sleep(0.01)
if __name__ == "__main__":
fp = FrameProcessor()
fp.run()
| from frame_receiver.ipc_channel import IpcChannel, IpcChannelException
from frame_receiver.ipc_message import IpcMessage, IpcMessageException
from frame_processor_config import FrameProcessorConfig
import time
class FrameProcessor(object):
def __init__(self):
# Instantiate a configuration container object, which will be populated
# with sensible default values
self.config = FrameProcessorConfig("FrameProcessor - test harness to simulate operation of FrameProcessor application")
# Create the appropriate IPC channels
self.ctrl_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_REQ)
def run(self):
self.ctrl_channel.connect(self.config.ctrl_endpoint)
for i in range(10):
msg = "HELLO " + str(i)
print "Sending message", msg
self.ctrl_channel.send(msg)
reply = self.ctrl_channel.recv()
print "Got reply:", reply
time.sleep(1)
if __name__ == "__main__":
fp = FrameProcessor()
fp.run()
| Revert "Update python frame processor test harness to send IPC JSON messages to frame receiver for testing of control path and channel multiplexing" | Revert "Update python frame processor test harness to send IPC JSON messages to frame receiver for testing of control path and channel multiplexing"
This reverts commit 0e301d3ee54366187b2e12fa5c6927f27e907347.
| Python | apache-2.0 | odin-detector/odin-data,odin-detector/odin-data,odin-detector/odin-data,percival-detector/odin-data,odin-detector/odin-data,odin-detector/odin-data,odin-detector/odin-data,percival-detector/odin-data,percival-detector/odin-data,percival-detector/odin-data,odin-detector/odin-data,percival-detector/odin-data,percival-detector/odin-data,percival-detector/odin-data | ---
+++
@@ -22,14 +22,13 @@
for i in range(10):
- #msg = "HELLO " + str(i)
- msg = IpcMessage(msg_type='cmd', msg_val='status')
+ msg = "HELLO " + str(i)
print "Sending message", msg
- self.ctrl_channel.send(msg.encode())
+ self.ctrl_channel.send(msg)
reply = self.ctrl_channel.recv()
print "Got reply:", reply
- time.sleep(0.01)
+ time.sleep(1)
if __name__ == "__main__": |
6f995fbe0532fc4ea36f3f7cd24240d3525b115f | Ref.py | Ref.py | """
MoinMoin - Ref Macro
Collect and emit footnotes. Note that currently footnote
text cannot contain wiki markup.
@copyright: 2011 Jason L. Wright <[email protected]>
@license: BSD
"""
from MoinMoin import config, wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
from MoinMoin.support.python_compatibility import hash_new
import MoinMoin.macro.FootNote as FootNote
import MoinMoin.macro.RefText as RefText
Dependencies = ["time"] # footnote macro cannot be cached
def execute(macro, args):
request = macro.request
formatter = macro.formatter
txt = RefText.execute(macro, args)
return FootNote.execute(macro, txt)
| """
MoinMoin - Ref Macro
Collect and emit references (as footnotes)
@copyright: 2011 Jason L. Wright <[email protected]>
@license: BSD
"""
from MoinMoin import config, wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
from MoinMoin.support.python_compatibility import hash_new
import MoinMoin.macro.FootNote as FootNote
import MoinMoin.macro.RefText as RefText
Dependencies = ["time"] # footnote macro cannot be cached
def execute(macro, args):
request = macro.request
formatter = macro.formatter
txt = RefText.execute(macro, args)
return FootNote.execute(macro, txt)
| Update text to reflect current usage | Update text to reflect current usage
| Python | bsd-2-clause | wrigjl/moin-ref-bibtex | ---
+++
@@ -1,8 +1,7 @@
"""
MoinMoin - Ref Macro
- Collect and emit footnotes. Note that currently footnote
- text cannot contain wiki markup.
+ Collect and emit references (as footnotes)
@copyright: 2011 Jason L. Wright <[email protected]>
@license: BSD |
7f44c6a114f95c25b533c9b69988798ba3919d68 | wger/email/forms.py | wger/email/forms.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager 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.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from django.utils.translation import (
pgettext,
ugettext_lazy as _
)
from django.forms import (
Form,
CharField,
Textarea
)
class EmailListForm(Form):
'''
Small form to send emails
'''
subject = CharField(label=pgettext('Subject', 'As in "email subject"'))
body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"'))
| # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager 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.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from django.utils.translation import (
pgettext,
ugettext_lazy as _
)
from django.forms import (
Form,
CharField,
Textarea
)
class EmailListForm(Form):
'''
Small form to send emails
'''
subject = CharField(label=pgettext('As in "email subject"', 'Subject'))
body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
| Use correct order of arguments of pgettext | Use correct order of arguments of pgettext
| Python | agpl-3.0 | rolandgeider/wger,rolandgeider/wger,wger-project/wger,DeveloperMal/wger,DeveloperMal/wger,wger-project/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger,rolandgeider/wger,petervanderdoes/wger,wger-project/wger,wger-project/wger,petervanderdoes/wger,DeveloperMal/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,kjagoo/wger_stark,DeveloperMal/wger | ---
+++
@@ -31,5 +31,5 @@
Small form to send emails
'''
- subject = CharField(label=pgettext('Subject', 'As in "email subject"'))
- body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"'))
+ subject = CharField(label=pgettext('As in "email subject"', 'Subject'))
+ body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content')) |
47bf5652c621da89a72597b8198fbfde84c2049c | healthfun/person/models.py | healthfun/person/models.py | from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Person(models.Model):
first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True)
last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True)
height = models.IntegerField(blank=True)
email = models.EmailField()
| from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Person(models.Model):
first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True)
last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True)
height = models.IntegerField(blank=True)
email = models.EmailField()
def __unicode__ (self):
return self.email
| Use email to 'print' a person | Use email to 'print' a person
| Python | agpl-3.0 | frlan/healthfun | ---
+++
@@ -7,3 +7,6 @@
last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True)
height = models.IntegerField(blank=True)
email = models.EmailField()
+
+ def __unicode__ (self):
+ return self.email |
80a08e9f5720e60536a74af6798d1126341ac158 | honeycomb/urls.py | honeycomb/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^', include('django.contrib.auth.urls')),
url('^', include('usermgmt.urls')),
url('^', include('app.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^_admin/', admin.site.urls),
url('^', include('django.contrib.auth.urls')),
url('^', include('usermgmt.urls')),
url('^', include('app.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| Move django admin to /_admin | Move django admin to /_admin
| Python | mit | OpenFurry/honeycomb,makyo/honeycomb,makyo/honeycomb,OpenFurry/honeycomb,OpenFurry/honeycomb,makyo/honeycomb,OpenFurry/honeycomb,makyo/honeycomb | ---
+++
@@ -5,7 +5,7 @@
urlpatterns = [
- url(r'^admin/', admin.site.urls),
+ url(r'^_admin/', admin.site.urls),
url('^', include('django.contrib.auth.urls')),
url('^', include('usermgmt.urls')),
url('^', include('app.urls')), |
c24a7287d0ac540d6ef6dcf353b06ee42aaa7a43 | serrano/decorators.py | serrano/decorators.py | from functools import wraps
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
def get_token(request):
return request.REQUEST.get('token', '')
def check_auth(func):
@wraps(func)
def inner(self, request, *args, **kwargs):
auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False)
user = getattr(request, 'user', None)
# Attempt to authenticate if a token is present
if not user or not user.is_authenticated():
token = get_token(request)
user = authenticate(token=token)
if user:
login(request, user)
elif auth_required:
return HttpResponse(status=401)
return func(self, request, *args, **kwargs)
return inner
| from functools import wraps
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
def get_token(request):
"Attempts to retrieve a token from the request."
if 'token' in request.REQUEST:
return request.REQUEST['token']
if 'HTTP_API_TOKEN' in request.META:
return request.META['HTTP_API_TOKEN']
return ''
def check_auth(func):
@wraps(func)
def inner(self, request, *args, **kwargs):
auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False)
user = getattr(request, 'user', None)
# Attempt to authenticate if a token is present
if not user or not user.is_authenticated():
token = get_token(request)
user = authenticate(token=token)
if user:
login(request, user)
elif auth_required:
return HttpResponse(status=401)
return func(self, request, *args, **kwargs)
return inner
| Add support for extracting the token from request headers | Add support for extracting the token from request headers
Clients can now set the `Api-Token` header instead of supplying the
token as a GET or POST parameter. | Python | bsd-2-clause | chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night,chop-dbhi/serrano | ---
+++
@@ -5,7 +5,12 @@
def get_token(request):
- return request.REQUEST.get('token', '')
+ "Attempts to retrieve a token from the request."
+ if 'token' in request.REQUEST:
+ return request.REQUEST['token']
+ if 'HTTP_API_TOKEN' in request.META:
+ return request.META['HTTP_API_TOKEN']
+ return ''
def check_auth(func): |
e31099e964f809a8a6ebcb071c7c2b57e17248c2 | reviewboard/changedescs/evolutions/changedesc_user.py | reviewboard/changedescs/evolutions/changedesc_user.py | from __future__ import unicode_literals
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('ChangeDescription', 'user', models.ForeignKey, blank=True,
related_model='auth.User'),
]
| from __future__ import unicode_literals
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('ChangeDescription', 'user', models.ForeignKey, null=True,
related_model='auth.User'),
]
| Fix evolution for change description users | Fix evolution for change description users
Trivial change
| Python | mit | sgallagher/reviewboard,chipx86/reviewboard,chipx86/reviewboard,chipx86/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,davidt/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,brennie/reviewboard,brennie/reviewboard,davidt/reviewboard,brennie/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,davidt/reviewboard | ---
+++
@@ -5,6 +5,6 @@
MUTATIONS = [
- AddField('ChangeDescription', 'user', models.ForeignKey, blank=True,
+ AddField('ChangeDescription', 'user', models.ForeignKey, null=True,
related_model='auth.User'),
] |
cd5bfa0fb09835e4e33236ec4292a16ed5556088 | tests/parser.py | tests/parser.py | from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def has_and_requires_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def may_also_take_additional_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
def can_take_just_other_contexts(self):
c = Context('foo')
p = Parser(contexts=[c])
eq_(p.contexts['foo'], c)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| Update tests to explicitly account for previous | Update tests to explicitly account for previous
| Python | bsd-2-clause | mattrobenolt/invoke,frol/invoke,sophacles/invoke,pyinvoke/invoke,tyewang/invoke,frol/invoke,mattrobenolt/invoke,pfmoore/invoke,singingwolfboy/invoke,kejbaly2/invoke,pfmoore/invoke,pyinvoke/invoke,mkusz/invoke,alex/invoke,mkusz/invoke,kejbaly2/invoke | ---
+++
@@ -5,17 +5,22 @@
class Parser_(Spec):
- def has_and_requires_initial_context(self):
+ def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
- def may_also_take_additional_contexts(self):
+ def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
+
+ def can_take_just_other_contexts(self):
+ c = Context('foo')
+ p = Parser(contexts=[c])
+ eq_(p.contexts['foo'], c)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self): |
d01b09256f8fda4b222f3e26366817f4ac5b4c5a | zinnia/tests/test_admin_forms.py | zinnia/tests/test_admin_forms.py | """Test cases for Zinnia's admin forms"""
from django.test import TestCase
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from zinnia.models import Category
from zinnia.admin.forms import EntryAdminForm
from zinnia.admin.forms import CategoryAdminForm
class EntryAdminFormTestCase(TestCase):
def test_categories_has_related_widget(self):
form = EntryAdminForm()
self.assertTrue(
isinstance(form.fields['categories'].widget,
RelatedFieldWidgetWrapper))
def test_initial_sites(self):
form = EntryAdminForm()
self.assertEqual(
len(form.fields['sites'].initial), 1)
class CategoryAdminFormTestCase(TestCase):
def test_parent_has_related_widget(self):
form = CategoryAdminForm()
self.assertTrue(
isinstance(form.fields['parent'].widget,
RelatedFieldWidgetWrapper))
def test_clean_parent(self):
category = Category.objects.create(
title='Category 1', slug='cat-1')
datas = {'parent': category.pk,
'title': category.title,
'slug': category.slug}
form = CategoryAdminForm(datas, instance=category)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors['parent']), 1)
subcategory = Category.objects.create(
title='Category 2', slug='cat-2')
self.assertEqual(subcategory.parent, None)
datas = {'parent': category.pk,
'title': subcategory.title,
'slug': subcategory.slug}
form = CategoryAdminForm(datas, instance=subcategory)
self.assertTrue(form.is_valid())
| """Test cases for Zinnia's admin forms"""
from django.test import TestCase
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from zinnia.models import Category
from zinnia.admin.forms import EntryAdminForm
from zinnia.admin.forms import CategoryAdminForm
class EntryAdminFormTestCase(TestCase):
def test_categories_has_related_widget(self):
form = EntryAdminForm()
self.assertTrue(
isinstance(form.fields['categories'].widget,
RelatedFieldWidgetWrapper))
class CategoryAdminFormTestCase(TestCase):
def test_parent_has_related_widget(self):
form = CategoryAdminForm()
self.assertTrue(
isinstance(form.fields['parent'].widget,
RelatedFieldWidgetWrapper))
def test_clean_parent(self):
category = Category.objects.create(
title='Category 1', slug='cat-1')
datas = {'parent': category.pk,
'title': category.title,
'slug': category.slug}
form = CategoryAdminForm(datas, instance=category)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors['parent']), 1)
subcategory = Category.objects.create(
title='Category 2', slug='cat-2')
self.assertEqual(subcategory.parent, None)
datas = {'parent': category.pk,
'title': subcategory.title,
'slug': subcategory.slug}
form = CategoryAdminForm(datas, instance=subcategory)
self.assertTrue(form.is_valid())
| Remove now useless test for initial sites value in form | Remove now useless test for initial sites value in form
| Python | bsd-3-clause | extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Zopieux/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,bywbilly/django-blog-zinnia,dapeng0802/django-blog-zinnia,Zopieux/django-blog-zinnia,aorzh/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,aorzh/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,Fantomas42/django-blog-zinnia,marctc/django-blog-zinnia,petecummings/django-blog-zinnia,ZuluPro/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,Maplecroft/django-blog-zinnia,petecummings/django-blog-zinnia,marctc/django-blog-zinnia,bywbilly/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,marctc/django-blog-zinnia | ---
+++
@@ -14,11 +14,6 @@
self.assertTrue(
isinstance(form.fields['categories'].widget,
RelatedFieldWidgetWrapper))
-
- def test_initial_sites(self):
- form = EntryAdminForm()
- self.assertEqual(
- len(form.fields['sites'].initial), 1)
class CategoryAdminFormTestCase(TestCase): |
f096225138afff2a722b1b019eb94e14f8d18fc3 | sutro/dispatcher.py | sutro/dispatcher.py | import random
import gevent.queue
class MessageDispatcher(object):
def __init__(self, stats):
self.consumers = {}
self.stats = stats
def get_connection_count(self):
return sum(len(sockets) for sockets in self.consumers.itervalues())
def on_message_received(self, namespace, message):
consumers = self.consumers.get(namespace, [])
with self.stats.timer("sutro.dispatch"):
for consumer in consumers:
consumer.put(message)
def listen(self, namespace, max_timeout):
queue = gevent.queue.Queue()
self.consumers.setdefault(namespace, []).append(queue)
try:
while True:
# jitter the timeout a bit to ensure we don't herd
timeout = max_timeout - random.uniform(0, max_timeout / 2)
try:
yield queue.get(block=True, timeout=timeout)
except gevent.queue.Empty:
yield None
# ensure we're not starving others by spinning
gevent.sleep()
finally:
self.consumers[namespace].remove(queue)
if not self.consumers[namespace]:
del self.consumers[namespace]
| import posixpath
import random
import gevent.queue
def _walk_namespace_hierarchy(namespace):
assert namespace.startswith("/")
yield namespace
while namespace != "/":
namespace = posixpath.dirname(namespace)
yield namespace
class MessageDispatcher(object):
def __init__(self, stats):
self.consumers = {}
self.stats = stats
def get_connection_count(self):
return sum(len(sockets) for sockets in self.consumers.itervalues())
def on_message_received(self, namespace, message):
consumers = self.consumers.get(namespace, [])
with self.stats.timer("sutro.dispatch"):
for consumer in consumers:
consumer.put(message)
def listen(self, namespace, max_timeout):
queue = gevent.queue.Queue()
namespace = namespace.rstrip("/")
for ns in _walk_namespace_hierarchy(namespace):
self.consumers.setdefault(ns, []).append(queue)
try:
while True:
# jitter the timeout a bit to ensure we don't herd
timeout = max_timeout - random.uniform(0, max_timeout / 2)
try:
yield queue.get(block=True, timeout=timeout)
except gevent.queue.Empty:
yield None
# ensure we're not starving others by spinning
gevent.sleep()
finally:
for ns in _walk_namespace_hierarchy(namespace):
self.consumers[ns].remove(queue)
if not self.consumers[ns]:
del self.consumers[ns]
| Make sockets listen to parent namespaces as well. | Make sockets listen to parent namespaces as well.
For example, /live/test will now receive messages destined for
/live/test, /live and /. This allows us to send messages to multiple
endpoints at once such as refreshing all liveupdate threads or the like.
| Python | bsd-3-clause | spladug/sutro,spladug/sutro | ---
+++
@@ -1,6 +1,16 @@
+import posixpath
import random
import gevent.queue
+
+
+def _walk_namespace_hierarchy(namespace):
+ assert namespace.startswith("/")
+
+ yield namespace
+ while namespace != "/":
+ namespace = posixpath.dirname(namespace)
+ yield namespace
class MessageDispatcher(object):
@@ -20,7 +30,10 @@
def listen(self, namespace, max_timeout):
queue = gevent.queue.Queue()
- self.consumers.setdefault(namespace, []).append(queue)
+
+ namespace = namespace.rstrip("/")
+ for ns in _walk_namespace_hierarchy(namespace):
+ self.consumers.setdefault(ns, []).append(queue)
try:
while True:
@@ -35,6 +48,7 @@
# ensure we're not starving others by spinning
gevent.sleep()
finally:
- self.consumers[namespace].remove(queue)
- if not self.consumers[namespace]:
- del self.consumers[namespace]
+ for ns in _walk_namespace_hierarchy(namespace):
+ self.consumers[ns].remove(queue)
+ if not self.consumers[ns]:
+ del self.consumers[ns] |
f4ee715a5bd6ea979cf09fb847a861f621d42c7b | CFC_WebApp/utils/update_client.py | CFC_WebApp/utils/update_client.py | from dao.client import Client
import sys
def update_entry(clientName, createKeyOpt):
newKey = Client(clientName).update(createKey = createKeyOpt)
print "%s: %s" % (clientName, newKey)
if __name__ == '__main__':
# Deal with getopt here to support -a
update_entry(sys.argv[1], bool(sys.argv[2]))
| from dao.client import Client
import sys
def update_entry(clientName, createKeyOpt):
print "createKeyOpt = %s" % createKeyOpt
newKey = Client(clientName).update(createKey = createKeyOpt)
print "%s: %s" % (clientName, newKey)
if __name__ == '__main__':
# Deal with getopt here to support -a
update_entry(sys.argv[1], sys.argv[2] == "true" or sys.argv[2] == "True")
| Fix stupid bug in the client creation script | Fix stupid bug in the client creation script
bool(String) doesn't actually convert a string to a boolean.
So we were creating a new ID even if the user typed in "False".
Fixed with a simple boolean check instead.
| Python | bsd-3-clause | sunil07t/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,joshzarrabi/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,sdsingh/e-mission-server,shankari/e-mission-server,joshzarrabi/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,sdsingh/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server | ---
+++
@@ -2,9 +2,10 @@
import sys
def update_entry(clientName, createKeyOpt):
+ print "createKeyOpt = %s" % createKeyOpt
newKey = Client(clientName).update(createKey = createKeyOpt)
print "%s: %s" % (clientName, newKey)
if __name__ == '__main__':
# Deal with getopt here to support -a
- update_entry(sys.argv[1], bool(sys.argv[2]))
+ update_entry(sys.argv[1], sys.argv[2] == "true" or sys.argv[2] == "True") |
9697010c909e3a4777bdef7c2889813ae3decad7 | telemetry/telemetry/internal/platform/profiler/android_screen_recorder_profiler.py | telemetry/telemetry/internal/platform/profiler/android_screen_recorder_profiler.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.
import os
import subprocess
from telemetry.internal.platform import profiler
from telemetry.internal import util
from telemetry.internal.backends.chrome import android_browser_finder
class AndroidScreenRecordingProfiler(profiler.Profiler):
"""Captures a screen recording on Android."""
def __init__(self, browser_backend, platform_backend, output_path, state):
super(AndroidScreenRecordingProfiler, self).__init__(
browser_backend, platform_backend, output_path, state)
self._output_path = output_path + '.mp4'
self._recorder = subprocess.Popen(
[os.path.join(util.GetChromiumSrcDir(), 'build', 'android',
'screenshot.py'),
'--video',
'--file', self._output_path,
'--device', browser_backend.device.adb.GetDeviceSerial()],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
@classmethod
def name(cls):
return 'android-screen-recorder'
@classmethod
def is_supported(cls, browser_type):
if browser_type == 'any':
return android_browser_finder.CanFindAvailableBrowsers()
return browser_type.startswith('android')
def CollectProfile(self):
self._recorder.communicate(input='\n')
print 'Screen recording saved as %s' % self._output_path
print 'To view, open in Chrome or a video player'
return [self._output_path]
| # 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.
import os
import subprocess
from telemetry.core import util
from telemetry.internal.platform import profiler
from telemetry.internal.backends.chrome import android_browser_finder
class AndroidScreenRecordingProfiler(profiler.Profiler):
"""Captures a screen recording on Android."""
def __init__(self, browser_backend, platform_backend, output_path, state):
super(AndroidScreenRecordingProfiler, self).__init__(
browser_backend, platform_backend, output_path, state)
self._output_path = output_path + '.mp4'
self._recorder = subprocess.Popen(
[os.path.join(util.GetChromiumSrcDir(), 'build', 'android',
'screenshot.py'),
'--video',
'--file', self._output_path,
'--device', browser_backend.device.adb.GetDeviceSerial()],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
@classmethod
def name(cls):
return 'android-screen-recorder'
@classmethod
def is_supported(cls, browser_type):
if browser_type == 'any':
return android_browser_finder.CanFindAvailableBrowsers()
return browser_type.startswith('android')
def CollectProfile(self):
self._recorder.communicate(input='\n')
print 'Screen recording saved as %s' % self._output_path
print 'To view, open in Chrome or a video player'
return [self._output_path]
| Fix an import path in the Android screen recorder | telemetry: Fix an import path in the Android screen recorder
Review URL: https://codereview.chromium.org/1301613004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#343960}
| Python | bsd-3-clause | benschmaus/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult,benschmaus/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm | ---
+++
@@ -5,8 +5,8 @@
import os
import subprocess
+from telemetry.core import util
from telemetry.internal.platform import profiler
-from telemetry.internal import util
from telemetry.internal.backends.chrome import android_browser_finder
|
4268f8194bd93bd7f4be24c34938ca343e457c34 | dbaas/workflow/steps/tests/__init__.py | dbaas/workflow/steps/tests/__init__.py | from unittest import TestCase
from physical.tests.factory import PlanFactory, DatabaseInfraFactory, InstanceFactory
class TestBaseStep(TestCase):
def setUp(self):
self.plan = PlanFactory()
self.environment = self.plan.environments.first()
self.infra = DatabaseInfraFactory(plan=self.plan, environment=self.environment)
self.instance = InstanceFactory(
address="127.0.0.1", port=27017, databaseinfra=self.infra
)
def tearDown(self):
self.instance.delete()
self.infra.delete()
self.environment.delete()
self.plan.delete()
| from django.test import TestCase
from physical.tests.factory import PlanFactory, DatabaseInfraFactory, InstanceFactory
class TestBaseStep(TestCase):
def setUp(self):
self.plan = PlanFactory()
self.environment = self.plan.environments.first()
self.infra = DatabaseInfraFactory(plan=self.plan, environment=self.environment)
self.instance = InstanceFactory(
address="127.0.0.1", port=27017, databaseinfra=self.infra
)
def tearDown(self):
self.instance.delete()
self.infra.delete()
self.environment.delete()
self.plan.delete()
| Change TestCase from unittest to django.test | Change TestCase from unittest to django.test
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -1,4 +1,4 @@
-from unittest import TestCase
+from django.test import TestCase
from physical.tests.factory import PlanFactory, DatabaseInfraFactory, InstanceFactory
|
3031bcfda01a55c70f3af860bb5620a5530e654a | Motor/src/main/python/vehicles.py | Motor/src/main/python/vehicles.py | from Adafruit_MotorHAT import Adafruit_MotorHAT
class Vehicle:
def __init__(self, motor_hat=None):
self.motor_hat = motor_hat
self.motors = []
def release(self):
self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)
def update_motor(self, index, command, speed):
with self.motor_hat.getMotor(index) as motor:
motor.run(command)
motor.setSpeed(speed)
motor = {"location": index, "command": command, "speed": speed}
n = len(self.motors)
if index < n:
self.motors[index] = motor
elif index == n:
self.motors.append(motor)
else:
raise IndexError()
| from Adafruit_MotorHAT import Adafruit_MotorHAT
class Vehicle:
def __init__(self, motor_hat=Adafruit_MotorHAT()):
self.motor_hat = motor_hat
self.motors = []
def release(self):
self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)
def update_motor(self, index, command, speed):
with self.motor_hat.getMotor(index) as motor:
motor.run(command)
motor.setSpeed(speed)
motor = {"location": index, "command": command, "speed": speed}
n = len(self.motors)
if index < n:
self.motors[index] = motor
elif index == n:
self.motors.append(motor)
else:
raise IndexError()
| Build vehicle with motor hat. | Build vehicle with motor hat.
| Python | mit | misalcedo/RapBot,misalcedo/RapBot,misalcedo/RapBot,misalcedo/RapBot | ---
+++
@@ -2,7 +2,7 @@
class Vehicle:
- def __init__(self, motor_hat=None):
+ def __init__(self, motor_hat=Adafruit_MotorHAT()):
self.motor_hat = motor_hat
self.motors = []
|
0007ea4aa0f7ebadfadb0c6f605c51a1d11e483c | account/managers.py | account/managers.py | from __future__ import unicode_literals
from django.db import models, IntegrityError
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
try:
email_address = self.create(user=user, email=email, **kwargs)
except IntegrityError:
return None
else:
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
| from __future__ import unicode_literals
from django.db import models, IntegrityError
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address = self.create(user=user, email=email, **kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
| Allow IntegrityError to propagate with duplicate email | Allow IntegrityError to propagate with duplicate email
Fixes #62. When ACCOUNT_EMAIL_UNIQUE is True we should fail loudly when an
attempt to insert a duplicate occurs. Let the callers handle the failure.
| Python | mit | mentholi/django-user-accounts,jawed123/django-user-accounts,ntucker/django-user-accounts,jpotterm/django-user-accounts,rizumu/django-user-accounts,jacobwegner/django-user-accounts,mentholi/django-user-accounts,pinax/django-user-accounts,GeoNode/geonode-user-accounts,nderituedwin/django-user-accounts,mysociety/django-user-accounts,jmburbach/django-user-accounts,jawed123/django-user-accounts,jpotterm/django-user-accounts,GeoNode/geonode-user-accounts,jacobwegner/django-user-accounts,gem/geonode-user-accounts,mgpyh/django-user-accounts,gem/geonode-user-accounts,pinax/django-user-accounts,osmfj/django-user-accounts,gem/geonode-user-accounts,nderituedwin/django-user-accounts,jmburbach/django-user-accounts,rizumu/django-user-accounts,osmfj/django-user-accounts,ntucker/django-user-accounts,mysociety/django-user-accounts | ---
+++
@@ -7,14 +7,10 @@
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
- try:
- email_address = self.create(user=user, email=email, **kwargs)
- except IntegrityError:
- return None
- else:
- if confirm and not email_address.verified:
- email_address.send_confirmation()
- return email_address
+ email_address = self.create(user=user, email=email, **kwargs)
+ if confirm and not email_address.verified:
+ email_address.send_confirmation()
+ return email_address
def get_primary(self, user):
try: |
2ee1e8046323e2632c8cd8c8d88e3c313caabe1e | kobo/hub/forms.py | kobo/hub/forms.py | # -*- coding: utf-8 -*-
import django.forms as forms
from django.db.models import Q
class TaskSearchForm(forms.Form):
search = forms.CharField(required=False)
my = forms.BooleanField(required=False)
def get_query(self, request):
self.is_valid()
search = self.cleaned_data["search"]
my = self.cleaned_data["my"]
query = Q()
if search:
query |= Q(method__icontains=search)
query |= Q(owner__username__icontains=search)
if my and request.user.is_authenticated():
query &= Q(owner=request.user)
return query
| # -*- coding: utf-8 -*-
import django.forms as forms
from django.db.models import Q
class TaskSearchForm(forms.Form):
search = forms.CharField(required=False)
my = forms.BooleanField(required=False)
def get_query(self, request):
self.is_valid()
search = self.cleaned_data["search"]
my = self.cleaned_data["my"]
query = Q()
if search:
query |= Q(method__icontains=search)
query |= Q(owner__username__icontains=search)
query |= Q(label__icontains=search)
if my and request.user.is_authenticated():
query &= Q(owner=request.user)
return query
| Enable searching in task list by label. | Enable searching in task list by label.
| Python | lgpl-2.1 | pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo | ---
+++
@@ -19,6 +19,7 @@
if search:
query |= Q(method__icontains=search)
query |= Q(owner__username__icontains=search)
+ query |= Q(label__icontains=search)
if my and request.user.is_authenticated():
query &= Q(owner=request.user) |
56aa7fa21b218e047e9f3d7c2239aa6a22d9a5b1 | kombu/__init__.py | kombu/__init__.py | """AMQP Messaging Framework for Python"""
VERSION = (1, 0, 0, "rc4")
__version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
__author__ = "Ask Solem"
__contact__ = "[email protected]"
__homepage__ = "http://github.com/ask/kombu/"
__docformat__ = "restructuredtext"
import os
if not os.environ.get("KOMBU_NO_EVAL", False):
from kombu.connection import BrokerConnection
from kombu.entity import Exchange, Queue
from kombu.messaging import Consumer, Producer
| """AMQP Messaging Framework for Python"""
VERSION = (1, 0, 0, "rc4")
__version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
__author__ = "Ask Solem"
__contact__ = "[email protected]"
__homepage__ = "http://github.com/ask/kombu/"
__docformat__ = "restructuredtext en"
import os
import sys
if not os.environ.get("KOMBU_NO_EVAL", False):
# Lazy loading.
# - See werkzeug/__init__.py for the rationale behind this.
from types import ModuleType
all_by_module = {
"kombu.connection": ["BrokerConnection"],
"kombu.entity": ["Exchange", "Queue"],
"kombu.messaging": ["Consumer", "Producer"],
}
object_origins = {}
for module, items in all_by_module.iteritems():
for item in items:
object_origins[item] = module
class module(ModuleType):
def __getattr__(self, name):
if name in object_origins:
module = __import__(object_origins[name], None, None, [name])
for extra_name in all_by_module[module.__name__]:
setattr(self, extra_name, getattr(module, extra_name))
return getattr(module, name)
return ModuleType.__getattribute__(self, name)
def __dir__(self):
result = list(new_module.__all__)
result.extend(("__file__", "__path__", "__doc__", "__all__",
"__docformat__", "__name__", "__path__", "VERSION",
"__package__", "__version__", "__author__",
"__contact__", "__homepage__", "__docformat__"))
return result
# keep a reference to this module so that it's not garbage collected
old_module = sys.modules[__name__]
new_module = sys.modules[__name__] = module(__name__)
new_module.__dict__.update({
"__file__": __file__,
"__path__": __path__,
"__doc__": __doc__,
"__all__": tuple(object_origins),
"__version__": __version__,
"__author__": __author__,
"__contact__": __contact__,
"__homepage__": __homepage__,
"__docformat__": __docformat__,
"VERSION": VERSION})
| Load kombu root module lazily | Load kombu root module lazily
| Python | bsd-3-clause | urbn/kombu,depop/kombu,bmbouter/kombu,WoLpH/kombu,ZoranPavlovic/kombu,depop/kombu,mathom/kombu,xujun10110/kombu,romank0/kombu,xujun10110/kombu,alex/kombu,numb3r3/kombu,alex/kombu,andresriancho/kombu,daevaorn/kombu,daevaorn/kombu,iris-edu-int/kombu,ZoranPavlovic/kombu,WoLpH/kombu,cce/kombu,mverrilli/kombu,disqus/kombu,cce/kombu,Elastica/kombu,numb3r3/kombu,Elastica/kombu,pantheon-systems/kombu,tkanemoto/kombu,romank0/kombu,bmbouter/kombu,iris-edu-int/kombu,disqus/kombu,andresriancho/kombu,jindongh/kombu,celery/kombu,tkanemoto/kombu,mathom/kombu,pantheon-systems/kombu,mverrilli/kombu,jindongh/kombu | ---
+++
@@ -4,10 +4,56 @@
__author__ = "Ask Solem"
__contact__ = "[email protected]"
__homepage__ = "http://github.com/ask/kombu/"
-__docformat__ = "restructuredtext"
+__docformat__ = "restructuredtext en"
import os
+import sys
if not os.environ.get("KOMBU_NO_EVAL", False):
- from kombu.connection import BrokerConnection
- from kombu.entity import Exchange, Queue
- from kombu.messaging import Consumer, Producer
+ # Lazy loading.
+ # - See werkzeug/__init__.py for the rationale behind this.
+ from types import ModuleType
+
+ all_by_module = {
+ "kombu.connection": ["BrokerConnection"],
+ "kombu.entity": ["Exchange", "Queue"],
+ "kombu.messaging": ["Consumer", "Producer"],
+ }
+
+ object_origins = {}
+ for module, items in all_by_module.iteritems():
+ for item in items:
+ object_origins[item] = module
+
+ class module(ModuleType):
+
+ def __getattr__(self, name):
+ if name in object_origins:
+ module = __import__(object_origins[name], None, None, [name])
+ for extra_name in all_by_module[module.__name__]:
+ setattr(self, extra_name, getattr(module, extra_name))
+ return getattr(module, name)
+ return ModuleType.__getattribute__(self, name)
+
+ def __dir__(self):
+ result = list(new_module.__all__)
+ result.extend(("__file__", "__path__", "__doc__", "__all__",
+ "__docformat__", "__name__", "__path__", "VERSION",
+ "__package__", "__version__", "__author__",
+ "__contact__", "__homepage__", "__docformat__"))
+ return result
+
+ # keep a reference to this module so that it's not garbage collected
+ old_module = sys.modules[__name__]
+
+ new_module = sys.modules[__name__] = module(__name__)
+ new_module.__dict__.update({
+ "__file__": __file__,
+ "__path__": __path__,
+ "__doc__": __doc__,
+ "__all__": tuple(object_origins),
+ "__version__": __version__,
+ "__author__": __author__,
+ "__contact__": __contact__,
+ "__homepage__": __homepage__,
+ "__docformat__": __docformat__,
+ "VERSION": VERSION}) |
3b75688e18ed3adb06f26a51c7f12b6e419b6837 | tests/test_domain_parser.py | tests/test_domain_parser.py | import unittest
from domain_parser import domain_parser
class DomainParserTestCase(unittest.TestCase):
def test_google(self):
"""Is google.com properly parsed?"""
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
def test_gaurdian(self):
"""Is 'co.uk', which is wildcarded in the TLD list, parsed properly?"""
assert domain_parser.parse_domain(
'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www')
| import unittest
from domain_parser import domain_parser
class DomainParserTestCase(unittest.TestCase):
def test_google(self):
"""Is google.com properly parsed?"""
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
def test_guardian(self):
"""Is 'co.uk', which is wildcarded in the TLD list, parsed properly?"""
assert domain_parser.parse_domain(
'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www')
| Fix a very small typo in the name of the test. | Fix a very small typo in the name of the test.
Test name has been changed from test_gaurdian to test_guardian, to reflect Guardian website name | Python | apache-2.0 | jeffknupp/domain-parser,jeffknupp/domain-parser | ---
+++
@@ -9,7 +9,7 @@
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
- def test_gaurdian(self):
+ def test_guardian(self):
"""Is 'co.uk', which is wildcarded in the TLD list, parsed properly?"""
assert domain_parser.parse_domain(
'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') |
33524fe8cad5f8bf4448c7dd7426d1e1452bb324 | example_of_usage.py | example_of_usage.py | # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: GPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprint import pprint
from html_table_parser import HTMLTableParser
def url_get_contents(url):
""" Opens a website and read its binary contents (HTTP Response Body) """
req = urllib.request.Request(url=url)
f = urllib.request.urlopen(req)
return f.read()
def main():
url = 'http://www.twitter.com'
xhtml = url_get_contents(url).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
pprint(p.tables)
if __name__ == '__main__':
main()
| # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: AGPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprint import pprint
from html_table_parser import HTMLTableParser
def url_get_contents(url):
""" Opens a website and read its binary contents (HTTP Response Body) """
req = urllib.request.Request(url=url)
f = urllib.request.urlopen(req)
return f.read()
def main():
url = 'http://www.twitter.com'
xhtml = url_get_contents(url).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
pprint(p.tables)
if __name__ == '__main__':
main()
| Change license according to project license | Change license according to project license
| Python | agpl-3.0 | schmijos/html-table-parser-python3,schmijos/html-table-parser-python3 | ---
+++
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
-# Licence: GPLv3
+# Licence: AGPLv3
#
# Sample script for parsing HTML tables
# ----------------------------------------------------------------------------- |
b471b4d3a6d9da439f05ccb27d5d39aa884e724b | piwars/controllers/__main__.py | piwars/controllers/__main__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import importlib
from .. import robots
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--controller", default="remote")
parser.add_argument("--robot", default="text")
args = parser.parse_args()
try:
module = importlib.import_module(".%s" % args.robot, "piwars.robots")
except ImportError:
raise RuntimeError("Invalid robot: %s" % args.robot)
else:
robot = module.Robot()
try:
module = importlib.import_module(".%s" % args.controller, "piwars.controllers")
except ImportError:
raise RuntimeError("Invalid controller: %s" % args.controller)
else:
controller = module.Controller(robot)
controller.start()
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import importlib
from .. import robots
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--controller", default="remote")
parser.add_argument("--robot", default="text")
args = parser.parse_args()
try:
module = importlib.import_module(".%s" % args.robot, "piwars.robots")
except ImportError:
raise RuntimeError("Invalid robot: %s" % args.robot)
else:
robot = module.Robot()
try:
module = importlib.import_module(".%s" % args.controller, "piwars.controllers")
except ImportError:
raise RuntimeError("Invalid controller: %s" % args.controller)
else:
controller = module.Controller(robot)
controller.run()
| Switch to .run from .start to avoid confusion with an incoming command | Switch to .run from .start to avoid confusion with an incoming command
| Python | mit | westpark/robotics | ---
+++
@@ -25,4 +25,4 @@
else:
controller = module.Controller(robot)
- controller.start()
+ controller.run() |
23bce5ac6a73473f6f166c674988e68af18d2b51 | billing/__init__.py | billing/__init__.py | __version__ = '1.7.2'
__copyright__ = 'Copyright (c) 2020, Skioo SA'
__licence__ = 'MIT'
__URL__ = 'https://github.com/skioo/django-customer-billing'
| __version__ = '1.7.3'
__copyright__ = 'Copyright (c) 2020, Skioo SA'
__licence__ = 'MIT'
__URL__ = 'https://github.com/skioo/django-customer-billing'
| Update project version to 1.7.3 | Update project version to 1.7.3
| Python | mit | skioo/django-customer-billing,skioo/django-customer-billing | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '1.7.2'
+__version__ = '1.7.3'
__copyright__ = 'Copyright (c) 2020, Skioo SA'
__licence__ = 'MIT'
__URL__ = 'https://github.com/skioo/django-customer-billing' |
f22a217e86602b138451801afd3cd3c1c6314655 | bin/post_reports.py | bin/post_reports.py | #!/usr/bin/env python3
import os
import django
from fitbit.slack import post_message
IDS_TO_POST = os.environ['AUTOPOST'].split(',')
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings")
django.setup()
# Cannot import these until django is setup
from fitbit.models import Token
from fitbit.views import get_message
for token in Token.objects.filter(fitbit_id__in=IDS_TO_POST):
try:
post_message(get_message(token.fitbit_id))
except Exception:
print("Could not send message for {}".format(token.fitbit_id))
| #!/usr/bin/env python3
import os
import django
from fitbit.slack import post_message
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings")
django.setup()
# Cannot import these until django is setup
from fitbit.models import Token
from fitbit.views import get_message
for token in Token.objects.all():
try:
post_message(get_message(token.fitbit_id))
except Exception:
print("Could not send message for {}".format(token.fitbit_id))
| Send all user data to the slack | Send all user data to the slack
| Python | apache-2.0 | Bachmann1234/fitbitSlackBot,Bachmann1234/fitbitSlackBot | ---
+++
@@ -4,7 +4,6 @@
import django
from fitbit.slack import post_message
-IDS_TO_POST = os.environ['AUTOPOST'].split(',')
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings")
@@ -14,7 +13,7 @@
from fitbit.models import Token
from fitbit.views import get_message
- for token in Token.objects.filter(fitbit_id__in=IDS_TO_POST):
+ for token in Token.objects.all():
try:
post_message(get_message(token.fitbit_id))
except Exception: |
83bb9f15ae8ceed3352232b26176b74607a08efb | tests/test_tools.py | tests/test_tools.py | """Test the functions in the tools file."""
import bibpy.tools
def test_version_format():
assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0'
program_name = dict(prog='tool_name')
assert (bibpy.tools.version_format() % program_name).format('2.3') ==\
'tool_name v2.3'
def test_key_grammar():
pass
def test_entry_grammar():
pass
def test_field_grammar():
pass
def test_numeric_grammar():
pass
def test_parse_query():
assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author'])
assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author'])
def test_predicate_composition():
pass
| """Test the functions in the tools file."""
import bibpy.tools
def test_version_format():
assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0'
program_name = dict(prog='tool_name')
assert (bibpy.tools.version_format() % program_name).format('2.3') ==\
'tool_name v2.3'
def test_key_grammar():
pass
def test_entry_grammar():
pass
def test_field_grammar():
pass
def test_numeric_grammar():
pass
def test_parse_query():
assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author'])
assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author'])
def always_true(value):
"""A function that always returns True."""
return True
def always_false(value):
"""A function that always returns False."""
return False
def test_predicate_composition():
pred1 = bibpy.tools.compose_predicates([always_false, always_true,
always_false], any)
pred2 = bibpy.tools.compose_predicates([always_false, always_false,
always_false], any)
pred3 = bibpy.tools.compose_predicates([always_false, always_true], all)
pred4 = bibpy.tools.compose_predicates([always_true, always_true], all)
assert pred1(1)
assert not pred2(1)
assert not pred3(1)
assert pred4(1)
| Add test for predicate composition | Add test for predicate composition
| Python | mit | MisanthropicBit/bibpy,MisanthropicBit/bibpy | ---
+++
@@ -32,5 +32,25 @@
assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author'])
+def always_true(value):
+ """A function that always returns True."""
+ return True
+
+
+def always_false(value):
+ """A function that always returns False."""
+ return False
+
+
def test_predicate_composition():
- pass
+ pred1 = bibpy.tools.compose_predicates([always_false, always_true,
+ always_false], any)
+ pred2 = bibpy.tools.compose_predicates([always_false, always_false,
+ always_false], any)
+ pred3 = bibpy.tools.compose_predicates([always_false, always_true], all)
+ pred4 = bibpy.tools.compose_predicates([always_true, always_true], all)
+
+ assert pred1(1)
+ assert not pred2(1)
+ assert not pred3(1)
+ assert pred4(1) |
9c5a088af964a70453617b9925f9a027890497bb | tests/test_utils.py | tests/test_utils.py | import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
return sample_page
def test_build_img_path(sample_page_bad_format):
chapter = sample_page_bad_format["chapter"]
page = sample_page_bad_format["page"]
expected_output = "/chapter1/3"
assert utils.build_img_path(chapter,page) == expected_output
def test_increment_page_number_bad_format(sample_page_bad_format):
with pytest.raises(ValueError):
current_page = utils.build_img_path(sample_page_bad_format["chapter"],
sample_page_bad_format["page"])
utils.increment_page_number(current_page)
def test_increment_page_number_good_format(sample_page_good_format):
chapter = sample_page_good_format["chapter"]
page = sample_page_good_format["page"]
current_page = utils.build_img_path(chapter, page)
next_page = utils.increment_page_number(current_page)
expected_output = '/manga_ch1/x_v001-002'
assert next_page == expected_output
| import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-009'}
return sample_page
def test_build_img_path(sample_page_bad_format):
chapter = sample_page_bad_format["chapter"]
page = sample_page_bad_format["page"]
expected_output = "/chapter1/3"
assert utils.build_img_path(chapter,page) == expected_output
def test_increment_page_number_bad_format(sample_page_bad_format):
with pytest.raises(ValueError):
current_page = utils.build_img_path(sample_page_bad_format["chapter"],
sample_page_bad_format["page"])
utils.increment_page_number(current_page)
def test_increment_page_number_good_format(sample_page_good_format):
chapter = sample_page_good_format["chapter"]
page = sample_page_good_format["page"]
current_page = utils.build_img_path(chapter, page)
next_page = utils.increment_page_number(current_page)
expected_output = '/manga_ch1/x_v001-010'
assert next_page == expected_output
| Update sample good page to test changes from 1 to 2 digits | Update sample good page to test changes from 1 to 2 digits
| Python | mit | ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork | ---
+++
@@ -9,7 +9,7 @@
@pytest.fixture
def sample_page_good_format():
- sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
+ sample_page = {'chapter':'manga_ch1', 'page':'x_v001-009'}
return sample_page
def test_build_img_path(sample_page_bad_format):
@@ -30,5 +30,5 @@
page = sample_page_good_format["page"]
current_page = utils.build_img_path(chapter, page)
next_page = utils.increment_page_number(current_page)
- expected_output = '/manga_ch1/x_v001-002'
+ expected_output = '/manga_ch1/x_v001-010'
assert next_page == expected_output |
096800e08d29581e5a515dd01031c64eb2f01539 | pyxform/tests_v1/test_audit.py | pyxform/tests_v1/test_audit.py | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_audit(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | | |
| | type | name | label | parameters |
| | audit | audit | | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
) | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_audit(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | audit | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
) | Remove non-required column from test. | Remove non-required column from test.
| Python | bsd-2-clause | XLSForm/pyxform,XLSForm/pyxform | ---
+++
@@ -6,9 +6,9 @@
self.assertPyxformXform(
name="meta_audit",
md="""
- | survey | | | | |
- | | type | name | label | parameters |
- | | audit | audit | | |
+ | survey | | | |
+ | | type | name | label |
+ | | audit | audit | |
""",
xml__contains=[
'<meta>', |
7b3276708417284242b4e0c9a13c6194dcc83aa7 | quickstartup/contacts/views.py | quickstartup/contacts/views.py | # coding: utf-8
from django.core.urlresolvers import reverse
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .forms import ContactForm
class ContactView(CreateView):
template_name = 'contacts/contact.html'
form_class = ContactForm
def get_success_url(self):
return reverse("qs_contacts:contact")
def form_valid(self, form):
messages.success(self.request, _("Your message was sent successfully!"))
return super(ContactView, self).form_valid(form)
| # coding: utf-8
from django.core.urlresolvers import reverse
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .forms import ContactForm
class ContactView(CreateView):
template_name = 'contacts/contact.html'
form_class = ContactForm
def get_success_url(self):
return reverse("qs_contacts:contact")
def form_valid(self, form):
valid = super(ContactView, self).form_valid(form)
messages.success(self.request, _("Your message was sent successfully!"))
return valid
| Set flash message *after* message sending | Set flash message *after* message sending
| Python | mit | georgeyk/quickstartup,georgeyk/quickstartup,osantana/quickstartup,osantana/quickstartup,osantana/quickstartup,georgeyk/quickstartup | ---
+++
@@ -17,5 +17,6 @@
return reverse("qs_contacts:contact")
def form_valid(self, form):
+ valid = super(ContactView, self).form_valid(form)
messages.success(self.request, _("Your message was sent successfully!"))
- return super(ContactView, self).form_valid(form)
+ return valid |
77a5ecc7c406e4a6acf814a2f0381dc605e0d14c | leds/led_dance.py | leds/led_dance.py | # Light LEDs at 'random' and make them fade over time
#
# Usage:
#
# led_dance(speed)
#
# 'speed' is the time between each new LED being turned on. Note that the
# random number is actually based on time and so the speed will determine
# the pattern (and it is not really random).
#
# Hold button 'A' pressed to stop new LEDs being turned on.
import pyb
def led_dance(delay):
dots = {}
control = pyb.Switch(1)
while True:
if not control.value():
dots[pyb.millis() % 25] = 16
for d in dots:
pyb.pixel(d, dots[d])
if dots[d] == 0:
del(dots[d])
else:
dots[d] = int(dots[d]/2)
pyb.delay(delay)
led_dance(101)
| # Light LEDs at random and make them fade over time
#
# Usage:
#
# led_dance(delay)
#
# 'delay' is the time between each new LED being turned on.
import microbit
def led_dance(delay):
dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
microbit.display.set_display_mode(1)
while True:
dots[microbit.random(5)][microbit.random(5)] = 128
for i in range(5):
for j in range(5):
microbit.display.image.set_pixel_value(i, j, dots[i][j])
dots[i][j] = int(dots[i][j]/2)
microbit.sleep(delay)
led_dance(100)
| Update for new version of micropython for microbit | Update for new version of micropython for microbit
| Python | mit | jrmhaig/microbit_playground | ---
+++
@@ -1,29 +1,22 @@
-# Light LEDs at 'random' and make them fade over time
+# Light LEDs at random and make them fade over time
#
# Usage:
#
-# led_dance(speed)
+# led_dance(delay)
#
-# 'speed' is the time between each new LED being turned on. Note that the
-# random number is actually based on time and so the speed will determine
-# the pattern (and it is not really random).
-#
-# Hold button 'A' pressed to stop new LEDs being turned on.
+# 'delay' is the time between each new LED being turned on.
-import pyb
+import microbit
def led_dance(delay):
- dots = {}
- control = pyb.Switch(1)
+ dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
+ microbit.display.set_display_mode(1)
while True:
- if not control.value():
- dots[pyb.millis() % 25] = 16
- for d in dots:
- pyb.pixel(d, dots[d])
- if dots[d] == 0:
- del(dots[d])
- else:
- dots[d] = int(dots[d]/2)
- pyb.delay(delay)
+ dots[microbit.random(5)][microbit.random(5)] = 128
+ for i in range(5):
+ for j in range(5):
+ microbit.display.image.set_pixel_value(i, j, dots[i][j])
+ dots[i][j] = int(dots[i][j]/2)
+ microbit.sleep(delay)
-led_dance(101)
+led_dance(100) |
dccc51fcc51290648964c350cfff2254cfa99834 | oauth_provider/consts.py | oauth_provider/consts.py | from django.utils.translation import ugettext_lazy as _
KEY_SIZE = 16
SECRET_SIZE = 16
VERIFIER_SIZE = 10
CONSUMER_KEY_SIZE = 256
MAX_URL_LENGTH = 2083 # http://www.boutell.com/newfaq/misc/urllength.html
PENDING = 1
ACCEPTED = 2
CANCELED = 3
REJECTED = 4
CONSUMER_STATES = (
(PENDING, _('Pending')),
(ACCEPTED, _('Accepted')),
(CANCELED, _('Canceled')),
(REJECTED, _('Rejected')),
)
PARAMETERS_NAMES = ('consumer_key', 'token', 'signature',
'signature_method', 'timestamp', 'nonce')
OAUTH_PARAMETERS_NAMES = ['oauth_'+s for s in PARAMETERS_NAMES]
OUT_OF_BAND = 'oob'
| from django.utils.translation import ugettext_lazy as _
from django.conf import settings
KEY_SIZE = getattr(settings, 'OAUTH_PROVIDER_KEY_SIZE', 16)
SECRET_SIZE = getattr(settings, 'OAUTH_PROVIDER_SECRET_SIZE', 16)
VERIFIER_SIZE = getattr(settings, 'OAUTH_PROVIDER_VERIFIER_SIZE', 10)
CONSUMER_KEY_SIZE = getattr(settings, 'OAUTH_PROVIDER_CONSUMER_KEY_SIZE', 256)
MAX_URL_LENGTH = 2083 # http://www.boutell.com/newfaq/misc/urllength.html
PENDING = 1
ACCEPTED = 2
CANCELED = 3
REJECTED = 4
CONSUMER_STATES = (
(PENDING, _('Pending')),
(ACCEPTED, _('Accepted')),
(CANCELED, _('Canceled')),
(REJECTED, _('Rejected')),
)
PARAMETERS_NAMES = ('consumer_key', 'token', 'signature',
'signature_method', 'timestamp', 'nonce')
OAUTH_PARAMETERS_NAMES = ['oauth_'+s for s in PARAMETERS_NAMES]
OUT_OF_BAND = 'oob'
| Allow settings to override default lengths. | Allow settings to override default lengths.
| Python | bsd-3-clause | e-loue/django-oauth-plus | ---
+++
@@ -1,9 +1,10 @@
from django.utils.translation import ugettext_lazy as _
+from django.conf import settings
-KEY_SIZE = 16
-SECRET_SIZE = 16
-VERIFIER_SIZE = 10
-CONSUMER_KEY_SIZE = 256
+KEY_SIZE = getattr(settings, 'OAUTH_PROVIDER_KEY_SIZE', 16)
+SECRET_SIZE = getattr(settings, 'OAUTH_PROVIDER_SECRET_SIZE', 16)
+VERIFIER_SIZE = getattr(settings, 'OAUTH_PROVIDER_VERIFIER_SIZE', 10)
+CONSUMER_KEY_SIZE = getattr(settings, 'OAUTH_PROVIDER_CONSUMER_KEY_SIZE', 256)
MAX_URL_LENGTH = 2083 # http://www.boutell.com/newfaq/misc/urllength.html
PENDING = 1 |
99a8147a31060442368d79ebeee231744183a6d1 | tests/test_adam.py | tests/test_adam.py | import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1 | import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
assert asset.essence != None | Test for reading a wave file asserts that the essence is set. | Test for reading a wave file asserts that the essence is set.
| Python | agpl-3.0 | eseifert/madam | ---
+++
@@ -44,3 +44,4 @@
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
+ assert asset.essence != None |
268718b9ad28c8bad26a7fede52a88d51ac5a8da | tests/test_opts.py | tests/test_opts.py | import sys
from skeletor import config
from skeletor.config import Config
from .base import BaseTestCase
from .helpers import nostdout
class OptsTests(BaseTestCase):
def test_something(self):
assert True
| import optparse
from skeletor.opts import Option
from .base import BaseTestCase
class OptsTests(BaseTestCase):
def should_raise_exception_when_require_used_incorrectly(self):
try:
Option('-n', '--does_not_take_val', action="store_true",
default=None, required=True)
except optparse.OptionError:
assert True
| Test for custom option class | Test for custom option class
| Python | bsd-3-clause | krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio | ---
+++
@@ -1,13 +1,15 @@
-import sys
+import optparse
-from skeletor import config
-from skeletor.config import Config
+from skeletor.opts import Option
from .base import BaseTestCase
-from .helpers import nostdout
class OptsTests(BaseTestCase):
- def test_something(self):
- assert True
+ def should_raise_exception_when_require_used_incorrectly(self):
+ try:
+ Option('-n', '--does_not_take_val', action="store_true",
+ default=None, required=True)
+ except optparse.OptionError:
+ assert True |
80c3d7693b17f38c80b2e1a06716969a8ef11adf | tests/test_simple_features.py | tests/test_simple_features.py | from wordgraph.points import Point
import wordgraph
EPOCH_START = 1407109280
def time_values(values, start=EPOCH_START, increment=1):
datapoints = []
for index, value in enumerate(values):
datapoints.append(Point(x=value, y=start + (increment * index)))
return datapoints
def test_monotonic_up_per_second():
datapoints = time_values(float(i) for i in range(10))
features = wordgraph.describe(datapoints)
assert "" in features
def test_monotonic_down_per_second():
datapoints = time_values(10.0 - i for i in range(10))
features = wordgraph.describe(datapoints)
assert "" in features
| from wordgraph.points import Point
import wordgraph
EPOCH_START = 1407109280
def time_values(values, start=EPOCH_START, increment=1):
datapoints = []
for index, value in enumerate(values):
datapoints.append(Point(x=value, y=start + (increment * index)))
return datapoints
def test_monotonic_up_per_second():
datapoints = time_values(float(i) for i in range(10))
features = wordgraph.describe(datapoints)
assert "" in features
def test_monotonic_down_per_second():
datapoints = time_values(10.0 - i for i in range(10))
features = wordgraph.describe(datapoints)
assert "" in features
def test_tent_map():
values = list(float(i) for i in range(10))
values.append(11.0)
values+= list(10.0 - i for i in range(10))
datapoints = time_values(values)
features = wordgraph.describe(datapoints)
assert "" in features
| Test case for tent map time series | Test case for tent map time series
Generate a time series with both a monionically increase and decreasing
sections.
| Python | apache-2.0 | tleeuwenburg/wordgraph,tleeuwenburg/wordgraph | ---
+++
@@ -18,3 +18,11 @@
datapoints = time_values(10.0 - i for i in range(10))
features = wordgraph.describe(datapoints)
assert "" in features
+
+def test_tent_map():
+ values = list(float(i) for i in range(10))
+ values.append(11.0)
+ values+= list(10.0 - i for i in range(10))
+ datapoints = time_values(values)
+ features = wordgraph.describe(datapoints)
+ assert "" in features |
6a940fbd0cc8c4e4a9f17423c593452d010b6883 | app/lib/query/__init__.py | app/lib/query/__init__.py | # -*- coding: utf-8 -*-
"""
Initialisation file for query directory.
"""
| # -*- coding: utf-8 -*-
"""
Initialisation file for query directory, relating to local database queries.
"""
| Update query init file docstring. | Update query init file docstring.
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse | ---
+++
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
"""
-Initialisation file for query directory.
+Initialisation file for query directory, relating to local database queries.
""" |
3ebf82c7ef356de3c4d427cea3723737661522e8 | pinax/waitinglist/management/commands/mail_out_survey_links.py | pinax/waitinglist/management/commands/mail_out_survey_links.py | from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from ...models import WaitingListEntry, Survey
class Command(BaseCommand):
help = "Email links to survey instances for those that never saw a survey"
def handle(self, *args, **options):
survey = Survey.objects.get(active=True)
entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True)
for entry in entries:
instance = survey.instances.create(entry=entry)
site = Site.objects.get_current()
protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
ctx = {
"instance": instance,
"site": site,
"protocol": protocol,
}
subject = render_to_string("waitinglist/survey_invite_subject.txt", ctx)
subject = subject.strip()
message = render_to_string("waitinglist/survey_invite_body.txt", ctx)
EmailMessage(
subject,
message,
to=[entry.email],
from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL
).send()
| from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from ...models import WaitingListEntry, Survey
class Command(BaseCommand):
help = "Email links to survey instances for those that never saw a survey"
def handle(self, *args, **options):
survey = Survey.objects.get(active=True)
entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True)
for entry in entries:
instance = survey.instances.create(entry=entry)
site = Site.objects.get_current()
protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
ctx = {
"instance": instance,
"site": site,
"protocol": protocol,
}
subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx)
subject = subject.strip()
message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx)
EmailMessage(
subject,
message,
to=[entry.email],
from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL
).send()
| Fix paths in mail out email management command | Fix paths in mail out email management command
| Python | mit | pinax/pinax-waitinglist,pinax/pinax-waitinglist | ---
+++
@@ -25,9 +25,9 @@
"site": site,
"protocol": protocol,
}
- subject = render_to_string("waitinglist/survey_invite_subject.txt", ctx)
+ subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx)
subject = subject.strip()
- message = render_to_string("waitinglist/survey_invite_body.txt", ctx)
+ message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx)
EmailMessage(
subject,
message, |
73c7161d4414a9259ee6123ee3d3540153f30b9e | purchase_edi_file/models/purchase_order_line.py | purchase_edi_file/models/purchase_order_line.py | # Copyright (C) 2021 Akretion (http://www.akretion.com).
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
seller = product._select_seller(partner_id=partner)
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
| # Copyright (C) 2021 Akretion (http://www.akretion.com).
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
seller = product._select_seller(
partner_id=partner, quantity=line.product_uom_qty
)
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
| Add qty when searching seller because even if not passed a verification is made by default in _select_seller | Add qty when searching seller because even if not passed a verification is made by default in _select_seller
| Python | agpl-3.0 | akretion/ak-odoo-incubator,akretion/ak-odoo-incubator,akretion/ak-odoo-incubator,akretion/ak-odoo-incubator | ---
+++
@@ -13,7 +13,9 @@
}
for line in self:
product = line.product_id
- seller = product._select_seller(partner_id=partner)
+ seller = product._select_seller(
+ partner_id=partner, quantity=line.product_uom_qty
+ )
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid |
701b935564521d64cc35dc51753493f4dc2782f6 | python/ql/test/library-tests/frameworks/django/SqlExecution.py | python/ql/test/library-tests/frameworks/django/SqlExecution.py | from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
cursor.execute(sql="some sql") # $getSql="some sql"
class User(models.Model):
pass
def test_model():
User.objects.raw("some sql") # $getSql="some sql"
User.objects.annotate(RawSQL("some sql")) # $getSql="some sql"
User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar"
User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql"
User.objects.extra("some sql") # $getSql="some sql"
User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by"
raw = RawSQL("so raw")
User.objects.annotate(val=raw) # $getSql="so raw"
| from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
cursor.execute(sql="some sql") # $getSql="some sql"
class User(models.Model):
pass
def test_model():
User.objects.raw("some sql") # $getSql="some sql"
User.objects.annotate(RawSQL("some sql")) # $getSql="some sql"
User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar"
User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql"
User.objects.extra("some sql") # $getSql="some sql"
User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by"
raw = RawSQL("so raw")
User.objects.annotate(val=raw) # $getSql="so raw"
# chaining QuerySet calls
User.objects.using("db-name").exclude(username="admin").extra("some sql") # $ MISSING: getSql="some sql"
| Add example of QuerySet chain (django) | Python: Add example of QuerySet chain (django)
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | ---
+++
@@ -27,3 +27,6 @@
raw = RawSQL("so raw")
User.objects.annotate(val=raw) # $getSql="so raw"
+
+ # chaining QuerySet calls
+ User.objects.using("db-name").exclude(username="admin").extra("some sql") # $ MISSING: getSql="some sql" |
3fe0313d67857ec302cc20e0cdc30d658e41dd97 | troposphere/ecr.py | troposphere/ecr.py | from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class LifecyclePolicy(AWSProperty):
props = {
'LifecyclePolicyText': (basestring, False),
'RegistryId': (basestring, False),
}
class Repository(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ImageScanningConfiguration': (dict, False),
'ImageTagMutability': (basestring, False),
'LifecyclePolicy': (LifecyclePolicy, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
| # Copyright (c) 2012-2021, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 31.0.0
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class PublicRepository(AWSObject):
resource_type = "AWS::ECR::PublicRepository"
props = {
'RepositoryCatalogData': (dict, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
class RegistryPolicy(AWSObject):
resource_type = "AWS::ECR::RegistryPolicy"
props = {
'PolicyText': (policytypes, True),
}
class ReplicationDestination(AWSProperty):
props = {
'Region': (basestring, True),
'RegistryId': (basestring, True),
}
class ReplicationRule(AWSProperty):
props = {
'Destinations': ([ReplicationDestination], True),
}
class ReplicationConfigurationProperty(AWSProperty):
props = {
'Rules': ([ReplicationRule], True),
}
class ReplicationConfiguration(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ReplicationConfigurationProperty':
(ReplicationConfigurationProperty, True),
}
class LifecyclePolicy(AWSProperty):
props = {
'LifecyclePolicyText': (basestring, False),
'RegistryId': (basestring, False),
}
class Repository(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ImageScanningConfiguration': (dict, False),
'ImageTagMutability': (basestring, False),
'LifecyclePolicy': (LifecyclePolicy, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
| Update ECR per 2020-12-18 and 2021-02-04 changes | Update ECR per 2020-12-18 and 2021-02-04 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -1,5 +1,61 @@
+# Copyright (c) 2012-2021, Mark Peek <[email protected]>
+# All rights reserved.
+#
+# See LICENSE file for full license.
+#
+# *** Do not modify - this file is autogenerated ***
+# Resource specification version: 31.0.0
+
+
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
+
+
+class PublicRepository(AWSObject):
+ resource_type = "AWS::ECR::PublicRepository"
+
+ props = {
+ 'RepositoryCatalogData': (dict, False),
+ 'RepositoryName': (basestring, False),
+ 'RepositoryPolicyText': (policytypes, False),
+ 'Tags': (Tags, False),
+ }
+
+
+class RegistryPolicy(AWSObject):
+ resource_type = "AWS::ECR::RegistryPolicy"
+
+ props = {
+ 'PolicyText': (policytypes, True),
+ }
+
+
+class ReplicationDestination(AWSProperty):
+ props = {
+ 'Region': (basestring, True),
+ 'RegistryId': (basestring, True),
+ }
+
+
+class ReplicationRule(AWSProperty):
+ props = {
+ 'Destinations': ([ReplicationDestination], True),
+ }
+
+
+class ReplicationConfigurationProperty(AWSProperty):
+ props = {
+ 'Rules': ([ReplicationRule], True),
+ }
+
+
+class ReplicationConfiguration(AWSObject):
+ resource_type = "AWS::ECR::Repository"
+
+ props = {
+ 'ReplicationConfigurationProperty':
+ (ReplicationConfigurationProperty, True),
+ }
class LifecyclePolicy(AWSProperty): |
5b7e2c7c4ad28634db9641a2b8c96f4d047ae503 | arim/fields.py | arim/fields.py | import re
from django import forms
mac_pattern = re.compile("^[0-9a-f]{12}$")
class MacAddrFormField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
super(MacAddrFormField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(MacAddrFormField, self).clean(value)
value = filter(lambda x: x in "0123456789abcdef", value)
if mac_pattern.match(value) is None:
raise forms.ValidationError('Invalid MAC address')
value = reduce(lambda x,y: x + ':' + y,
(value[i:i+2] for i in xrange(0, 12, 2)))
return value
| import re
from django import forms
mac_pattern = re.compile("^[0-9a-f]{12}$")
class MacAddrFormField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
super(MacAddrFormField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(MacAddrFormField, self).clean(value)
value = value.lower().replace(':', '').replace('-', '')
if mac_pattern.match(value) is None:
raise forms.ValidationError('Invalid MAC address')
value = reduce(lambda x,y: x + ':' + y,
(value[i:i+2] for i in xrange(0, 12, 2)))
return value
| Revert "Properly handle non-hex characters in MAC" | Revert "Properly handle non-hex characters in MAC"
This reverts commit 2734a3f0212c722fb9fe3698dfea0dbd8a14faa7.
| Python | bsd-3-clause | OSU-Net/arim,drkitty/arim,OSU-Net/arim,drkitty/arim,drkitty/arim,OSU-Net/arim | ---
+++
@@ -13,8 +13,7 @@
def clean(self, value):
value = super(MacAddrFormField, self).clean(value)
- value = filter(lambda x: x in "0123456789abcdef", value)
-
+ value = value.lower().replace(':', '').replace('-', '')
if mac_pattern.match(value) is None:
raise forms.ValidationError('Invalid MAC address')
value = reduce(lambda x,y: x + ':' + y, |
bd3dad98976d5e02c4a941ae3c687174db78781d | src/WebCatch/catchLink.py | src/WebCatch/catchLink.py | import requests
import re
import os
url = "https://www.autohome.com.cn/shanghai/"
urlBox = []
def catchURL(url):
file = requests.get(url,timeout=2)
data = file.content
links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data))
for i in links:
try:
currentURL = i[0]
if currentURL not in urlBox:
urlBox.append(currentURL)
os.system("ssh [email protected] psql test -c \
'insert into url values(nextval('url_seq'), '"+ currentURL +"')'")
print(currentURL)
catchURL(currentURL)
except Exception as e:
pass
continue
catchURL(url) | import requests
import re
import os
url = "https://www.autohome.com.cn/shanghai/"
urlBox = []
def catchURL(url):
file = requests.get(url,timeout=5)
data = file.content
links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data))
for i in links:
try:
currentURL = i[0]
if currentURL not in urlBox:
urlBox.append(currentURL)
sql = """
ssh [email protected] psql test -U pgadmin << EOF
insert into url values(nextval(\'url_seq\'), \'"""+currentURL+"""\');
EOF
"""
print(sql)
os.popen(sql)
print(currentURL)
catchURL(currentURL)
except Exception as e:
pass
continue
catchURL(url) | Put the crawled link into the database | Put the crawled link into the database
| Python | mit | zhaodjie/py_learning | ---
+++
@@ -5,7 +5,7 @@
url = "https://www.autohome.com.cn/shanghai/"
urlBox = []
def catchURL(url):
- file = requests.get(url,timeout=2)
+ file = requests.get(url,timeout=5)
data = file.content
links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data))
for i in links:
@@ -13,8 +13,13 @@
currentURL = i[0]
if currentURL not in urlBox:
urlBox.append(currentURL)
- os.system("ssh [email protected] psql test -c \
- 'insert into url values(nextval('url_seq'), '"+ currentURL +"')'")
+ sql = """
+ ssh [email protected] psql test -U pgadmin << EOF
+ insert into url values(nextval(\'url_seq\'), \'"""+currentURL+"""\');
+ EOF
+ """
+ print(sql)
+ os.popen(sql)
print(currentURL)
catchURL(currentURL)
except Exception as e: |
9d077b9c2d37b7cfc46849fe70c45b238806f134 | aiorest/__init__.py | aiorest/__init__.py | import collections
import re
import sys
__version__ = '0.1.2'
version = __version__ + ' , Python ' + sys.version
VersionInfo = collections.namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
from .server import RESTServer
from .request import Request, Response
from .errors import RESTError, JsonDecodeError, JsonLoadError
# make pyflakes happy
(RESTServer, Request, Response, RESTError, JsonDecodeError, JsonLoadError)
| import collections
import re
import sys
__version__ = '0.1.2'
version = __version__ + ' , Python ' + sys.version
VersionInfo = collections.namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'c': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
from .server import RESTServer
from .request import Request, Response
from .errors import RESTError, JsonDecodeError, JsonLoadError
# make pyflakes happy
(RESTServer, Request, Response, RESTError, JsonDecodeError, JsonLoadError)
| Make version format PEP 440 compatible | Make version format PEP 440 compatible
| Python | mit | aio-libs/aiorest | ---
+++
@@ -20,7 +20,7 @@
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
- levels = {'rc': 'candidate',
+ levels = {'c': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'} |
cf4015104cd8043024e55de4bab2ef598d6209a9 | mhvdb2/resources/payments.py | mhvdb2/resources/payments.py | from mhvdb2.models import Payment, Entity
import re
from datetime import datetime
from peewee import DoesNotExist
def validate(amount, email, method, type, notes, reference):
errors = []
if not amount or not amount.isdigit() or int(amount) <= 0:
errors.append("Sorry, you need to provide a valid amount.")
if not re.match("[^@\s]+@[^@\s]+", email):
errors.append("Sorry, you need to provide a valid email address.")
else: # Valid email, so check that they're a member
try:
Entity.get(Entity.email == email)
except DoesNotExist:
errors.append("Sorry, you need to provide a valid member's email address.")
if not type or not type.isdigit() or int(type) > 2:
errors.append("Sorry, you need to provide a valid payment type.")
if not method or not method.isdigit() or int(method) > 2:
errors.append("Sorry, you need to provide a valid payment method.")
if not reference:
errors.append("Sorry, you need to provide a reference.")
return errors
def create(amount, email, method, type, notes, reference):
# Create payment
payment = Payment()
payment.time = datetime.now()
payment.entity = Entity.get(Entity.email == email)
payment.amount = amount
payment.source = method
payment.is_donation = type != 0
payment.notes = notes
if method == 0: # Bank transfer
payment.bank_reference = reference
payment.pending = True
payment.save()
| from mhvdb2.models import Payment, Entity
import re
from datetime import datetime
from peewee import DoesNotExist
def validate(amount, email, method, type, notes, reference):
errors = []
if not amount or not amount.isdigit() or int(amount) <= 0:
errors.append("Sorry, you need to provide a valid amount.")
if not re.match("[^@\s]+@[^@\s]+", email):
errors.append("Sorry, you need to provide a valid email address.")
else: # Valid email, so check that they're a member
try:
Entity.get(Entity.email == email)
except DoesNotExist:
errors.append("Sorry, you need to provide a valid member's email address.")
if not type or not type.isdigit() or int(type) > 2:
errors.append("Sorry, you need to provide a valid payment type.")
if not method or not method.isdigit() or int(method) > 0:
errors.append("Sorry, you need to provide a valid payment method.")
if not reference:
errors.append("Sorry, you need to provide a reference.")
return errors
def create(amount, email, method, type, notes, reference):
# Create payment
payment = Payment()
payment.time = datetime.now()
payment.entity = Entity.get(Entity.email == email)
payment.amount = amount
payment.source = method
payment.is_donation = type != 0
payment.notes = notes
if method == 0: # Bank transfer
payment.bank_reference = reference
payment.pending = True
payment.save()
| Return invalid if payment method is not supported yet | Return invalid if payment method is not supported yet
| Python | mit | makehackvoid/mhvdb2,makehackvoid/mhvdb2 | ---
+++
@@ -18,7 +18,7 @@
errors.append("Sorry, you need to provide a valid member's email address.")
if not type or not type.isdigit() or int(type) > 2:
errors.append("Sorry, you need to provide a valid payment type.")
- if not method or not method.isdigit() or int(method) > 2:
+ if not method or not method.isdigit() or int(method) > 0:
errors.append("Sorry, you need to provide a valid payment method.")
if not reference:
errors.append("Sorry, you need to provide a reference.") |
545f688f0dd59df009e2392cbf27ef06865a4b89 | src/azure/cli/__main__.py | src/azure/cli/__main__.py | import sys
import azure.cli.main
from azure.cli._telemetry import init_telemetry, user_agrees_to_telemetry, telemetry_flush
try:
try:
if user_agrees_to_telemetry():
init_telemetry()
except Exception: #pylint: disable=broad-except
pass
sys.exit(azure.cli.main.main(sys.argv[1:]))
finally:
telemetry_flush()
| import sys
import os
import azure.cli.main
from azure.cli._telemetry import init_telemetry, user_agrees_to_telemetry, telemetry_flush
try:
try:
if user_agrees_to_telemetry():
init_telemetry()
except Exception: #pylint: disable=broad-except
pass
args = sys.argv[1:]
# Check if we are in argcomplete mode - if so, we
# need to pick up our args from environment variables
if os.environ.get('_ARGCOMPLETE'):
comp_line = os.environ.get('COMP_LINE')
if comp_line:
args = comp_line.split()[1:]
sys.exit(azure.cli.main.main(args))
finally:
telemetry_flush()
| Speed up argument completions by not loading all command packages unless we have to... | Speed up argument completions by not loading all command packages unless we have to...
| Python | mit | yugangw-msft/azure-cli,BurtBiel/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,samedder/azure-cli,BurtBiel/azure-cli,yugangw-msft/azure-cli,samedder/azure-cli,QingChenmsft/azure-cli,samedder/azure-cli,QingChenmsft/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,samedder/azure-cli | ---
+++
@@ -1,4 +1,5 @@
import sys
+import os
import azure.cli.main
@@ -11,6 +12,15 @@
except Exception: #pylint: disable=broad-except
pass
- sys.exit(azure.cli.main.main(sys.argv[1:]))
+ args = sys.argv[1:]
+
+ # Check if we are in argcomplete mode - if so, we
+ # need to pick up our args from environment variables
+ if os.environ.get('_ARGCOMPLETE'):
+ comp_line = os.environ.get('COMP_LINE')
+ if comp_line:
+ args = comp_line.split()[1:]
+
+ sys.exit(azure.cli.main.main(args))
finally:
telemetry_flush() |
e6ca7ef801115d16d809c563b657c3a63e828fb1 | corehq/apps/locations/management/commands/location_last_modified.py | corehq/apps/locations/management/commands/location_last_modified.py | from django.core.management.base import BaseCommand
from corehq.apps.locations.models import Location
from dimagi.utils.couch.database import iter_docs
from datetime import datetime
class Command(BaseCommand):
help = 'Populate last_modified field for locations'
def handle(self, *args, **options):
self.stdout.write("Processing locations...\n")
relevant_ids = set([r['id'] for r in Location.get_db().view(
'commtrack/locations_by_code',
reduce=False,
).all()])
to_save = []
for location in iter_docs(Location.get_db(), relevant_ids):
if 'last_modified' not in location or not location['last_modified']:
location['last_modified'] = datetime.now().isoformat()
to_save.append(location)
if len(to_save) > 500:
Location.get_db().bulk_save(to_save)
to_save = []
if to_save:
Location.get_db().bulk_save(to_save)
| from django.core.management.base import BaseCommand
from corehq.apps.locations.models import Location
from dimagi.utils.couch.database import iter_docs
from datetime import datetime
class Command(BaseCommand):
help = 'Populate last_modified field for locations'
def handle(self, *args, **options):
self.stdout.write("Processing locations...\n")
relevant_ids = set([r['id'] for r in Location.get_db().view(
'commtrack/locations_by_code',
reduce=False,
).all()])
to_save = []
for location in iter_docs(Location.get_db(), relevant_ids):
# exclude any psi domain to make this take a realistic
# amount fo time
if (
not location.get('last_modified', False) and
'psi' not in location.get('domain', '')
):
location['last_modified'] = datetime.now().isoformat()
to_save.append(location)
if len(to_save) > 500:
Location.get_db().bulk_save(to_save)
to_save = []
if to_save:
Location.get_db().bulk_save(to_save)
| Exclude psi domains or this takes forever | Exclude psi domains or this takes forever
| Python | bsd-3-clause | qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq | ---
+++
@@ -17,7 +17,12 @@
to_save = []
for location in iter_docs(Location.get_db(), relevant_ids):
- if 'last_modified' not in location or not location['last_modified']:
+ # exclude any psi domain to make this take a realistic
+ # amount fo time
+ if (
+ not location.get('last_modified', False) and
+ 'psi' not in location.get('domain', '')
+ ):
location['last_modified'] = datetime.now().isoformat()
to_save.append(location)
|
e2813d7c27079a259f542ff36383ec0aa2233a9e | spyder_terminal/__init__.py | spyder_terminal/__init__.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Spyder Terminal Plugin."""
from .terminalplugin import TerminalPlugin as PLUGIN_CLASS
PLUGIN_CLASS
VERSION_INFO = (0, 2, 4)
__version__ = '.'.join(map(str, VERSION_INFO))
| # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Spyder Terminal Plugin."""
from .terminalplugin import TerminalPlugin as PLUGIN_CLASS
PLUGIN_CLASS
VERSION_INFO = (0, 3, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))
| Set development version to v0.3.0.dev0 | Set development version to v0.3.0.dev0
| Python | mit | spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal | ---
+++
@@ -11,5 +11,5 @@
PLUGIN_CLASS
-VERSION_INFO = (0, 2, 4)
+VERSION_INFO = (0, 3, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO)) |
352cb871a86abd926842a0624475db1f2ee2c0ce | TorGTK/list_elements.py | TorGTK/list_elements.py | from var import *
from ui_elements import *
from gi.repository import Gtk
from torctl import *
# ORGANIZATION OF THESE LISTS:
# 1. Main list for all the elements
# 2. A sublist for each element, with the first being a label, and the second
# being the element itself
# List for main listbox
lb_main_elements = [
["", init_menubutton("btnMainMenu", objs["menuMain"])],
["Enable Tor", init_switch("swEnable", enableTor)],
]
# List for settings listbox
lb_settings_elements = [
["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)],
["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)],
]
| from var import *
from ui_elements import *
from gi.repository import Gtk
from torctl import *
# ORGANIZATION OF THESE LISTS:
# 1. Main list for all the elements
# 2. A sublist for each element, with the first being a label, and the second
# being the element itself
# List for main listbox
lb_main_elements = [
["", init_menubutton("btnMainMenu", objs["menuMain"])],
["Enable Tor", init_switch("swEnable", enableTor)],
]
# List for settings listbox
lb_settings_elements = [
["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)],
["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)],
["Exit Nodes", init_textfield("txtExit")],
]
| Add field (not working yet) for Tor exit node selection | Add field (not working yet) for Tor exit node selection
| Python | bsd-2-clause | neelchauhan/TorNova,neelchauhan/TorGTK | ---
+++
@@ -18,4 +18,5 @@
lb_settings_elements = [
["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)],
["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)],
+ ["Exit Nodes", init_textfield("txtExit")],
] |
3f136f153cdc60c1dcc757a8a35ef116bb892a1c | python/prep_policekml.py | python/prep_policekml.py | """
A collection of classes used to manipulate Police KML data, used with prepgml4ogr.py.
"""
import os
from lxml import etree
class prep_kml():
def __init__ (self, inputfile):
self.inputfile = inputfile
self.infile = os.path.basename(inputfile)
self.feat_types = ['Placemark']
def get_feat_types(self):
return self.feat_types
def prepare_feature(self, feat_str):
# Parse the xml string into something useful
feat_elm = etree.fromstring(feat_str)
feat_elm = self._prepare_feat_elm(feat_elm)
return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8');
def _prepare_feat_elm(self, feat_elm):
feat_elm = self._add_filename_elm(feat_elm)
return feat_elm
def _add_filename_elm(self, feat_elm):
# Create an element with the fid
elm = etree.SubElement(feat_elm, "name")
elm.text = self.infile[:-4]
elm = etree.SubElement(feat_elm, "description")
elm.text = os.path.dirname(self.inputfile).split('/')[-1]
return feat_elm
| """
prep_kml class used to manipulate police.uk KML data, used with prepgml4ogr.py
"""
import os
from lxml import etree
class prep_kml():
def __init__(self, inputfile):
self.inputfile = inputfile
self.infile = os.path.basename(inputfile)
self.feat_types = ['Placemark']
def get_feat_types(self):
return self.feat_types
def prepare_feature(self, feat_str):
# Parse the xml string into something useful
feat_elm = etree.fromstring(feat_str)
feat_elm = self._prepare_feat_elm(feat_elm)
return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8');
def _prepare_feat_elm(self, feat_elm):
feat_elm = self._add_filename_elm(feat_elm)
return feat_elm
def _add_filename_elm(self, feat_elm):
elm = etree.SubElement(feat_elm, "name")
elm.text = self.infile[:-4]
elm = etree.SubElement(feat_elm, "description")
elm.text = os.path.dirname(self.inputfile).split('/')[-1]
return feat_elm
| Remove stray comment, update docstring and minor PEP8 changes | Remove stray comment, update docstring and minor PEP8 changes
| Python | mit | AstunTechnology/Loader | ---
+++
@@ -1,12 +1,13 @@
"""
-A collection of classes used to manipulate Police KML data, used with prepgml4ogr.py.
+prep_kml class used to manipulate police.uk KML data, used with prepgml4ogr.py
"""
import os
from lxml import etree
+
class prep_kml():
- def __init__ (self, inputfile):
+ def __init__(self, inputfile):
self.inputfile = inputfile
self.infile = os.path.basename(inputfile)
self.feat_types = ['Placemark']
@@ -19,22 +20,21 @@
# Parse the xml string into something useful
feat_elm = etree.fromstring(feat_str)
feat_elm = self._prepare_feat_elm(feat_elm)
-
+
return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8');
def _prepare_feat_elm(self, feat_elm):
feat_elm = self._add_filename_elm(feat_elm)
-
+
return feat_elm
def _add_filename_elm(self, feat_elm):
- # Create an element with the fid
+
elm = etree.SubElement(feat_elm, "name")
elm.text = self.infile[:-4]
-
+
elm = etree.SubElement(feat_elm, "description")
elm.text = os.path.dirname(self.inputfile).split('/')[-1]
return feat_elm
- |
3ebf7f1633a072cd09f006910660373527d335bb | project_template/project_settings.py | project_template/project_settings.py | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.icekit import * # glamkit, icekit
# Override the default ICEkit settings to form project settings.
| # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.glamkit import * # glamkit, icekit
# Override the default ICEkit settings to form project settings.
| Use glamkit settings as default in glamkit branch. | Use glamkit settings as default in glamkit branch.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -4,6 +4,6 @@
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
-from icekit.project.settings.icekit import * # glamkit, icekit
+from icekit.project.settings.glamkit import * # glamkit, icekit
# Override the default ICEkit settings to form project settings. |
fe65e85e0a29341a6eebbb1bafb28b8d1225abfc | harvester/rq_worker_sns_msgs.py | harvester/rq_worker_sns_msgs.py | '''A custom rq worker class to add start & stop SNS messages to all jobs'''
import logging
from rq.worker import Worker
from harvester.sns_message import publish_to_harvesting
logger = logging.getLogger(__name__)
class SNSWorker(Worker):
def execute_job(self, job, queue):
"""Spawns a work horse to perform the actual work and passes it a job.
The worker will wait for the work horse and make sure it executes
within the given timeout bounds, or will end the work horse with
SIGALRM.
"""
worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0]
subject = 'Worker {} starting job {}'.format(
worker_name,
job.description)
publish_to_harvesting(subject, subject)
self.set_state('busy')
self.fork_work_horse(job, queue)
self.monitor_work_horse(job)
subject = 'Worker {} finished job {}'.format(
worker_name,
job.description)
publish_to_harvesting(subject, subject)
self.set_state('idle')
| '''A custom rq worker class to add start & stop SNS messages to all jobs'''
import logging
from rq.worker import Worker
from harvester.sns_message import publish_to_harvesting
logger = logging.getLogger(__name__)
def exception_to_sns(job, *exc_info):
'''Make an exception handler to report exceptions to SNS msg queue'''
subject = 'FAILED: job {}'.format(job.description)
message = 'ERROR: job {} failed\n{}'.format(
job.description,
exc_info[1])
logging.error(message)
publish_to_harvesting(subject, message)
class SNSWorker(Worker):
def execute_job(self, job, queue):
"""Spawns a work horse to perform the actual work and passes it a job.
The worker will wait for the work horse and make sure it executes
within the given timeout bounds, or will end the work horse with
SIGALRM.
"""
worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0]
subject = 'Worker {} starting job {}'.format(
worker_name,
job.description)
#publish_to_harvesting(subject, subject)
self.set_state('busy')
self.fork_work_horse(job, queue)
self.monitor_work_horse(job)
subject = 'Worker {} finished job {}'.format(
worker_name,
job.description)
#publish_to_harvesting(subject, subject)
self.set_state('idle')
| Add RQ exception handler to report to SNS topic | Add RQ exception handler to report to SNS topic
| Python | bsd-3-clause | mredar/harvester,barbarahui/harvester,barbarahui/harvester,mredar/harvester,ucldc/harvester,ucldc/harvester | ---
+++
@@ -5,6 +5,16 @@
from harvester.sns_message import publish_to_harvesting
logger = logging.getLogger(__name__)
+
+
+def exception_to_sns(job, *exc_info):
+ '''Make an exception handler to report exceptions to SNS msg queue'''
+ subject = 'FAILED: job {}'.format(job.description)
+ message = 'ERROR: job {} failed\n{}'.format(
+ job.description,
+ exc_info[1])
+ logging.error(message)
+ publish_to_harvesting(subject, message)
class SNSWorker(Worker):
@@ -18,12 +28,12 @@
subject = 'Worker {} starting job {}'.format(
worker_name,
job.description)
- publish_to_harvesting(subject, subject)
+ #publish_to_harvesting(subject, subject)
self.set_state('busy')
self.fork_work_horse(job, queue)
self.monitor_work_horse(job)
subject = 'Worker {} finished job {}'.format(
worker_name,
job.description)
- publish_to_harvesting(subject, subject)
+ #publish_to_harvesting(subject, subject)
self.set_state('idle') |
e27088976467dd95ad2672123cb39dd54b78f413 | blog/models.py | blog/models.py | from django.db import models
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse_lazy
class Category(models.Model):
title = models.CharField(max_length=80)
class Meta:
verbose_name_plural = 'categories'
def __unicode__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(editable=False, unique=True)
image = models.ImageField(upload_to='posts', blank=True, null=False)
created_on = models.DateTimeField(auto_now_add=True)
content = models.TextField()
categories = models.ManyToManyField(Category)
class Meta:
ordering = ('created_on',)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
| from django.db import models
from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse_lazy
def validate_no_commas(value):
if ',' in value:
raise ValidationError('%s contains commas' % value)
class Category(models.Model):
title = models.CharField(max_length=80, validators=[validate_no_commas])
class Meta:
verbose_name_plural = 'categories'
def __unicode__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(editable=False, unique=True)
image = models.ImageField(upload_to='posts', blank=True, null=False)
created_on = models.DateTimeField(auto_now_add=True)
content = models.TextField()
categories = models.ManyToManyField(Category)
class Meta:
ordering = ('created_on',)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = self.get_slug()
super(Post, self).save(*args, **kwargs)
def get_slug(self):
return self.slug or slugify(self.title)
def get_absolute_url(self):
return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
| Add validation in category and get_slug in post | Add validation in category and get_slug in post
| Python | mit | jmcomets/jmcomets.github.io | ---
+++
@@ -1,9 +1,14 @@
from django.db import models
+from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse_lazy
+def validate_no_commas(value):
+ if ',' in value:
+ raise ValidationError('%s contains commas' % value)
+
class Category(models.Model):
- title = models.CharField(max_length=80)
+ title = models.CharField(max_length=80, validators=[validate_no_commas])
class Meta:
verbose_name_plural = 'categories'
@@ -26,8 +31,11 @@
return self.title
def save(self, *args, **kwargs):
- self.slug = slugify(self.title)
+ self.slug = self.get_slug()
super(Post, self).save(*args, **kwargs)
+
+ def get_slug(self):
+ return self.slug or slugify(self.title)
def get_absolute_url(self):
return reverse_lazy('blog:show_post', kwargs={'slug': self.slug}) |
f9c178e641fa27b6c0c2bf32a969c52ba17042bf | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
backupCount=5)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s: %(message)s - %(name)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) | Update log output so that it works more nicely with ELK | Update log output so that it works more nicely with ELK
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -9,7 +9,7 @@
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
- backupCount=5)
+ backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
@@ -17,8 +17,8 @@
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
-formatterch = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
-formattertfh = logging.Formatter('%(asctime)s %(levelname)s: %(message)s - %(name)s')
+formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
+formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
|
eff3195097e9599b87f5cec9bbae744b91ae16cf | buses/utils.py | buses/utils.py | import re
def minify(template_source):
template_source = re.sub(r'(\n *)+', '\n', template_source)
template_source = re.sub(r'({%.+%})\n+', r'\1', template_source)
return template_source
| import re
from haystack.utils import default_get_identifier
def minify(template_source):
template_source = re.sub(r'(\n *)+', '\n', template_source)
template_source = re.sub(r'({%.+%})\n+', r'\1', template_source)
return template_source
def get_identifier(obj_or_string):
if isinstance(obj_or_string, basestring):
return obj_or_string
return default_get_identifier(obj_or_string)
| Add custom Hastack get_identifier function | Add custom Hastack get_identifier function
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | ---
+++
@@ -1,7 +1,13 @@
import re
+from haystack.utils import default_get_identifier
def minify(template_source):
template_source = re.sub(r'(\n *)+', '\n', template_source)
template_source = re.sub(r'({%.+%})\n+', r'\1', template_source)
return template_source
+
+def get_identifier(obj_or_string):
+ if isinstance(obj_or_string, basestring):
+ return obj_or_string
+ return default_get_identifier(obj_or_string) |
303923dd287014551e4b542a9300a13ecebfa2f9 | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| Add utility function for retrieving the active registration backend. | Add utility function for retrieving the active registration backend.
| Python | bsd-3-clause | dinie/django-registration,Avenza/django-registration,FundedByMe/django-registration,FundedByMe/django-registration,dinie/django-registration | ---
+++
@@ -0,0 +1,23 @@
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.importlib import import_module
+
+def get_backend():
+ """
+ Return an instance of the registration backend for use on this
+ site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
+ ``django.core.exceptions.ImproperlyConfigured`` if the specified
+ backend cannot be located.
+
+ """
+ i = settings.REGISTRATION_BACKEND.rfind('.')
+ module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
+ try:
+ mod = import_module(module)
+ except ImportError, e:
+ raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
+ try:
+ backend_class = getattr(mod, attr)
+ except AttributeError:
+ raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
+ return backend_class() |
|
b9a7289c1f3466bb0caee1488a16dafbae327c6f | tartpy/eventloop.py | tartpy/eventloop.py | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(object, metaclass=Singleton):
"""A generic event loop object."""
def __init__(self):
self.scheduler = sched.scheduler()
def schedule(self, event):
"""Schedule an event.
An `event` is a thunk.
"""
self.scheduler.enter(0, 1, event)
def stop(self):
"""Stop the loop."""
pass
def run(self, block=False):
self.scheduler.run(blocking=block)
def run_in_thread(self):
self.thread = threading.Thread(target=self.run, args=(True,),
name='event_loop')
self.thread.daemon = True
self.thread.start()
| """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(object, metaclass=Singleton):
"""A generic event loop object."""
def __init__(self):
self.scheduler = sched.scheduler()
def schedule(self, event):
"""Schedule an event.
An `event` is a thunk.
"""
self.scheduler.enter(0, 1, event)
def stop(self):
"""Stop the loop."""
pass
def run(self, block=False):
self.scheduler.run(blocking=block)
def run_forever(self, wait=0.05):
while True:
self.run()
time.sleep(wait)
def run_in_thread(self):
self.thread = threading.Thread(target=self.run_forever,
name='event_loop')
self.thread.daemon = True
self.thread.start()
| Fix threaded run of the new event loop | Fix threaded run of the new event loop | Python | mit | waltermoreira/tartpy | ---
+++
@@ -41,8 +41,13 @@
def run(self, block=False):
self.scheduler.run(blocking=block)
+ def run_forever(self, wait=0.05):
+ while True:
+ self.run()
+ time.sleep(wait)
+
def run_in_thread(self):
- self.thread = threading.Thread(target=self.run, args=(True,),
+ self.thread = threading.Thread(target=self.run_forever,
name='event_loop')
self.thread.daemon = True
self.thread.start() |
ae42042d38d4f53a88a25cb4dc18ad86f23c0f28 | derrida/__init__.py | derrida/__init__.py | __version_info__ = (1, 3, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__
}
| __version_info__ = (1, 2, 2, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__
}
| Set version to 1.2.2 final | Set version to 1.2.2 final
| Python | apache-2.0 | Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django | ---
+++
@@ -1,4 +1,4 @@
-__version_info__ = (1, 3, 0, 'dev')
+__version_info__ = (1, 2, 2, None)
# Dot-connect all but the last. Last is dash-connected if not None. |
3409aa543b4f0a4c574afd7ff4fdd59d1bd8a4b0 | tests/date_tests.py | tests/date_tests.py | # -*- coding: utf-8 -*-
#
# (C) Pywikibot team, 2014
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
from tests.utils import unittest
from pywikibot import date
class TestDate(unittest.TestCase):
"""Test cases for date library"""
def __init__(self, formatname):
super(TestDate, self).__init__()
self.formatname = formatname
def testMapEntry(self, formatname):
"""The test ported from date.py"""
step = 1
if formatname in date.decadeFormats:
step = 10
predicate, start, stop = date.formatLimits[formatname]
for code, convFunc in date.formats[formatname].items():
for value in range(start, stop, step):
self.assertTrue(
predicate(value),
"date.formats['%(formatname)s']['%(code)s']:\n"
"invalid value %(value)d" % locals())
newValue = convFunc(convFunc(value))
self.assertEqual(
newValue, value,
"date.formats['%(formatname)s']['%(code)s']:\n"
"value %(newValue)d does not match %(value)s"
% locals())
def runTest(self):
"""method called by unittest"""
self.testMapEntry(self.formatname)
def suite():
"""Setup the test suite and register all test to different instances"""
suite = unittest.TestSuite()
suite.addTests(TestDate(formatname) for formatname in date.formats)
return suite
if __name__ == '__main__':
try:
unittest.TextTestRunner().run(suite())
except SystemExit:
pass
| # -*- coding: utf-8 -*-
#
# (C) Pywikibot team, 2014
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
from tests.utils import unittest
from pywikibot import date
class TestDate(unittest.TestCase):
"""Test cases for date library"""
def testMapEntry(self):
"""Test the validity of the pywikibot.date format maps."""
for formatName in date.formats:
step = 1
if formatName in date.decadeFormats:
step = 10
predicate, start, stop = date.formatLimits[formatName]
for code, convFunc in date.formats[formatName].items():
for value in range(start, stop, step):
self.assertTrue(
predicate(value),
"date.formats['%(formatName)s']['%(code)s']:\n"
"invalid value %(value)d" % locals())
newValue = convFunc(convFunc(value))
self.assertEqual(
newValue, value,
"date.formats['%(formatName)s']['%(code)s']:\n"
"value %(newValue)d does not match %(value)s"
% locals())
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass
| Revert "Progressing dots to show test is running" | Revert "Progressing dots to show test is running"
Breaks tests; https://travis-ci.org/wikimedia/pywikibot-core/builds/26752150
This reverts commit 93379dbf499c58438917728b74862f282c15dba4.
Change-Id: Iacb4cc9e6999d265b46c558ed3999c1198f87de0
| Python | mit | hasteur/g13bot_tools_new,smalyshev/pywikibot-core,h4ck3rm1k3/pywikibot-core,TridevGuha/pywikibot-core,npdoty/pywikibot,icyflame/batman,valhallasw/pywikibot-core,darthbhyrava/pywikibot-local,hasteur/g13bot_tools_new,xZise/pywikibot-core,npdoty/pywikibot,magul/pywikibot-core,happy5214/pywikibot-core,VcamX/pywikibot-core,h4ck3rm1k3/pywikibot-core,happy5214/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,Darkdadaah/pywikibot-core,hasteur/g13bot_tools_new,emijrp/pywikibot-core,wikimedia/pywikibot-core,jayvdb/pywikibot-core,trishnaguha/pywikibot-core,PersianWikipedia/pywikibot-core,magul/pywikibot-core,wikimedia/pywikibot-core | ---
+++
@@ -13,45 +13,31 @@
class TestDate(unittest.TestCase):
"""Test cases for date library"""
- def __init__(self, formatname):
- super(TestDate, self).__init__()
- self.formatname = formatname
+ def testMapEntry(self):
+ """Test the validity of the pywikibot.date format maps."""
+ for formatName in date.formats:
+ step = 1
+ if formatName in date.decadeFormats:
+ step = 10
+ predicate, start, stop = date.formatLimits[formatName]
- def testMapEntry(self, formatname):
- """The test ported from date.py"""
- step = 1
- if formatname in date.decadeFormats:
- step = 10
- predicate, start, stop = date.formatLimits[formatname]
+ for code, convFunc in date.formats[formatName].items():
+ for value in range(start, stop, step):
+ self.assertTrue(
+ predicate(value),
+ "date.formats['%(formatName)s']['%(code)s']:\n"
+ "invalid value %(value)d" % locals())
- for code, convFunc in date.formats[formatname].items():
- for value in range(start, stop, step):
- self.assertTrue(
- predicate(value),
- "date.formats['%(formatname)s']['%(code)s']:\n"
- "invalid value %(value)d" % locals())
-
- newValue = convFunc(convFunc(value))
- self.assertEqual(
- newValue, value,
- "date.formats['%(formatname)s']['%(code)s']:\n"
- "value %(newValue)d does not match %(value)s"
- % locals())
-
- def runTest(self):
- """method called by unittest"""
- self.testMapEntry(self.formatname)
-
-
-def suite():
- """Setup the test suite and register all test to different instances"""
- suite = unittest.TestSuite()
- suite.addTests(TestDate(formatname) for formatname in date.formats)
- return suite
+ newValue = convFunc(convFunc(value))
+ self.assertEqual(
+ newValue, value,
+ "date.formats['%(formatName)s']['%(code)s']:\n"
+ "value %(newValue)d does not match %(value)s"
+ % locals())
if __name__ == '__main__':
try:
- unittest.TextTestRunner().run(suite())
+ unittest.main()
except SystemExit:
pass |
9fbef73081b0cb608e32c91a57502aaefa0599cc | tests/test_basic.py | tests/test_basic.py | import unittest
import os, sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.append(os.path.join(PROJECT_ROOT, ".."))
from CodeConverter import CodeConverter
class TestBasic(unittest.TestCase):
def setUp(self):
pass
def test_initialize(self):
self.assertEqual(CodeConverter('foo').s, 'foo')
if __name__ == '__main__':
unittest.main()
| import unittest
import os, sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.append(os.path.join(PROJECT_ROOT, ".."))
from CodeConverter import CodeConverter
class TestBasic(unittest.TestCase):
def setUp(self):
pass
def test_initialize(self):
self.assertEqual(CodeConverter('foo').s, 'foo')
# def test_python_version(self):
# # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00)
# if sys.version_info[:3] != (2, 6, 7):
# print 'Sublime Text 2 uses python 2.6.7'
# print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3])
# self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
| Add test to check python version | Add test to check python version
| Python | mit | kyamaguchi/SublimeObjC2RubyMotion,kyamaguchi/SublimeObjC2RubyMotion | ---
+++
@@ -13,5 +13,12 @@
def test_initialize(self):
self.assertEqual(CodeConverter('foo').s, 'foo')
+ # def test_python_version(self):
+ # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00)
+ # if sys.version_info[:3] != (2, 6, 7):
+ # print 'Sublime Text 2 uses python 2.6.7'
+ # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3])
+ # self.assertTrue(True)
+
if __name__ == '__main__':
unittest.main() |
5d6206f42323c9fd5e4185f36e75a2466adf79e8 | thinc/neural/_classes/feed_forward.py | thinc/neural/_classes/feed_forward.py | from .model import Model
class FeedForward(Model):
'''A feed-forward network, that chains multiple Model instances together.'''
def __init__(self, layers, **kwargs):
Model.__init__(self, **kwargs)
self.layers.extend(layers)
if self.layers:
nO = self.layers[0].output_shape[1]
for layer in self.layers[1:]:
if nO is not None and layer.nI is None:
layer.nI = nO
nO = layer.nO
@property
def input_shape(self):
return self.layers[0].input_shape
@property
def output_shape(self):
return self.layers[-1].output_shape
def begin_update(self, X, drop=0.):
callbacks = []
for layer in self.layers:
assert layer.W is not None
assert layer.b is not None
X = self.ops.xp.ascontiguousarray(X, dtype='float32')
X, inc_layer_grad = layer.begin_update(X, drop=drop)
callbacks.append(inc_layer_grad)
def continue_update(gradient, sgd=None):
for callback in reversed(callbacks):
gradient = self.ops.xp.ascontiguousarray(gradient, dtype='float32')
gradient = callback(gradient, sgd)
return gradient
return X, continue_update
| from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
@describe.on_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that chains multiple Model instances together.'''
def __init__(self, layers, **kwargs):
Model.__init__(self, **kwargs)
self._layers.extend(layers)
@property
def input_shape(self):
return self._layers[0].input_shape
@property
def output_shape(self):
return self._layers[-1].output_shape
def begin_update(self, X, drop=0.):
callbacks = []
for layer in self.layers:
X = self.ops.xp.ascontiguousarray(X, dtype='float32')
X, inc_layer_grad = layer.begin_update(X, drop=drop)
callbacks.append(inc_layer_grad)
def continue_update(gradient, sgd=None):
for callback in reversed(callbacks):
gradient = self.ops.xp.ascontiguousarray(gradient, dtype='float32')
gradient = callback(gradient, sgd)
return gradient
return X, continue_update
| Improve how child hooks are run in FeedForward | Improve how child hooks are run in FeedForward
| Python | mit | explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc | ---
+++
@@ -1,31 +1,29 @@
from .model import Model
+from ... import describe
+def _run_child_hooks(model, X, y):
+ for layer in model._layers:
+ for hook in layer.on_data_hooks:
+ hook(layer, X, y)
[email protected]_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that chains multiple Model instances together.'''
def __init__(self, layers, **kwargs):
Model.__init__(self, **kwargs)
- self.layers.extend(layers)
- if self.layers:
- nO = self.layers[0].output_shape[1]
- for layer in self.layers[1:]:
- if nO is not None and layer.nI is None:
- layer.nI = nO
- nO = layer.nO
+ self._layers.extend(layers)
@property
def input_shape(self):
- return self.layers[0].input_shape
+ return self._layers[0].input_shape
@property
def output_shape(self):
- return self.layers[-1].output_shape
+ return self._layers[-1].output_shape
def begin_update(self, X, drop=0.):
callbacks = []
for layer in self.layers:
- assert layer.W is not None
- assert layer.b is not None
X = self.ops.xp.ascontiguousarray(X, dtype='float32')
X, inc_layer_grad = layer.begin_update(X, drop=drop)
callbacks.append(inc_layer_grad) |
741db5b16922ceca0c23a95caa143f9ff7baeee2 | Api/app/types.py | Api/app/types.py | import graphene
from graphene_django import DjangoObjectType
from app import models
class TagType(DjangoObjectType):
class Meta:
model = models.Tag
interfaces = (graphene.relay.Node,)
@classmethod
def get_node(cls, id, context, info):
return models.Tag.objects.get(pk=id)
class TagConnection(graphene.relay.Connection):
class Meta:
node = TagType
class ArticleType(DjangoObjectType):
class Meta:
model = models.Article
interfaces = (graphene.relay.Node,)
tags = graphene.relay.ConnectionField(TagConnection)
@classmethod
def get_node(cls, id, context, info):
return models.Article.objects.get(pk=id)
@graphene.resolve_only_args
def resolve_tags(self):
return self.tags.all() | import graphene
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from app import models
class TagType(DjangoObjectType):
class Meta:
model = models.Tag
interfaces = (graphene.relay.Node,)
articles = DjangoFilterConnectionField(lambda: ArticleType)
@classmethod
def get_node(cls, id, context, info):
return models.Tag.objects.get(pk=id)
class ArticleType(DjangoObjectType):
class Meta:
model = models.Article
interfaces = (graphene.relay.Node,)
tags = DjangoFilterConnectionField(lambda: TagType)
@classmethod
def get_node(cls, id, context, info):
return models.Article.objects.get(pk=id)
| Fix tag and article connections | Fix tag and article connections
| Python | mit | rcatlin/ryancatlin-info,rcatlin/ryancatlin-info,rcatlin/ryancatlin-info,rcatlin/ryancatlin-info | ---
+++
@@ -1,8 +1,8 @@
import graphene
from graphene_django import DjangoObjectType
+from graphene_django.filter import DjangoFilterConnectionField
from app import models
-
class TagType(DjangoObjectType):
@@ -10,14 +10,11 @@
model = models.Tag
interfaces = (graphene.relay.Node,)
+ articles = DjangoFilterConnectionField(lambda: ArticleType)
+
@classmethod
def get_node(cls, id, context, info):
return models.Tag.objects.get(pk=id)
-
-
-class TagConnection(graphene.relay.Connection):
- class Meta:
- node = TagType
class ArticleType(DjangoObjectType):
@@ -25,12 +22,8 @@
model = models.Article
interfaces = (graphene.relay.Node,)
- tags = graphene.relay.ConnectionField(TagConnection)
+ tags = DjangoFilterConnectionField(lambda: TagType)
@classmethod
def get_node(cls, id, context, info):
return models.Article.objects.get(pk=id)
-
- @graphene.resolve_only_args
- def resolve_tags(self):
- return self.tags.all() |
d98ecce6e83db415338f946bfab5191f5671550e | numba/typesystem/__init__.py | numba/typesystem/__init__.py | from basetypes import *
from exttypes import *
from closuretypes import *
from ssatypes import *
from templatetypes import *
from typemapper import *
__all__ = minitypes.__all__ + [
'O', 'b1', 'i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',
'f4', 'f8', 'f16', 'c8', 'c16', 'c32', 'template',
]
#------------------------------------------------------------------------
# Utilities
#------------------------------------------------------------------------
def is_obj(type):
return type.is_object or type.is_array
def promote_closest(context, int_type, candidates):
"""
promote_closest(Py_ssize_t, [int_, long_, longlong]) -> longlong
"""
for candidate in candidates:
promoted = context.promote_types(int_type, candidate)
if promoted == candidate:
return candidate
return candidates[-1]
#------------------------------------------------------------------------
# Type shorthands
#------------------------------------------------------------------------
O = object_
b1 = bool_
i1 = int8
i2 = int16
i4 = int32
i8 = int64
u1 = uint8
u2 = uint16
u4 = uint32
u8 = uint64
f4 = float_
f8 = double
f16 = float128
c8 = complex64
c16 = complex128
c32 = complex256
| from basetypes import *
from exttypes import *
from closuretypes import *
from ssatypes import *
from templatetypes import *
from typemapper import *
__all__ = minitypes.__all__ + [
'O', 'b1', 'i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',
'f4', 'f8', 'f16', 'c8', 'c16', 'c32', 'template',
]
#------------------------------------------------------------------------
# Utilities
#------------------------------------------------------------------------
def is_obj(type):
return type.is_object or type.is_array
def promote_closest(context, int_type, candidates):
"""
promote_closest(Py_ssize_t, [int_, long_, longlong]) -> longlong
"""
for candidate in candidates:
promoted = context.promote_types(int_type, candidate)
if promoted == candidate:
return candidate
return candidates[-1]
#------------------------------------------------------------------------
# Type shorthands
#------------------------------------------------------------------------
O = object_
b1 = bool_
i1 = int8
i2 = int16
i4 = int32
i8 = int64
u1 = uint8
u2 = uint16
u4 = uint32
u8 = uint64
f4 = float32
f8 = float64
f16 = float128
c8 = complex64
c16 = complex128
c32 = complex256
| Use the right float names for type shortcuts | Use the right float names for type shortcuts
| Python | bsd-2-clause | stefanseefeld/numba,stonebig/numba,stefanseefeld/numba,pombredanne/numba,pitrou/numba,seibert/numba,GaZ3ll3/numba,pitrou/numba,numba/numba,cpcloud/numba,IntelLabs/numba,stefanseefeld/numba,numba/numba,pombredanne/numba,stonebig/numba,jriehl/numba,GaZ3ll3/numba,gmarkall/numba,seibert/numba,stefanseefeld/numba,gmarkall/numba,GaZ3ll3/numba,shiquanwang/numba,stuartarchibald/numba,IntelLabs/numba,ssarangi/numba,jriehl/numba,gdementen/numba,cpcloud/numba,pitrou/numba,numba/numba,cpcloud/numba,cpcloud/numba,stuartarchibald/numba,gdementen/numba,shiquanwang/numba,GaZ3ll3/numba,seibert/numba,gmarkall/numba,jriehl/numba,stuartarchibald/numba,gdementen/numba,ssarangi/numba,pombredanne/numba,pombredanne/numba,IntelLabs/numba,stonebig/numba,shiquanwang/numba,IntelLabs/numba,gdementen/numba,stonebig/numba,sklam/numba,sklam/numba,jriehl/numba,pitrou/numba,seibert/numba,ssarangi/numba,numba/numba,jriehl/numba,seibert/numba,gmarkall/numba,pombredanne/numba,stuartarchibald/numba,cpcloud/numba,gdementen/numba,sklam/numba,IntelLabs/numba,gmarkall/numba,ssarangi/numba,sklam/numba,numba/numba,sklam/numba,GaZ3ll3/numba,stuartarchibald/numba,pitrou/numba,stonebig/numba,ssarangi/numba,stefanseefeld/numba | ---
+++
@@ -43,8 +43,8 @@
u4 = uint32
u8 = uint64
-f4 = float_
-f8 = double
+f4 = float32
+f8 = float64
f16 = float128
c8 = complex64 |
379c083be77ba5373881f84adf7d2a8e87e930f4 | birdy/dependencies.py | birdy/dependencies.py | # -*- coding: utf-8 -*-
"""
This module is used to manage optional dependencies.
Example usage::
from birdy.dependencies import ipywidgets as widgets
"""
import warnings
from .exceptions import IPythonWarning
# TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook,
# but we currently don't know how to handle this (see #89 and #138).
warnings.filterwarnings('ignore', category=IPythonWarning)
try:
import ipywidgets
except ImportError:
ipywidgets = None
warnings.warn('Jupyter Notebook is not supported. Please install *ipywidgets*.', IPythonWarning)
try:
import IPython
except ImportError:
IPython = None
warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning)
try:
import ipyleaflet
except ImportError:
ipyleaflet = None
warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning)
| # -*- coding: utf-8 -*-
"""
This module is used to manage optional dependencies.
Example usage::
from birdy.dependencies import ipywidgets as widgets
"""
import warnings
from .exceptions import IPythonWarning
# TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook,
# but we currently don't know how to handle this (see #89 and #138).
warnings.filterwarnings('ignore', category=IPythonWarning)
try:
import ipywidgets
except ImportError:
ipywidgets = None
warnings.warn('Jupyter Notebook is not supported. Please install *ipywidgets*.', IPythonWarning)
try:
import IPython
except ImportError:
IPython = None
warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning)
try:
import ipyleaflet # noqa: F401
except ImportError:
ipyleaflet = None
warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning)
| Fix unused import flag by codacy | Fix unused import flag by codacy
| Python | apache-2.0 | bird-house/birdy | ---
+++
@@ -28,7 +28,7 @@
warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning)
try:
- import ipyleaflet
+ import ipyleaflet # noqa: F401
except ImportError:
ipyleaflet = None
warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning) |
d7d2361bb27c8649e38b61b65ba193e5ea716ed5 | blog/posts/helpers.py | blog/posts/helpers.py | from models import Post
def get_post_url(post):
post_year = str(post.publication_date.year)
post_month = '%02d' % post.publication_date.month
post_title = post.title
url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/'
return url
def post_as_components(post_text):
''' This function returns the components of a blog post for use with other
functions. Given a Markdown formatted post, it returns a three-tuple. The
first element is the blog title (not markdowned), the second is the first
paragraph (in Markdown format) and the third is the entire post body (in
Markdown format).
'''
post_content = post_text.split('\n\n')
title = post_content[0].strip('# ')
first_para = post_content[1]
body = u'\n\n'.join(post_content[1:])
return (title, first_para, body)
| from models import Post
from django.core.urlresolvers import reverse
def get_post_url(post):
post_year = str(post.publication_date.year)
post_month = '%02d' % post.publication_date.month
post_title = post.title
#url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/'
url = reverse('blog_post', kwargs={'post_year': post_year,
'post_month': post_month,
'post_title': post_title})
return url
def post_as_components(post_text):
''' This function returns the components of a blog post for use with other
functions. Given a Markdown formatted post, it returns a three-tuple. The
first element is the blog title (not markdowned), the second is the first
paragraph (in Markdown format) and the third is the entire post body (in
Markdown format).
'''
post_content = post_text.split('\n\n')
title = post_content[0].strip('# ')
first_para = post_content[1]
body = u'\n\n'.join(post_content[1:])
return (title, first_para, body)
| Use named urls for get_post_url(). | Use named urls for get_post_url().
The helper should not assume knowledge of the post url structure.
| Python | mit | Lukasa/minimalog | ---
+++
@@ -1,10 +1,14 @@
from models import Post
+from django.core.urlresolvers import reverse
def get_post_url(post):
post_year = str(post.publication_date.year)
post_month = '%02d' % post.publication_date.month
post_title = post.title
- url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/'
+ #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/'
+ url = reverse('blog_post', kwargs={'post_year': post_year,
+ 'post_month': post_month,
+ 'post_title': post_title})
return url
def post_as_components(post_text): |
77a6bb72318e9b02cbb1179cbbbacd3dd0bad55f | bookstore/__init__.py | bookstore/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Bookstore
Stores IPython notebooks automagically onto OpenStack clouds through Swift.
'''
__title__ = 'bookstore'
__version__ = '1.0.0'
__build__ = 0x010000
__author__ = 'Kyle Kelley'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Kyle Kelley'
from . import swift
from . import cloudfiles
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Bookstore
Stores IPython notebooks automagically onto OpenStack clouds through Swift.
'''
__title__ = 'bookstore'
__version__ = '1.0.0'
__build__ = 0x010000
__author__ = 'Kyle Kelley'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Kyle Kelley'
#from . import swift
#from . import cloudfiles
from . import filenotebookmanager
| Add unit test for bookstore | Add unit test for bookstore
| Python | apache-2.0 | wusung/ipython-notebook-store | ---
+++
@@ -13,5 +13,6 @@
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Kyle Kelley'
-from . import swift
-from . import cloudfiles
+#from . import swift
+#from . import cloudfiles
+from . import filenotebookmanager |
14b9ed3052054cf983fe6b7b1903faca3f1a0a13 | couchdb/tests/testutil.py | couchdb/tests/testutil.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
name = 'couchdb-python/' + uuid.uuid4().hex
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
| # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
# Find an unused database name
while True:
name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
if name not in self.temp_dbs:
break
print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
| Use a random number instead of uuid for temp database name. | Use a random number instead of uuid for temp database name.
| Python | bsd-3-clause | djc/couchdb-python,djc/couchdb-python,infinit/couchdb-python,Roger/couchdb-python | ---
+++
@@ -6,7 +6,8 @@
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
-import uuid
+import random
+import sys
from couchdb import client
class TempDatabaseMixin(object):
@@ -25,7 +26,12 @@
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
- name = 'couchdb-python/' + uuid.uuid4().hex
+ # Find an unused database name
+ while True:
+ name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
+ if name not in self.temp_dbs:
+ break
+ print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db |
ee5cf0b47d50904061daf62c33741d50b848f02b | feature_extraction.py | feature_extraction.py | from PIL import Image
import glob
def _get_rectangle_masks():
TRAIN_MASKS = './data/train/*_mask.tif'
rectangle_masks = []
for file_name in glob.glob(TRAIN_MASKS):
image = Image.open(file_name)
rectangle_mask = ((0,0), (0,0))
mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0]
if mask_coord:
mask_xs, mask_ys = zip(*mask_coord)
rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))
rectangle_masks.append(rectangle_mask)
return rectangle_masks
def run():
print _get_rectangle_masks()
if __name__ == '__main__':
run()
| from PIL import Image
import glob
def _get_masks():
TRAIN_MASKS = './data/train/*_mask.tif'
return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)]
def _get_rectangle_masks():
rectangle_masks = []
for image in _get_masks():
rectangle_mask = ((0,0), (0,0))
mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0]
if mask_coord:
mask_xs, mask_ys = zip(*mask_coord)
rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))
rectangle_masks.append(rectangle_mask)
return rectangle_masks
def run():
print _get_rectangle_masks()
if __name__ == '__main__':
run()
| Move mask gathering to it's own function | Move mask gathering to it's own function
| Python | mit | Brok-Bucholtz/Ultrasound-Nerve-Segmentation | ---
+++
@@ -2,11 +2,14 @@
import glob
+def _get_masks():
+ TRAIN_MASKS = './data/train/*_mask.tif'
+ return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)]
+
+
def _get_rectangle_masks():
- TRAIN_MASKS = './data/train/*_mask.tif'
rectangle_masks = []
- for file_name in glob.glob(TRAIN_MASKS):
- image = Image.open(file_name)
+ for image in _get_masks():
rectangle_mask = ((0,0), (0,0))
mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0]
|
d28cb58c91e1282569eaa4f3f4d99f50d6e23ceb | clippings/__init__.py | clippings/__init__.py | """Python module to manipulate Kindle clippings files."""
__version__ = '0.3.0'
| """Python module to manipulate Kindle clippings files."""
__version__ = '0.4.0'
| Set correct version in package | Set correct version in package
| Python | mit | samueldg/clippings | ---
+++
@@ -1,3 +1,3 @@
"""Python module to manipulate Kindle clippings files."""
-__version__ = '0.3.0'
+__version__ = '0.4.0' |
a1b4afc062b246dc347526202ef00a43992afa28 | code/kmeans.py | code/kmeans.py | #returns the distance between two data points
def distance(X, Y):
d = 0
for row in range(len(X)):
for col in range(len(X[row]):
if X[row][col] != Y[row][col]:
d += 1
return d
#partitions the data into the sets closest to each centroid
def fit(data, centroids):
pass
#returns k centroids which partition the data optimally into k clusters
def cluster(data, k):
pass
#allows the user to assign character names to each centroid given
def label(centroids):
pass
| from random import randint
from copy import deepcopy
from parse import parse
#In this file, I am assuming that the 6 metadata entries at the front of each
# raw data point hae been stripped off during initial parsing.
#returns the distance between two data points
def distance(X, Y):
assert(len(X) == len(Y))
d = 0
for pixel in range(len(X)):
if X[pixel] != Y[pixel]:
d += 1
return d
#Intelligently find some starting centroids, instead of choosing k random points.
# Choose one random point to start with, then find the point with largest
# sum of distances from all other centroids selected so far and make it a centroid
# until k have been chosen.
def find_initial_centroids(data, k):
assert(len(data) >= k)
data = deepcopy(data)
centroids = []
i = randint(0, len(data - 1))
if k > 0:
centroids.append(data[i])
while (len(centroids) < k):
new_i = None
max_distance = None
for i in range(len(data)):
total_distance = 0
for c in centroids:
total_distance += distance(data[i], c)
if (new_i == None) or (total_distance > max_distance):
new_i = i
max_distance = total_distance
centroids.append(data.pop(i))
return centroids
#Finds the representative centroid of a subset of data, based on the most
# common pixel in each position
def find_centroid(data):
assert(len(data) > 0)
centroid = [0]*len(data[0])
for i in range(len(centroid)):
sum = 0
for point in data:
sum += point[i] #Assuming pixel values are either 1 or 0
if (sum / len(data)) >= .5: #If a majority of pixels have value 1
centroid[i] = 1
return centroid
#partitions the data into the sets closest to each centroid
def fit(data, centroids):
pass
#returns k centroids which partition the data optimally into k clusters
def cluster(data, k):
centroids = find_initial_centroids(data, k)
| Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently | Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
| Python | mit | mkaplan218/clusterverify | ---
+++
@@ -1,20 +1,74 @@
+from random import randint
+from copy import deepcopy
+
+from parse import parse
+
+#In this file, I am assuming that the 6 metadata entries at the front of each
+# raw data point hae been stripped off during initial parsing.
+
#returns the distance between two data points
+
def distance(X, Y):
+ assert(len(X) == len(Y))
+
d = 0
- for row in range(len(X)):
- for col in range(len(X[row]):
- if X[row][col] != Y[row][col]:
- d += 1
+ for pixel in range(len(X)):
+ if X[pixel] != Y[pixel]:
+ d += 1
return d
+#Intelligently find some starting centroids, instead of choosing k random points.
+# Choose one random point to start with, then find the point with largest
+# sum of distances from all other centroids selected so far and make it a centroid
+# until k have been chosen.
+
+def find_initial_centroids(data, k):
+ assert(len(data) >= k)
+ data = deepcopy(data)
+
+ centroids = []
+ i = randint(0, len(data - 1))
+
+ if k > 0:
+ centroids.append(data[i])
+
+ while (len(centroids) < k):
+ new_i = None
+ max_distance = None
+ for i in range(len(data)):
+ total_distance = 0
+ for c in centroids:
+ total_distance += distance(data[i], c)
+ if (new_i == None) or (total_distance > max_distance):
+ new_i = i
+ max_distance = total_distance
+ centroids.append(data.pop(i))
+
+ return centroids
+
+#Finds the representative centroid of a subset of data, based on the most
+# common pixel in each position
+
+def find_centroid(data):
+ assert(len(data) > 0)
+
+ centroid = [0]*len(data[0])
+ for i in range(len(centroid)):
+ sum = 0
+ for point in data:
+ sum += point[i] #Assuming pixel values are either 1 or 0
+ if (sum / len(data)) >= .5: #If a majority of pixels have value 1
+ centroid[i] = 1
+
+ return centroid
+
#partitions the data into the sets closest to each centroid
+
def fit(data, centroids):
pass
#returns k centroids which partition the data optimally into k clusters
+
def cluster(data, k):
- pass
-
-#allows the user to assign character names to each centroid given
-def label(centroids):
- pass
+ centroids = find_initial_centroids(data, k)
+ |
1c26d3e2237d731024fe5c9494c2da7e0867653d | inonemonth/challenges/serializers.py | inonemonth/challenges/serializers.py | from rest_framework import serializers
from .models import Challenge, Role
from core.serializers import UserSerializer
#from comments.serializers import HeadCommentSerializer, TailCommentSerializer
class ChallengeSerializer(serializers.ModelSerializer):
#role_set = serializers.HyperlinkedRelatedField(view_name="role_api_retrieve", many=True)
#role_set = serializers.RelatedField(many=True)
#role_set = serializers.SlugRelatedField(many=True, slug_field="type")
#role_set = RoleSerializer(many=True)
#get_clencher = serializers.Field(source="get_clencher")
in_challenge_period = serializers.Field(source="in_challenge_period")
class Meta:
model = Challenge
fields = ("id", "title", "body", "repo_name", "creation_datetime",
"headcomment_set", "tailcomment_set",
"in_challenge_period")
class RoleSerializer(serializers.ModelSerializer):
#user = UserSerializer()
#challenge = serializers.RelatedField()
challenge = ChallengeSerializer()
#comment_set = CommentSerializer()
can_make_head_comment = serializers.Field(source="can_make_head_comment")
is_juror = serializers.Field(source="is_juror")
class Meta:
model = Role
fields = ("id", "user", "type", "challenge",
"vote", "can_make_head_comment",
"headcomment_set", "tailcomment_set", "is_juror")
#"comment_set")
depth = 2
| from rest_framework import serializers
from .models import Challenge, Role
from core.serializers import UserSerializer
#from comments.serializers import HeadCommentSerializer, TailCommentSerializer
class ChallengeSerializer(serializers.ModelSerializer):
#role_set = serializers.HyperlinkedRelatedField(view_name="role_api_retrieve", many=True)
#role_set = serializers.RelatedField(many=True)
#role_set = serializers.SlugRelatedField(many=True, slug_field="type")
#role_set = RoleSerializer(many=True)
#get_clencher = serializers.Field(source="get_clencher")
in_challenge_period = serializers.Field(source="in_challenge_period")
class Meta:
model = Challenge
fields = ("id", "title", "body", "repo", "creation_datetime",
"headcomment_set", "tailcomment_set",
"in_challenge_period")
class RoleSerializer(serializers.ModelSerializer):
#user = UserSerializer()
#challenge = serializers.RelatedField()
challenge = ChallengeSerializer()
#comment_set = CommentSerializer()
can_make_head_comment = serializers.Field(source="can_make_head_comment")
is_juror = serializers.Field(source="is_juror")
class Meta:
model = Role
fields = ("id", "user", "type", "challenge",
"vote", "can_make_head_comment",
"headcomment_set", "tailcomment_set", "is_juror")
#"comment_set")
depth = 2
| Correct repo field name in serializer | Correct repo field name in serializer
| Python | mit | robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth | ---
+++
@@ -17,7 +17,7 @@
class Meta:
model = Challenge
- fields = ("id", "title", "body", "repo_name", "creation_datetime",
+ fields = ("id", "title", "body", "repo", "creation_datetime",
"headcomment_set", "tailcomment_set",
"in_challenge_period")
|
cd6429cd177e550d047408cc212b64648e0cbe6c | calc_cov.py | calc_cov.py | import mne
import sys
from mne import compute_covariance
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from my_settings import *
reject = dict(grad=4000e-13, # T / m (gradiometers)
mag=4e-12, # T (magnetometers)
eeg=180e-6 #
)
subject = sys.argv[1]
epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject)
epochs.drop_bad_epochs(reject)
fig = epochs.plot_drop_log(subject=subject, show=False)
fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject)
# Make noise cov
cov = compute_covariance(epochs, tmin=None, tmax=0,
method="shrunk")
mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov)
| import mne
import sys
from mne import compute_covariance
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from my_settings import *
subject = sys.argv[1]
epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject)
epochs.drop_bad_epochs(reject=reject_params)
fig = epochs.plot_drop_log(subject=subject, show=False)
fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject)
# Make noise cov
cov = compute_covariance(epochs, tmin=None, tmax=-0.2,
method="shrunk")
mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov)
| Clean up and change cov time | Clean up and change cov time
| Python | bsd-3-clause | MadsJensen/CAA,MadsJensen/CAA | ---
+++
@@ -9,22 +9,15 @@
from my_settings import *
-reject = dict(grad=4000e-13, # T / m (gradiometers)
- mag=4e-12, # T (magnetometers)
- eeg=180e-6 #
- )
-
-
subject = sys.argv[1]
epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject)
-epochs.drop_bad_epochs(reject)
+epochs.drop_bad_epochs(reject=reject_params)
fig = epochs.plot_drop_log(subject=subject, show=False)
fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject)
# Make noise cov
-cov = compute_covariance(epochs, tmin=None, tmax=0,
+cov = compute_covariance(epochs, tmin=None, tmax=-0.2,
method="shrunk")
mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov)
- |
666952b40005bf1695b5a5473c05d2e4b066f240 | reporter/reporter/reports/briccs/data_quality/blank_study_id.py | reporter/reporter/reports/briccs/data_quality/blank_study_id.py | #!/usr/bin/env python3
from reporter.reports import Report, Schedule
from reporter import get_case_link, RECIPIENT_BRICCS_ADMIN
class BriccsCivcrmBlankStudyId(Report):
def __init__(self):
super().__init__(
introduction=("The following participants have a blank "
"study ID in the CiviCRM Study Enrolment"),
recipients=[RECIPIENT_BRICCS_ADMIN],
schedule=Schedule.daily,
sql='''
SELECT civicrm_case_id, civicrm_contact_id
FROM i2b2_app03_b1_Data.dbo.LOAD_Civicrm
WHERE blank_study_id = 1
AND (
is_recruited = 1
OR is_withdrawn = 1
OR is_duplicate = 1
)
'''
)
def get_report_line(self, row):
return '- {}\r\n\r\n'.format(
get_case_link(
'Click to View',
row["civicrm_case_id"],
row["civicrm_contact_id"]))
| #!/usr/bin/env python3
from reporter.reports import Report, Schedule
from reporter import get_case_link, RECIPIENT_BRICCS_DQ
class BriccsCivcrmBlankStudyId(Report):
def __init__(self):
super().__init__(
introduction=("The following participants have a blank "
"study ID in the CiviCRM Study Enrolment"),
recipients=[RECIPIENT_BRICCS_DQ],
schedule=Schedule.daily,
sql='''
SELECT civicrm_case_id, civicrm_contact_id
FROM i2b2_app03_b1_Data.dbo.LOAD_Civicrm
WHERE blank_study_id = 1
AND (
is_recruited = 1
OR is_withdrawn = 1
OR is_duplicate = 1
)
'''
)
def get_report_line(self, row):
return '- {}\r\n\r\n'.format(
get_case_link(
'Click to View',
row["civicrm_case_id"],
row["civicrm_contact_id"]))
| Send to DQ not admin | Send to DQ not admin
| Python | mit | LCBRU/reporter,LCBRU/reporter | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
from reporter.reports import Report, Schedule
-from reporter import get_case_link, RECIPIENT_BRICCS_ADMIN
+from reporter import get_case_link, RECIPIENT_BRICCS_DQ
class BriccsCivcrmBlankStudyId(Report):
@@ -9,7 +9,7 @@
super().__init__(
introduction=("The following participants have a blank "
"study ID in the CiviCRM Study Enrolment"),
- recipients=[RECIPIENT_BRICCS_ADMIN],
+ recipients=[RECIPIENT_BRICCS_DQ],
schedule=Schedule.daily,
sql='''
|
bfd34a7aaf903c823d41068173c09bc5b1a251bc | test/sasdataloader/test/utest_sesans.py | test/sasdataloader/test/utest_sesans.py | """
Unit tests for the SESANS .ses reader
"""
import unittest
from sas.sascalc.dataloader.loader import Loader
import os.path
class sesans_reader(unittest.TestCase):
def setUp(self):
self.loader = Loader()
def test_sesans_load(self):
"""
Test .SES file loading
"""
f =self.loader.load("sphere3micron.ses")
# self.assertEqual(f, 5)
self.assertEqual(len(f.x), 40)
self.assertEqual(f.x[0], 391.56)
self.assertEqual(f.x[-1], 46099)
self.assertEqual(f.y[-1], -0.19956)
self.assertEqual(f.x_unit, "A")
self.assertEqual(f.y_unit, "A-2 cm-1")
self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O")
self.assertEqual(f.sample.thickness, 0.2)
self.assertEqual(f.sample.zacceptance, (0.0168, "radians"))
if __name__ == "__main__":
unittest.main()
| """
Unit tests for the SESANS .ses reader
"""
import unittest
from sas.sascalc.dataloader.loader import Loader
import os.path
class sesans_reader(unittest.TestCase):
def setUp(self):
self.loader = Loader()
def test_sesans_load(self):
"""
Test .SES file loading
"""
f =self.loader.load("sphere3micron.ses")
# self.assertEqual(f, 5)
self.assertEqual(len(f.x), 40)
self.assertEqual(f.x[0], 391.56)
self.assertEqual(f.x[-1], 46099)
self.assertEqual(f.y[-1], -0.19956)
self.assertEqual(f.x_unit, "A")
self.assertEqual(f.y_unit, "A-2 cm-1")
self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O")
self.assertEqual(f.sample.thickness, 0.2)
self.assertEqual(f.sample.zacceptance, (0.0168, "radians"))
self.assertEqual(f.isSesans, True)
if __name__ == "__main__":
unittest.main()
| Test that .SES files are tagged as Sesans | Test that .SES files are tagged as Sesans
| Python | bsd-3-clause | lewisodriscoll/sasview,lewisodriscoll/sasview,SasView/sasview,lewisodriscoll/sasview,SasView/sasview,SasView/sasview,SasView/sasview,lewisodriscoll/sasview,SasView/sasview,SasView/sasview,lewisodriscoll/sasview | ---
+++
@@ -27,6 +27,7 @@
self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O")
self.assertEqual(f.sample.thickness, 0.2)
self.assertEqual(f.sample.zacceptance, (0.0168, "radians"))
+ self.assertEqual(f.isSesans, True)
if __name__ == "__main__":
unittest.main() |
8581fae9a70571ed19a97078b7de87eeae8b7033 | data/models.py | data/models.py | from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=200)
exact_name = models.CharField(max_length=600, null=True, blank=True)
options = models.CharField(max_length=100)
occupied = models.FloatField()
virtual = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
| Add model to store log data | Add model to store log data
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -0,0 +1,14 @@
+from django.db import models
+
+
+class DataPoint(models.Model):
+ name = models.CharField(max_length=200)
+ exact_name = models.CharField(max_length=600, null=True, blank=True)
+
+ options = models.CharField(max_length=100)
+ occupied = models.FloatField()
+ virtual = models.FloatField()
+ homo_orbital = models.IntegerField()
+ energy = models.FloatField()
+ dipole = models.FloatField()
+ band_gap = models.FloatField(null=True, blank=True) |
|
d0aba6489a96003c9a746bd38818cffa717d1469 | akatsuki/bib2html.py | akatsuki/bib2html.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from akatsuki.exporter import export_html
from akatsuki.parser import load_bibtex_file
from akatsuki.utils import sort_by_date
def main(bibtex_file, html_file):
"""Load BibTeX file and export to HTML file"""
entries = load_bibtex_file(bibtex_file)
entries = sort_by_date(entries, reverse=True)
export_html(html_file, entries)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from akatsuki.exporter import export_html
from akatsuki.parser import load_bibtex_file
from akatsuki.utils import pmid_to_url, sort_by_date
def main(bibtex_file, html_file):
"""Load BibTeX file and export to HTML file"""
entries = load_bibtex_file(bibtex_file)
entries = pmid_to_url(entries)
entries = sort_by_date(entries, reverse=True)
export_html(html_file, entries)
| Add pmid to url convertion | Add pmid to url convertion
| Python | mit | 403JFW/akatsuki | ---
+++
@@ -5,11 +5,12 @@
from akatsuki.exporter import export_html
from akatsuki.parser import load_bibtex_file
-from akatsuki.utils import sort_by_date
+from akatsuki.utils import pmid_to_url, sort_by_date
def main(bibtex_file, html_file):
"""Load BibTeX file and export to HTML file"""
entries = load_bibtex_file(bibtex_file)
+ entries = pmid_to_url(entries)
entries = sort_by_date(entries, reverse=True)
export_html(html_file, entries) |
ea48d59c4e4073de940b394d2bc99e411cfbd3fb | example_of_usage.py | example_of_usage.py | # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: AGPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprint import pprint
from html_table_parser import HTMLTableParser
def url_get_contents(url):
""" Opens a website and read its binary contents (HTTP Response Body) """
req = urllib.request.Request(url=url)
f = urllib.request.urlopen(req)
return f.read()
def main():
url = 'http://www.twitter.com'
xhtml = url_get_contents(url).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
pprint(p.tables)
if __name__ == '__main__':
main()
| # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: AGPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprint import pprint
from html_table_parser import HTMLTableParser
def url_get_contents(url):
""" Opens a website and read its binary contents (HTTP Response Body) """
req = urllib.request.Request(url=url)
f = urllib.request.urlopen(req)
return f.read()
def main():
url = 'https://w3schools.com/html/html_tables.asp'
xhtml = url_get_contents(url).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
# Get all tables
pprint(p.tables)
# Get tables with id attribute
pprint(p.named_tables)
if __name__ == '__main__':
main()
| Add named tables to the examples | Add named tables to the examples
| Python | agpl-3.0 | schmijos/html-table-parser-python3,schmijos/html-table-parser-python3 | ---
+++
@@ -19,12 +19,17 @@
def main():
- url = 'http://www.twitter.com'
+ url = 'https://w3schools.com/html/html_tables.asp'
xhtml = url_get_contents(url).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
+
+ # Get all tables
pprint(p.tables)
+
+ # Get tables with id attribute
+ pprint(p.named_tables)
if __name__ == '__main__': |
246d2f47791f26ffe55bc9d09c59875b6045a847 | data/models.py | data/models.py | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_all_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_all_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP | Add created field to DataPoint model | Add created field to DataPoint model
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -8,6 +8,7 @@
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
+ created = models.DateTimeField(auto_now_add=True)
options = models.CharField(max_length=100)
homo = models.FloatField() |
80d052df13653943bc2a2369cfbea4cf0e77ce12 | django_tables/__init__.py | django_tables/__init__.py | __version__ = (0, 3, 'dev')
from memory import *
from models import *
from columns import *
from options import *
| __version__ = (0, 2, 1)
from memory import *
from models import *
from columns import *
from options import *
| Prepare to fix a new version. | Prepare to fix a new version.
| Python | bsd-2-clause | PolicyStat/django-tables,miracle2k/django-tables,isolationism/mongoengine-tables | ---
+++
@@ -1,4 +1,4 @@
-__version__ = (0, 3, 'dev')
+__version__ = (0, 2, 1)
from memory import * |
1082db1f71ed3e84fd4068d3834ce72e744cdcca | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.github_project_workdir('krb5/krb5', 'src'),
builder.autoconf_install('krb5/krb5'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
| #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
| Cut fbcode_builder dep for thrift on krb5 | Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and no longer has any build-time dependency on `krb5`. Clean this up.
Reviewed By: stevegury, vitaut
Differential Revision: D14814205
fbshipit-source-id: dca469d22098e34573674194facaaac6c4c6aa32
| Python | apache-2.0 | facebook/wangle,facebook/wangle,facebook/wangle | ---
+++
@@ -21,15 +21,12 @@
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
- builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
- builder.github_project_workdir('krb5/krb5', 'src'),
- builder.autoconf_install('krb5/krb5'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
} |
020e48affc34162676193ab97dad7f8ffbdaaaa6 | jupyter_kernel/magics/shell_magic.py | jupyter_kernel/magics/shell_magic.py | # Copyright (c) Calico Development Team.
# Distributed under the terms of the Modified BSD License.
# http://calicoproject.org/
from jupyter_kernel import Magic
import subprocess
class ShellMagic(Magic):
def line_shell(self, *args):
"""%shell COMMAND - run the line as a shell command"""
command = " ".join(args)
try:
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retval, error = process.communicate()
if error:
self.kernel.Error(error)
except Exception as e:
self.kernel.Error(e.message)
retval = None
if retval:
self.kernel.Print(retval)
def cell_shell(self):
"""%%shell - run the contents of the cell as shell commands"""
self.line_shell(self.code)
self.evaluate = False
def register_magics(kernel):
kernel.register_magics(ShellMagic)
| # Copyright (c) Calico Development Team.
# Distributed under the terms of the Modified BSD License.
# http://calicoproject.org/
from jupyter_kernel import Magic
import subprocess
class ShellMagic(Magic):
def line_shell(self, *args):
"""%shell COMMAND - run the line as a shell command"""
command = " ".join(args)
try:
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retval, error = process.communicate()
if error:
self.kernel.Error(error)
except Exception as e:
self.kernel.Error(e.message)
retval = None
if retval:
retval = retval.decode('utf-8')
self.kernel.Print(retval)
def cell_shell(self):
"""%%shell - run the contents of the cell as shell commands"""
self.line_shell(self.code)
self.evaluate = False
def register_magics(kernel):
kernel.register_magics(ShellMagic)
| Fix bytes problem on python 3. | Fix bytes problem on python 3.
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -20,6 +20,7 @@
self.kernel.Error(e.message)
retval = None
if retval:
+ retval = retval.decode('utf-8')
self.kernel.Print(retval)
def cell_shell(self): |
15f482fbb7b1b98b48545f6e5ab3986859c38e55 | watchman/main.py | watchman/main.py | from __future__ import print_function
import sys
import os
from sh import cd, hg
def _get_subdirectories(current_dir):
return [directory for directory in os.listdir(current_dir)
if os.path.isdir(os.path.join(current_dir, directory))
and directory[0] != '.']
def check():
current_working_directory = os.getcwd()
child_dirs = _get_subdirectories(current_working_directory)
for child in child_dirs:
try:
change_dir = '%s/%s' % (current_working_directory, child)
cd(change_dir); current_branch = hg('branch')
output = '%-25s is on branch: %s' % (child, current_branch)
print(output, end=''); cd('..') # print and step back one dir
except Exception:
continue
def main():
arguments = sys.argv
if 'check' == arguments[1]:
check()
else:
print("type watchman help for, you know, help.")
if __name__ == '__main__':
main()
| from __future__ import print_function
import sys
import os
from sh import cd, hg
def _get_subdirectories(current_dir):
return [directory for directory in os.listdir(current_dir)
if os.path.isdir(os.path.join(current_dir, directory))
and directory[0] != '.']
def check():
current_working_directory = os.getcwd()
child_dirs = _get_subdirectories(current_working_directory)
for child in child_dirs:
try:
current_branch = hg('branch', '-R', './%s' % child)
output = '%-25s is on branch: %s' % (child, current_branch)
print(output, end='')
except Exception as e:
continue
def main():
arguments = sys.argv
if 'check' == arguments[1]:
check()
else:
print("type watchman help for, you know, help.")
if __name__ == '__main__':
main()
| Remove change dir commands and now it sends directly. | Remove change dir commands and now it sends directly.
| Python | mit | alephmelo/watchman | ---
+++
@@ -15,13 +15,11 @@
child_dirs = _get_subdirectories(current_working_directory)
for child in child_dirs:
try:
- change_dir = '%s/%s' % (current_working_directory, child)
- cd(change_dir); current_branch = hg('branch')
+ current_branch = hg('branch', '-R', './%s' % child)
+ output = '%-25s is on branch: %s' % (child, current_branch)
+ print(output, end='')
- output = '%-25s is on branch: %s' % (child, current_branch)
-
- print(output, end=''); cd('..') # print and step back one dir
- except Exception:
+ except Exception as e:
continue
|
84942c895343d7803144b0a95feeabe481fe0e3d | behave/formatter/base.py | behave/formatter/base.py | class Formatter(object):
name = None
description = None
def __init__(self, stream, config):
self.stream = stream
self.config = config
def uri(self, uri):
pass
def feature(self, feature):
pass
def background(self, background):
pass
def scenario(self, scenario):
pass
def scenario_outline(self, outline):
pass
def examples(self, examples):
pass
def step(self, step):
pass
def match(self, match):
pass
def result(self, result):
pass
def eof(self):
pass
def close(self):
pass
| class Formatter(object):
name = None
description = None
def __init__(self, stream, config):
self.stream = stream
self.config = config
def uri(self, uri):
pass
def feature(self, feature):
pass
def background(self, background):
pass
def scenario(self, scenario):
pass
def scenario_outline(self, outline):
pass
def examples(self, examples):
pass
def step(self, step):
pass
def match(self, match):
pass
def result(self, result):
pass
def eof(self):
pass
def close(self):
pass
| Remove blank line at end of file. | Remove blank line at end of file.
| Python | bsd-2-clause | hugeinc/behave-parallel,metaperl/behave,KevinOrtman/behave,KevinOrtman/behave,connorsml/behave,Gimpneek/behave,charleswhchan/behave,charleswhchan/behave,vrutkovs/behave,mzcity123/behave,Gimpneek/behave,spacediver/behave,KevinMarkVI/behave-parallel,jenisys/behave,memee/behave,allanlewis/behave,vrutkovs/behave,mzcity123/behave,tokunbo/behave-parallel,metaperl/behave,spacediver/behave,Gimpneek/behave,Abdoctor/behave,jenisys/behave,joshal/behave,kymbert/behave,benthomasson/behave,joshal/behave,kymbert/behave,connorsml/behave,allanlewis/behave,benthomasson/behave,tokunbo/behave-parallel,Abdoctor/behave | ---
+++
@@ -38,4 +38,3 @@
def close(self):
pass
- |
88647bd762da9619c066c9bd79e48cb234247707 | geotagging/views.py | geotagging/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
| from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
try:
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
except ObjectDoesNotExist:
geotag = None
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
| Fix a bug when you try to add a geo tag to an object that does not have already one | Fix a bug when you try to add a geo tag to an object that does not have already one | Python | bsd-3-clause | uclastudentmedia/django-geotagging,uclastudentmedia/django-geotagging,uclastudentmedia/django-geotagging | ---
+++
@@ -2,6 +2,7 @@
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
+from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
@@ -11,8 +12,11 @@
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
- geotag = Point.objects.get(content_type__pk=object_content_type.id,
+ try:
+ geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
+ except ObjectDoesNotExist:
+ geotag = None
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid(): |
ef11a6388dabd07afb3d11f7b097226e68fdf243 | project/estimation/models.py | project/estimation/models.py | from .. import db
class Question(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(240), unique=True, index=True)
answer = db.Column(db.Numeric) | from .. import db
class Question(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(240), unique=True, index=True)
answer = db.Column(db.Numeric)
class Estimate(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
lowerbound = db.Column(db.Numeric)
upperbound = db.Column(db.Numeric)
created_on = db.Column(db.DateTime, default=db.func.now()) | Add model to keep track of users' estimates. | Add model to keep track of users' estimates.
| Python | mit | rahimnathwani/measure-anything | ---
+++
@@ -1,6 +1,14 @@
from .. import db
class Question(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- text = db.Column(db.String(240), unique=True, index=True)
- answer = db.Column(db.Numeric)
+ id = db.Column(db.Integer, primary_key=True)
+ text = db.Column(db.String(240), unique=True, index=True)
+ answer = db.Column(db.Numeric)
+
+class Estimate(db.Model):
+ id = db.Column(db.Integer, primary_key=True)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
+ question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
+ lowerbound = db.Column(db.Numeric)
+ upperbound = db.Column(db.Numeric)
+ created_on = db.Column(db.DateTime, default=db.func.now()) |
224269d0794d1037213b429c0fcb7c5953129230 | aldryn_config.py | aldryn_config.py | # -*- coding: utf-8 -*-
from aldryn_client import forms
class Form(forms.BaseForm):
def to_settings(self, cleaned_data, settings_dict):
settings_dict['MIDDLEWARE_CLASSES'].append(
'country_segment.middleware.ResolveCountryCodeMiddleware')
return settings_dict
| # -*- coding: utf-8 -*-
from aldryn_client import forms
class Form(forms.BaseForm):
def to_settings(self, cleaned_data, settings_dict):
country_mw = 'country_segment.middleware.ResolveCountryCodeMiddleware'
if country_mw not in settings_dict['MIDDLEWARE_CLASSES']:
for position, mw in enumerate(settings_dict['MIDDLEWARE_CLASSES']):
#
# Its not a strict requirement that the
# ResolveCountryCodeMiddleware go after SessionMiddleware,
# but, it seems like a pretty nice place.
#
if mw == 'django.contrib.sessions.middleware.SessionMiddleware':
settings_dict['MIDDLEWARE_CLASSES'].insert(position + 1, country_mw)
break
else:
#
# B'okay, not sure how this CMS installation works, but...
# let's just put it at the top.
#
settings_dict['MIDDLEWARE_CLASSES'].insert(0, country_mw)
return settings_dict
| Put the middleware near the top (again). | Put the middleware near the top (again).
| Python | bsd-3-clause | aldryn/aldryn-country-segment | ---
+++
@@ -5,6 +5,23 @@
class Form(forms.BaseForm):
def to_settings(self, cleaned_data, settings_dict):
- settings_dict['MIDDLEWARE_CLASSES'].append(
- 'country_segment.middleware.ResolveCountryCodeMiddleware')
- return settings_dict
+
+ country_mw = 'country_segment.middleware.ResolveCountryCodeMiddleware'
+ if country_mw not in settings_dict['MIDDLEWARE_CLASSES']:
+ for position, mw in enumerate(settings_dict['MIDDLEWARE_CLASSES']):
+ #
+ # Its not a strict requirement that the
+ # ResolveCountryCodeMiddleware go after SessionMiddleware,
+ # but, it seems like a pretty nice place.
+ #
+ if mw == 'django.contrib.sessions.middleware.SessionMiddleware':
+ settings_dict['MIDDLEWARE_CLASSES'].insert(position + 1, country_mw)
+ break
+ else:
+ #
+ # B'okay, not sure how this CMS installation works, but...
+ # let's just put it at the top.
+ #
+ settings_dict['MIDDLEWARE_CLASSES'].insert(0, country_mw)
+
+ return settings_dict |
ed09054447b17a88b902dcff95dee89772867cf7 | dropbot/stomp_listener.py | dropbot/stomp_listener.py | import stomp
import urlparse
import json
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(object):
def __init__(self, bot):
self.bot = bot
self.conn = None
def on_error(self, headers, message):
pass
def on_message(self, headers, message):
kill = json.loads(message)
for attacker in kill['attackers']:
if int(attacker['corporationID']) in self.bot.kill_corps:
break
else:
if kill['victim']['corporationID'] not in self.bot.kill_corps:
return
print message
body, html = self.bot.call_command('kill', [], None, no_url=False, raw=kill)
text = 'New Kill: {}'.format(body)
for room in self.bot.rooms:
self.bot.send_message(room, text, mtype='groupchat')
def connect(self, url):
url = urlparse.urlparse(url)
self.conn = stomp.Connection([(url.hostname, url.port)])
self.conn.set_listener('', self)
self.conn.start()
self.conn.connect('guest', 'guest')
self.conn.subscribe(destination='/topic/kills', ack='auto', id=1) | import stomp
import urlparse
import json
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(object):
def __init__(self, bot):
self.bot = bot
self.conn = None
def on_error(self, headers, message):
pass
def on_message(self, headers, message):
kill = json.loads(message)
for attacker in kill['attackers']:
if int(attacker['corporationID']) in self.bot.kill_corps:
break
else:
if int(kill['victim']['corporationID']) not in self.bot.kill_corps:
return
print message
body, html = self.bot.call_command('kill', [], None, no_url=False, raw=kill)
text = 'New Kill: {}'.format(body)
for room in self.bot.rooms:
self.bot.send_message(room, text, mtype='groupchat')
def connect(self, url):
url = urlparse.urlparse(url)
self.conn = stomp.Connection([(url.hostname, url.port)])
self.conn.set_listener('', self)
self.conn.start()
self.conn.connect('guest', 'guest')
self.conn.subscribe(destination='/topic/kills', ack='auto', id=1) | Make sure we're checking ints to ints. | Make sure we're checking ints to ints.
| Python | mit | nikdoof/dropbot,nikdoof/dropbot | ---
+++
@@ -19,7 +19,7 @@
if int(attacker['corporationID']) in self.bot.kill_corps:
break
else:
- if kill['victim']['corporationID'] not in self.bot.kill_corps:
+ if int(kill['victim']['corporationID']) not in self.bot.kill_corps:
return
print message |
be7c5fc964ce3386df2bf246f12838e4ba2a2cb6 | saleor/core/utils/filters.py | saleor/core/utils/filters.py | from __future__ import unicode_literals
def get_sort_by_choices(filter):
return [(choice[0], choice[1].lower()) for choice in
filter.filters['sort_by'].field.choices[1::2]]
def get_now_sorted_by(filter, fields):
sort_by = filter.form.cleaned_data.get('sort_by')
if sort_by:
sort_by = fields[sort_by[0].strip('-')]
else:
sort_by = fields['name']
return sort_by
| from __future__ import unicode_literals
def get_sort_by_choices(filter):
return [(choice[0], choice[1].lower()) for choice in
filter.filters['sort_by'].field.choices[1::2]]
def get_now_sorted_by(filter, fields, default_sort='name'):
sort_by = filter.form.cleaned_data.get('sort_by')
if sort_by:
sort_by = fields[sort_by[0].strip('-')]
else:
sort_by = fields[default_sort]
return sort_by
| Add default_sort param to get_now_sorting_by | Add default_sort param to get_now_sorting_by
| Python | bsd-3-clause | UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,UITools/saleor | ---
+++
@@ -6,10 +6,10 @@
filter.filters['sort_by'].field.choices[1::2]]
-def get_now_sorted_by(filter, fields):
+def get_now_sorted_by(filter, fields, default_sort='name'):
sort_by = filter.form.cleaned_data.get('sort_by')
if sort_by:
sort_by = fields[sort_by[0].strip('-')]
else:
- sort_by = fields['name']
+ sort_by = fields[default_sort]
return sort_by |
8f834aebfa2d0f3cf392a6c2530c00699a27dafa | crowd_anki/anki/overrides/exporting.py | crowd_anki/anki/overrides/exporting.py | import os
import anki.exporting
import anki.hooks
import anki.utils
import aqt.exporting
import aqt.utils
from aqt import QFileDialog
from aqt.exporting import ExportDialog
from ...utils import constants
# aqt part:
def exporter_changed(self, exporter_id):
self.exporter = aqt.exporting.exporters()[exporter_id][1](self.col)
self.frm.includeMedia.setVisible(hasattr(self.exporter, "includeMedia"))
def get_save_file(parent, title, dir_description, key, ext, fname=None):
if ext == constants.ANKI_EXPORT_EXTENSION:
directory = str(QFileDialog.getExistingDirectory(caption="Select Export Directory",
directory=fname))
if directory:
return os.path.join(directory, str(anki.utils.intTime()))
return None
return aqt.utils.getSaveFile_old(parent, title, dir_description, key, ext, fname)
ExportDialog.exporterChanged = anki.hooks.wrap(ExportDialog.exporterChanged, exporter_changed)
aqt.utils.getSaveFile_old = aqt.utils.getSaveFile
aqt.exporting.getSaveFile = get_save_file # Overriding instance imported with from style import
aqt.utils.getSaveFile = get_save_file
| import os
import anki.exporting
import anki.hooks
import anki.utils
import aqt.exporting
import aqt.utils
from aqt import QFileDialog
from aqt.exporting import ExportDialog
from ...utils import constants
# aqt part:
def exporter_changed(self, exporter_id):
self.exporter = aqt.exporting.exporters(self.col)[exporter_id][1](self.col)
self.frm.includeMedia.setVisible(hasattr(self.exporter, "includeMedia"))
def get_save_file(parent, title, dir_description, key, ext, fname=None):
if ext == constants.ANKI_EXPORT_EXTENSION:
directory = str(QFileDialog.getExistingDirectory(caption="Select Export Directory",
directory=fname))
if directory:
return os.path.join(directory, str(anki.utils.intTime()))
return None
return aqt.utils.getSaveFile_old(parent, title, dir_description, key, ext, fname)
ExportDialog.exporterChanged = anki.hooks.wrap(ExportDialog.exporterChanged, exporter_changed)
aqt.utils.getSaveFile_old = aqt.utils.getSaveFile
aqt.exporting.getSaveFile = get_save_file # Overriding instance imported with from style import
aqt.utils.getSaveFile = get_save_file
| Update exporter to work with Anki ≥ 2.1.36 | Update exporter to work with Anki ≥ 2.1.36
`exporters` now takes an argument.
See e3b4802f47395b9c1a75ff89505410e91f34477e
Introduced after 2.1.35 but before 2.1.36. (Testing explicitly shows
that this change is needed for 2.1.36 and 2.1.37, but breaks 2.1.35.)
Fix #113.
| Python | mit | Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki | ---
+++
@@ -14,7 +14,7 @@
def exporter_changed(self, exporter_id):
- self.exporter = aqt.exporting.exporters()[exporter_id][1](self.col)
+ self.exporter = aqt.exporting.exporters(self.col)[exporter_id][1](self.col)
self.frm.includeMedia.setVisible(hasattr(self.exporter, "includeMedia"))
|
2ad47f6ce00246cbf54639438d9279b8a7fa9b29 | python/tests/t_envoy_logs.py | python/tests/t_envoy_logs.py | import pytest, re
from kat.utils import ShellCommand
from abstract_tests import AmbassadorTest, ServiceType, HTTP
access_log_entry_regex = re.compile('^ACCESS \\[.*?\\] \\\"GET \\/ambassador')
class EnvoyLogPathTest(AmbassadorTest):
target: ServiceType
log_path: str
def init(self):
self.target = HTTP()
self.log_path = '/tmp/ambassador/ambassador.log'
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v1
kind: Module
name: ambassador
ambassador_id: {self.ambassador_id}
config:
envoy_log_path: {self.log_path}
""")
def check(self):
cmd = ShellCommand("kubectl", "exec", self.path.k8s, "cat", self.log_path)
if not cmd.check("check envoy access log"):
pytest.exit("envoy access log does not exist")
for line in cmd.stdout.splitlines():
assert access_log_entry_regex.match(line)
| import pytest, re
from kat.utils import ShellCommand
from abstract_tests import AmbassadorTest, ServiceType, HTTP
access_log_entry_regex = re.compile('^MY_REQUEST 200 .*')
class EnvoyLogTest(AmbassadorTest):
target: ServiceType
log_path: str
def init(self):
self.target = HTTP()
self.log_path = '/tmp/ambassador/ambassador.log'
self.log_format = 'MY_REQUEST %RESPONSE_CODE% \"%REQ(:AUTHORITY)%\" \"%REQ(USER-AGENT)%\" \"%REQ(X-REQUEST-ID)%\" \"%UPSTREAM_HOST%\"'
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v1
kind: Module
name: ambassador
ambassador_id: {self.ambassador_id}
config:
envoy_log_path: {self.log_path}
envoy_log_format: {self.log_format}
""")
def check(self):
cmd = ShellCommand("kubectl", "exec", self.path.k8s, "cat", self.log_path)
if not cmd.check("check envoy access log"):
pytest.exit("envoy access log does not exist")
for line in cmd.stdout.splitlines():
assert access_log_entry_regex.match(line), f"{line} does not match {access_log_entry_regex}"
| Test for Envoy logs format | Test for Envoy logs format
Signed-off-by: Alvaro Saurin <[email protected]>
| Python | apache-2.0 | datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador | ---
+++
@@ -3,16 +3,17 @@
from kat.utils import ShellCommand
from abstract_tests import AmbassadorTest, ServiceType, HTTP
-access_log_entry_regex = re.compile('^ACCESS \\[.*?\\] \\\"GET \\/ambassador')
+access_log_entry_regex = re.compile('^MY_REQUEST 200 .*')
-class EnvoyLogPathTest(AmbassadorTest):
+class EnvoyLogTest(AmbassadorTest):
target: ServiceType
log_path: str
def init(self):
self.target = HTTP()
self.log_path = '/tmp/ambassador/ambassador.log'
+ self.log_format = 'MY_REQUEST %RESPONSE_CODE% \"%REQ(:AUTHORITY)%\" \"%REQ(USER-AGENT)%\" \"%REQ(X-REQUEST-ID)%\" \"%UPSTREAM_HOST%\"'
def config(self):
yield self, self.format("""
@@ -23,6 +24,7 @@
ambassador_id: {self.ambassador_id}
config:
envoy_log_path: {self.log_path}
+ envoy_log_format: {self.log_format}
""")
def check(self):
@@ -31,4 +33,4 @@
pytest.exit("envoy access log does not exist")
for line in cmd.stdout.splitlines():
- assert access_log_entry_regex.match(line)
+ assert access_log_entry_regex.match(line), f"{line} does not match {access_log_entry_regex}" |
7adfe4822bf75d1df2dc2a566b3b26c9fd494431 | rest_framework_jwt/compat.py | rest_framework_jwt/compat.py | from distutils.version import StrictVersion
import rest_framework
from rest_framework import serializers
from django.forms import widgets
if StrictVersion(rest_framework.VERSION) < StrictVersion('3.0.0'):
class Serializer(serializers.Serializer):
pass
class PasswordField(serializers.CharField):
widget = widgets.PasswordInput
else:
class Serializer(serializers.Serializer):
@property
def object(self):
return self.validated_data
class PasswordField(serializers.CharField):
def __init__(self, *args, **kwargs):
if 'style' not in kwargs:
kwargs['style'] = {'input_type': 'password'}
else:
kwargs['style']['input_type'] = 'password'
super(PasswordField, self).__init__(*args, **kwargs)
def get_user_model():
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return User
def get_username_field():
try:
username_field = get_user_model().USERNAME_FIELD
except:
username_field = 'username'
return username_field
def get_username(user):
try:
username = user.get_username()
except AttributeError:
username = user.username
return username
def get_request_data(request):
if getattr(request, 'data', None):
data = request.data
else:
# DRF < 3.2
data = request.DATA
return data
| from distutils.version import StrictVersion
import rest_framework
from rest_framework import serializers
from django.forms import widgets
DRF_VERSION_INFO = StrictVersion(rest_framework.VERSION).version
DRF2 = DRF_VERSION_INFO[0] == 2
DRF3 = DRF_VERSION_INFO[0] == 3
if DRF2:
class Serializer(serializers.Serializer):
pass
class PasswordField(serializers.CharField):
widget = widgets.PasswordInput
else:
class Serializer(serializers.Serializer):
@property
def object(self):
return self.validated_data
class PasswordField(serializers.CharField):
def __init__(self, *args, **kwargs):
if 'style' not in kwargs:
kwargs['style'] = {'input_type': 'password'}
else:
kwargs['style']['input_type'] = 'password'
super(PasswordField, self).__init__(*args, **kwargs)
def get_user_model():
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return User
def get_username_field():
try:
username_field = get_user_model().USERNAME_FIELD
except:
username_field = 'username'
return username_field
def get_username(user):
try:
username = user.get_username()
except AttributeError:
username = user.username
return username
def get_request_data(request):
if DRF2:
data = request.DATA
else:
data = request.data
return data
| Use request.data in DRF >= 3 | Use request.data in DRF >= 3
| Python | mit | orf/django-rest-framework-jwt,shanemgrey/django-rest-framework-jwt,GetBlimp/django-rest-framework-jwt,blaklites/django-rest-framework-jwt,plentific/django-rest-framework-jwt,ArabellaTech/django-rest-framework-jwt | ---
+++
@@ -5,7 +5,12 @@
from django.forms import widgets
-if StrictVersion(rest_framework.VERSION) < StrictVersion('3.0.0'):
+DRF_VERSION_INFO = StrictVersion(rest_framework.VERSION).version
+DRF2 = DRF_VERSION_INFO[0] == 2
+DRF3 = DRF_VERSION_INFO[0] == 3
+
+
+if DRF2:
class Serializer(serializers.Serializer):
pass
@@ -57,10 +62,8 @@
def get_request_data(request):
- if getattr(request, 'data', None):
+ if DRF2:
+ data = request.DATA
+ else:
data = request.data
- else:
- # DRF < 3.2
- data = request.DATA
-
return data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.