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
|
|---|---|---|---|---|---|---|---|---|---|---|
7d756efb7361c13b0db0f37ead9668351c3a6887
|
unitTestUtils/parseXML.py
|
unitTestUtils/parseXML.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
try:
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
eprint("Error detected")
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
sys.exit(1)
def main():
parse()
if __name__ == '__main__':
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
try:
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
eprint("Error detected")
print(infile)
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
sys.exit(1)
def main():
parse()
if __name__ == '__main__':
main()
|
Add a print with file where mistake is
|
Add a print with file where mistake is
|
Python
|
apache-2.0
|
wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework
|
---
+++
@@ -17,6 +17,7 @@
root = tree.getroot()
if root.findall('.//FatalError'):
eprint("Error detected")
+ print(infile)
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
|
817de880b1bce7b16348ae3e0b1494753e7fe6b8
|
emission/net/ext_service/push/notify_queries.py
|
emission/net/ext_service/push/notify_queries.py
|
# Standard imports
import json
import logging
import uuid
# Our imports
import emission.core.get_database as edb
def get_platform_query(platform):
return {"curr_platform": platform}
def get_sync_interval_query(interval):
return {"curr_sync_interval": interval}
def get_user_query(user_id_list):
return {"user_id": {"$in": user_id_list}}
def combine_queries(query_list):
combined_query = {}
for query in query_list:
combined_query.update(query)
return combined_query
def get_matching_tokens(query):
logging.debug("Getting tokens matching query %s" % query)
ret_cursor = edb.get_profile_db().find(query, {"_id": False, "device_token": True})
mapped_list = map(lambda e: e.get("device_token"), ret_cursor)
ret_list = [item for item in mapped_list if item is not None]
return ret_list
|
# Standard imports
import json
import logging
import uuid
# Our imports
import emission.core.get_database as edb
def get_platform_query(platform):
return {"curr_platform": platform}
def get_sync_interval_query(interval):
return {"curr_sync_interval": interval}
def get_user_query(user_id_list):
return {"user_id": {"$in": user_id_list}}
def combine_queries(query_list):
combined_query = {}
for query in query_list:
combined_query.update(query)
return combined_query
def get_matching_tokens(query):
logging.debug("Getting tokens matching query %s" % query)
ret_cursor = edb.get_profile_db().find(query, {"_id": False, "device_token": True})
mapped_list = map(lambda e: e.get("device_token"), ret_cursor)
ret_list = [item for item in mapped_list if item is not None]
return ret_list
def get_matching_user_ids(query):
logging.debug("Getting tokens matching query %s" % query)
ret_cursor = edb.get_profile_db().find(query, {"_id": False, "user_id": True})
mapped_list = map(lambda e: e.get("user_id"), ret_cursor)
ret_list = [item for item in mapped_list if item is not None]
return ret_list
|
Add support for returning the uuids for a profile query
|
Add support for returning the uuids for a profile query
in addition to the tokens. This allows us to link profile query results to the
survey/push notification feature.
|
Python
|
bsd-3-clause
|
e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server
|
---
+++
@@ -28,3 +28,9 @@
ret_list = [item for item in mapped_list if item is not None]
return ret_list
+def get_matching_user_ids(query):
+ logging.debug("Getting tokens matching query %s" % query)
+ ret_cursor = edb.get_profile_db().find(query, {"_id": False, "user_id": True})
+ mapped_list = map(lambda e: e.get("user_id"), ret_cursor)
+ ret_list = [item for item in mapped_list if item is not None]
+ return ret_list
|
e885701a12fcb2d2557c975fadbabc7ee28ebf8b
|
djoauth2/helpers.py
|
djoauth2/helpers.py
|
# coding: utf-8
import random
from string import ascii_letters, digits
# From http://tools.ietf.org/html/rfc6750#section-2.1
BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/'
def random_hash(length):
return ''.join(random.sample(BEARER_TOKEN_CHARSET, length))
def random_hash_generator(length):
return lambda: random_hash(length)
|
# coding: utf-8
import random
import urlparse
from string import ascii_letters, digits
from urllib2 import urlencode
# From http://tools.ietf.org/html/rfc6750#section-2.1
BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/'
def random_hash(length):
return ''.join(random.sample(BEARER_TOKEN_CHARSET, length))
def random_hash_generator(length):
return lambda: random_hash(length)
def update_parameters(url, parameters):
""" Updates a URL's existing GET parameters.
@url: a URL string.
@parameters: a dictionary of parameters, {string:string}.
"""
parsed_url = urlparse(url)
query_parameters = urlparse.parse_qsl(parsed_url.query)
parsed_url.query = urlencode(query_parameters + parameters.items())
return urlparse.urlunparse(parsed_url)
|
Add helper for updating URL GET parameters.
|
Add helper for updating URL GET parameters.
|
Python
|
mit
|
vden/djoauth2-ng,vden/djoauth2-ng,Locu/djoauth2,seler/djoauth2,Locu/djoauth2,seler/djoauth2
|
---
+++
@@ -1,7 +1,8 @@
# coding: utf-8
import random
+import urlparse
from string import ascii_letters, digits
-
+from urllib2 import urlencode
# From http://tools.ietf.org/html/rfc6750#section-2.1
BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/'
@@ -10,6 +11,21 @@
def random_hash(length):
return ''.join(random.sample(BEARER_TOKEN_CHARSET, length))
+
def random_hash_generator(length):
return lambda: random_hash(length)
+
+def update_parameters(url, parameters):
+ """ Updates a URL's existing GET parameters.
+
+ @url: a URL string.
+ @parameters: a dictionary of parameters, {string:string}.
+ """
+ parsed_url = urlparse(url)
+
+ query_parameters = urlparse.parse_qsl(parsed_url.query)
+ parsed_url.query = urlencode(query_parameters + parameters.items())
+
+ return urlparse.urlunparse(parsed_url)
+
|
e2722385831a0930765d2c4bb78a582d41f4b64b
|
src/sentry/replays.py
|
src/sentry/replays.py
|
from __future__ import absolute_import
import socket
from httplib import HTTPConnection, HTTPSConnection
from urllib import urlencode
from urlparse import urlparse
class Replayer(object):
def __init__(self, url, method, data=None, headers=None):
self.url = url
self.method = method
self.data = data
self.headers = headers
def replay(self):
urlparts = urlparse(self.url)
if urlparts.scheme == 'http':
conn_cls = HTTPConnection
elif urlparts.scheme == 'https':
conn_cls = HTTPSConnection
else:
raise ValueError(self.url)
data = self.data
if isinstance(data, dict):
data = urlencode(data)
if urlparts.query:
full_url = urlparts.path + '?' + urlparts.query
else:
full_url = urlparts.path
conn = conn_cls(urlparts.netloc)
try:
conn.request(self.method, full_url, data, self.headers or {})
response = conn.getresponse()
except socket.error as e:
return {
'status': 'error',
'reason': str(e),
}
return {
'status': response.status,
'reason': response.reason,
'headers': response.getheaders(),
'body': response.read(),
}
|
from __future__ import absolute_import
import requests
class Replayer(object):
def __init__(self, url, method, data=None, headers=None):
self.url = url
self.method = method
self.data = data
self.headers = headers
def replay(self):
try:
response = requests.request(
self.method,
self.url,
data=self.data,
headers=self.headers or {}
)
except requests.RequestException as e:
return {
'status': 'error',
'reason': str(e),
}
return {
'status': response.status_code,
'reason': response.reason,
'headers': response.headers,
'body': response.content,
}
|
Use requests instead of httplib to do replay
|
Use requests instead of httplib to do replay
|
Python
|
bsd-3-clause
|
beeftornado/sentry,nicholasserra/sentry,Kryz/sentry,JackDanger/sentry,imankulov/sentry,JamesMura/sentry,zenefits/sentry,kevinlondon/sentry,mvaled/sentry,JamesMura/sentry,ifduyue/sentry,looker/sentry,daevaorn/sentry,fotinakis/sentry,gencer/sentry,looker/sentry,JackDanger/sentry,mvaled/sentry,Natim/sentry,beeftornado/sentry,korealerts1/sentry,imankulov/sentry,zenefits/sentry,jean/sentry,alexm92/sentry,fotinakis/sentry,daevaorn/sentry,beeftornado/sentry,BuildingLink/sentry,ngonzalvez/sentry,BayanGroup/sentry,mvaled/sentry,mitsuhiko/sentry,daevaorn/sentry,ngonzalvez/sentry,looker/sentry,korealerts1/sentry,mvaled/sentry,gencer/sentry,imankulov/sentry,Kryz/sentry,looker/sentry,felixbuenemann/sentry,jean/sentry,mitsuhiko/sentry,fotinakis/sentry,ifduyue/sentry,mvaled/sentry,korealerts1/sentry,kevinlondon/sentry,Natim/sentry,alexm92/sentry,zenefits/sentry,zenefits/sentry,BayanGroup/sentry,jean/sentry,mvaled/sentry,ifduyue/sentry,JamesMura/sentry,kevinlondon/sentry,BuildingLink/sentry,BayanGroup/sentry,JamesMura/sentry,nicholasserra/sentry,felixbuenemann/sentry,Kryz/sentry,BuildingLink/sentry,BuildingLink/sentry,Natim/sentry,BuildingLink/sentry,jean/sentry,JackDanger/sentry,felixbuenemann/sentry,fotinakis/sentry,nicholasserra/sentry,daevaorn/sentry,ngonzalvez/sentry,looker/sentry,alexm92/sentry,gencer/sentry,gencer/sentry,gencer/sentry,zenefits/sentry,JamesMura/sentry,ifduyue/sentry,jean/sentry,ifduyue/sentry
|
---
+++
@@ -1,10 +1,5 @@
from __future__ import absolute_import
-
-import socket
-
-from httplib import HTTPConnection, HTTPSConnection
-from urllib import urlencode
-from urlparse import urlparse
+import requests
class Replayer(object):
@@ -15,37 +10,22 @@
self.headers = headers
def replay(self):
- urlparts = urlparse(self.url)
- if urlparts.scheme == 'http':
- conn_cls = HTTPConnection
- elif urlparts.scheme == 'https':
- conn_cls = HTTPSConnection
- else:
- raise ValueError(self.url)
-
- data = self.data
- if isinstance(data, dict):
- data = urlencode(data)
-
- if urlparts.query:
- full_url = urlparts.path + '?' + urlparts.query
- else:
- full_url = urlparts.path
-
- conn = conn_cls(urlparts.netloc)
try:
- conn.request(self.method, full_url, data, self.headers or {})
-
- response = conn.getresponse()
- except socket.error as e:
+ response = requests.request(
+ self.method,
+ self.url,
+ data=self.data,
+ headers=self.headers or {}
+ )
+ except requests.RequestException as e:
return {
'status': 'error',
'reason': str(e),
}
return {
- 'status': response.status,
+ 'status': response.status_code,
'reason': response.reason,
- 'headers': response.getheaders(),
- 'body': response.read(),
+ 'headers': response.headers,
+ 'body': response.content,
}
|
133617660fe96a817b47d4d0fba4cfa7567dcafb
|
exceptional.py
|
exceptional.py
|
"""A module to demonstrate exceptions."""
import sys
def convert(item):
'''
Convert to an integer.
Args:
item: some object
Returns:
an integer representation of the object
Throws:
a ValueException
'''
try:
x = int(item)
print(str.format('Conversion succeeded! x= {}', x))
except ValueError:
print('Conversion Failed')
x = -1
return x
if __name__ == '__main__':
print(convert(sys.argv[1]))
|
"""A module to demonstrate exceptions."""
import sys
def convert(item):
"""
Convert to an integer.
Args:
item: some object
Returns:
an integer representation of the object
Throws:
a ValueException
"""
try:
return int(item)
except (ValueError, TypeError):
return -1
if __name__ == '__main__':
print(convert(sys.argv[1]))
|
Use two return statements and remove printing
|
Use two return statements and remove printing
|
Python
|
mit
|
kentoj/python-fundamentals
|
---
+++
@@ -4,7 +4,7 @@
def convert(item):
- '''
+ """
Convert to an integer.
Args:
item: some object
@@ -14,14 +14,11 @@
Throws:
a ValueException
- '''
+ """
try:
- x = int(item)
- print(str.format('Conversion succeeded! x= {}', x))
- except ValueError:
- print('Conversion Failed')
- x = -1
- return x
+ return int(item)
+ except (ValueError, TypeError):
+ return -1
if __name__ == '__main__':
print(convert(sys.argv[1]))
|
972073f7d65fe4ea2910241a7f8ba42a78ab3a86
|
fore/config.py
|
fore/config.py
|
# Basic config for stuff that can be easily changed, but which is git-managed.
# See also apikeys_sample.py for the configs which are _not_ git-managed.
app_name = "fore"
server_domain = "http://www.infiniteglitch.net"
lag_limit = 88200 # samples - how much we can lag by before dropping frames.
restart_timeout = 3 # seconds between polls to restart.txt
http_port = 8888
mini_http_port = 8193
uid = 1000 # User ID and group ID to drop privileges to
gid = 1000 # Set both to 0 to not drop privileges, eg if the server is started without privs
use_sudo_uid_gid = True # If set, uid/gid will be overridden with SUDO_UID/SUDO_GID if available
frontend_buffer = 20 # seconds of audio to buffer in frontend
past_played_buffer = 600 # seconds of audio to store track metadata for in the past
template_dir = "templates/"
drift_limit = 0.1 # seconds of audio after which drift should be corrected
max_track_length = 400
min_track_length = 90
# Default values when nothing exists
no_bpm_diff = 20
|
# Basic config for stuff that can be easily changed, but which is git-managed.
# See also apikeys_sample.py for the configs which are _not_ git-managed.
app_name = "fore"
server_domain = "http://www.infiniteglitch.net"
lag_limit = 88200 # samples - how much we can lag by before dropping frames.
restart_timeout = 3 # seconds between polls to restart.txt
http_port = 8888
mini_http_port = 8193
uid = 0 # User ID and group ID to drop privileges to
gid = 0 # Set both to 0 to not drop privileges, eg if the server is started without privs
use_sudo_uid_gid = True # If set, uid/gid will be overridden with SUDO_UID/SUDO_GID if available
frontend_buffer = 20 # seconds of audio to buffer in frontend
past_played_buffer = 600 # seconds of audio to store track metadata for in the past
template_dir = "templates/"
drift_limit = 0.1 # seconds of audio after which drift should be corrected
max_track_length = 400
min_track_length = 90
# Default values when nothing exists
no_bpm_diff = 20
|
Decrease user and group IDs from 1000 to 0.
|
Decrease user and group IDs from 1000 to 0.
|
Python
|
artistic-2.0
|
Rosuav/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension
|
---
+++
@@ -7,8 +7,8 @@
restart_timeout = 3 # seconds between polls to restart.txt
http_port = 8888
mini_http_port = 8193
-uid = 1000 # User ID and group ID to drop privileges to
-gid = 1000 # Set both to 0 to not drop privileges, eg if the server is started without privs
+uid = 0 # User ID and group ID to drop privileges to
+gid = 0 # Set both to 0 to not drop privileges, eg if the server is started without privs
use_sudo_uid_gid = True # If set, uid/gid will be overridden with SUDO_UID/SUDO_GID if available
frontend_buffer = 20 # seconds of audio to buffer in frontend
past_played_buffer = 600 # seconds of audio to store track metadata for in the past
|
a0172116503f0b212a184fc4a1d2179115675e17
|
fuzzyfinder/main.py
|
fuzzyfinder/main.py
|
# -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(text, collection):
"""
Args:
text (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the input `text`.
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collections` using the `text`
input.
"""
suggestions = []
pat = '.*?'.join(map(re.escape, text))
regex = re.compile('%s' % pat)
for item in sorted(collection):
r = regex.search(item)
if r:
suggestions.append((len(r.group()), r.start(), item))
return (z for _, _, z in sorted(suggestions))
|
# -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(text, collection):
"""
Args:
text (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the input `text`.
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collections` using the `text`
input.
"""
suggestions = []
pat = '.*?'.join(map(re.escape, text))
regex = re.compile(pat)
for item in collection:
r = regex.search(item)
if r:
suggestions.append((len(r.group()), r.start(), item))
return (z for _, _, z in sorted(suggestions))
|
Remove string interpolation and sorting the collection.
|
Remove string interpolation and sorting the collection.
|
Python
|
bsd-3-clause
|
adammenges/fuzzyfinder,amjith/fuzzyfinder,harrisonfeng/fuzzyfinder
|
---
+++
@@ -17,8 +17,8 @@
"""
suggestions = []
pat = '.*?'.join(map(re.escape, text))
- regex = re.compile('%s' % pat)
- for item in sorted(collection):
+ regex = re.compile(pat)
+ for item in collection:
r = regex.search(item)
if r:
suggestions.append((len(r.group()), r.start(), item))
|
caf0829191e9f3276fb144486ad602dcd482b60d
|
ignition/dsl/sfl/proteus_coefficient_printer.py
|
ignition/dsl/sfl/proteus_coefficient_printer.py
|
"""Generator for Proteus coefficient evaluator"""
from .sfl_printer import SFLPrinter
from ...code_tools import comment_code, indent_code, PythonCodePrinter
coefficient_header = """\
Proteus Coefficient file generated from Ignition
"""
class_header = """\
class %{class_name}s(TC_base):
"""
class ProteusCoefficientPrinter(SFLPrinter):
"""Generator for Proteus Coefficient evaluator"""
language = 'Python'
comment_str = '//'
block_comment_tuple = ('"""', '"""')
def print_file(self, indent=0):
ret_code = ""
ret_code += self._print_header(indent)
ret_code += PythonCodePrinter(self._generator.class_dag)
return ret_code
|
"""Generator for Proteus coefficient evaluator"""
from .sfl_printer import SFLPrinter
from ...code_tools import comment_code, indent_code, PythonCodePrinter
coefficient_header = """\
Proteus Coefficient file generated from Ignition
"""
class ProteusCoefficientPrinter(SFLPrinter):
"""Generator for Proteus Coefficient evaluator"""
language = 'Python'
comment_str = '//'
block_comment_tuple = ('"""', '"""\n')
def _print_header(self, indent):
return comment_code(indent_code(coefficient_header, indent),
block_comment=self.block_comment_tuple)
def print_file(self, indent=0):
ret_code = ""
ret_code += self._print_header(indent)
ret_code += PythonCodePrinter(self._generator.class_dag).code_str()
return ret_code
|
Print head, remove code for proteus python class head (use codeobj)
|
Print head, remove code for proteus python class head (use codeobj)
|
Python
|
bsd-3-clause
|
IgnitionProject/ignition,IgnitionProject/ignition,IgnitionProject/ignition
|
---
+++
@@ -8,20 +8,20 @@
Proteus Coefficient file generated from Ignition
"""
-class_header = """\
-class %{class_name}s(TC_base):
-"""
-
class ProteusCoefficientPrinter(SFLPrinter):
"""Generator for Proteus Coefficient evaluator"""
language = 'Python'
comment_str = '//'
- block_comment_tuple = ('"""', '"""')
+ block_comment_tuple = ('"""', '"""\n')
+
+ def _print_header(self, indent):
+ return comment_code(indent_code(coefficient_header, indent),
+ block_comment=self.block_comment_tuple)
def print_file(self, indent=0):
ret_code = ""
ret_code += self._print_header(indent)
- ret_code += PythonCodePrinter(self._generator.class_dag)
+ ret_code += PythonCodePrinter(self._generator.class_dag).code_str()
return ret_code
|
373e4e0e58cfec09b60983494f7b3bb4712e0ccd
|
2/ConfNEP.py
|
2/ConfNEP.py
|
"""A custom ILAMB confrontation for net ecosystem productivity (nep)."""
import os
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
import ilamblib as il
class ConfNEP(Confrontation):
"""Confront ``nep`` model outputs with ``nee`` observations.
Net ecosystem productivity (``nep``) is a CMIP5 standard output
provided by the MsTMIP models, and is the inverse of net ecosystem
exchange (``nee``), for which benchmark datasets are provided in
ILAMB.
"""
def __init__(self, **keywords):
super(ConfNEP, self).__init__(**keywords)
def stageData(self, m):
obs = Variable(filename=self.source,
variable_name=self.variable)
self._checkRegions(obs)
obs.data *= -1.0 # Reverse sign of benchmark data.
mod = m.extractTimeSeries(self.variable,
alt_vars=self.alternate_vars)
mod.data *= -1.0 # Reverse sign of modified model outputs.
obs, mod = il.MakeComparable(obs, mod, clip_ref=True,
logstring="[%s][%s]" %
(self.longname, m.name))
return obs, mod
|
"""A custom ILAMB confrontation for net ecosystem productivity (nep)."""
import os
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
from ILAMB.ilamblib import MakeComparable
class ConfNEP(Confrontation):
"""Confront ``nep`` model outputs with ``nee`` observations.
Net ecosystem productivity (``nep``) is a CMIP5 standard output
provided by the MsTMIP models, and is the inverse of net ecosystem
exchange (``nee``), for which benchmark datasets are provided in
ILAMB.
"""
def __init__(self, **keywords):
super(ConfNEP, self).__init__(**keywords)
def stageData(self, m):
obs = Variable(filename=self.source,
variable_name=self.variable)
self._checkRegions(obs)
obs.data *= -1.0 # Reverse sign of benchmark data.
mod = m.extractTimeSeries(self.variable,
alt_vars=self.alternate_vars)
mod.data *= -1.0 # Reverse sign of modified model outputs.
obs, mod = MakeComparable(obs, mod, clip_ref=True,
logstring="[%s][%s]" %
(self.longname, m.name))
return obs, mod
|
Change import so it works
|
Change import so it works
|
Python
|
mit
|
permamodel/ILAMB-experiments
|
---
+++
@@ -3,7 +3,7 @@
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
-import ilamblib as il
+from ILAMB.ilamblib import MakeComparable
class ConfNEP(Confrontation):
@@ -29,8 +29,8 @@
alt_vars=self.alternate_vars)
mod.data *= -1.0 # Reverse sign of modified model outputs.
- obs, mod = il.MakeComparable(obs, mod, clip_ref=True,
- logstring="[%s][%s]" %
- (self.longname, m.name))
+ obs, mod = MakeComparable(obs, mod, clip_ref=True,
+ logstring="[%s][%s]" %
+ (self.longname, m.name))
return obs, mod
|
23ec0899eaf60a9dc79f6671461a33eea7e7f464
|
authtools/backends.py
|
authtools/backends.py
|
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveEmailBackend(ModelBackend):
"""
This authentication backend assumes that usernames are email addresses and simply lowercases
a username before an attempt is made to authenticate said username using Django's ModelBackend.
Example usage:
# In settings.py
AUTHENTICATION_BACKENDS = ('authtools.backends.CaseInsensitiveEmailBackend',)
NOTE:
A word of caution. Use of this backend presupposes a way to ensure that users cannot create
usernames that differ only in case (e.g., joe@test.org and JOE@test.org). Using this backend
in such a system is a huge security risk.
"""
def authenticate(self, username=None, password=None, **kwargs):
if username is not None:
username = username.lower()
return super(CaseInsensitiveEmailBackend, self).authenticate(
username=username,
password=password,
**kwargs
)
|
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveEmailBackendMixin(object):
def authenticate(self, username=None, password=None, **kwargs):
if username is not None:
username = username.lower()
return super(CaseInsensitiveEmailBackendMixin, self).authenticate(
username=username,
password=password,
**kwargs
)
class CaseInsensitiveEmailBackend(ModelBackend):
"""
This authentication backend assumes that usernames are email addresses and simply lowercases
a username before an attempt is made to authenticate said username using Django's ModelBackend.
Example usage:
# In settings.py
AUTHENTICATION_BACKENDS = ('authtools.backends.CaseInsensitiveEmailBackend',)
NOTE:
A word of caution. Use of this backend presupposes a way to ensure that users cannot create
usernames that differ only in case (e.g., joe@test.org and JOE@test.org). Using this backend
in such a system is a huge security risk.
"""
def authenticate(self, username=None, password=None, **kwargs):
if username is not None:
username = username.lower()
return super(CaseInsensitiveEmailBackend, self).authenticate(
username=username,
password=password,
**kwargs
)
|
Add mixin to make the case-insensitive email auth backend more flexible
|
Add mixin to make the case-insensitive email auth backend more flexible
|
Python
|
bsd-2-clause
|
fusionbox/django-authtools,vuchau/django-authtools,moreati/django-authtools,eevol/django-authtools,kivikakk/django-authtools
|
---
+++
@@ -1,4 +1,16 @@
from django.contrib.auth.backends import ModelBackend
+
+
+class CaseInsensitiveEmailBackendMixin(object):
+ def authenticate(self, username=None, password=None, **kwargs):
+ if username is not None:
+ username = username.lower()
+
+ return super(CaseInsensitiveEmailBackendMixin, self).authenticate(
+ username=username,
+ password=password,
+ **kwargs
+ )
class CaseInsensitiveEmailBackend(ModelBackend):
|
e7d171b8b3721093c126560d1982e8eaebc4de6b
|
jay/urls.py
|
jay/urls.py
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls, namespace='votes')),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
Add namespace to votes app URLs
|
Add namespace to votes app URLs
|
Python
|
mit
|
kuboschek/jay,OpenJUB/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay,OpenJUB/jay
|
---
+++
@@ -26,7 +26,7 @@
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
- url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
+ url(r'^(?P<system_name>[\w-]+)/', include(votes_urls, namespace='votes')),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
4874f1b1a7a3ff465493f601f5f056bf8f3f1921
|
badgekit_webhooks/urls.py
|
badgekit_webhooks/urls.py
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^instances/([-A-Za-z.0-9_]+)/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
)
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
url(r"^badges/([-A-Za-z.0-9_]+)/instances/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
)
|
Move badge instance list beneath 'badges' url
|
Move badge instance list beneath 'badges' url
|
Python
|
mit
|
tgs/django-badgekit-webhooks
|
---
+++
@@ -9,8 +9,6 @@
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
- url(r"^instances/([-A-Za-z.0-9_]+)/$", staff_member_required(views.badge_instance_list),
- name="badge_instance_list"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
@@ -19,4 +17,6 @@
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
+ url(r"^badges/([-A-Za-z.0-9_]+)/instances/$", staff_member_required(views.badge_instance_list),
+ name="badge_instance_list"),
)
|
11312893661ac339212fad7d81a21c9ddc2533d3
|
identities/tasks.py
|
identities/tasks.py
|
import json
import requests
from celery.task import Task
from django.conf import settings
class DeliverHook(Task):
def run(self, target, payload, instance=None, hook=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance: a possibly null "trigger" instance
hook: the defining Hook object
"""
requests.post(
url=target,
data=json.dumps(payload),
headers={
'Content-Type': 'application/json',
'Authorization': 'Token %s' % settings.HOOK_AUTH_TOKEN
}
)
def deliver_hook_wrapper(target, payload, instance, hook):
if instance is not None:
instance_id = instance.id
else:
instance_id = None
kwargs = dict(target=target, payload=payload,
instance_id=instance_id, hook_id=hook.id)
DeliverHook.apply_async(kwargs=kwargs)
|
import json
import requests
from celery.task import Task
from django.conf import settings
class DeliverHook(Task):
def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
"""
requests.post(
url=target,
data=json.dumps(payload),
headers={
'Content-Type': 'application/json',
'Authorization': 'Token %s' % settings.HOOK_AUTH_TOKEN
}
)
def deliver_hook_wrapper(target, payload, instance, hook):
if instance is not None:
instance_id = instance.id
else:
instance_id = None
kwargs = dict(target=target, payload=payload,
instance_id=instance_id, hook_id=hook.id)
DeliverHook.apply_async(kwargs=kwargs)
|
Clean up params and docstrings
|
Clean up params and docstrings
|
Python
|
bsd-3-clause
|
praekelt/seed-identity-store,praekelt/seed-identity-store
|
---
+++
@@ -5,12 +5,12 @@
class DeliverHook(Task):
- def run(self, target, payload, instance=None, hook=None, **kwargs):
+ def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
- instance: a possibly null "trigger" instance
- hook: the defining Hook object
+ instance_id: a possibly None "trigger" instance ID
+ hook_id: the ID of defining Hook object
"""
requests.post(
url=target,
|
42a0fbf29168f12a4bc3afc53bbf7148b9d008f6
|
spacy/tests/pipeline/test_textcat.py
|
spacy/tests/pipeline/test_textcat.py
|
from __future__ import unicode_literals
from ...language import Language
def test_simple_train():
nlp = Language()
nlp.add_pipe(nlp.create_pipe('textcat'))
nlp.get_pipe('textcat').add_label('is_good')
nlp.begin_training()
for i in range(5):
for text, answer in [('aaaa', 1.), ('bbbb', 0), ('aa', 1.),
('bbbbbbbbb', 0.), ('aaaaaa', 1)]:
nlp.update([text], [{'cats': {'answer': answer}}])
doc = nlp(u'aaa')
assert 'is_good' in doc.cats
assert doc.cats['is_good'] >= 0.5
|
# coding: utf8
from __future__ import unicode_literals
from ...language import Language
def test_simple_train():
nlp = Language()
nlp.add_pipe(nlp.create_pipe('textcat'))
nlp.get_pipe('textcat').add_label('answer')
nlp.begin_training()
for i in range(5):
for text, answer in [('aaaa', 1.), ('bbbb', 0), ('aa', 1.),
('bbbbbbbbb', 0.), ('aaaaaa', 1)]:
nlp.update([text], [{'cats': {'answer': answer}}])
doc = nlp(u'aaa')
assert 'answer' in doc.cats
assert doc.cats['answer'] >= 0.5
|
Fix textcat simple train example
|
Fix textcat simple train example
|
Python
|
mit
|
aikramer2/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy
|
---
+++
@@ -1,19 +1,18 @@
+# coding: utf8
+
from __future__ import unicode_literals
from ...language import Language
+
def test_simple_train():
nlp = Language()
-
nlp.add_pipe(nlp.create_pipe('textcat'))
- nlp.get_pipe('textcat').add_label('is_good')
-
+ nlp.get_pipe('textcat').add_label('answer')
nlp.begin_training()
-
for i in range(5):
for text, answer in [('aaaa', 1.), ('bbbb', 0), ('aa', 1.),
('bbbbbbbbb', 0.), ('aaaaaa', 1)]:
nlp.update([text], [{'cats': {'answer': answer}}])
doc = nlp(u'aaa')
- assert 'is_good' in doc.cats
- assert doc.cats['is_good'] >= 0.5
-
+ assert 'answer' in doc.cats
+ assert doc.cats['answer'] >= 0.5
|
0b5b25b5cc3b5fe59c0a263983dae05ebfdc8de9
|
plenum/common/transactions.py
|
plenum/common/transactions.py
|
from enum import Enum
class Transactions(Enum):
def __str__(self):
return self.name
class PlenumTransactions(Transactions):
# These numeric constants CANNOT be changed once they have been used,
# because that would break backwards compatibility with the ledger
# Also the numeric constants CANNOT collide with transactions in dependent
# components.
NODE = "0"
NYM = "1"
AUDIT = "2"
GET_TXN = "3"
|
from enum import Enum
class Transactions(Enum):
def __str__(self):
return self.name
class PlenumTransactions(Transactions):
# These numeric constants CANNOT be changed once they have been used,
# because that would break backwards compatibility with the ledger
# Also the numeric constants CANNOT collide with transactions in dependent
# components.
NODE = "0"
NYM = "1"
AUDIT = "2"
GET_TXN = "3"
TXN_AUTHOR_AGREEMENT = "4"
TXN_AUTHOR_AGREEMENT_AML = "5"
GET_TXN_AUTHOR_AGREEMENT = "6"
GET_TXN_AUTHOR_AGREEMENT_AML = "7"
|
Add new TAA transaction codes
|
INDY-2066: Add new TAA transaction codes
Signed-off-by: Sergey Khoroshavin <b770466c7a06c5fe47531d5f0e31684f1131354d@dsr-corporation.com>
|
Python
|
apache-2.0
|
evernym/zeno,evernym/plenum
|
---
+++
@@ -15,3 +15,8 @@
NYM = "1"
AUDIT = "2"
GET_TXN = "3"
+
+ TXN_AUTHOR_AGREEMENT = "4"
+ TXN_AUTHOR_AGREEMENT_AML = "5"
+ GET_TXN_AUTHOR_AGREEMENT = "6"
+ GET_TXN_AUTHOR_AGREEMENT_AML = "7"
|
6ad84b8cc930922296fbe8c583c8c69f5b94d9c9
|
bots/humbug_git_config.py
|
bots/humbug_git_config.py
|
# Humbug Inc's internal git plugin configuration.
# The plugin and example config are under api/integrations/
# Leaving all the instructions out of this file to avoid having to
# sync them as we update the comments.
HUMBUG_USER = "humbug+commits@humbughq.com"
HUMBUG_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# commit_notice_destination() lets you customize where commit notices
# are sent to.
#
# It takes the following arguments:
# * repo = the name of the git repository
# * branch = the name of the branch that was pushed to
# * commit = the commit id
#
# Returns a dictionary encoding the stream and subject to send the
# notification to (or None to send no notification, e.g. for ).
#
# The default code below will send every commit pushed to "master" to
# * stream "commits"
# * subject "deploy => master" (using a pretty unicode right arrow)
# And similarly for branch "test-post-receive" (for use when testing).
def commit_notice_destination(repo, branch, commit):
if branch in ["master", "post-receive-test"]:
return dict(stream = "commits",
subject = u"deploy \u21D2 %s" % (branch,))
# Return None for cases where you don't want a notice sent
return None
HUMBUG_API_PATH = "/home/humbug/humbug/api"
HUMBUG_SITE = "https://staging.humbughq.com"
|
# Humbug Inc's internal git plugin configuration.
# The plugin and example config are under api/integrations/
# Leaving all the instructions out of this file to avoid having to
# sync them as we update the comments.
HUMBUG_USER = "humbug+commits@humbughq.com"
HUMBUG_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# commit_notice_destination() lets you customize where commit notices
# are sent to.
#
# It takes the following arguments:
# * repo = the name of the git repository
# * branch = the name of the branch that was pushed to
# * commit = the commit id
#
# Returns a dictionary encoding the stream and subject to send the
# notification to (or None to send no notification, e.g. for ).
#
# The default code below will send every commit pushed to "master" to
# * stream "commits"
# * subject "deploy => master" (using a pretty unicode right arrow)
# And similarly for branch "test-post-receive" (for use when testing).
def commit_notice_destination(repo, branch, commit):
if branch in ["master", "prod", "post-receive-test"]:
return dict(stream = "commits",
subject = u"deploy \u21D2 %s" % (branch,))
# Return None for cases where you don't want a notice sent
return None
HUMBUG_API_PATH = "/home/humbug/humbug/api"
HUMBUG_SITE = "https://staging.humbughq.com"
|
Put prod back on the list of branches to send notices about.
|
git: Put prod back on the list of branches to send notices about.
(imported from commit e608d7050b4e68045b03341dc41e8654e45a3af3)
|
Python
|
apache-2.0
|
MariaFaBella85/zulip,SmartPeople/zulip,blaze225/zulip,calvinleenyc/zulip,natanovia/zulip,moria/zulip,dnmfarrell/zulip,samatdav/zulip,tbutter/zulip,deer-hope/zulip,guiquanz/zulip,sharmaeklavya2/zulip,zulip/zulip,guiquanz/zulip,rishig/zulip,developerfm/zulip,schatt/zulip,AZtheAsian/zulip,praveenaki/zulip,glovebx/zulip,shaunstanislaus/zulip,sonali0901/zulip,KingxBanana/zulip,JanzTam/zulip,yocome/zulip,dawran6/zulip,hj3938/zulip,developerfm/zulip,shrikrishnaholla/zulip,adnanh/zulip,blaze225/zulip,bitemyapp/zulip,qq1012803704/zulip,bowlofstew/zulip,adnanh/zulip,wweiradio/zulip,LAndreas/zulip,KJin99/zulip,jainayush975/zulip,dwrpayne/zulip,akuseru/zulip,lfranchi/zulip,vikas-parashar/zulip,RobotCaleb/zulip,hayderimran7/zulip,Juanvulcano/zulip,Jianchun1/zulip,andersk/zulip,jessedhillon/zulip,eastlhu/zulip,pradiptad/zulip,aps-sids/zulip,ikasumiwt/zulip,atomic-labs/zulip,jerryge/zulip,RobotCaleb/zulip,bssrdf/zulip,zwily/zulip,jimmy54/zulip,technicalpickles/zulip,LeeRisk/zulip,zofuthan/zulip,Vallher/zulip,ryanbackman/zulip,natanovia/zulip,zachallaun/zulip,so0k/zulip,mansilladev/zulip,mohsenSy/zulip,jimmy54/zulip,johnnygaddarr/zulip,hustlzp/zulip,dhcrzf/zulip,hj3938/zulip,moria/zulip,udxxabp/zulip,avastu/zulip,lfranchi/zulip,jackrzhang/zulip,zhaoweigg/zulip,shubhamdhama/zulip,sonali0901/zulip,bowlofstew/zulip,m1ssou/zulip,MariaFaBella85/zulip,brockwhittaker/zulip,hengqujushi/zulip,MayB/zulip,sonali0901/zulip,aps-sids/zulip,grave-w-grave/zulip,wdaher/zulip,Drooids/zulip,joshisa/zulip,synicalsyntax/zulip,hafeez3000/zulip,jessedhillon/zulip,rht/zulip,Gabriel0402/zulip,punchagan/zulip,dattatreya303/zulip,udxxabp/zulip,zulip/zulip,schatt/zulip,vikas-parashar/zulip,kou/zulip,amallia/zulip,tommyip/zulip,isht3/zulip,thomasboyt/zulip,aps-sids/zulip,AZtheAsian/zulip,ryansnowboarder/zulip,bluesea/zulip,brainwane/zulip,huangkebo/zulip,hengqujushi/zulip,kaiyuanheshang/zulip,jackrzhang/zulip,itnihao/zulip,rishig/zulip,souravbadami/zulip,vabs22/zulip,ahmadassaf/zulip,bastianh/zulip,susansls/zulip,peguin40/zulip,Qgap/zulip,udxxabp/zulip,bluesea/zulip,MariaFaBella85/zulip,easyfmxu/zulip,gigawhitlocks/zulip,amanharitsh123/zulip,Juanvulcano/zulip,KingxBanana/zulip,hackerkid/zulip,lfranchi/zulip,voidException/zulip,ericzhou2008/zulip,atomic-labs/zulip,Qgap/zulip,MayB/zulip,armooo/zulip,krtkmj/zulip,sonali0901/zulip,sup95/zulip,bitemyapp/zulip,dawran6/zulip,Batterfii/zulip,dotcool/zulip,yocome/zulip,umkay/zulip,brainwane/zulip,akuseru/zulip,wdaher/zulip,arpitpanwar/zulip,gkotian/zulip,jrowan/zulip,brainwane/zulip,ashwinirudrappa/zulip,j831/zulip,littledogboy/zulip,aakash-cr7/zulip,fw1121/zulip,Diptanshu8/zulip,littledogboy/zulip,cosmicAsymmetry/zulip,vabs22/zulip,susansls/zulip,ipernet/zulip,jimmy54/zulip,nicholasbs/zulip,itnihao/zulip,KJin99/zulip,mdavid/zulip,isht3/zulip,ryansnowboarder/zulip,hustlzp/zulip,ikasumiwt/zulip,amanharitsh123/zulip,JPJPJPOPOP/zulip,brainwane/zulip,Juanvulcano/zulip,reyha/zulip,noroot/zulip,saitodisse/zulip,DazWorrall/zulip,kokoar/zulip,mdavid/zulip,LeeRisk/zulip,swinghu/zulip,tbutter/zulip,ashwinirudrappa/zulip,bastianh/zulip,ryanbackman/zulip,Qgap/zulip,MayB/zulip,jeffcao/zulip,developerfm/zulip,shubhamdhama/zulip,Cheppers/zulip,Batterfii/zulip,he15his/zulip,joshisa/zulip,deer-hope/zulip,jrowan/zulip,hackerkid/zulip,sup95/zulip,firstblade/zulip,zachallaun/zulip,timabbott/zulip,j831/zulip,vikas-parashar/zulip,mansilladev/zulip,vakila/zulip,atomic-labs/zulip,rht/zulip,brockwhittaker/zulip,mdavid/zulip,peguin40/zulip,eastlhu/zulip,samatdav/zulip,kou/zulip,easyfmxu/zulip,ufosky-server/zulip,joyhchen/zulip,hengqujushi/zulip,praveenaki/zulip,xuxiao/zulip,Frouk/zulip,bowlofstew/zulip,paxapy/zulip,zhaoweigg/zulip,amyliu345/zulip,themass/zulip,glovebx/zulip,samatdav/zulip,suxinde2009/zulip,kokoar/zulip,jimmy54/zulip,deer-hope/zulip,mahim97/zulip,grave-w-grave/zulip,amallia/zulip,mansilladev/zulip,so0k/zulip,JPJPJPOPOP/zulip,xuxiao/zulip,alliejones/zulip,PhilSk/zulip,LeeRisk/zulip,rishig/zulip,praveenaki/zulip,avastu/zulip,j831/zulip,suxinde2009/zulip,amanharitsh123/zulip,ipernet/zulip,ufosky-server/zulip,glovebx/zulip,aliceriot/zulip,LAndreas/zulip,timabbott/zulip,jeffcao/zulip,hackerkid/zulip,isht3/zulip,joyhchen/zulip,synicalsyntax/zulip,noroot/zulip,saitodisse/zulip,ikasumiwt/zulip,peguin40/zulip,Cheppers/zulip,bssrdf/zulip,eeshangarg/zulip,bitemyapp/zulip,amallia/zulip,tiansiyuan/zulip,xuanhan863/zulip,ahmadassaf/zulip,mansilladev/zulip,SmartPeople/zulip,natanovia/zulip,peguin40/zulip,Drooids/zulip,nicholasbs/zulip,PaulPetring/zulip,dawran6/zulip,zhaoweigg/zulip,punchagan/zulip,luyifan/zulip,codeKonami/zulip,yocome/zulip,qq1012803704/zulip,eastlhu/zulip,zorojean/zulip,Galexrt/zulip,brockwhittaker/zulip,KingxBanana/zulip,xuxiao/zulip,wweiradio/zulip,synicalsyntax/zulip,christi3k/zulip,mahim97/zulip,ryansnowboarder/zulip,PhilSk/zulip,tdr130/zulip,so0k/zulip,jerryge/zulip,dattatreya303/zulip,umkay/zulip,jonesgithub/zulip,Jianchun1/zulip,synicalsyntax/zulip,sonali0901/zulip,Frouk/zulip,kaiyuanheshang/zulip,ryanbackman/zulip,SmartPeople/zulip,mohsenSy/zulip,ryansnowboarder/zulip,souravbadami/zulip,themass/zulip,amanharitsh123/zulip,synicalsyntax/zulip,SmartPeople/zulip,hustlzp/zulip,praveenaki/zulip,bssrdf/zulip,armooo/zulip,zachallaun/zulip,synicalsyntax/zulip,dxq-git/zulip,bowlofstew/zulip,LAndreas/zulip,joshisa/zulip,xuanhan863/zulip,itnihao/zulip,ufosky-server/zulip,littledogboy/zulip,firstblade/zulip,hackerkid/zulip,armooo/zulip,amyliu345/zulip,calvinleenyc/zulip,andersk/zulip,atomic-labs/zulip,rht/zulip,alliejones/zulip,MariaFaBella85/zulip,praveenaki/zulip,sup95/zulip,AZtheAsian/zulip,MariaFaBella85/zulip,zacps/zulip,bluesea/zulip,Cheppers/zulip,verma-varsha/zulip,eastlhu/zulip,zacps/zulip,avastu/zulip,udxxabp/zulip,AZtheAsian/zulip,bitemyapp/zulip,ericzhou2008/zulip,zacps/zulip,technicalpickles/zulip,luyifan/zulip,zulip/zulip,Gabriel0402/zulip,themass/zulip,synicalsyntax/zulip,showell/zulip,avastu/zulip,PaulPetring/zulip,gigawhitlocks/zulip,Qgap/zulip,levixie/zulip,susansls/zulip,m1ssou/zulip,ApsOps/zulip,LeeRisk/zulip,umkay/zulip,easyfmxu/zulip,babbage/zulip,bssrdf/zulip,peguin40/zulip,yuvipanda/zulip,technicalpickles/zulip,technicalpickles/zulip,showell/zulip,blaze225/zulip,shrikrishnaholla/zulip,Gabriel0402/zulip,moria/zulip,paxapy/zulip,reyha/zulip,pradiptad/zulip,rht/zulip,ipernet/zulip,cosmicAsymmetry/zulip,jeffcao/zulip,shrikrishnaholla/zulip,firstblade/zulip,saitodisse/zulip,itnihao/zulip,fw1121/zulip,verma-varsha/zulip,guiquanz/zulip,timabbott/zulip,hj3938/zulip,hayderimran7/zulip,shrikrishnaholla/zulip,wavelets/zulip,bastianh/zulip,kou/zulip,Suninus/zulip,brockwhittaker/zulip,eeshangarg/zulip,reyha/zulip,wweiradio/zulip,zwily/zulip,huangkebo/zulip,Galexrt/zulip,Frouk/zulip,Gabriel0402/zulip,udxxabp/zulip,showell/zulip,qq1012803704/zulip,mahim97/zulip,hustlzp/zulip,bssrdf/zulip,ryansnowboarder/zulip,he15his/zulip,wangdeshui/zulip,schatt/zulip,jonesgithub/zulip,Galexrt/zulip,natanovia/zulip,levixie/zulip,LeeRisk/zulip,punchagan/zulip,DazWorrall/zulip,KJin99/zulip,andersk/zulip,willingc/zulip,samatdav/zulip,glovebx/zulip,AZtheAsian/zulip,jimmy54/zulip,pradiptad/zulip,blaze225/zulip,jrowan/zulip,tommyip/zulip,jonesgithub/zulip,wangdeshui/zulip,umkay/zulip,qq1012803704/zulip,Galexrt/zulip,zofuthan/zulip,dxq-git/zulip,DazWorrall/zulip,AZtheAsian/zulip,yocome/zulip,peiwei/zulip,zofuthan/zulip,proliming/zulip,johnnygaddarr/zulip,proliming/zulip,jessedhillon/zulip,timabbott/zulip,swinghu/zulip,MariaFaBella85/zulip,dattatreya303/zulip,shubhamdhama/zulip,PaulPetring/zulip,tbutter/zulip,so0k/zulip,jackrzhang/zulip,timabbott/zulip,Batterfii/zulip,jessedhillon/zulip,mahim97/zulip,seapasulli/zulip,calvinleenyc/zulip,joyhchen/zulip,firstblade/zulip,PaulPetring/zulip,grave-w-grave/zulip,he15his/zulip,zulip/zulip,grave-w-grave/zulip,mdavid/zulip,akuseru/zulip,johnny9/zulip,bastianh/zulip,schatt/zulip,stamhe/zulip,paxapy/zulip,deer-hope/zulip,alliejones/zulip,bssrdf/zulip,vaidap/zulip,ApsOps/zulip,krtkmj/zulip,PhilSk/zulip,codeKonami/zulip,calvinleenyc/zulip,isht3/zulip,developerfm/zulip,yocome/zulip,mohsenSy/zulip,dhcrzf/zulip,gigawhitlocks/zulip,jainayush975/zulip,hafeez3000/zulip,saitodisse/zulip,xuxiao/zulip,wdaher/zulip,themass/zulip,dattatreya303/zulip,tommyip/zulip,swinghu/zulip,bluesea/zulip,ipernet/zulip,arpith/zulip,JanzTam/zulip,zorojean/zulip,luyifan/zulip,LAndreas/zulip,ryanbackman/zulip,alliejones/zulip,avastu/zulip,xuanhan863/zulip,dawran6/zulip,j831/zulip,vikas-parashar/zulip,armooo/zulip,fw1121/zulip,dnmfarrell/zulip,gkotian/zulip,stamhe/zulip,JanzTam/zulip,sonali0901/zulip,fw1121/zulip,punchagan/zulip,swinghu/zulip,LAndreas/zulip,seapasulli/zulip,he15his/zulip,willingc/zulip,kou/zulip,RobotCaleb/zulip,jackrzhang/zulip,akuseru/zulip,stamhe/zulip,dxq-git/zulip,adnanh/zulip,avastu/zulip,wdaher/zulip,deer-hope/zulip,ApsOps/zulip,thomasboyt/zulip,bowlofstew/zulip,j831/zulip,DazWorrall/zulip,tdr130/zulip,vakila/zulip,sharmaeklavya2/zulip,littledogboy/zulip,wangdeshui/zulip,littledogboy/zulip,levixie/zulip,proliming/zulip,vakila/zulip,dxq-git/zulip,LeeRisk/zulip,pradiptad/zulip,cosmicAsymmetry/zulip,kokoar/zulip,nicholasbs/zulip,tiansiyuan/zulip,dawran6/zulip,itnihao/zulip,PaulPetring/zulip,JPJPJPOPOP/zulip,babbage/zulip,ApsOps/zulip,Juanvulcano/zulip,babbage/zulip,easyfmxu/zulip,zhaoweigg/zulip,souravbadami/zulip,johnnygaddarr/zulip,shaunstanislaus/zulip,proliming/zulip,dwrpayne/zulip,bitemyapp/zulip,dxq-git/zulip,aakash-cr7/zulip,jrowan/zulip,zorojean/zulip,krtkmj/zulip,yuvipanda/zulip,jphilipsen05/zulip,seapasulli/zulip,zwily/zulip,lfranchi/zulip,ahmadassaf/zulip,vikas-parashar/zulip,showell/zulip,dhcrzf/zulip,zwily/zulip,Qgap/zulip,KingxBanana/zulip,atomic-labs/zulip,gkotian/zulip,Batterfii/zulip,souravbadami/zulip,dnmfarrell/zulip,codeKonami/zulip,mansilladev/zulip,cosmicAsymmetry/zulip,wweiradio/zulip,Vallher/zulip,jrowan/zulip,ufosky-server/zulip,gigawhitlocks/zulip,zulip/zulip,dattatreya303/zulip,dnmfarrell/zulip,amanharitsh123/zulip,verma-varsha/zulip,DazWorrall/zulip,eeshangarg/zulip,JPJPJPOPOP/zulip,kou/zulip,dwrpayne/zulip,karamcnair/zulip,KingxBanana/zulip,dotcool/zulip,qq1012803704/zulip,TigorC/zulip,MayB/zulip,mohsenSy/zulip,stamhe/zulip,udxxabp/zulip,lfranchi/zulip,arpith/zulip,hengqujushi/zulip,dwrpayne/zulip,reyha/zulip,shubhamdhama/zulip,hj3938/zulip,mansilladev/zulip,ryansnowboarder/zulip,reyha/zulip,wangdeshui/zulip,bowlofstew/zulip,niftynei/zulip,shaunstanislaus/zulip,kokoar/zulip,vabs22/zulip,hayderimran7/zulip,umkay/zulip,saitodisse/zulip,ryansnowboarder/zulip,wavelets/zulip,tdr130/zulip,hustlzp/zulip,calvinleenyc/zulip,RobotCaleb/zulip,zwily/zulip,atomic-labs/zulip,itnihao/zulip,tiansiyuan/zulip,johnnygaddarr/zulip,xuanhan863/zulip,Vallher/zulip,amyliu345/zulip,dhcrzf/zulip,dnmfarrell/zulip,ipernet/zulip,tbutter/zulip,wangdeshui/zulip,thomasboyt/zulip,jerryge/zulip,jerryge/zulip,wavelets/zulip,Qgap/zulip,amallia/zulip,EasonYi/zulip,esander91/zulip,JPJPJPOPOP/zulip,deer-hope/zulip,ikasumiwt/zulip,Frouk/zulip,babbage/zulip,KingxBanana/zulip,stamhe/zulip,zachallaun/zulip,shaunstanislaus/zulip,christi3k/zulip,jphilipsen05/zulip,Jianchun1/zulip,qq1012803704/zulip,codeKonami/zulip,zhaoweigg/zulip,m1ssou/zulip,EasonYi/zulip,arpitpanwar/zulip,aliceriot/zulip,swinghu/zulip,kaiyuanheshang/zulip,sup95/zulip,suxinde2009/zulip,xuxiao/zulip,zorojean/zulip,moria/zulip,bssrdf/zulip,seapasulli/zulip,rishig/zulip,jphilipsen05/zulip,ashwinirudrappa/zulip,EasonYi/zulip,bluesea/zulip,dhcrzf/zulip,udxxabp/zulip,tiansiyuan/zulip,wweiradio/zulip,Suninus/zulip,tommyip/zulip,voidException/zulip,dawran6/zulip,hafeez3000/zulip,yuvipanda/zulip,blaze225/zulip,karamcnair/zulip,natanovia/zulip,vakila/zulip,willingc/zulip,dwrpayne/zulip,verma-varsha/zulip,noroot/zulip,ashwinirudrappa/zulip,themass/zulip,themass/zulip,jrowan/zulip,yuvipanda/zulip,jphilipsen05/zulip,jimmy54/zulip,jonesgithub/zulip,dotcool/zulip,andersk/zulip,Frouk/zulip,eastlhu/zulip,vikas-parashar/zulip,xuxiao/zulip,Qgap/zulip,xuxiao/zulip,punchagan/zulip,zachallaun/zulip,aps-sids/zulip,hengqujushi/zulip,PaulPetring/zulip,luyifan/zulip,nicholasbs/zulip,krtkmj/zulip,brainwane/zulip,vabs22/zulip,showell/zulip,niftynei/zulip,praveenaki/zulip,proliming/zulip,karamcnair/zulip,so0k/zulip,guiquanz/zulip,gigawhitlocks/zulip,Jianchun1/zulip,isht3/zulip,jimmy54/zulip,seapasulli/zulip,avastu/zulip,rht/zulip,zachallaun/zulip,suxinde2009/zulip,seapasulli/zulip,suxinde2009/zulip,arpitpanwar/zulip,arpitpanwar/zulip,aakash-cr7/zulip,schatt/zulip,joshisa/zulip,johnny9/zulip,Suninus/zulip,zwily/zulip,hafeez3000/zulip,ApsOps/zulip,ahmadassaf/zulip,vaidap/zulip,jerryge/zulip,technicalpickles/zulip,guiquanz/zulip,peiwei/zulip,joshisa/zulip,nicholasbs/zulip,punchagan/zulip,arpitpanwar/zulip,hackerkid/zulip,jeffcao/zulip,pradiptad/zulip,Drooids/zulip,ufosky-server/zulip,littledogboy/zulip,tdr130/zulip,thomasboyt/zulip,vakila/zulip,ikasumiwt/zulip,christi3k/zulip,ufosky-server/zulip,kokoar/zulip,ericzhou2008/zulip,johnny9/zulip,amanharitsh123/zulip,easyfmxu/zulip,amyliu345/zulip,zofuthan/zulip,m1ssou/zulip,codeKonami/zulip,sup95/zulip,ashwinirudrappa/zulip,kaiyuanheshang/zulip,TigorC/zulip,aps-sids/zulip,krtkmj/zulip,huangkebo/zulip,Drooids/zulip,voidException/zulip,jonesgithub/zulip,zacps/zulip,PaulPetring/zulip,he15his/zulip,pradiptad/zulip,fw1121/zulip,vaidap/zulip,Suninus/zulip,developerfm/zulip,ericzhou2008/zulip,armooo/zulip,huangkebo/zulip,developerfm/zulip,johnnygaddarr/zulip,gigawhitlocks/zulip,levixie/zulip,cosmicAsymmetry/zulip,tbutter/zulip,zulip/zulip,peiwei/zulip,aakash-cr7/zulip,jeffcao/zulip,wweiradio/zulip,JanzTam/zulip,zorojean/zulip,kou/zulip,vabs22/zulip,akuseru/zulip,shaunstanislaus/zulip,dxq-git/zulip,LeeRisk/zulip,amallia/zulip,zhaoweigg/zulip,xuanhan863/zulip,shubhamdhama/zulip,johnnygaddarr/zulip,niftynei/zulip,esander91/zulip,jackrzhang/zulip,amyliu345/zulip,yuvipanda/zulip,dhcrzf/zulip,niftynei/zulip,paxapy/zulip,eastlhu/zulip,peiwei/zulip,willingc/zulip,SmartPeople/zulip,hackerkid/zulip,aps-sids/zulip,huangkebo/zulip,moria/zulip,Gabriel0402/zulip,kou/zulip,JanzTam/zulip,gkotian/zulip,ericzhou2008/zulip,glovebx/zulip,jainayush975/zulip,Suninus/zulip,suxinde2009/zulip,grave-w-grave/zulip,christi3k/zulip,tommyip/zulip,seapasulli/zulip,LAndreas/zulip,tiansiyuan/zulip,stamhe/zulip,brockwhittaker/zulip,amallia/zulip,noroot/zulip,souravbadami/zulip,m1ssou/zulip,cosmicAsymmetry/zulip,jeffcao/zulip,babbage/zulip,christi3k/zulip,Galexrt/zulip,shaunstanislaus/zulip,vaidap/zulip,Vallher/zulip,karamcnair/zulip,samatdav/zulip,rishig/zulip,ikasumiwt/zulip,Vallher/zulip,jphilipsen05/zulip,joyhchen/zulip,hayderimran7/zulip,esander91/zulip,Jianchun1/zulip,saitodisse/zulip,schatt/zulip,karamcnair/zulip,bastianh/zulip,voidException/zulip,suxinde2009/zulip,Gabriel0402/zulip,xuanhan863/zulip,dhcrzf/zulip,mohsenSy/zulip,JanzTam/zulip,calvinleenyc/zulip,showell/zulip,technicalpickles/zulip,zulip/zulip,wavelets/zulip,firstblade/zulip,RobotCaleb/zulip,kaiyuanheshang/zulip,luyifan/zulip,Drooids/zulip,Juanvulcano/zulip,lfranchi/zulip,PhilSk/zulip,he15his/zulip,DazWorrall/zulip,huangkebo/zulip,peiwei/zulip,wavelets/zulip,jphilipsen05/zulip,Galexrt/zulip,aakash-cr7/zulip,aakash-cr7/zulip,amallia/zulip,armooo/zulip,alliejones/zulip,brockwhittaker/zulip,ericzhou2008/zulip,bluesea/zulip,umkay/zulip,schatt/zulip,hayderimran7/zulip,adnanh/zulip,arpitpanwar/zulip,saitodisse/zulip,andersk/zulip,ipernet/zulip,aps-sids/zulip,mohsenSy/zulip,blaze225/zulip,zhaoweigg/zulip,arpith/zulip,andersk/zulip,joshisa/zulip,arpith/zulip,dnmfarrell/zulip,paxapy/zulip,mahim97/zulip,wangdeshui/zulip,ahmadassaf/zulip,levixie/zulip,esander91/zulip,kaiyuanheshang/zulip,ashwinirudrappa/zulip,susansls/zulip,christi3k/zulip,nicholasbs/zulip,andersk/zulip,arpitpanwar/zulip,natanovia/zulip,jackrzhang/zulip,showell/zulip,jerryge/zulip,eeshangarg/zulip,aliceriot/zulip,j831/zulip,RobotCaleb/zulip,ryanbackman/zulip,thomasboyt/zulip,jessedhillon/zulip,shubhamdhama/zulip,ApsOps/zulip,RobotCaleb/zulip,PhilSk/zulip,eastlhu/zulip,amyliu345/zulip,lfranchi/zulip,zofuthan/zulip,yuvipanda/zulip,niftynei/zulip,firstblade/zulip,xuanhan863/zulip,kokoar/zulip,gigawhitlocks/zulip,shrikrishnaholla/zulip,willingc/zulip,guiquanz/zulip,hafeez3000/zulip,gkotian/zulip,adnanh/zulip,huangkebo/zulip,umkay/zulip,EasonYi/zulip,sharmaeklavya2/zulip,kaiyuanheshang/zulip,hj3938/zulip,hafeez3000/zulip,wdaher/zulip,moria/zulip,MayB/zulip,KJin99/zulip,SmartPeople/zulip,zwily/zulip,praveenaki/zulip,tiansiyuan/zulip,bitemyapp/zulip,hengqujushi/zulip,technicalpickles/zulip,hustlzp/zulip,jainayush975/zulip,Batterfii/zulip,tdr130/zulip,sup95/zulip,Diptanshu8/zulip,babbage/zulip,akuseru/zulip,zorojean/zulip,proliming/zulip,bastianh/zulip,johnny9/zulip,Cheppers/zulip,Vallher/zulip,voidException/zulip,ApsOps/zulip,shrikrishnaholla/zulip,voidException/zulip,mdavid/zulip,verma-varsha/zulip,brainwane/zulip,krtkmj/zulip,vabs22/zulip,Batterfii/zulip,shrikrishnaholla/zulip,wavelets/zulip,susansls/zulip,natanovia/zulip,eeshangarg/zulip,willingc/zulip,esander91/zulip,wweiradio/zulip,shubhamdhama/zulip,zorojean/zulip,Jianchun1/zulip,tiansiyuan/zulip,littledogboy/zulip,dnmfarrell/zulip,tbutter/zulip,fw1121/zulip,TigorC/zulip,reyha/zulip,m1ssou/zulip,qq1012803704/zulip,stamhe/zulip,armooo/zulip,sharmaeklavya2/zulip,KJin99/zulip,joshisa/zulip,souravbadami/zulip,m1ssou/zulip,jessedhillon/zulip,KJin99/zulip,mdavid/zulip,Batterfii/zulip,babbage/zulip,Gabriel0402/zulip,bluesea/zulip,tdr130/zulip,luyifan/zulip,alliejones/zulip,DazWorrall/zulip,sharmaeklavya2/zulip,nicholasbs/zulip,kokoar/zulip,Vallher/zulip,TigorC/zulip,punchagan/zulip,dotcool/zulip,MariaFaBella85/zulip,swinghu/zulip,guiquanz/zulip,yuvipanda/zulip,krtkmj/zulip,esander91/zulip,karamcnair/zulip,zofuthan/zulip,ufosky-server/zulip,dotcool/zulip,JPJPJPOPOP/zulip,hengqujushi/zulip,tommyip/zulip,johnny9/zulip,ryanbackman/zulip,vaidap/zulip,thomasboyt/zulip,jerryge/zulip,hj3938/zulip,Suninus/zulip,yocome/zulip,noroot/zulip,fw1121/zulip,JanzTam/zulip,verma-varsha/zulip,thomasboyt/zulip,itnihao/zulip,atomic-labs/zulip,adnanh/zulip,dxq-git/zulip,johnnygaddarr/zulip,proliming/zulip,aliceriot/zulip,brainwane/zulip,paxapy/zulip,EasonYi/zulip,esander91/zulip,so0k/zulip,peiwei/zulip,dwrpayne/zulip,willingc/zulip,Cheppers/zulip,easyfmxu/zulip,bastianh/zulip,joyhchen/zulip,so0k/zulip,adnanh/zulip,codeKonami/zulip,codeKonami/zulip,tommyip/zulip,he15his/zulip,rht/zulip,deer-hope/zulip,wangdeshui/zulip,timabbott/zulip,jeffcao/zulip,ericzhou2008/zulip,ikasumiwt/zulip,ipernet/zulip,ahmadassaf/zulip,Diptanshu8/zulip,moria/zulip,akuseru/zulip,Juanvulcano/zulip,hackerkid/zulip,themass/zulip,dattatreya303/zulip,noroot/zulip,jessedhillon/zulip,hustlzp/zulip,Drooids/zulip,arpith/zulip,luyifan/zulip,alliejones/zulip,wdaher/zulip,hafeez3000/zulip,Drooids/zulip,glovebx/zulip,susansls/zulip,yocome/zulip,wdaher/zulip,PhilSk/zulip,Frouk/zulip,vakila/zulip,mansilladev/zulip,bowlofstew/zulip,MayB/zulip,pradiptad/zulip,eeshangarg/zulip,rishig/zulip,voidException/zulip,gkotian/zulip,rishig/zulip,shaunstanislaus/zulip,glovebx/zulip,EasonYi/zulip,jackrzhang/zulip,tbutter/zulip,Diptanshu8/zulip,swinghu/zulip,dotcool/zulip,sharmaeklavya2/zulip,ashwinirudrappa/zulip,johnny9/zulip,KJin99/zulip,zacps/zulip,samatdav/zulip,dwrpayne/zulip,Galexrt/zulip,eeshangarg/zulip,peguin40/zulip,Diptanshu8/zulip,jonesgithub/zulip,timabbott/zulip,joyhchen/zulip,LAndreas/zulip,jonesgithub/zulip,Cheppers/zulip,developerfm/zulip,karamcnair/zulip,mahim97/zulip,EasonYi/zulip,easyfmxu/zulip,firstblade/zulip,hayderimran7/zulip,hj3938/zulip,aliceriot/zulip,ahmadassaf/zulip,arpith/zulip,peiwei/zulip,zachallaun/zulip,mdavid/zulip,vakila/zulip,niftynei/zulip,vaidap/zulip,aliceriot/zulip,Diptanshu8/zulip,dotcool/zulip,Cheppers/zulip,levixie/zulip,zofuthan/zulip,TigorC/zulip,grave-w-grave/zulip,isht3/zulip,wavelets/zulip,johnny9/zulip,zacps/zulip,tdr130/zulip,aliceriot/zulip,noroot/zulip,MayB/zulip,levixie/zulip,jainayush975/zulip,rht/zulip,hayderimran7/zulip,Frouk/zulip,gkotian/zulip,Suninus/zulip,TigorC/zulip,bitemyapp/zulip,jainayush975/zulip
|
---
+++
@@ -23,7 +23,7 @@
# * subject "deploy => master" (using a pretty unicode right arrow)
# And similarly for branch "test-post-receive" (for use when testing).
def commit_notice_destination(repo, branch, commit):
- if branch in ["master", "post-receive-test"]:
+ if branch in ["master", "prod", "post-receive-test"]:
return dict(stream = "commits",
subject = u"deploy \u21D2 %s" % (branch,))
|
e1c58062db9c107c358e3617793aaed7cdb3a133
|
jobmon/util.py
|
jobmon/util.py
|
import os
import threading
class TerminableThreadMixin:
"""
TerminableThreadMixin is useful for threads that need to be terminated
from the outside. It provides a method called 'terminate', which communicates
to the thread that it needs to die, and then waits for the death to occur.
It imposes the following rules:
1. Call it's .__init__ inside of your __init__
2. Use the .reader inside of the thread - when it has data written on it,
that is an exit request
3. Call it's .cleanup method before exiting.
"""
def __init__(self):
reader, writer = os.pipe()
self.exit_reader = os.fdopen(reader, 'rb')
self.exit_writer = os.fdopen(writer, 'wb')
def cleanup(self):
self.exit_reader.close()
self.exit_writer.close()
def terminate(self):
"""
Asynchronously terminates the thread, without waiting for it to exit.
"""
try:
self.exit_writer.write(b' ')
self.exit_writer.flush()
except ValueError:
pass
def wait_for_exit(self):
"""
Waits for the thread to exit - should be run only after terminating
the thread.
"""
self.join()
|
import logging
import os
import threading
def reset_loggers():
"""
Removes all handlers from the current loggers to allow for a new basicConfig.
"""
root = logging.getLogger()
for handler in root.handlers[:]:
root.removeHandler(handler)
class TerminableThreadMixin:
"""
TerminableThreadMixin is useful for threads that need to be terminated
from the outside. It provides a method called 'terminate', which communicates
to the thread that it needs to die, and then waits for the death to occur.
It imposes the following rules:
1. Call it's .__init__ inside of your __init__
2. Use the .reader inside of the thread - when it has data written on it,
that is an exit request
3. Call it's .cleanup method before exiting.
"""
def __init__(self):
reader, writer = os.pipe()
self.exit_reader = os.fdopen(reader, 'rb')
self.exit_writer = os.fdopen(writer, 'wb')
def cleanup(self):
self.exit_reader.close()
self.exit_writer.close()
def terminate(self):
"""
Asynchronously terminates the thread, without waiting for it to exit.
"""
try:
self.exit_writer.write(b' ')
self.exit_writer.flush()
except ValueError:
pass
def wait_for_exit(self):
"""
Waits for the thread to exit - should be run only after terminating
the thread.
"""
self.join()
|
Add way to reset loggers
|
Add way to reset loggers
logging.basicConfig doesn't reset the current logging infrastructure, which
was messing up some tests that expected logs to be one place even though
they ended up in another
|
Python
|
bsd-2-clause
|
adamnew123456/jobmon
|
---
+++
@@ -1,5 +1,14 @@
+import logging
import os
import threading
+
+def reset_loggers():
+ """
+ Removes all handlers from the current loggers to allow for a new basicConfig.
+ """
+ root = logging.getLogger()
+ for handler in root.handlers[:]:
+ root.removeHandler(handler)
class TerminableThreadMixin:
"""
|
232a9fd87f15a8b118c835d6f888d6bb9e236d19
|
cat/search_indexes.py
|
cat/search_indexes.py
|
from haystack.indexes import SearchIndex, CharField, MultiValueField, BooleanField
from haystack import site
from .models import MuseumObject
class MuseumObjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr='artefact_type', faceted=True)
global_region = CharField(model_attr='global_region', faceted=True)
country = CharField(model_attr='country', faceted=True)
people = MultiValueField(faceted=True)
has_images = BooleanField(faceted=True)
def prepare_categories(self, object):
return [unicode(cat) for cat in object.category.all()]
def prepare_people(self, object):
people = set()
if object.maker:
people.add(unicode(object.maker))
people.add(unicode(object.donor))
people.add(unicode(object.collector))
return list(people)
def prepare_has_images(self, object):
return object.artefactrepresentation_set.exists()
def get_model(self):
return MuseumObject
def index_queryset(self):
"""
Used when the entire index for model is updated.
"""
### TODO ###
# Ignore private/reserved etc objects
return self.get_model().objects.all()
site.register(MuseumObject, MuseumObjectIndex)
|
from haystack.indexes import SearchIndex, CharField, MultiValueField, BooleanField
from haystack import site
from .models import MuseumObject
class MuseumObjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr='artefact_type', faceted=True)
global_region = CharField(model_attr='global_region', faceted=True)
country = CharField(model_attr='country', faceted=True, default='')
people = MultiValueField(faceted=True)
has_images = BooleanField(faceted=True)
def prepare_categories(self, object):
return [unicode(cat) for cat in object.category.all()]
def prepare_people(self, object):
people = set()
if object.maker:
people.add(unicode(object.maker))
people.add(unicode(object.donor))
people.add(unicode(object.collector))
return list(people)
def prepare_has_images(self, object):
return object.artefactrepresentation_set.exists()
def get_model(self):
return MuseumObject
def index_queryset(self):
"""
Used when the entire index for model is updated.
"""
### TODO ###
# Ignore private/reserved etc objects
return self.get_model().objects.all()
site.register(MuseumObject, MuseumObjectIndex)
|
Allow indexing blank country field
|
Allow indexing blank country field
|
Python
|
bsd-3-clause
|
uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam
|
---
+++
@@ -8,7 +8,7 @@
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr='artefact_type', faceted=True)
global_region = CharField(model_attr='global_region', faceted=True)
- country = CharField(model_attr='country', faceted=True)
+ country = CharField(model_attr='country', faceted=True, default='')
people = MultiValueField(faceted=True)
has_images = BooleanField(faceted=True)
|
76ed5eb9d9d2f3a453de6976f52221e6970b6b71
|
tests/unit/test_offline_compression.py
|
tests/unit/test_offline_compression.py
|
import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
class TestOfflineCompression(TestCase):
def tearDown(self):
super(TestOfflineCompression, self).tearDown()
if os.path.exists(TMP_STATIC_DIR):
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress')
|
import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
class TestOfflineCompression(TestCase):
def tearDown(self):
super(TestOfflineCompression, self).tearDown()
if os.path.exists(TMP_STATIC_DIR):
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress', verbosity=0)
|
Add test for offline compression using django_compressor
|
Add test for offline compression using django_compressor
|
Python
|
bsd-3-clause
|
tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages
|
---
+++
@@ -23,4 +23,4 @@
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
- call_command('compress')
+ call_command('compress', verbosity=0)
|
d7e9eba6fb3628f0736bd468ae76e05099b9d651
|
space/decorators.py
|
space/decorators.py
|
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from incubator.settings import STATUS_SECRETS
def one_or_zero(arg):
"""Typecast to 1 or 0"""
if arg == '1':
return 1
elif arg == '0':
return 0
raise ValueError("not one or zero")
def private_api(**required_params):
"""
Filter incoming private API requests, and perform parameter validation and
extraction
"""
def outer(some_view):
@csrf_exempt
def inner(request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseBadRequest("Only POST is allowed")
if 'secret' not in request.POST.keys():
return HttpResponseBadRequest(
"You must query this endpoint with a secret.")
if request.POST['secret'] not in STATUS_SECRETS:
message = 'Bad secret {} is not in the allowed list'.format(
request.POST['secret'])
return HttpResponseForbidden(message)
params = {}
for name, typecast in required_params.items():
if name not in request.POST.keys():
return HttpResponseBadRequest(
"Parameter %s is required" % name)
try:
params[name] = typecast(request.POST[name])
except ValueError:
return HttpResponseBadRequest(
"Did not understood %s=%s" % (name, request.POST[name]))
return some_view(request, **params)
return inner
return outer
|
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
def one_or_zero(arg):
"""Typecast to 1 or 0"""
if arg == '1':
return 1
elif arg == '0':
return 0
raise ValueError("not one or zero")
def private_api(**required_params):
"""
Filter incoming private API requests, and perform parameter validation and
extraction
"""
def outer(some_view):
@csrf_exempt
def inner(request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseBadRequest("Only POST is allowed")
if 'secret' not in request.POST.keys():
return HttpResponseBadRequest(
"You must query this endpoint with a secret.")
if request.POST['secret'] not in settings.STATUS_SECRETS:
message = 'Bad secret {} is not in the allowed list'.format(
request.POST['secret'])
return HttpResponseForbidden(message)
params = {}
for name, typecast in required_params.items():
if name not in request.POST.keys():
return HttpResponseBadRequest(
"Parameter %s is required" % name)
try:
params[name] = typecast(request.POST[name])
except ValueError:
return HttpResponseBadRequest(
"Did not understood %s=%s" % (name, request.POST[name]))
return some_view(request, **params)
return inner
return outer
|
Use from django.conf import settings
|
Use from django.conf import settings
|
Python
|
agpl-3.0
|
UrLab/incubator,UrLab/incubator,UrLab/incubator,UrLab/incubator
|
---
+++
@@ -1,6 +1,6 @@
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
-from incubator.settings import STATUS_SECRETS
+from django.conf import settings
def one_or_zero(arg):
@@ -27,7 +27,7 @@
return HttpResponseBadRequest(
"You must query this endpoint with a secret.")
- if request.POST['secret'] not in STATUS_SECRETS:
+ if request.POST['secret'] not in settings.STATUS_SECRETS:
message = 'Bad secret {} is not in the allowed list'.format(
request.POST['secret'])
return HttpResponseForbidden(message)
|
ce3c7daff5eaaf8eefecf3f4e5bd9fbca40a7a2a
|
cob/subsystems/tasks_subsystem.py
|
cob/subsystems/tasks_subsystem.py
|
import os
import logbook
from .base import SubsystemBase
_logger = logbook.Logger(__name__)
class TasksSubsystem(SubsystemBase):
NAME = 'tasks'
def activate(self, flask_app):
from ..celery.app import celery_app
self._config = self.project.config.get('celery', {})
# ensure critical celery config exists
self._config.setdefault('broker_url', 'amqp://guest:guest@localhost/')
override_broker_url = os.environ.get('COB_CELERY_BROKER_URL')
if override_broker_url is not None:
self._config['broker_url'] = override_broker_url
celery_app.conf.broker_url = self._config['broker_url']
self.queues = set()
def get_queue_names(self):
names = {queue_name for grain in self.grains for queue_name in grain.config.get('queue_names', [])}
names.add('celery')
return sorted(names)
def configure_grain(self, grain, flask_app):
_ = grain.load()
def configure_app(self, flask_app):
super().configure_app(flask_app)
from ..celery.app import celery_app
for task in celery_app.tasks.values():
queue_name = getattr(task, 'queue', None)
if queue_name is not None:
self.queues.add(queue_name)
def iter_locations(self):
return None
|
import os
import logbook
from .base import SubsystemBase
_logger = logbook.Logger(__name__)
class TasksSubsystem(SubsystemBase):
NAME = 'tasks'
def activate(self, flask_app):
from ..celery.app import celery_app
self._config = self.project.config.get('celery', {})
# ensure critical celery config exists
self._config.setdefault('broker_url', 'amqp://guest:guest@localhost/')
override_broker_url = os.environ.get('COB_CELERY_BROKER_URL')
if override_broker_url is not None:
self._config['broker_url'] = override_broker_url
celery_app.conf.update(self._config)
self.queues = set()
def get_queue_names(self):
names = {queue_name for grain in self.grains for queue_name in grain.config.get('queue_names', [])}
names.add('celery')
return sorted(names)
def configure_grain(self, grain, flask_app):
_ = grain.load()
def configure_app(self, flask_app):
super().configure_app(flask_app)
from ..celery.app import celery_app
for task in celery_app.tasks.values():
queue_name = getattr(task, 'queue', None)
if queue_name is not None:
self.queues.add(queue_name)
def iter_locations(self):
return None
|
Allow passing Celery configuration under the project's config
|
Allow passing Celery configuration under the project's config
|
Python
|
bsd-3-clause
|
getweber/weber-cli
|
---
+++
@@ -22,7 +22,7 @@
if override_broker_url is not None:
self._config['broker_url'] = override_broker_url
- celery_app.conf.broker_url = self._config['broker_url']
+ celery_app.conf.update(self._config)
self.queues = set()
def get_queue_names(self):
|
68d1943b591afe55f75fa31dfb3c4c61b8f4297f
|
daybed/tests/support.py
|
daybed/tests/support.py
|
import os
from uuid import uuid4
from unittest import TestCase
import webtest
from daybed.db import DatabaseConnection
HERE = os.path.dirname(os.path.abspath(__file__))
class BaseWebTest(TestCase):
"""Base Web Test to test your cornice service.
It setups the database before each test and delete it after.
"""
def setUp(self):
self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4()
self.db_server = self.app.app.registry.settings['db_server']
self.db_base = self.db_server[self.db_name]
self.db = DatabaseConnection(self.db_base)
self.app = webtest.TestApp("config:tests.ini", relative_to=HERE)
def tearDown(self):
# Delete Test DB
self.db_server.delete(self.db_name)
def put_valid_definition(self):
"""Create a valid definition named "todo".
"""
# Put a valid definition
self.app.put_json('/definitions/todo',
self.valid_definition,
headers=self.headers)
|
import os
from uuid import uuid4
from unittest import TestCase
import webtest
from daybed.db import DatabaseConnection
HERE = os.path.dirname(os.path.abspath(__file__))
class BaseWebTest(TestCase):
"""Base Web Test to test your cornice service.
It setups the database before each test and delete it after.
"""
def setUp(self):
self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4()
self.app = webtest.TestApp("config:tests.ini", relative_to=HERE)
self.db_server = self.app.app.registry.settings['db_server']
self.db_base = self.db_server[self.db_name]
self.db = DatabaseConnection(self.db_base)
def tearDown(self):
# Delete Test DB
self.db_server.delete(self.db_name)
def put_valid_definition(self):
"""Create a valid definition named "todo".
"""
# Put a valid definition
self.app.put_json('/definitions/todo',
self.valid_definition,
headers=self.headers)
|
Fix db deletion, take 2
|
Fix db deletion, take 2
|
Python
|
bsd-3-clause
|
spiral-project/daybed,spiral-project/daybed
|
---
+++
@@ -15,12 +15,12 @@
"""
def setUp(self):
+
self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4()
+ self.app = webtest.TestApp("config:tests.ini", relative_to=HERE)
self.db_server = self.app.app.registry.settings['db_server']
self.db_base = self.db_server[self.db_name]
self.db = DatabaseConnection(self.db_base)
-
- self.app = webtest.TestApp("config:tests.ini", relative_to=HERE)
def tearDown(self):
# Delete Test DB
|
455c8ed93dcac20b6393cf781e19971fa3b92cdb
|
tests/test_cookies.py
|
tests/test_cookies.py
|
# -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_sth(bar):
assert bar == "europython2015"
""")
# run pytest with the following cmd args
result = testdir.runpytest(
'--foo=europython2015',
'-v'
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'*::test_sth PASSED',
])
# make sure that that we get a '0' exit code for the testsuite
assert result.ret == 0
def test_help_message(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'cookies:',
'*--foo=DEST_FOO*Set the value for the fixture "bar".',
])
def test_hello_ini_setting(testdir):
testdir.makeini("""
[pytest]
HELLO = world
""")
testdir.makepyfile("""
import pytest
@pytest.fixture
def hello(request):
return request.config.getini('HELLO')
def test_hello_world(hello):
assert hello == 'world'
""")
result = testdir.runpytest('-v')
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'*::test_hello_world PASSED',
])
# make sure that that we get a '0' exit code for the testsuite
assert result.ret == 0
|
# -*- coding: utf-8 -*-
def test_cookies_fixture(testdir):
"""Make sure that pytest accepts the `cookies` fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_valid_fixture(cookies):
assert hasattr(cookies, 'bake')
assert callable(cookies.bake)
assert callable(cookies.bake)
""")
# run pytest with the following cmd args
result = testdir.runpytest('-v')
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'*::test_valid_fixture PASSED',
])
# make sure that that we get a '0' exit code for the testsuite
assert result.ret == 0
def test_help_message(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'cookies:',
])
|
Implement simple tests for the 'cookies' fixture
|
Implement simple tests for the 'cookies' fixture
|
Python
|
mit
|
hackebrot/pytest-cookies
|
---
+++
@@ -1,24 +1,23 @@
# -*- coding: utf-8 -*-
-def test_bar_fixture(testdir):
- """Make sure that pytest accepts our fixture."""
+def test_cookies_fixture(testdir):
+ """Make sure that pytest accepts the `cookies` fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
- def test_sth(bar):
- assert bar == "europython2015"
+ def test_valid_fixture(cookies):
+ assert hasattr(cookies, 'bake')
+ assert callable(cookies.bake)
+ assert callable(cookies.bake)
""")
# run pytest with the following cmd args
- result = testdir.runpytest(
- '--foo=europython2015',
- '-v'
- )
+ result = testdir.runpytest('-v')
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
- '*::test_sth PASSED',
+ '*::test_valid_fixture PASSED',
])
# make sure that that we get a '0' exit code for the testsuite
@@ -32,33 +31,4 @@
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'cookies:',
- '*--foo=DEST_FOO*Set the value for the fixture "bar".',
])
-
-
-def test_hello_ini_setting(testdir):
- testdir.makeini("""
- [pytest]
- HELLO = world
- """)
-
- testdir.makepyfile("""
- import pytest
-
- @pytest.fixture
- def hello(request):
- return request.config.getini('HELLO')
-
- def test_hello_world(hello):
- assert hello == 'world'
- """)
-
- result = testdir.runpytest('-v')
-
- # fnmatch_lines does an assertion internally
- result.stdout.fnmatch_lines([
- '*::test_hello_world PASSED',
- ])
-
- # make sure that that we get a '0' exit code for the testsuite
- assert result.ret == 0
|
134fcbd6e82957ac3abd2eebdc296fd4ccb457e9
|
alexandria/api/books.py
|
alexandria/api/books.py
|
from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util
class BooksView(FlaskView):
route_prefix = '/api/'
@authenticated
def index(self):
query = mongo.Books.find()
books = json.loads(json_util.dumps(query, default=json_util.default))
for book in books:
book['id'] = book['_id']['$oid']
book.pop('_id')
return jsonify(books=books)
@authenticated
def genre(self, id):
query = mongo.Books.find({'genres':id})
books = json.loads(json_util.dumps(query, default=json_util.default))
for book in books:
book['id'] = book['_id']['$oid']
book.pop('_id')
return jsonify(books=books)
@authenticated
def author(self, id):
query = mongo.Books.find({'authors':id})
books = json.loads(json_util.dumps(query, default=json_util.default))
for book in books:
book['id'] = book['_id']['$oid']
book.pop('_id')
return jsonify(books=books)
BooksView.register(app)
|
from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util
class BooksView(FlaskView):
route_prefix = '/api/'
@authenticated
def index(self):
query = mongo.Books.find()
books = json.loads(json_util.dumps(query, default=json_util.default))
for book in books:
book['id'] = book['_id']['$oid']
book.pop('_id')
book['owner'] = book['owner']['$oid']
return jsonify(books=books)
@authenticated
def genre(self, id):
query = mongo.Books.find({'genres':id})
books = json.loads(json_util.dumps(query, default=json_util.default))
for book in books:
book['id'] = book['_id']['$oid']
book.pop('_id')
book['owner'] = book['owner']['$oid']
return jsonify(books=books)
@authenticated
def author(self, id):
query = mongo.Books.find({'authors':id})
books = json.loads(json_util.dumps(query, default=json_util.default))
for book in books:
book['id'] = book['_id']['$oid']
book.pop('_id')
book['owner'] = book['owner']['$oid']
return jsonify(books=books)
BooksView.register(app)
|
Set value of 'owner' to the value of the ObjectId
|
Set value of 'owner' to the value of the ObjectId
|
Python
|
mit
|
citruspi/Alexandria,citruspi/Alexandria
|
---
+++
@@ -21,6 +21,8 @@
book['id'] = book['_id']['$oid']
book.pop('_id')
+ book['owner'] = book['owner']['$oid']
+
return jsonify(books=books)
@authenticated
@@ -34,6 +36,8 @@
book['id'] = book['_id']['$oid']
book.pop('_id')
+
+ book['owner'] = book['owner']['$oid']
return jsonify(books=books)
@@ -50,6 +54,8 @@
book['id'] = book['_id']['$oid']
book.pop('_id')
+ book['owner'] = book['owner']['$oid']
+
return jsonify(books=books)
|
233e74abcc4a70f573e199074f5184b30bdfe1d2
|
seam/__init__.py
|
seam/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" __init__.py
Seam
====
Seam is a simple layer between existing neuroimaging tools and your data.
While it is opinionated in how to execute tools, it makes no decisions
as to how data is organized or how the scripts are ultimately run. These
decisions are are up to you.
This is the main API.
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'
__version__ = '0.0'
import freesurfer
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" __init__.py
Seam
====
Seam is a simple layer between existing neuroimaging tools and your data.
While it is opinionated in how to execute tools, it makes no decisions
as to how data is organized or how the scripts are ultimately run. These
decisions are are up to you.
This is the main API.
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'
__version__ = '0.0'
from . import freesurfer
__all__ = ['freesurfer', ]
|
Fix py3k relative import error
|
Fix py3k relative import error
|
Python
|
mit
|
VUIIS/seam,VUIIS/seam
|
---
+++
@@ -18,4 +18,6 @@
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'
__version__ = '0.0'
-import freesurfer
+from . import freesurfer
+
+__all__ = ['freesurfer', ]
|
b193df5080cc8076739509523cf391f5b7132d56
|
kerastuner/utils.py
|
kerastuner/utils.py
|
# Copyright 2019 The Keras Tuner Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gc
import numpy as np
from tensorflow.python import Session, ConfigProto
from tensorflow.python.keras import backend as K
def compute_model_size(model):
"comput the size of a given model"
params = [K.count_params(p) for p in set(model.trainable_weights)]
return int(np.sum(params))
def clear_tf_session():
"Clear tensorflow graph to avoid OOM issues"
K.clear_session()
# K.get_session().close() # unsure if it is needed
gc.collect()
if hasattr(K, 'set_session'):
cfg = ConfigProto()
cfg.gpu_options.allow_growth = True # pylint: disable=no-member
K.set_session(Session(config=cfg))
|
# Copyright 2019 The Keras Tuner Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gc
import numpy as np
from tensorflow.python import Session, ConfigProto
from tensorflow.python.keras import backend as K
def compute_model_size(model):
"comput the size of a given model"
params = [K.count_params(p) for p in model.trainable_weights]
return int(np.sum(params))
def clear_tf_session():
"Clear tensorflow graph to avoid OOM issues"
K.clear_session()
# K.get_session().close() # unsure if it is needed
gc.collect()
if hasattr(K, 'set_session'):
cfg = ConfigProto()
cfg.gpu_options.allow_growth = True # pylint: disable=no-member
K.set_session(Session(config=cfg))
|
Fix bugs for updating from tf 2.0b0 to rc0
|
Fix bugs for updating from tf 2.0b0 to rc0
Updating the dependency of tensorflow from 2.0.0b1 to 2.0.0rc0 is causing crashes in keras-tuner.
Not sure the "set" operation is really useful, but it is causing the crash because it tries to hash a tensor with equality enabled.
```
../../.virtualenvs/ak/lib/python3.6/site-packages/kerastuner/utils.py:23: in compute_model_size
params = [K.count_params(p) for p in set(model.trainable_weights)]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <tf.Variable 'dense/kernel:0' shape=(32, 32) dtype=float32, numpy=
array([[ 0.03147817, -0.30117437, -0.08552131, ...,...],
[ 0.23273078, -0.10847142, 0.0151484 , ..., 0.16468436,
-0.21210298, -0.1087181 ]], dtype=float32)>
def __hash__(self):
if ops.Tensor._USE_EQUALITY and ops.executing_eagerly_outside_functions(): # pylint: disable=protected-access
> raise TypeError("Variable is unhashable if Tensor equality is enabled. "
"Instead, use tensor.experimental_ref() as the key.")
E TypeError: Variable is unhashable if Tensor equality is enabled. Instead, use tensor.experimental_ref() as the key.
../../.virtualenvs/ak/lib/python3.6/site-packages/tensorflow_core/python/ops/variables.py:1085: TypeError
```
|
Python
|
apache-2.0
|
keras-team/keras-tuner,keras-team/keras-tuner
|
---
+++
@@ -20,7 +20,7 @@
def compute_model_size(model):
"comput the size of a given model"
- params = [K.count_params(p) for p in set(model.trainable_weights)]
+ params = [K.count_params(p) for p in model.trainable_weights]
return int(np.sum(params))
|
3a21137a09c58612044580f5835be1bbe2765500
|
markdown-pp.py
|
markdown-pp.py
|
#!/usr/bin/env python
# Copyright (C) 2010 John Reese
# Licensed under the MIT license
import sys
import MarkdownPP
if len(sys.argv) > 2:
mdpp = open(sys.argv[1], "r")
md = open(sys.argv[2], "w")
elif len(sys.argv) > 1:
mdpp = open(sys.argv[1], "r")
md = sys.stdout
else:
sys.exit(1)
MarkdownPP.MarkdownPP(input=mdpp, output=md, modules=MarkdownPP.modules.keys())
mdpp.close()
md.close()
|
#!/usr/bin/env python2
# Copyright (C) 2010 John Reese
# Licensed under the MIT license
import sys
import MarkdownPP
if len(sys.argv) > 2:
mdpp = open(sys.argv[1], "r")
md = open(sys.argv[2], "w")
elif len(sys.argv) > 1:
mdpp = open(sys.argv[1], "r")
md = sys.stdout
else:
sys.exit(1)
MarkdownPP.MarkdownPP(input=mdpp, output=md, modules=MarkdownPP.modules.keys())
mdpp.close()
md.close()
|
Allow specifying depth of TOC headers and rewrites
|
Allow specifying depth of TOC headers and rewrites
|
Python
|
mit
|
triAGENS/markdown-pp,jreese/markdown-pp
|
---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python2
# Copyright (C) 2010 John Reese
# Licensed under the MIT license
|
418e7a7d8c8261578df046d251041ab0794d1580
|
decorators.py
|
decorators.py
|
#!/usr/bin/env python
class RequiresType(object):
"""
Checks that the first (or position given by the keyword argument 'position'
argument to the function is an instance of one of the types given in the
positional decorator arguments
"""
def __init__(self, *types, **kwargs):
self.types = types
self.position = 0
self.returnvalue = False
if 'position' in kwargs:
self.position = int(kwargs['position']) - 1
if 'returnvalue' in kwargs:
self.returnvalue = kwargs['returnvalue']
def __call__(self, f):
def wrapped_f(*args, **kwargs):
if type(args[self.position]) not in self.types:
return self.returnvalue
return f(*args, **kwargs)
return wrapped_f
|
#!/usr/bin/env python
class RequiresType(object):
"""
Checks that the first (or position given by the keyword argument 'position'
argument to the function is an instance of one of the types given in the
positional decorator arguments
"""
def __init__(self, *types, **kwargs):
self.types = types
self.position = 0
if 'position' in kwargs:
self.position = int(kwargs['position']) - 1
def __call__(self, f):
def wrapped_f(*args, **kwargs):
if type(args[self.position]) not in self.types:
raise TypeError("Invalid argument type '%s' at position %d. " +
"Expected one of (%s)" % (
type(args[self.position]).__name__, self.position,
", ".join([t.__name__ for t in self.types])))
return f(*args, **kwargs)
return wrapped_f
|
Raise TypeError instead of returning
|
Raise TypeError instead of returning
|
Python
|
bsd-3-clause
|
rasher/reddit-modbot
|
---
+++
@@ -11,15 +11,15 @@
def __init__(self, *types, **kwargs):
self.types = types
self.position = 0
- self.returnvalue = False
if 'position' in kwargs:
self.position = int(kwargs['position']) - 1
- if 'returnvalue' in kwargs:
- self.returnvalue = kwargs['returnvalue']
def __call__(self, f):
def wrapped_f(*args, **kwargs):
if type(args[self.position]) not in self.types:
- return self.returnvalue
+ raise TypeError("Invalid argument type '%s' at position %d. " +
+ "Expected one of (%s)" % (
+ type(args[self.position]).__name__, self.position,
+ ", ".join([t.__name__ for t in self.types])))
return f(*args, **kwargs)
return wrapped_f
|
94d54e20fe5590fad0449bef79366654b3c7f23d
|
swingtime/urls.py
|
swingtime/urls.py
|
from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.CalendarView.as_view(),
name='swingtime-calendar'
),
url(
r'^calendar/json/$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.CalendarView.as_view(),
name='swingtime-yearly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/$',
views.CalendarView.as_view(),
name='swingtime-monthly-view'
),
url(
r'^agenda/$',
views.AgendaView.as_view(),
name='swingtime-events'
),
url(
r'^event/(\d+)/$',
views.event_view,
name='swingtime-event'
),
url(
r'^event/(\d+)/occurrence/(\d+)/$',
views.occurrence_view,
name='swingtime-occurrence'
),
)
|
from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.CalendarView.as_view(),
name='swingtime-calendar'
),
url(
r'^calendar.json$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.CalendarView.as_view(),
name='swingtime-yearly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/$',
views.CalendarView.as_view(),
name='swingtime-monthly-view'
),
url(
r'^agenda/$',
views.AgendaView.as_view(),
name='swingtime-events'
),
url(
r'^event/(\d+)/$',
views.event_view,
name='swingtime-event'
),
url(
r'^event/(\d+)/occurrence/(\d+)/$',
views.occurrence_view,
name='swingtime-occurrence'
),
)
|
Change calendar JSON view url
|
Change calendar JSON view url
|
Python
|
mit
|
jonge-democraten/mezzanine-fullcalendar
|
---
+++
@@ -9,7 +9,7 @@
),
url(
- r'^calendar/json/$',
+ r'^calendar.json$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'
),
|
0d0d43f957cb79a99eaacef0623cd57351ca40f6
|
test/factories.py
|
test/factories.py
|
# coding: utf-8
import factory
from django.contrib.auth.models import User
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = "Boy"
last_name = "Factory"
email = factory.LazyAttribute(
lambda a:
"{0}_{1}@example.com".format(a.first_name, a.last_name).lower())
username = factory.Sequence(lambda n: "username_%s" % n)
|
# coding: utf-8
import factory
from django.contrib.auth.models import User
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = "Boy"
last_name = "Factory"
email = factory.LazyAttribute(
lambda a:
"{0}_{1}@example.com".format(a.first_name, a.last_name).lower())
username = factory.Sequence(lambda n: "username_%s" % n)
is_active = False
is_staff = False
is_superuser = False
|
Fix userfactory - set user flags
|
Fix userfactory - set user flags
|
Python
|
mit
|
sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa
|
---
+++
@@ -14,3 +14,6 @@
lambda a:
"{0}_{1}@example.com".format(a.first_name, a.last_name).lower())
username = factory.Sequence(lambda n: "username_%s" % n)
+ is_active = False
+ is_staff = False
+ is_superuser = False
|
f4fdba652a1822698778c65df66a2639ec0fc5ad
|
tests/conftest.py
|
tests/conftest.py
|
import pytest
from .app import setup, teardown
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
|
from __future__ import absolute_import
import pytest
from .app import setup, teardown
from app import create_app
from app.models import db, Framework
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
@pytest.fixture(scope='session')
def app(request):
return create_app('test')
@pytest.fixture()
def live_framework(request, app, status='live'):
with app.app_context():
framework = Framework.query.filter(
Framework.slug == 'digital-outcomes-and-specialists'
).first()
original_framework_status = framework.status
framework.status = status
db.session.add(framework)
db.session.commit()
def teardown():
with app.app_context():
framework = Framework.query.filter(
Framework.slug == 'digital-outcomes-and-specialists'
).first()
framework.status = original_framework_status
db.session.add(framework)
db.session.commit()
request.addfinalizer(teardown)
@pytest.fixture()
def expired_framework(request, app):
return live_framework(request, app, status='expired')
|
Add live and expired framework pytest fixtures
|
Add live and expired framework pytest fixtures
This is a tiny attempt to move away from relying on database migrations
to set up framework records for tests. Using migration framework records
means we need to use actual (sometimes expired) frameworks to write tests
ties us to existing frameworks and require manual rollbacks for any record
changes since frameworks/lots tables are not reset between tests.
Using fixtures for frameworks makes it possible to depend explicitly
on database state required to run the test. This works better than
creating objects in setup/teardown since we can create more complicated
objects by using fixture dependencies (eg a service fixture relying on
framework and supplier fixtures etc.).
The fixture is still using DOS for now, but we could change it to create
a test framework with test lots as long as any additional test objects
are created using the fixture dependencies.
|
Python
|
mit
|
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
|
---
+++
@@ -1,9 +1,49 @@
+from __future__ import absolute_import
+
import pytest
from .app import setup, teardown
+
+from app import create_app
+from app.models import db, Framework
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
+
+
+@pytest.fixture(scope='session')
+def app(request):
+ return create_app('test')
+
+
+@pytest.fixture()
+def live_framework(request, app, status='live'):
+ with app.app_context():
+ framework = Framework.query.filter(
+ Framework.slug == 'digital-outcomes-and-specialists'
+ ).first()
+ original_framework_status = framework.status
+ framework.status = status
+
+ db.session.add(framework)
+ db.session.commit()
+
+ def teardown():
+ with app.app_context():
+ framework = Framework.query.filter(
+ Framework.slug == 'digital-outcomes-and-specialists'
+ ).first()
+ framework.status = original_framework_status
+
+ db.session.add(framework)
+ db.session.commit()
+
+ request.addfinalizer(teardown)
+
+
+@pytest.fixture()
+def expired_framework(request, app):
+ return live_framework(request, app, status='expired')
|
95c23b465bc0e0ce0e1ae633ddd1573cfdc997e2
|
unbound_legacy_api/blueprints/stats.py
|
unbound_legacy_api/blueprints/stats.py
|
from flask import Blueprint
from unbound_legacy_api.utils.response import create_response
stats_bp = Blueprint('stats', __name__, url_prefix='/stats')
@stats_bp.route('/ping')
def ping():
"""Generic ping route to check if api is up"""
return create_response(status='success')
|
from flask import Blueprint
from unbound_legacy_api.utils.response import create_response
stats_bp = Blueprint('stats', __name__, url_prefix='/v1/stats')
@stats_bp.route('/ping')
def ping():
"""Generic ping route to check if api is up"""
return create_response(status='success')
|
Add versioning to api routes
|
fix(): Add versioning to api routes
|
Python
|
mit
|
UnboundLegacy/api
|
---
+++
@@ -2,7 +2,7 @@
from unbound_legacy_api.utils.response import create_response
-stats_bp = Blueprint('stats', __name__, url_prefix='/stats')
+stats_bp = Blueprint('stats', __name__, url_prefix='/v1/stats')
@stats_bp.route('/ping')
def ping():
|
9145be89c1a5ba1a2c47bfeef571d40b9eb060bc
|
test/integration/test_user_args.py
|
test/integration/test_user_args.py
|
from . import *
class TestUserArgs(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(
self, os.path.join(examples_dir, '10_custom_args'),
configure=False, *args, **kwargs
)
def test_build_default(self):
self.configure()
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from unnamed!\n')
def test_build_with_args(self):
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
|
from six import assertRegex
from . import *
class TestUserArgs(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(
self, os.path.join(examples_dir, '10_custom_args'),
configure=False, *args, **kwargs
)
def test_build_default(self):
self.configure()
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from unnamed!\n')
def test_build_with_args(self):
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
def test_help(self):
os.chdir(self.srcdir)
output = self.assertPopen(
['bfg9000', 'help', 'configure']
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
def test_help_explicit_srcdir(self):
output = self.assertPopen(
['bfg9000', 'help', 'configure', self.srcdir]
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
|
Add integration test for user-args help
|
Add integration test for user-args help
|
Python
|
bsd-3-clause
|
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
|
---
+++
@@ -1,3 +1,5 @@
+from six import assertRegex
+
from . import *
@@ -17,3 +19,20 @@
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
+
+ def test_help(self):
+ os.chdir(self.srcdir)
+ output = self.assertPopen(
+ ['bfg9000', 'help', 'configure']
+ )
+ assertRegex(self, output, r'(?m)^project-defined arguments:$')
+ assertRegex(self, output,
+ r'(?m)^\s+--name NAME\s+set the name to greet$')
+
+ def test_help_explicit_srcdir(self):
+ output = self.assertPopen(
+ ['bfg9000', 'help', 'configure', self.srcdir]
+ )
+ assertRegex(self, output, r'(?m)^project-defined arguments:$')
+ assertRegex(self, output,
+ r'(?m)^\s+--name NAME\s+set the name to greet$')
|
6a17674897bbb3a44fb2153967e3985dfdb3d5df
|
zounds/learn/graph.py
|
zounds/learn/graph.py
|
import featureflow as ff
from random_samples import ShuffledSamples
from random_samples import InfiniteSampler
from preprocess import PreprocessingPipeline
def learning_pipeline():
class LearningPipeline(ff.BaseModel):
samples = ff.PickleFeature(ff.IteratorNode)
shuffled = ff.PickleFeature(
ShuffledSamples,
nsamples=ff.Var('nsamples'),
dtype=ff.Var('dtype'),
needs=samples)
return LearningPipeline
def infinite_streaming_learning_pipeline(cls):
roots = filter(lambda feature: feature.is_root, cls.features.itervalues())
if len(roots) != 1:
raise ValueError('cls must have a single root feature')
root = roots[0]
class InfiniteLearningPipeline(cls):
dataset = ff.Feature(
InfiniteSampler,
nsamples=ff.Var('nsamples'),
dtype=ff.Var('dtype'))
pipeline = ff.ClobberPickleFeature(
PreprocessingPipeline,
needs=cls.features,
store=True)
@classmethod
def load_network(cls):
if not cls.exists():
raise RuntimeError('No network has been trained or saved')
instance = cls()
for p in instance.pipeline:
try:
return p.network
except AttributeError:
pass
raise RuntimeError('There is no network in the pipeline')
root.needs = InfiniteLearningPipeline.dataset
InfiniteLearningPipeline.__name__ = cls.__name__
InfiniteLearningPipeline.__module__ = cls.__module__
return InfiniteLearningPipeline
|
import featureflow as ff
from random_samples import ShuffledSamples
from random_samples import InfiniteSampler
from preprocess import PreprocessingPipeline
def learning_pipeline():
class LearningPipeline(ff.BaseModel):
samples = ff.PickleFeature(ff.IteratorNode)
shuffled = ff.PickleFeature(
ShuffledSamples,
nsamples=ff.Var('nsamples'),
dtype=ff.Var('dtype'),
needs=samples)
return LearningPipeline
def infinite_streaming_learning_pipeline(cls):
roots = filter(lambda feature: feature.is_root, cls.features.itervalues())
if len(roots) != 1:
raise ValueError('cls must have a single root feature')
root = roots[0]
class InfiniteLearningPipeline(cls):
dataset = ff.Feature(
InfiniteSampler,
nsamples=ff.Var('nsamples'),
dtype=ff.Var('dtype'),
feature_filter=ff.Var('feature_filter'),
parallel=ff.Var('parallel'))
pipeline = ff.ClobberPickleFeature(
PreprocessingPipeline,
needs=cls.features,
store=True)
@classmethod
def load_network(cls):
if not cls.exists():
raise RuntimeError('No network has been trained or saved')
instance = cls()
for p in instance.pipeline:
try:
return p.network
except AttributeError:
pass
raise RuntimeError('There is no network in the pipeline')
root.needs = InfiniteLearningPipeline.dataset
InfiniteLearningPipeline.__name__ = cls.__name__
InfiniteLearningPipeline.__module__ = cls.__module__
return InfiniteLearningPipeline
|
Add a new option allowing client code to turn off parallelism
|
Add a new option allowing client code to turn off parallelism
|
Python
|
mit
|
JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds
|
---
+++
@@ -29,7 +29,9 @@
dataset = ff.Feature(
InfiniteSampler,
nsamples=ff.Var('nsamples'),
- dtype=ff.Var('dtype'))
+ dtype=ff.Var('dtype'),
+ feature_filter=ff.Var('feature_filter'),
+ parallel=ff.Var('parallel'))
pipeline = ff.ClobberPickleFeature(
PreprocessingPipeline,
|
bfaf9d326fc0a2fc72a6f7b6ed92640c3fe9b87b
|
hirlite/__init__.py
|
hirlite/__init__.py
|
from .hirlite import Rlite, HirliteError
from .version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
|
import functools
from hirlite.hirlite import Rlite as RliteExtension, HirliteError
from hirlite.version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
class Rlite(RliteExtension):
def __getattr__(self, command):
return functools.partial(self.command, command)
|
Add support for calling commands by attr access
|
Add support for calling commands by attr access
|
Python
|
bsd-2-clause
|
seppo0010/rlite-py,seppo0010/rlite-py,pombredanne/rlite-py,pombredanne/rlite-py
|
---
+++
@@ -1,4 +1,11 @@
-from .hirlite import Rlite, HirliteError
-from .version import __version__
+import functools
+
+from hirlite.hirlite import Rlite as RliteExtension, HirliteError
+from hirlite.version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
+
+
+class Rlite(RliteExtension):
+ def __getattr__(self, command):
+ return functools.partial(self.command, command)
|
9aef1f357a3319a31bd1995f462eb356011b6a93
|
huxley/shortcuts.py
|
huxley/shortcuts.py
|
# Copyright (c) 2011-2013 Kunal Mehta. All rights reserved.
# Use of this source code is governed by a BSD License found in README.md.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from itertools import izip_longest
def render_template(request, template, context=None):
'''Wrap render_to_response with the context_instance argument set.'''
return render_to_response(template, context,
context_instance=RequestContext(request))
def render_json(data):
'''Return an HttpResponse object containing json-encoded data.'''
return HttpResponse(simplejson.dumps(data), mimetype='application/json')
def pairwise(iterable):
'''Group the elements of the given interable into 2-tuples.'''
i = iter(iterable)
return izip_longest(i, i)
|
# Copyright (c) 2011-2013 Kunal Mehta. All rights reserved.
# Use of this source code is governed by a BSD License found in README.md.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from itertools import izip_longest
def render_template(request, template, context=None):
'''Wrap render_to_response with the context_instance argument set.'''
return render_to_response(template, context,
context_instance=RequestContext(request))
def render_json(data):
'''Return an HttpResponse object containing json-encoded data.'''
return HttpResponse(simplejson.dumps(data), content_type='application/json')
def pairwise(iterable):
'''Group the elements of the given interable into 2-tuples.'''
i = iter(iterable)
return izip_longest(i, i)
|
Change mimetype kwarg to content_type.
|
Change mimetype kwarg to content_type.
|
Python
|
bsd-3-clause
|
nathanielparke/huxley,bmun/huxley,bmun/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,bmun/huxley,bmun/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley,nathanielparke/huxley
|
---
+++
@@ -15,7 +15,7 @@
def render_json(data):
'''Return an HttpResponse object containing json-encoded data.'''
- return HttpResponse(simplejson.dumps(data), mimetype='application/json')
+ return HttpResponse(simplejson.dumps(data), content_type='application/json')
def pairwise(iterable):
'''Group the elements of the given interable into 2-tuples.'''
|
700f6e6ef40a2d33e5678e260f03cd15148e0b3a
|
test/test_parse_file_guess_format.py
|
test/test_parse_file_guess_format.py
|
import unittest
import logging
from pathlib import Path
from shutil import copyfile
from tempfile import TemporaryDirectory
from rdflib.exceptions import ParserError
from rdflib import Graph
class FileParserGuessFormatTest(unittest.TestCase):
def test_ttl(self):
g = Graph()
self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)
def test_n3(self):
g = Graph()
self.assertIsInstance(g.parse("test/n3/example-lots_of_graphs.n3"), Graph)
def test_warning(self):
g = Graph()
graph_logger = logging.getLogger("rdflib")
with TemporaryDirectory() as tmpdirname:
newpath = Path(tmpdirname).joinpath("no_file_ext")
copyfile("test/rdf/Manifest.rdf", str(newpath))
with self.assertLogs(graph_logger, "WARNING"):
with self.assertRaises(ParserError):
g.parse(str(newpath))
if __name__ == "__main__":
unittest.main()
|
import unittest
import logging
from pathlib import Path
from shutil import copyfile
from tempfile import TemporaryDirectory
from rdflib.exceptions import ParserError
from rdflib import Graph
class FileParserGuessFormatTest(unittest.TestCase):
def test_jsonld(self):
g = Graph()
self.assertIsInstance(g.parse("test/jsonld/1.1/manifest.jsonld"), Graph)
def test_ttl(self):
g = Graph()
self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)
def test_n3(self):
g = Graph()
self.assertIsInstance(g.parse("test/n3/example-lots_of_graphs.n3"), Graph)
def test_warning(self):
g = Graph()
graph_logger = logging.getLogger("rdflib")
with TemporaryDirectory() as tmpdirname:
newpath = Path(tmpdirname).joinpath("no_file_ext")
copyfile("test/rdf/Manifest.rdf", str(newpath))
with self.assertLogs(graph_logger, "WARNING"):
with self.assertRaises(ParserError):
g.parse(str(newpath))
if __name__ == "__main__":
unittest.main()
|
Add test for adding JSON-LD to guess_format()
|
Add test for adding JSON-LD to guess_format()
This is a follow-on patch to:
e778e9413510721c2fedaae56d4ff826df265c30
Test was confirmed to pass by running this on the current `master`
branch, and confirmed to fail with e778e941 reverted.
nosetests test/test_parse_file_guess_format.py
Signed-off-by: Alex Nelson <d5aca716d6ed55a86fa350cb5231ca56b21085ca@nist.gov>
|
Python
|
bsd-3-clause
|
RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib
|
---
+++
@@ -10,6 +10,10 @@
class FileParserGuessFormatTest(unittest.TestCase):
+ def test_jsonld(self):
+ g = Graph()
+ self.assertIsInstance(g.parse("test/jsonld/1.1/manifest.jsonld"), Graph)
+
def test_ttl(self):
g = Graph()
self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)
|
24c8122db0f38a1f798461a23d08535e4e6781d5
|
photo/idxitem.py
|
photo/idxitem.py
|
"""Provide the class IdxItem which represents an item in the index.
"""
import hashlib
def _md5file(fname):
"""Calculate the md5 hash for a file.
"""
m = hashlib.md5()
chunksize = 8192
with open(fname, 'rb') as f:
while True:
chunk = f.read(chunksize)
if not chunk:
break
m.update(chunk)
return m.hexdigest()
class IdxItem(object):
def __init__(self, filename=None, data=None):
self.filename = None
self.tags = []
if data is not None:
self.__dict__.update(data)
elif filename is not None:
self.filename = filename
self.md5 = _md5file(filename)
def as_dict(self):
return dict(self.__dict__)
|
"""Provide the class IdxItem which represents an item in the index.
"""
import hashlib
def _md5file(fname):
"""Calculate the md5 hash for a file.
"""
m = hashlib.md5()
chunksize = 8192
with open(fname, 'rb') as f:
while True:
chunk = f.read(chunksize)
if not chunk:
break
m.update(chunk)
return m.hexdigest()
class IdxItem(object):
def __init__(self, filename=None, data=None):
self.filename = None
self.tags = []
if data is not None:
self.__dict__.update(data)
elif filename is not None:
self.filename = filename
self.md5 = _md5file(filename)
self.tags = set(self.tags)
def as_dict(self):
d = self.__dict__.copy()
d['tags'] = list(d['tags'])
return d
|
Convert tags to a set on init and back to a list on writing.
|
Convert tags to a set on init and back to a list on writing.
|
Python
|
apache-2.0
|
RKrahl/photo-tools
|
---
+++
@@ -28,6 +28,9 @@
elif filename is not None:
self.filename = filename
self.md5 = _md5file(filename)
+ self.tags = set(self.tags)
def as_dict(self):
- return dict(self.__dict__)
+ d = self.__dict__.copy()
+ d['tags'] = list(d['tags'])
+ return d
|
a75dbd5aa5e9b84d08919ea14743afb75182ee8b
|
steel/chunks/iff.py
|
steel/chunks/iff.py
|
import collections
import io
from steel.fields.numbers import BigEndian
from steel import fields
from steel.chunks import base
__all__ = ['Chunk', 'ChunkList', 'Form']
class Chunk(base.Chunk):
id = fields.String(size=4, encoding='ascii')
size = fields.Integer(size=4, endianness=BigEndian)
payload = base.Payload(size=size)
class ChunkList(base.ChunkList):
def __init__(self, *args, **kwargs):
# Just a simple override to default to a list of IFF chunks
return super(ChunkList, self).__init__(Chunk, *args, **kwargs)
class Form(base.Chunk, encoding='ascii'):
tag = fields.FixedString('FORM')
size = fields.Integer(size=4, endianness=BigEndian)
id = fields.String(size=4)
payload = base.Payload(size=size)
|
import collections
import io
from steel.fields.numbers import BigEndian
from steel import fields
from steel.chunks import base
__all__ = ['Chunk', 'ChunkList', 'List', 'Form', 'Prop']
class Chunk(base.Chunk):
id = fields.String(size=4, encoding='ascii')
size = fields.Integer(size=4, endianness=BigEndian)
payload = base.Payload(size=size)
class ChunkList(base.ChunkList):
def __init__(self, *args, **kwargs):
# Just a simple override to default to a list of IFF chunks
return super(ChunkList, self).__init__(Chunk, *args, **kwargs)
class List(base.Chunk, encoding='ascii'):
tag = fields.FixedString('LIST')
size = fields.Integer(size=4, endianness=BigEndian)
id = fields.String(size=4)
payload = base.Payload(size=size)
class Form(base.Chunk, encoding='ascii'):
tag = fields.FixedString('FORM')
size = fields.Integer(size=4, endianness=BigEndian)
id = fields.String(size=4)
payload = base.Payload(size=size)
class Prop(base.Chunk, encoding='ascii'):
tag = fields.FixedString('PROP')
size = fields.Integer(size=4, endianness=BigEndian)
id = fields.String(size=4)
payload = base.Payload(size=size)
|
Add a List and Prop for better IFF compliance
|
Add a List and Prop for better IFF compliance
|
Python
|
bsd-3-clause
|
gulopine/steel
|
---
+++
@@ -5,7 +5,7 @@
from steel import fields
from steel.chunks import base
-__all__ = ['Chunk', 'ChunkList', 'Form']
+__all__ = ['Chunk', 'ChunkList', 'List', 'Form', 'Prop']
class Chunk(base.Chunk):
@@ -20,6 +20,13 @@
return super(ChunkList, self).__init__(Chunk, *args, **kwargs)
+class List(base.Chunk, encoding='ascii'):
+ tag = fields.FixedString('LIST')
+ size = fields.Integer(size=4, endianness=BigEndian)
+ id = fields.String(size=4)
+ payload = base.Payload(size=size)
+
+
class Form(base.Chunk, encoding='ascii'):
tag = fields.FixedString('FORM')
size = fields.Integer(size=4, endianness=BigEndian)
@@ -27,3 +34,10 @@
payload = base.Payload(size=size)
+class Prop(base.Chunk, encoding='ascii'):
+ tag = fields.FixedString('PROP')
+ size = fields.Integer(size=4, endianness=BigEndian)
+ id = fields.String(size=4)
+ payload = base.Payload(size=size)
+
+
|
376fa8dead817ae0b1e1e97547d7c95858b1fb0e
|
cairis/data/ImportDAO.py
|
cairis/data/ImportDAO.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from cairis.core.ARM import *
from cairis.daemon.CairisHTTPError import CairisHTTPError, ARMHTTPError
from cairis.data.CairisDAO import CairisDAO
from cairis.bin.cimport import file_import
__author__ = 'Shamal Faily'
class ImportDAO(CairisDAO):
def __init__(self, session_id):
CairisDAO.__init__(self, session_id)
def file_import(self,importFile,mFormat,overwriteFlag):
try:
file_import(importFile,mFormat,overwriteFlag,self.session_id)
except DatabaseProxyException as ex:
self.close()
raise ARMHTTPError(ex)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from cairis.core.ARM import *
from cairis.daemon.CairisHTTPError import CairisHTTPError, ARMHTTPError
from cairis.data.CairisDAO import CairisDAO
from cairis.bin.cimport import file_import
__author__ = 'Shamal Faily'
class ImportDAO(CairisDAO):
def __init__(self, session_id):
CairisDAO.__init__(self, session_id)
def file_import(self,importFile,mFormat,overwriteFlag):
try:
return file_import(importFile,mFormat,overwriteFlag,self.session_id)
except DatabaseProxyException as ex:
self.close()
raise ARMHTTPError(ex)
|
Fix problems identified by broken test
|
Fix problems identified by broken test
|
Python
|
apache-2.0
|
nathanbjenx/cairis,failys/CAIRIS,failys/CAIRIS,nathanbjenx/cairis,nathanbjenx/cairis,nathanbjenx/cairis,failys/CAIRIS
|
---
+++
@@ -30,7 +30,7 @@
def file_import(self,importFile,mFormat,overwriteFlag):
try:
- file_import(importFile,mFormat,overwriteFlag,self.session_id)
+ return file_import(importFile,mFormat,overwriteFlag,self.session_id)
except DatabaseProxyException as ex:
self.close()
raise ARMHTTPError(ex)
|
15ebd5a3509b20bad4cf0123dfac9be6878fa91c
|
app/models/bookmarks.py
|
app/models/bookmarks.py
|
from flask import current_app
from .. import db, login_manager
class Bookmarks(db.Model):
id = db.Column(db.Integer, primary_key=True)
listing_id = db.Column(db.Integer, unique=True)
merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) #also needs to be added to Hunter's Vendors model
def __init__(self, listing_id, merchant_id):
self.listing_id = listing_id
self.merchant_id = merchant_id
def __repr__(self):
return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id)
|
from flask import current_app
from .. import db, login_manager
class Bookmarks(db.Model):
id = db.Column(db.Integer, primary_key=True)
listing_id = db.Column(db.Integer, unique=True)
merchant_id = db.Column(db.Integer, db.ForeignKey('user.id'))
merchant = db.relationship('User', backref=db.backref('bookmarks', lazy='dynamic'))
def __init__(self, listing_id, merchant):
self.listing_id = listing_id
self.merchant = merchant
def __repr__(self):
return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id)
|
Set up the relationship between bookmark and merchant
|
Set up the relationship between bookmark and merchant
|
Python
|
mit
|
hack4impact/reading-terminal-market,hack4impact/reading-terminal-market,hack4impact/reading-terminal-market
|
---
+++
@@ -4,11 +4,12 @@
class Bookmarks(db.Model):
id = db.Column(db.Integer, primary_key=True)
listing_id = db.Column(db.Integer, unique=True)
- merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) #also needs to be added to Hunter's Vendors model
+ merchant_id = db.Column(db.Integer, db.ForeignKey('user.id'))
+ merchant = db.relationship('User', backref=db.backref('bookmarks', lazy='dynamic'))
- def __init__(self, listing_id, merchant_id):
+ def __init__(self, listing_id, merchant):
self.listing_id = listing_id
- self.merchant_id = merchant_id
+ self.merchant = merchant
def __repr__(self):
return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id)
|
c8aca84619493cd75cb12b2fc63dc4dccb158032
|
common/lib/chem/setup.py
|
common/lib/chem/setup.py
|
from setuptools import setup
setup(
name="chem",
version="0.1.1",
packages=["chem"],
install_requires=[
"pyparsing==2.0.7",
"numpy==1.6.2",
"scipy==0.14.0",
"nltk==3.2.5",
],
)
|
from setuptools import setup
setup(
name="chem",
version="0.1.2",
packages=["chem"],
install_requires=[
"pyparsing==2.0.7",
"numpy==1.6.2",
"scipy==0.14.0",
"nltk==3.2.5",
],
)
|
Update chem version to force new nltk requirement to be picked up
|
Update chem version to force new nltk requirement to be picked up
|
Python
|
agpl-3.0
|
procangroup/edx-platform,teltek/edx-platform,kmoocdev2/edx-platform,eduNEXT/edunext-platform,a-parhom/edx-platform,edx-solutions/edx-platform,a-parhom/edx-platform,gymnasium/edx-platform,Edraak/edraak-platform,appsembler/edx-platform,edx-solutions/edx-platform,ahmedaljazzar/edx-platform,kmoocdev2/edx-platform,eduNEXT/edx-platform,proversity-org/edx-platform,eduNEXT/edunext-platform,arbrandes/edx-platform,cpennington/edx-platform,arbrandes/edx-platform,stvstnfrd/edx-platform,proversity-org/edx-platform,angelapper/edx-platform,cpennington/edx-platform,ahmedaljazzar/edx-platform,Edraak/edraak-platform,appsembler/edx-platform,msegado/edx-platform,CredoReference/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,jolyonb/edx-platform,ESOedX/edx-platform,stvstnfrd/edx-platform,stvstnfrd/edx-platform,Edraak/edraak-platform,TeachAtTUM/edx-platform,proversity-org/edx-platform,eduNEXT/edx-platform,proversity-org/edx-platform,arbrandes/edx-platform,a-parhom/edx-platform,philanthropy-u/edx-platform,procangroup/edx-platform,gsehub/edx-platform,Edraak/edraak-platform,eduNEXT/edunext-platform,BehavioralInsightsTeam/edx-platform,procangroup/edx-platform,gsehub/edx-platform,CredoReference/edx-platform,gymnasium/edx-platform,jolyonb/edx-platform,gymnasium/edx-platform,cpennington/edx-platform,edx/edx-platform,ahmedaljazzar/edx-platform,Stanford-Online/edx-platform,TeachAtTUM/edx-platform,EDUlib/edx-platform,appsembler/edx-platform,EDUlib/edx-platform,edx-solutions/edx-platform,philanthropy-u/edx-platform,procangroup/edx-platform,mitocw/edx-platform,eduNEXT/edunext-platform,msegado/edx-platform,gymnasium/edx-platform,mitocw/edx-platform,philanthropy-u/edx-platform,TeachAtTUM/edx-platform,ESOedX/edx-platform,arbrandes/edx-platform,edx-solutions/edx-platform,ESOedX/edx-platform,EDUlib/edx-platform,stvstnfrd/edx-platform,BehavioralInsightsTeam/edx-platform,gsehub/edx-platform,appsembler/edx-platform,cpennington/edx-platform,msegado/edx-platform,eduNEXT/edx-platform,kmoocdev2/edx-platform,angelapper/edx-platform,CredoReference/edx-platform,msegado/edx-platform,mitocw/edx-platform,TeachAtTUM/edx-platform,angelapper/edx-platform,EDUlib/edx-platform,a-parhom/edx-platform,teltek/edx-platform,BehavioralInsightsTeam/edx-platform,kmoocdev2/edx-platform,edx/edx-platform,jolyonb/edx-platform,teltek/edx-platform,edx/edx-platform,ahmedaljazzar/edx-platform,msegado/edx-platform,eduNEXT/edx-platform,CredoReference/edx-platform,BehavioralInsightsTeam/edx-platform,edx/edx-platform,ESOedX/edx-platform,Stanford-Online/edx-platform,mitocw/edx-platform,teltek/edx-platform,philanthropy-u/edx-platform,angelapper/edx-platform,gsehub/edx-platform,kmoocdev2/edx-platform,jolyonb/edx-platform
|
---
+++
@@ -2,7 +2,7 @@
setup(
name="chem",
- version="0.1.1",
+ version="0.1.2",
packages=["chem"],
install_requires=[
"pyparsing==2.0.7",
|
013fa911c7b882a0b362549d4d9b1f9e1e688bc8
|
violations/py_unittest.py
|
violations/py_unittest.py
|
import re
from django.template.loader import render_to_string
from tasks.const import STATUS_SUCCESS, STATUS_FAILED
from .base import library
@library.register('py_unittest')
def py_unittest_violation(data):
"""Python unittest violation parser"""
lines = data['raw'].split('\n')
line = ''
while len(lines) and not line.startswith('Ran'):
line = lines.pop(0)
summary = line
status = lines.pop(1)
data['status'] =\
STATUS_SUCCESS if status.find('OK') == 0 else STATUS_FAILED
data['preview'] = render_to_string('violations/py_tests/preview.html', {
'summary': summary,
'status': status,
})
data['prepared'] = render_to_string('violations/py_tests/prepared.html', {
'raw': data['raw'],
})
plot = {'failures': 0, 'errors': 0}
fail_match = re.match(r'.*failures=(\d*).*', status)
if fail_match:
plot['failures'] = int(fail_match.groups()[0])
error_match = re.match(r'.*errors=(\d*).*', status)
if error_match:
plot['errors'] = int(error_match.groups()[0])
data['plot'] = plot
return data
|
import re
from django.template.loader import render_to_string
from tasks.const import STATUS_SUCCESS, STATUS_FAILED
from .base import library
@library.register('py_unittest')
def py_unittest_violation(data):
"""Python unittest violation parser"""
lines = data['raw'].split('\n')
line = ''
while len(lines) and not line.startswith('Ran'):
line = lines.pop(0)
summary = line
status = lines.pop(1)
data['status'] =\
STATUS_SUCCESS if status.find('OK') == 0 else STATUS_FAILED
data['preview'] = render_to_string('violations/py_tests/preview.html', {
'summary': summary,
'status': status,
})
data['prepared'] = render_to_string('violations/py_tests/prepared.html', {
'raw': data['raw'],
})
plot = {'failures': 0, 'errors': 0}
fail_match = re.match(r'.*failures=(\d*).*', status)
if fail_match:
plot['failures'] = int(fail_match.groups()[0])
error_match = re.match(r'.*errors=(\d*).*', status)
if error_match:
plot['errors'] = int(error_match.groups()[0])
total_match = re.match(r'Ran (\d*) tests .*', summary)
if total_match:
plot['test_count'] = int(total_match.groups()[0])
data['plot'] = plot
return data
|
Add total tests count to py unittest graph
|
Add total tests count to py unittest graph
|
Python
|
mit
|
nvbn/coviolations_web,nvbn/coviolations_web
|
---
+++
@@ -33,6 +33,9 @@
error_match = re.match(r'.*errors=(\d*).*', status)
if error_match:
plot['errors'] = int(error_match.groups()[0])
+ total_match = re.match(r'Ran (\d*) tests .*', summary)
+ if total_match:
+ plot['test_count'] = int(total_match.groups()[0])
data['plot'] = plot
return data
|
1c627347a55faadc28cd975d313ec45a84fcba21
|
freetalks/__init__.py
|
freetalks/__init__.py
|
import webapp2
from freetalks import handler
application = webapp2.WSGIApplication([
webapp2.Route(r'/', handler.general.Home, 'home'),
webapp2.Route(r'/talk/<talk:[a-z\d-]*>', handler.talk.Display, 'talk-display'),
])
|
import webapp2
from freetalks import handler
application = webapp2.WSGIApplication([
webapp2.Route(r'/', handler.general.Home, 'home'),
webapp2.Route(r'/talk/<talk:[\w]+>', handler.talk.Display, 'talk-display'),
])
|
Make generic more liberal although it doesn't match all valid keys
|
Make generic more liberal although it doesn't match all valid keys
|
Python
|
mit
|
preichenberger/freetalks,preichenberger/freetalks
|
---
+++
@@ -3,5 +3,5 @@
application = webapp2.WSGIApplication([
webapp2.Route(r'/', handler.general.Home, 'home'),
- webapp2.Route(r'/talk/<talk:[a-z\d-]*>', handler.talk.Display, 'talk-display'),
+ webapp2.Route(r'/talk/<talk:[\w]+>', handler.talk.Display, 'talk-display'),
])
|
83c79251b5040e18c5c8ac65a5e140e59edc4d3f
|
test_readability.py
|
test_readability.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import readability
import unittest
good_code = """
def this_is_some_good_code(var):
for i in range(10):
print(i)
"""
bad_code = """
tisgc = lambda var: [print(i) for i in range(10)]
"""
apl_code = u"""
life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
"""
class TestReadability(unittest.TestCase):
def setUp(self):
pass
def test_good_better_than_bad(self):
good_score = readability.score(good_code)
bad_score = readability.score(bad_code)
apl_score = readability.score(apl_code)
self.assertTrue(good_score < bad_score < apl_score)
def test_ignore_pattern(self):
self.assertFalse(readability.EXT_RE.match("abc.py"))
self.assertTrue(readability.EXT_RE.match("abc.pyc"))
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import readability
import unittest
good_code = """
def this_is_some_good_code(var):
for i in range(10):
print(i)
"""
bad_code = """
tisgc = lambda var: [print(i) for i in range(10)]
"""
# taken from http://en.wikipedia.org/wiki/APL_%28programming_language%29#Examples
apl_code = u"""
life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
"""
class TestReadability(unittest.TestCase):
def setUp(self):
pass
def test_good_better_than_bad(self):
good_score = readability.score(good_code)
bad_score = readability.score(bad_code)
apl_score = readability.score(apl_code)
self.assertTrue(good_score < bad_score < apl_score)
def test_ignore_pattern(self):
self.assertFalse(readability.EXT_RE.match("abc.py"))
self.assertTrue(readability.EXT_RE.match("abc.pyc"))
if __name__ == '__main__':
unittest.main()
|
Test APL code should give credit to Wikipedia
|
Test APL code should give credit to Wikipedia
|
Python
|
mit
|
swenson/readability
|
---
+++
@@ -14,6 +14,7 @@
tisgc = lambda var: [print(i) for i in range(10)]
"""
+# taken from http://en.wikipedia.org/wiki/APL_%28programming_language%29#Examples
apl_code = u"""
life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
"""
|
db03af21b3f46e5f5af89ccf224bc2bf4b9f6d9b
|
zephyr/projects/herobrine/BUILD.py
|
zephyr/projects/herobrine/BUILD.py
|
# Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def register_variant(project_name, extra_dts_overlays=(), extra_kconfig_files=()):
register_npcx_project(
project_name=project_name,
zephyr_board="npcx9",
dts_overlays=[
# Common to all projects.
here / "adc.dts",
here / "battery.dts",
here / "gpio.dts",
here / "common.dts",
here / "i2c.dts",
here / "interrupts.dts",
here / "motionsense.dts",
here / "pwm.dts",
here / "switchcap.dts",
here / "usbc.dts",
# Project-specific DTS customization.
*extra_dts_overlays,
],
kconfig_files=[
# Common to all projects.
here / "prj.conf",
# Project-specific KConfig customization.
*extra_kconfig_files,
],
)
register_variant(
project_name="herobrine_npcx9",
)
register_variant(
project_name="hoglin",
extra_kconfig_files=[here / "prj_hoglin.conf"],
)
|
# Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def register_variant(project_name, extra_dts_overlays=(), extra_kconfig_files=()):
register_npcx_project(
project_name=project_name,
zephyr_board="npcx9",
dts_overlays=[
# Common to all projects.
here / "adc.dts",
here / "battery.dts",
here / "gpio.dts",
here / "common.dts",
here / "i2c.dts",
here / "interrupts.dts",
here / "motionsense.dts",
here / "pwm.dts",
here / "switchcap.dts",
here / "usbc.dts",
# Project-specific DTS customization.
*extra_dts_overlays,
],
kconfig_files=[
# Common to all projects.
here / "prj.conf",
# Project-specific KConfig customization.
*extra_kconfig_files,
],
)
register_variant(
project_name="herobrine_npcx9",
extra_kconfig_files=[here / "prj_herobrine_npcx9.conf"],
)
register_variant(
project_name="hoglin",
extra_kconfig_files=[here / "prj_hoglin.conf"],
)
|
Include the missing project config
|
herobrine: Include the missing project config
Need to include the project config prj_herobrine_npcx9.conf to
the build. It defines CONFIG_BOARD_HEROBRINE_NPCX9=y. The board
specific alternative component code (alt_dev_replacement.c)
requires this Kconfig option.
BRANCH=None
BUG=b:216836197
TEST=Booted the herobrine_npcx9 image. No PPC access error and
PD message loop.
Change-Id: I73a9987ff49a4dfb346ebe7c994418278817c03b
Signed-off-by: Wai-Hong Tam <04b587fdf5845741a0c5a8b9cd59ca72d73ef8fc@google.com>
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/ec/+/3422771
Reviewed-by: Keith Short <f6d578f97033c25f1206cb57d52f358974c82954@chromium.org>
|
Python
|
bsd-3-clause
|
coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec
|
---
+++
@@ -33,6 +33,7 @@
register_variant(
project_name="herobrine_npcx9",
+ extra_kconfig_files=[here / "prj_herobrine_npcx9.conf"],
)
|
f2ca059d6e3e9e593b053e6483ad071d58cc99d2
|
tests/core/admin.py
|
tests/core/admin.py
|
from django.contrib import admin
from import_export.admin import ImportExportMixin
from .models import Book, Category, Author
class BookAdmin(ImportExportMixin, admin.ModelAdmin):
pass
admin.site.register(Book, BookAdmin)
admin.site.register(Category)
admin.site.register(Author)
|
from django.contrib import admin
from import_export.admin import ImportExportMixin
from .models import Book, Category, Author
class BookAdmin(ImportExportMixin, admin.ModelAdmin):
list_filter = ['categories', 'author']
admin.site.register(Book, BookAdmin)
admin.site.register(Category)
admin.site.register(Author)
|
Add BookAdmin options in test app
|
Add BookAdmin options in test app
|
Python
|
bsd-2-clause
|
PetrDlouhy/django-import-export,copperleaftech/django-import-export,Akoten/django-import-export,daniell/django-import-export,pajod/django-import-export,piran/django-import-export,bmihelac/django-import-export,sergei-maertens/django-import-export,bmihelac/django-import-export,PetrDlouhy/django-import-export,copperleaftech/django-import-export,SalahAdDin/django-import-export,piran/django-import-export,ericdwang/django-import-export,ericdwang/django-import-export,bmihelac/django-import-export,daniell/django-import-export,bmihelac/django-import-export,django-import-export/django-import-export,rhunwicks/django-import-export,manelclos/django-import-export,SalahAdDin/django-import-export,copperleaftech/django-import-export,luto/django-import-export,Akoten/django-import-export,PetrDlouhy/django-import-export,daniell/django-import-export,brillgen/django-import-export,PetrDlouhy/django-import-export,Apkawa/django-import-export,luto/django-import-export,ylteq/dj-import-export,pajod/django-import-export,brillgen/django-import-export,jnns/django-import-export,sergei-maertens/django-import-export,brillgen/django-import-export,copperleaftech/django-import-export,Apkawa/django-import-export,brillgen/django-import-export,piran/django-import-export,ylteq/dj-import-export,daniell/django-import-export,jnns/django-import-export,jnns/django-import-export,django-import-export/django-import-export,rhunwicks/django-import-export,SalahAdDin/django-import-export,pajod/django-import-export,ericdwang/django-import-export,Akoten/django-import-export,jnns/django-import-export,luto/django-import-export,manelclos/django-import-export,pajod/django-import-export,django-import-export/django-import-export,manelclos/django-import-export,rhunwicks/django-import-export,Apkawa/django-import-export,django-import-export/django-import-export,sergei-maertens/django-import-export,ylteq/dj-import-export
|
---
+++
@@ -6,7 +6,7 @@
class BookAdmin(ImportExportMixin, admin.ModelAdmin):
- pass
+ list_filter = ['categories', 'author']
admin.site.register(Book, BookAdmin)
|
25c56d4c68ec484b47ef320cfb46601c4435470b
|
tests/test_crc32.py
|
tests/test_crc32.py
|
import hmac
import unittest
from twoping import crc32
class TestCRC32(unittest.TestCase):
def test_crc32(self):
c = crc32.new()
c.update(b"Data to hash")
self.assertEqual(c.digest(), b"\x44\x9e\x0a\x5c")
def test_hmac(self):
h = hmac.new(b"Secret key", b"Data to hash", crc32)
self.assertEqual(h.digest(), b"\x3c\xe1\xb6\xb9")
if __name__ == "__main__":
unittest.main()
|
import hmac
import unittest
from twoping import crc32
class TestCRC32(unittest.TestCase):
def test_crc32(self):
c = crc32.new(b"Data to hash")
self.assertEqual(c.digest(), b"\x44\x9e\x0a\x5c")
def test_hmac(self):
h = hmac.new(b"Secret key", b"Data to hash", crc32)
self.assertEqual(h.digest(), b"\x3c\xe1\xb6\xb9")
def test_update(self):
c = crc32.new()
c.update(b"Data to hash")
self.assertEqual(c.digest(), b"\x44\x9e\x0a\x5c")
def test_hexdigest(self):
c = crc32.new(b"Data to hash")
self.assertEqual(c.hexdigest(), "449e0a5c")
def test_clear(self):
c = crc32.new(b"Data to hash")
c.clear()
self.assertEqual(c.digest(), b"\x00\x00\x00\x00")
def test_zero_padding(self):
c = crc32.new(b"jade")
self.assertEqual(c.digest(), b"\x00\x83\x52\x18")
if __name__ == "__main__":
unittest.main()
|
Increase test coverage on crc32
|
Increase test coverage on crc32
|
Python
|
mpl-2.0
|
rfinnie/2ping,rfinnie/2ping
|
---
+++
@@ -6,14 +6,31 @@
class TestCRC32(unittest.TestCase):
def test_crc32(self):
- c = crc32.new()
- c.update(b"Data to hash")
+ c = crc32.new(b"Data to hash")
self.assertEqual(c.digest(), b"\x44\x9e\x0a\x5c")
def test_hmac(self):
h = hmac.new(b"Secret key", b"Data to hash", crc32)
self.assertEqual(h.digest(), b"\x3c\xe1\xb6\xb9")
+ def test_update(self):
+ c = crc32.new()
+ c.update(b"Data to hash")
+ self.assertEqual(c.digest(), b"\x44\x9e\x0a\x5c")
+
+ def test_hexdigest(self):
+ c = crc32.new(b"Data to hash")
+ self.assertEqual(c.hexdigest(), "449e0a5c")
+
+ def test_clear(self):
+ c = crc32.new(b"Data to hash")
+ c.clear()
+ self.assertEqual(c.digest(), b"\x00\x00\x00\x00")
+
+ def test_zero_padding(self):
+ c = crc32.new(b"jade")
+ self.assertEqual(c.digest(), b"\x00\x83\x52\x18")
+
if __name__ == "__main__":
unittest.main()
|
096e41266ac3686c1757fc4b5087e3b786287f91
|
webapp/byceps/database.py
|
webapp/byceps/database.py
|
# -*- coding: utf-8 -*-
"""
byceps.database
~~~~~~~~~~~~~~~
Database utilities.
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
import uuid
from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID
db = SQLAlchemy()
db.Uuid = UUID
def generate_uuid():
"""Generate a random UUID (Universally Unique IDentifier)."""
return uuid.uuid4()
|
# -*- coding: utf-8 -*-
"""
byceps.database
~~~~~~~~~~~~~~~
Database utilities.
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
import uuid
from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID
db = SQLAlchemy(session_options={'autoflush': False})
db.Uuid = UUID
def generate_uuid():
"""Generate a random UUID (Universally Unique IDentifier)."""
return uuid.uuid4()
|
Disable autoflushing as introduced with Flask-SQLAlchemy 2.0.
|
Disable autoflushing as introduced with Flask-SQLAlchemy 2.0.
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
|
---
+++
@@ -15,7 +15,7 @@
from sqlalchemy.dialects.postgresql import UUID
-db = SQLAlchemy()
+db = SQLAlchemy(session_options={'autoflush': False})
db.Uuid = UUID
|
a393881b4cf79a34101c7d4821ed0ccd78f117cb
|
zsh/zsh_concat.py
|
zsh/zsh_concat.py
|
#!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------------------
{data}
# -------------------------------------------------------------------------------
# END
# -------------------------------------------------------------------------------
"""
def read_and_format_data(filename, outbuf):
"""
Read file and format
Args:
filename
Returns:
str
:param outbuf:
"""
with open(filename, 'r') as inbuf:
data = inbuf.read()
data = filename_template.format(filename=filename,
data=data)
outbuf.write(data)
def main(args):
parent_dir = Path(args[0]).parent
lib_dir = parent_dir.joinpath('lib')
hostname = uname()[1]
local_dir = parent_dir.joinpath('local')
with open('zsh_plugins.zsh', 'w') as outbuf:
for filename in scandir(str(lib_dir)):
read_and_format_data(filename.path, outbuf)
for filename in scandir(str(local_dir)):
filename = Path(filename.path)
if filename.stem == hostname:
read_and_format_data(str(filename), outbuf)
if __name__ == "__main__":
main(argv)
|
#!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------------------
{data}
# -------------------------------------------------------------------------------
# END
# -------------------------------------------------------------------------------
"""
def read_and_format_data(filename, outbuf):
"""
Read file and format
Args:
filename:
Returns:
str
"""
with open(filename, 'r') as inbuf:
data = inbuf.read()
data = filename_template.format(filename=filename,
data=data)
outbuf.write(data)
def main(args):
parent_dir = Path(args[0]).parent
lib_dir = parent_dir.joinpath('lib')
hostname = uname()[1]
local_dir = parent_dir.joinpath('local')
outfilename = parent_dir.joinpath("zsh_plugins.zsh")
with open(str(outfilename), 'w') as outbuf:
for filename in scandir(str(lib_dir)):
read_and_format_data(filename.path, outbuf)
for filename in scandir(str(local_dir)):
filename = Path(filename.path)
if filename.stem == hostname:
read_and_format_data(str(filename), outbuf)
if __name__ == "__main__":
main(argv)
|
Fix script to save output to script’s directory.
|
Fix script to save output to script’s directory.
|
Python
|
mit
|
skk/dotfiles,skk/dotfiles
|
---
+++
@@ -22,11 +22,10 @@
Read file and format
Args:
- filename
+ filename:
Returns:
str
- :param outbuf:
"""
@@ -43,7 +42,9 @@
hostname = uname()[1]
local_dir = parent_dir.joinpath('local')
- with open('zsh_plugins.zsh', 'w') as outbuf:
+ outfilename = parent_dir.joinpath("zsh_plugins.zsh")
+
+ with open(str(outfilename), 'w') as outbuf:
for filename in scandir(str(lib_dir)):
read_and_format_data(filename.path, outbuf)
|
ee32d3746a9fa788a06931063a8242f936b6ed18
|
src/data/meta.py
|
src/data/meta.py
|
import collections
class Meta(collections.OrderedDict):
def __init__(self, *args, **kwargs):
self._smallest = float('inf')
self._largest = 0
self._ordered = True
super(Meta, self).__init__(*args, **kwargs)
def __setitem__(self, key, value, *args, **kwargs):
if key in self and self[key] == value:
raise AssertionError('Redundant assignment')
if value > self._smallest:
self._ordered = False
else:
self._smallest = value
if value > self._largest:
self._largest = value
super(Meta, self).__setitem__(key, value, *args, **kwargs)
self._changed()
def items(self):
self._reorder()
return super(Meta, self).items()
def first(self):
self._reorder()
for k, v in self.items():
return k, v
def peek(self):
self._reorder()
for first in self:
return first
def magnitude(self):
return self._largest
def _reorder(self):
if self._ordered:
return
order = sorted(super(Meta, self).items(), key=lambda x: x[1], reverse=True)
for k, v in order:
self.move_to_end(k)
self._ordered = True
def _changed(self):
pass
|
import collections
import typing
class Meta(collections.OrderedDict, typing.MutableMapping[str, float]):
def __init__(self, *args, **kwargs) -> None:
self._smallest = float('inf')
self._largest = 0
self._ordered = True
super(Meta, self).__init__(*args, **kwargs)
def __setitem__(self, key: str, value: float) -> None:
if key in self and self[key] == value:
raise AssertionError('Redundant assignment')
if value > self._smallest:
self._ordered = False
else:
self._smallest = value
if value > self._largest:
self._largest = value
super(Meta, self).__setitem__(key, value)
self._changed()
def items(self) -> typing.ItemsView[str, float]:
self._reorder()
return super(Meta, self).items()
def first(self) -> typing.Tuple[str, float]:
self._reorder()
for k, v in self.items():
return k, v
def peek(self) -> str:
self._reorder()
for first in self:
return first
def magnitude(self) -> float:
return self._largest
def _reorder(self) -> None:
if self._ordered:
return
order = sorted(super(Meta, self).items(), key=lambda x: x[1], reverse=True)
for k, v in order:
self.move_to_end(k)
self._ordered = True
def _changed(self):
pass
|
Add typing information to Meta.
|
Add typing information to Meta.
|
Python
|
mit
|
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
|
---
+++
@@ -1,14 +1,15 @@
import collections
+import typing
-class Meta(collections.OrderedDict):
- def __init__(self, *args, **kwargs):
+class Meta(collections.OrderedDict, typing.MutableMapping[str, float]):
+ def __init__(self, *args, **kwargs) -> None:
self._smallest = float('inf')
self._largest = 0
self._ordered = True
super(Meta, self).__init__(*args, **kwargs)
- def __setitem__(self, key, value, *args, **kwargs):
+ def __setitem__(self, key: str, value: float) -> None:
if key in self and self[key] == value:
raise AssertionError('Redundant assignment')
if value > self._smallest:
@@ -17,27 +18,27 @@
self._smallest = value
if value > self._largest:
self._largest = value
- super(Meta, self).__setitem__(key, value, *args, **kwargs)
+ super(Meta, self).__setitem__(key, value)
self._changed()
- def items(self):
+ def items(self) -> typing.ItemsView[str, float]:
self._reorder()
return super(Meta, self).items()
- def first(self):
+ def first(self) -> typing.Tuple[str, float]:
self._reorder()
for k, v in self.items():
return k, v
- def peek(self):
+ def peek(self) -> str:
self._reorder()
for first in self:
return first
- def magnitude(self):
+ def magnitude(self) -> float:
return self._largest
- def _reorder(self):
+ def _reorder(self) -> None:
if self._ordered:
return
order = sorted(super(Meta, self).items(), key=lambda x: x[1], reverse=True)
|
213c25934aa15c9d607833f145f54647d17364ca
|
rnacentral/portal/templatetags/portal_extras.py
|
rnacentral/portal/templatetags/portal_extras.py
|
"""
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
[dbs[x] for x in [1,0,2,3,4,5,6]],
dbs[7:13],
dbs[13:19],
dbs[19:]
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
"""
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
[dbs[x] for x in [1,0,2,3,4,5,6,7]],
dbs[8:16],
dbs[16:23],
dbs[23:]
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
Update expert database list in the footer
|
Update expert database list in the footer
|
Python
|
apache-2.0
|
RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode
|
---
+++
@@ -24,10 +24,10 @@
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
- [dbs[x] for x in [1,0,2,3,4,5,6]],
- dbs[7:13],
- dbs[13:19],
- dbs[19:]
+ [dbs[x] for x in [1,0,2,3,4,5,6,7]],
+ dbs[8:16],
+ dbs[16:23],
+ dbs[23:]
]
@register.assignment_tag
|
fb27a53d0ea46e9012610eeccd90b50be07388d9
|
doctr/tests/test_local.py
|
doctr/tests/test_local.py
|
from ..local import check_repo_exists
from pytest import raises
def test_bad_user():
with raises(RuntimeError):
check_repo_exists('---/invaliduser')
def test_bad_repo():
with raises(RuntimeError):
check_repo_exists('drdoctr/---')
def test_repo_exists():
assert check_repo_exists('drdoctr/doctr')
def test_invalid_repo():
with raises(RuntimeError):
check_repo_exists('fdsf')
with raises(RuntimeError):
check_repo_exists('fdsf/fdfs/fd')
|
from ..local import check_repo_exists
from pytest import raises
def test_bad_user():
with raises(RuntimeError):
check_repo_exists('---/invaliduser')
def test_bad_repo():
with raises(RuntimeError):
check_repo_exists('drdoctr/---')
def test_repo_exists():
assert not check_repo_exists('drdoctr/doctr')
def test_invalid_repo():
with raises(RuntimeError):
check_repo_exists('fdsf')
with raises(RuntimeError):
check_repo_exists('fdsf/fdfs/fd')
|
Update expected test result for test_repo_exists now that check_repo_exists returns whether the repo is private or not
|
Update expected test result for test_repo_exists now that check_repo_exists returns whether the repo is private or not
|
Python
|
mit
|
gforsyth/doctr_testing,drdoctr/doctr
|
---
+++
@@ -11,7 +11,7 @@
check_repo_exists('drdoctr/---')
def test_repo_exists():
- assert check_repo_exists('drdoctr/doctr')
+ assert not check_repo_exists('drdoctr/doctr')
def test_invalid_repo():
with raises(RuntimeError):
|
30230cb6fcb29cd437d3ce71c3370da6d38cb622
|
python/04-2.py
|
python/04-2.py
|
#!/usr/bin/env python
import hashlib
prefix = ''
number = 1
with open('../inputs/04.txt') as f:
prefix = f.readlines()
prefix = prefix[0].rstrip()
while True:
md5 = hashlib.md5()
md5.update('{0}{1}'.format(prefix, number))
if md5.hexdigest()[:6] == '000000':
#print md5.hexdigest()
print number
break
number += 1
|
#!/usr/bin/env python
import hashlib
prefix = ''
number = 1
with open('../inputs/04.txt') as f:
prefix = f.readlines()
prefix = prefix[0].rstrip()
md5 = hashlib.md5()
md5.update(prefix)
while True:
m = md5.copy()
m.update(str(number))
if m.hexdigest()[:6] == '000000':
print number
break
number += 1
|
Use md5.copy() to be more efficient.
|
Use md5.copy() to be more efficient.
The hash.copy() documentation says this is more efficient given a common
initial substring.
|
Python
|
mit
|
opello/adventofcode
|
---
+++
@@ -10,12 +10,14 @@
prefix = prefix[0].rstrip()
+md5 = hashlib.md5()
+md5.update(prefix)
+
while True:
- md5 = hashlib.md5()
- md5.update('{0}{1}'.format(prefix, number))
+ m = md5.copy()
+ m.update(str(number))
- if md5.hexdigest()[:6] == '000000':
- #print md5.hexdigest()
+ if m.hexdigest()[:6] == '000000':
print number
break
|
1152e7a329ee20494a4856f7a83f5ab1e6c4390e
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
import os, sys
from django.conf import settings
import django
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'model_utils',
'model_utils.tests',
),
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3"
}
},
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
# Compatibility with Django 1.7's stricter initialization
if hasattr(django, 'setup'):
django.setup()
if not test_args:
test_args = ['tests']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
#!/usr/bin/env python
import os, sys
from django.conf import settings
import django
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=(
'model_utils',
'model_utils.tests',
),
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3"
}
},
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
# Compatibility with Django 1.7's stricter initialization
if hasattr(django, 'setup'):
django.setup()
if not test_args:
test_args = ['tests']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Remove contenttypes from INSTALLED_APPS for testing; no longer needed.
|
Remove contenttypes from INSTALLED_APPS for testing; no longer needed.
|
Python
|
bsd-3-clause
|
nemesisdesign/django-model-utils,timmygee/django-model-utils,patrys/django-model-utils,yeago/django-model-utils,nemesisdesign/django-model-utils,timmygee/django-model-utils,patrys/django-model-utils,carljm/django-model-utils,yeago/django-model-utils,carljm/django-model-utils
|
---
+++
@@ -8,7 +8,6 @@
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=(
- 'django.contrib.contenttypes',
'model_utils',
'model_utils.tests',
),
|
155b1e6b8d431f1169a3e71d08d93d76a3414c59
|
turbustat/statistics/vca_vcs/slice_thickness.py
|
turbustat/statistics/vca_vcs/slice_thickness.py
|
# Licensed under an MIT open source license - see LICENSE
import numpy as np
def change_slice_thickness(cube, slice_thickness=1.0):
'''
Degrades the velocity resolution of a data cube. This is to avoid
shot noise by removing velocity fluctuations at small thicknesses.
Parameters
----------
cube : numpy.ndarray
3D data cube to degrade
slice_thickness : float, optional
Thicknesses of the new slices. Minimum is 1.0
Thickness must be integer multiple of the original cube size
Returns
-------
degraded_cube : numpy.ndarray
Data cube degraded to new slice thickness
'''
assert isinstance(slice_thickness, float)
if slice_thickness < 1:
slice_thickness == 1
print "Slice Thickness must be at least 1.0. Returning original cube."
if slice_thickness == 1:
return cube
if cube.shape[0] % slice_thickness != 0:
raise TypeError("Slice thickness must be integer multiple of dimension"
" size % s" % (cube.shape[0]))
slice_thickness = int(slice_thickness)
# Want to average over velocity channels
new_channel_indices = np.arange(0, cube.shape[0] / slice_thickness)
degraded_cube = np.ones(
(cube.shape[0] / slice_thickness, cube.shape[1], cube.shape[2]))
for channel in new_channel_indices:
old_index = int(channel * slice_thickness)
channel = int(channel)
degraded_cube[channel, :, :] = \
np.nanmean(cube[old_index:old_index + slice_thickness], axis=0)
return degraded_cube
|
# Licensed under an MIT open source license - see LICENSE
import numpy as np
from astropy import units as u
from spectral_cube import SpectralCube
from astropy.convolution import Gaussian1DKernel
def spectral_regrid_cube(cube, channel_width):
fwhm_factor = np.sqrt(8 * np.log(2))
current_resolution = np.diff(cube.spectral_axis[:2])[0]
target_resolution = channel_width.to(current_resolution.unit)
diff_factor = np.abs(target_resolution / current_resolution).value
pixel_scale = np.abs(current_resolution)
gaussian_width = ((target_resolution**2 - current_resolution**2)**0.5 /
pixel_scale / fwhm_factor)
kernel = Gaussian1DKernel(gaussian_width)
new_cube = cube.spectral_smooth(kernel)
# Now define the new spectral axis at the new resolution
num_chan = int(np.floor_divide(cube.shape[0], diff_factor))
new_specaxis = np.linspace(cube.spectral_axis.min().value,
cube.spectral_axis.max().value,
num_chan) * current_resolution.unit
# Keep the same order (max to min or min to max)
if current_resolution.value < 0:
new_specaxis = new_specaxis[::-1]
return new_cube.spectral_interpolate(new_specaxis,
suppress_smooth_warning=True)
|
Add a corrected spectral regridding function that smooths before interpolating to a new spectral axis
|
Add a corrected spectral regridding function that smooths before interpolating to a new spectral axis
|
Python
|
mit
|
e-koch/TurbuStat,Astroua/TurbuStat
|
---
+++
@@ -2,51 +2,33 @@
import numpy as np
+from astropy import units as u
+from spectral_cube import SpectralCube
+from astropy.convolution import Gaussian1DKernel
-def change_slice_thickness(cube, slice_thickness=1.0):
- '''
+def spectral_regrid_cube(cube, channel_width):
- Degrades the velocity resolution of a data cube. This is to avoid
- shot noise by removing velocity fluctuations at small thicknesses.
+ fwhm_factor = np.sqrt(8 * np.log(2))
+ current_resolution = np.diff(cube.spectral_axis[:2])[0]
+ target_resolution = channel_width.to(current_resolution.unit)
+ diff_factor = np.abs(target_resolution / current_resolution).value
- Parameters
- ----------
- cube : numpy.ndarray
- 3D data cube to degrade
- slice_thickness : float, optional
- Thicknesses of the new slices. Minimum is 1.0
- Thickness must be integer multiple of the original cube size
+ pixel_scale = np.abs(current_resolution)
- Returns
- -------
- degraded_cube : numpy.ndarray
- Data cube degraded to new slice thickness
- '''
+ gaussian_width = ((target_resolution**2 - current_resolution**2)**0.5 /
+ pixel_scale / fwhm_factor)
+ kernel = Gaussian1DKernel(gaussian_width)
+ new_cube = cube.spectral_smooth(kernel)
- assert isinstance(slice_thickness, float)
- if slice_thickness < 1:
- slice_thickness == 1
- print "Slice Thickness must be at least 1.0. Returning original cube."
+ # Now define the new spectral axis at the new resolution
+ num_chan = int(np.floor_divide(cube.shape[0], diff_factor))
+ new_specaxis = np.linspace(cube.spectral_axis.min().value,
+ cube.spectral_axis.max().value,
+ num_chan) * current_resolution.unit
+ # Keep the same order (max to min or min to max)
+ if current_resolution.value < 0:
+ new_specaxis = new_specaxis[::-1]
- if slice_thickness == 1:
- return cube
-
- if cube.shape[0] % slice_thickness != 0:
- raise TypeError("Slice thickness must be integer multiple of dimension"
- " size % s" % (cube.shape[0]))
-
- slice_thickness = int(slice_thickness)
-
- # Want to average over velocity channels
- new_channel_indices = np.arange(0, cube.shape[0] / slice_thickness)
- degraded_cube = np.ones(
- (cube.shape[0] / slice_thickness, cube.shape[1], cube.shape[2]))
-
- for channel in new_channel_indices:
- old_index = int(channel * slice_thickness)
- channel = int(channel)
- degraded_cube[channel, :, :] = \
- np.nanmean(cube[old_index:old_index + slice_thickness], axis=0)
-
- return degraded_cube
+ return new_cube.spectral_interpolate(new_specaxis,
+ suppress_smooth_warning=True)
|
e39925db2834a7491f9b8b505e1e1cf181840035
|
clowder_server/views.py
|
clowder_server/views.py
|
from braces.views import CsrfExemptMixin
from django.core.mail import send_mail
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from clowder_server.models import Alert, Ping
class APIView(CsrfExemptMixin, View):
def post(self, request):
name = request.POST.get('name')
frequency = request.POST.get('frequency')
value = request.POST.get('value')
status = int(request.POST.get('status', 1))
if status == -1:
send_mail('Subject here', 'Here is the message.', 'admin@clowder.io',
['keith@parkme.com'], fail_silently=False)
if frequency:
expiration_date = datetime.datetime.now() + int(frequency)
Alert.objects.filter(name=name).delete()
Alert.objects.create(
name=name,
expire_at=expiration_date
)
Ping.objects.create(
name=name,
value=value,
)
return HttpResponse('ok')
class DashboardView(TemplateView):
template_name = "dashboard.html"
def get_context_data(self, **context):
context['pings'] = Ping.objects.all().order_by('name', 'create')
return context
|
from braces.views import CsrfExemptMixin
from django.core.mail import send_mail
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from clowder_server.models import Alert, Ping
class APIView(CsrfExemptMixin, View):
def post(self, request):
name = request.POST.get('name')
frequency = request.POST.get('frequency')
value = request.POST.get('value')
status = int(request.POST.get('status', 1))
if status == -1:
send_mail('Subject here', 'Here is the message.', 'admin@clowder.io',
['keith@parkme.com'], fail_silently=False)
if frequency:
expiration_date = datetime.datetime.now() + int(frequency)
Alert.objects.filter(name=name).delete()
Alert.objects.create(
name=name,
expire_at=expiration_date
)
return HttpResponse('test')
Ping.objects.create(
name=name,
value=value,
)
return HttpResponse('ok')
class DashboardView(TemplateView):
template_name = "dashboard.html"
def get_context_data(self, **context):
context['pings'] = Ping.objects.all().order_by('name', 'create')
return context
|
Add test response to frequency
|
Add test response to frequency
|
Python
|
agpl-3.0
|
framewr/clowder_server,framewr/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server
|
---
+++
@@ -27,6 +27,7 @@
name=name,
expire_at=expiration_date
)
+ return HttpResponse('test')
Ping.objects.create(
name=name,
|
855434523df57183c31ed9b10e7458232b79046a
|
aclarknet/aclarknet/aclarknet/models.py
|
aclarknet/aclarknet/aclarknet/models.py
|
from django.db import models
class Client(models.Model):
client_name = models.CharField(max_length=60)
class Service(models.Model):
name = models.CharField(max_length=60)
class TeamMember(models.Model):
name = models.CharField(max_length=60)
|
from django.db import models
class Client(models.Model):
client_name = models.CharField(max_length=60)
def __unicode__(self):
return self.client_name
class Service(models.Model):
name = models.CharField(max_length=60)
def __unicode__(self):
return self.name
class TeamMember(models.Model):
name = models.CharField(max_length=60)
def __unicode__(self):
return self.name
|
Fix object name in Django Admin
|
Fix object name in Django Admin
http://stackoverflow.com/questions/9336463/django-xxxxxx-object-display-customization-in-admin-action-sidebar
|
Python
|
mit
|
ACLARKNET/aclarknet-django,ACLARKNET/aclarknet-django
|
---
+++
@@ -4,10 +4,19 @@
class Client(models.Model):
client_name = models.CharField(max_length=60)
+ def __unicode__(self):
+ return self.client_name
+
class Service(models.Model):
name = models.CharField(max_length=60)
+ def __unicode__(self):
+ return self.name
+
class TeamMember(models.Model):
name = models.CharField(max_length=60)
+
+ def __unicode__(self):
+ return self.name
|
6b06ff67097d0a2ef639df4a3d9baf4f6677b5fd
|
lmj/sim/__init__.py
|
lmj/sim/__init__.py
|
# Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''Yet another OpenGL-and-physics simulator framework !'''
from . import ode
from .log import enable_default_logging, get_logger
from .ode import make_quaternion
from .world import Viewer, World
import plac
def call(main):
'''Enable logging and start up a main method.'''
enable_default_logging()
plac.call(main)
args = plac.annotations
|
# Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''Yet another OpenGL-and-physics simulator framework !'''
from . import physics
from .log import enable_default_logging, get_logger
from .world import Viewer, World
import plac
def call(main):
'''Enable logging and start up a main method.'''
enable_default_logging()
plac.call(main)
args = plac.annotations
|
Update package imports for module name change.
|
Update package imports for module name change.
|
Python
|
mit
|
EmbodiedCognition/pagoda,EmbodiedCognition/pagoda
|
---
+++
@@ -20,9 +20,8 @@
'''Yet another OpenGL-and-physics simulator framework !'''
-from . import ode
+from . import physics
from .log import enable_default_logging, get_logger
-from .ode import make_quaternion
from .world import Viewer, World
import plac
|
fd907ac07d5d20dcf8964dbef324bfa2da93ed44
|
armstrong/core/arm_sections/managers.py
|
armstrong/core/arm_sections/managers.py
|
from django.db import models
class SectionSlugManager(models.Manager):
def __init__(self, section_field="primary_section", slug_field="slug",
*args, **kwargs):
super(SectionSlugManager, self).__init__(*args, **kwargs)
self.section_field = section_field
self.slug_field = slug_field
def get_by_slug(self, slug):
if slug[-1] == "/":
slug = slug[0:-1]
if slug[0] == "/":
slug = slug[1:]
section_slug, content_slug = slug.rsplit("/", 1)
section_slug += "/"
kwargs = {
"%s__full_slug" % self.section_field: section_slug,
self.slug_field: content_slug,
}
qs = self.model.objects.filter(**kwargs)
if hasattr(qs, "select_subclasses"):
qs = qs.select_subclasses()
try:
return qs[0]
except IndexError:
raise self.model.DoesNotExist
|
from django.db import models
class SectionSlugManager(models.Manager):
def __init__(self, section_field="primary_section", slug_field="slug",
*args, **kwargs):
super(SectionSlugManager, self).__init__(*args, **kwargs)
self.section_field = section_field
self.slug_field = slug_field
def get_by_slug(self, slug):
if slug[-1] == "/":
slug = slug[0:-1]
if slug[0] == "/":
slug = slug[1:]
try:
section_slug, content_slug = slug.rsplit("/", 1)
section_slug += "/"
except ValueError:
raise self.model.DoesNotExist
kwargs = {
"%s__full_slug" % self.section_field: section_slug,
self.slug_field: content_slug,
}
qs = self.model.objects.filter(**kwargs)
if hasattr(qs, "select_subclasses"):
qs = qs.select_subclasses()
try:
return qs[0]
except IndexError:
raise self.model.DoesNotExist
|
Handle situation where only a root full_slug is passed.
|
Handle situation where only a root full_slug is passed.
i.e. "section/" would break the rsplit(). If there is no slug, we can safely raise a DoesNotExist.
|
Python
|
apache-2.0
|
armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections
|
---
+++
@@ -13,8 +13,13 @@
slug = slug[0:-1]
if slug[0] == "/":
slug = slug[1:]
- section_slug, content_slug = slug.rsplit("/", 1)
- section_slug += "/"
+
+ try:
+ section_slug, content_slug = slug.rsplit("/", 1)
+ section_slug += "/"
+ except ValueError:
+ raise self.model.DoesNotExist
+
kwargs = {
"%s__full_slug" % self.section_field: section_slug,
self.slug_field: content_slug,
|
03340917e96b7076ca420bea4e121f89c05935f6
|
censusreporter/config/prod/settings.py
|
censusreporter/config/prod/settings.py
|
from censusreporter.config.base.settings import *
import os
DEBUG = False
ROOT_URLCONF = 'censusreporter.config.prod.urls'
WSGI_APPLICATION = "censusreporter.config.prod.wsgi.application"
ALLOWED_HOSTS = [
'censusreporter.org',
'www.censusreporter.org',
'censusreporter.dokku.censusreporter.org',
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': os.environ.get('REDIS_URL', ''),
}
}
|
from censusreporter.config.base.settings import *
import os
DEBUG = False
ROOT_URLCONF = 'censusreporter.config.prod.urls'
WSGI_APPLICATION = "censusreporter.config.prod.wsgi.application"
ALLOWED_HOSTS = ['*']
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': os.environ.get('REDIS_URL', ''),
}
}
|
Allow all hosts to support Dokku's healthcheck
|
Allow all hosts to support Dokku's healthcheck
|
Python
|
mit
|
censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter
|
---
+++
@@ -6,11 +6,7 @@
WSGI_APPLICATION = "censusreporter.config.prod.wsgi.application"
-ALLOWED_HOSTS = [
- 'censusreporter.org',
- 'www.censusreporter.org',
- 'censusreporter.dokku.censusreporter.org',
-]
+ALLOWED_HOSTS = ['*']
CACHES = {
'default': {
|
20b4c81137d4abdd4db0dc80ae9a2e38cca4e8eb
|
examples/hello_twisted.py
|
examples/hello_twisted.py
|
"""A simple example of Pyglet/Twisted integration. A Pyglet window
is displayed, and both Pyglet and Twisted are making scheduled calls
and regular intervals. Interacting with the window doesn't interfere
with either calls.
"""
import pyglet
import pygletreactor
pygletreactor.install() # <- this must come before...
from twisted.internet import reactor, task # <- ...importing this reactor!
# Create a Pyglet window with a simple message
window = pyglet.window.Window()
label = pyglet.text.Label('hello world',
x = window.width / 2,
y = window.height / 2,
anchor_x = 'center',
anchor_y = 'center')
@window.event
def on_draw():
window.clear()
label.draw()
@window.event
def on_close():
reactor.stop()
# Return true to ensure that no other handlers
# on the stack receive the on_close event
return True
# Schedule a function call in Pyglet
def runEverySecondPyglet(dt):
print "pyglet call: one second has passed"
pyglet.clock.schedule_interval(runEverySecondPyglet, 1)
# Schedule a function call in Twisted
def runEverySecondTwisted():
print "twisted call: 1.5 seconds have passed"
l = task.LoopingCall(runEverySecondTwisted)
l.start(1.5)
# Start the reactor
reactor.run()
|
"""A simple example of Pyglet/Twisted integration. A Pyglet window
is displayed, and both Pyglet and Twisted are making scheduled calls
and regular intervals. Interacting with the window doesn't interfere
with either calls.
"""
import pyglet
import pygletreactor
pygletreactor.install() # <- this must come before...
from twisted.internet import reactor, task # <- ...importing this reactor!
# Create a Pyglet window with a simple message
window = pyglet.window.Window()
label = pyglet.text.Label('hello world',
x = window.width / 2,
y = window.height / 2,
anchor_x = 'center',
anchor_y = 'center')
@window.event
def on_draw():
window.clear()
label.draw()
@window.event
def on_close():
reactor.callFromThread(reactor.stop)
# Return true to ensure that no other handlers
# on the stack receive the on_close event
return True
# Schedule a function call in Pyglet
def runEverySecondPyglet(dt):
print "pyglet call: one second has passed"
pyglet.clock.schedule_interval(runEverySecondPyglet, 1)
# Schedule a function call in Twisted
def runEverySecondTwisted():
print "twisted call: 1.5 seconds have passed"
l = task.LoopingCall(runEverySecondTwisted)
l.start(1.5)
# Start the reactor
reactor.run()
|
Call to stop the reactor now uses the correct convention when closing from a thread other than the main reactor thread.
|
Call to stop the reactor now uses the correct convention when closing from a thread other than the main reactor thread.
Fixes Issue 5.
git-svn-id: a0251d2471cc357dbf602d275638891bc89eba80@9 4515f058-c067-11dd-9cb5-179210ed59e1
|
Python
|
mit
|
padraigkitterick/pyglet-twisted
|
---
+++
@@ -24,7 +24,7 @@
@window.event
def on_close():
- reactor.stop()
+ reactor.callFromThread(reactor.stop)
# Return true to ensure that no other handlers
# on the stack receive the on_close event
|
7778b98e1a0d0ac7b9c14e4536e62de4db7debc9
|
tests/integration/suite/test_global_role_bindings.py
|
tests/integration/suite/test_global_role_bindings.py
|
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
|
import pytest
from rancher import ApiError
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
def test_globalrole_must_exist(admin_mc, remove_resource):
"""Asserts that globalRoleId must reference an existing role"""
admin_client = admin_mc.client
with pytest.raises(ApiError) as e:
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
globalRoleId="somefakerole",
userId=admin_mc.user.id
)
remove_resource(grb)
assert e.value.error.status == 404
assert "globalRole.management.cattle.io \"somefakerole\" not found" in \
e.value.error.message
|
Add test for GRB validator
|
Add test for GRB validator
|
Python
|
apache-2.0
|
cjellick/rancher,rancherio/rancher,cjellick/rancher,rancher/rancher,cjellick/rancher,rancherio/rancher,rancher/rancher,rancher/rancher,rancher/rancher
|
---
+++
@@ -1,3 +1,6 @@
+import pytest
+
+from rancher import ApiError
from .common import random_str
@@ -15,3 +18,19 @@
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
+
+
+def test_globalrole_must_exist(admin_mc, remove_resource):
+ """Asserts that globalRoleId must reference an existing role"""
+ admin_client = admin_mc.client
+
+ with pytest.raises(ApiError) as e:
+ grb = admin_client.create_global_role_binding(
+ name="gr-" + random_str(),
+ globalRoleId="somefakerole",
+ userId=admin_mc.user.id
+ )
+ remove_resource(grb)
+ assert e.value.error.status == 404
+ assert "globalRole.management.cattle.io \"somefakerole\" not found" in \
+ e.value.error.message
|
619253a51d0b79f170065e6023530937d7111102
|
awscfncli/config/config.py
|
awscfncli/config/config.py
|
# -*- encoding: utf-8 -*-
import logging
import yaml
from collections import namedtuple
log = logging.getLogger(__name__)
def load(filename):
with open(filename) as fp:
config = yaml.safe_load(fp)
return CfnCliConfig.load(config)
class CfnCliConfig(namedtuple('CfnCliConfig', 'version blueprints environments')):
CFNFILE_V1 = 1
CFNFILE_V2 = 2
VERSION_SECTION = 'Version'
BLUEPRINT_SECTION = 'Blueprints'
ENVIRONMENT_SECTION = 'Environments'
@classmethod
def load(cls, config):
# load version
version = config.get(cls.VERSION_SECTION, cls.CFNFILE_V1)
# load blueprint into dict
blueprint_section = config.get(cls.BLUEPRINT_SECTION, {})
blueprints = {}
for key, val in blueprint_section:
blueprints[key] = Blueprint.load(val)
# load environment into dict
environment_section = config.get(cls.ENVIRONMENT_SECTION, {})
environments = {}
for key, val in environment_section:
environments[key] = Environment.load(val)
return cls(version, blueprints, environments)
class Stack(namedtuple('Stack', '')):
@classmethod
def load(cls, config):
return cls()
class Environment(namedtuple('Environment', '')):
@classmethod
def load(cls, config):
return cls()
class Blueprint(namedtuple('Blueprint', '')):
@classmethod
def load(cls, config):
return cls()
|
# -*- encoding: utf-8 -*-
import logging
import yaml
from collections import namedtuple
log = logging.getLogger(__name__)
def load(filename):
with open(filename) as fp:
config = yaml.safe_load(fp)
return CfnCliConfig.load(config)
class CfnCliConfig(namedtuple('CfnCliConfig', 'version blueprints environments')):
CFNFILE_V1 = 1
CFNFILE_V2 = 2
VERSION_SECTION = 'Version'
BLUEPRINT_SECTION = 'Blueprints'
ENVIRONMENT_SECTION = 'Environments'
@staticmethod
def load(config):
# load version
version = config.get(CfnCliConfig.VERSION_SECTION, CfnCliConfig.CFNFILE_V1)
# load blueprint into dict
blueprint_section = config.get(CfnCliConfig.BLUEPRINT_SECTION, {})
blueprints = {}
for key, val in blueprint_section:
blueprints[key] = Blueprint.load(val)
# load environment into dict
environment_section = config.get(CfnCliConfig.ENVIRONMENT_SECTION, {})
environments = {}
for key, val in environment_section:
environments[key] = Environment.load(val)
return CfnCliConfig(version, blueprints, environments)
class Stack(namedtuple('Stack', '')):
@staticmethod
def load(config):
return Stack()
class Environment(namedtuple('Environment', '')):
@staticmethod
def load(config):
return Environment()
class Blueprint(namedtuple('Blueprint', '')):
@staticmethod
def load(config):
return Blueprint()
|
Use static method instead of classmethod
|
Use static method instead of classmethod
|
Python
|
mit
|
Kotaimen/awscfncli,Kotaimen/awscfncli
|
---
+++
@@ -22,40 +22,39 @@
BLUEPRINT_SECTION = 'Blueprints'
ENVIRONMENT_SECTION = 'Environments'
- @classmethod
- def load(cls, config):
+ @staticmethod
+ def load(config):
# load version
- version = config.get(cls.VERSION_SECTION, cls.CFNFILE_V1)
+ version = config.get(CfnCliConfig.VERSION_SECTION, CfnCliConfig.CFNFILE_V1)
# load blueprint into dict
- blueprint_section = config.get(cls.BLUEPRINT_SECTION, {})
+ blueprint_section = config.get(CfnCliConfig.BLUEPRINT_SECTION, {})
blueprints = {}
for key, val in blueprint_section:
blueprints[key] = Blueprint.load(val)
# load environment into dict
- environment_section = config.get(cls.ENVIRONMENT_SECTION, {})
+ environment_section = config.get(CfnCliConfig.ENVIRONMENT_SECTION, {})
environments = {}
for key, val in environment_section:
environments[key] = Environment.load(val)
- return cls(version, blueprints, environments)
+ return CfnCliConfig(version, blueprints, environments)
class Stack(namedtuple('Stack', '')):
- @classmethod
- def load(cls, config):
- return cls()
+ @staticmethod
+ def load(config):
+ return Stack()
class Environment(namedtuple('Environment', '')):
- @classmethod
- def load(cls, config):
- return cls()
+ @staticmethod
+ def load(config):
+ return Environment()
class Blueprint(namedtuple('Blueprint', '')):
- @classmethod
- def load(cls, config):
- return cls()
-
+ @staticmethod
+ def load(config):
+ return Blueprint()
|
1285e4bcbdbcf3c28eced497c8585892f3ae1239
|
django_summernote/admin.py
|
django_summernote/admin.py
|
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.models import Attachment
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
ordering = ('-id',)
def save_model(self, request, obj, form, change):
obj.name = obj.file.name if (not obj.name) else obj.name
super(AttachmentAdmin, self).save_model(request, obj, form, change)
admin.site.register(get_attachment_model(), AttachmentAdmin)
|
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
ordering = ('-id',)
def save_model(self, request, obj, form, change):
obj.name = obj.file.name if (not obj.name) else obj.name
super(AttachmentAdmin, self).save_model(request, obj, form, change)
admin.site.register(get_attachment_model(), AttachmentAdmin)
|
Remove a non-used module importing
|
Remove a non-used module importing
|
Python
|
mit
|
lqez/django-summernote,summernote/django-summernote,lqez/django-summernote,lqez/django-summernote,summernote/django-summernote,summernote/django-summernote
|
---
+++
@@ -1,7 +1,6 @@
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
-from django_summernote.models import Attachment
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
|
7e638636606a4f7f7b5b6a09ec508746c8ca8f32
|
Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py
|
Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
for imp_del_id in imp_del_ids:
try:
imp_obj.unlink([imp_del_id])
n +=1
print "%d/%d" % (n,total)
except Exception, e:
print e
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','=','Aquest fitxer XML ja s\'ha processat en els següents IDs')])
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','=','Ja existeix una factura amb el mateix origen')])
#imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
for imp_del_id in imp_del_ids:
try:
imp_obj.unlink([imp_del_id])
n +=1
print "%d/%d" % (n,total)
except Exception, e:
print e
|
Fix Cannot delete invoice(s) that are already opened or paid
|
Fix Cannot delete invoice(s) that are already opened or paid
|
Python
|
agpl-3.0
|
Som-Energia/invoice-janitor
|
---
+++
@@ -7,10 +7,14 @@
imp_obj = O.GiscedataFacturacioImportacioLinia
-imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
-imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
-imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
-imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
+imp_del_ids = imp_obj.search([('state','=','erroni'),('info','=','Aquest fitxer XML ja s\'ha processat en els següents IDs')])
+imp_del_ids = imp_obj.search([('state','=','erroni'),('info','=','Ja existeix una factura amb el mateix origen')])
+
+
+#imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
+#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
+#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
+#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
|
8cee7d5478cde2b188da4dc93f844073be729a48
|
src/gerobak/apps/profile/models.py
|
src/gerobak/apps/profile/models.py
|
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from gerobak import utils
class Profile(models.Model):
pid = models.CharField(max_length=8)
user = models.ForeignKey(User)
added = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=50)
desc = models.CharField(max_length=250, null=True, blank=True)
arch = models.CharField(max_length=10, choices=settings.GEROBAK_ARCHS,
default=settings.GEROBAK_DEFAULT_ARCH)
repo_updated = models.DateTimeField(null=True, default=None)
sources_updated = models.DateTimeField(null=True, default=None)
sources_total = models.IntegerField(null=True, default=None)
status_updated = models.DateTimeField(null=True, default=None)
status_hash = models.CharField(max_length=32, null=True, default=None)
status_size = models.IntegerField(default=0)
def is_ready(self):
return self.repo_updated is not None and \
self.status_updated is not None
def generate_pid(self):
import uuid
return str(uuid.uuid4()).split('-')[0]
|
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from gerobak import utils
class Profile(models.Model):
pid = models.CharField(max_length=8)
user = models.ForeignKey(User)
added = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=50)
desc = models.CharField(max_length=250, null=True, blank=True)
arch = models.CharField(max_length=10, choices=settings.GEROBAK_ARCHS,
default=settings.GEROBAK_DEFAULT_ARCH)
repo_updated = models.DateTimeField(null=True, default=None)
sources_updated = models.DateTimeField(null=True, default=None)
sources_total = models.IntegerField(null=True, default=None)
status_updated = models.DateTimeField(null=True, default=None)
status_hash = models.CharField(max_length=32, null=True, default=None)
status_size = models.IntegerField(default=0)
tid_update = models.CharField(max_length=36, null=True, default=None)
tid_install = models.CharField(max_length=36, null=True, default=None)
tid_upgrade = models.CharField(max_length=36, null=True, default=None)
def is_ready(self):
return self.repo_updated is not None and \
self.status_updated is not None
def generate_pid(self):
import uuid
return str(uuid.uuid4()).split('-')[0]
|
Store task_id for update, install, and upgrade processes in the database.
|
Store task_id for update, install, and upgrade processes in the database.
|
Python
|
agpl-3.0
|
fajran/gerobak,fajran/gerobak
|
---
+++
@@ -27,6 +27,10 @@
status_hash = models.CharField(max_length=32, null=True, default=None)
status_size = models.IntegerField(default=0)
+ tid_update = models.CharField(max_length=36, null=True, default=None)
+ tid_install = models.CharField(max_length=36, null=True, default=None)
+ tid_upgrade = models.CharField(max_length=36, null=True, default=None)
+
def is_ready(self):
return self.repo_updated is not None and \
self.status_updated is not None
|
6021f5af785e5234b9f83ea4ac740571b9308ae4
|
Communication/mavtester.py
|
Communication/mavtester.py
|
#!/usr/bin/env python
'''
test mavlink messages
Do not forget to precise the baudrate (default 115200)
'''
import sys, struct, time, os
from curses import ascii
from pymavlink import mavutil
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument("--baudrate", type=int,
help="master port baud rate", default=115200)
parser.add_argument("--device", required=True, help="serial device")
parser.add_argument("--source-system", dest='SOURCE_SYSTEM', type=int,
default=255, help='MAVLink source system for this GCS')
args = parser.parse_args()
def wait_heartbeat(m):
'''wait for a heartbeat so we know the target system IDs'''
print("Waiting for APM heartbeat")
msg = m.recv_match(type='HEARTBEAT', blocking=True)
print("Heartbeat from APM (system %u component %u)" % (m.target_system, m.target_component))
# create a mavlink serial instance
master = mavutil.mavlink_connection(args.device, baud=args.baudrate, source_system=args.SOURCE_SYSTEM)
# wait for the heartbeat msg to find the system ID
while True:
wait_heartbeat(master)
|
#!/usr/bin/env python
'''
test mavlink messages
Do not forget to precise the baudrate (default 115200)
'''
import sys, struct, time, os
from curses import ascii
from pymavlink import mavutil
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument("--baudrate", type=int,
help="master port baud rate", default=115200)
parser.add_argument("--device", required=True, help="serial device")
parser.add_argument("--source-system", dest='SOURCE_SYSTEM', type=int,
default=255, help='MAVLink source system for this GCS')
args = parser.parse_args()
def wait_heartbeat(m):
'''wait for a heartbeat so we know the target system IDs'''
print("Waiting for APM heartbeat")
msg = m.recv_match(type='HEARTBEAT', blocking=True)
print("Heartbeat from APM (system %u component %u)" % (m.target_system, m.target_component))
# create a mavlink serial instance
master = mavutil.mavlink_connection(args.device, baud=args.baudrate, source_system=args.SOURCE_SYSTEM)
# wait for the heartbeat msg to find the system ID
while True:
wait_heartbeat(master)
msg = master.recv_match(type='GPS_RAW_INT', blocking=False)
print msg
|
Add reception of GPS_RAW_INT messages as demo
|
Add reception of GPS_RAW_INT messages as demo
|
Python
|
mit
|
baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite
|
---
+++
@@ -32,3 +32,5 @@
# wait for the heartbeat msg to find the system ID
while True:
wait_heartbeat(master)
+ msg = master.recv_match(type='GPS_RAW_INT', blocking=False)
+ print msg
|
3b8811af898ec8cbaa93c69c6b702b92756713dc
|
vumi/persist/tests/test_riak_manager.py
|
vumi/persist/tests/test_riak_manager.py
|
"""Tests for vumi.persist.riak_manager."""
from twisted.trial.unittest import TestCase
from vumi.persist.riak_manager import RiakManager
class TestRiakManager(TestCase):
pass
|
"""Tests for vumi.persist.riak_manager."""
from itertools import count
from twisted.trial.unittest import TestCase
from twisted.internet.defer import returnValue
from vumi.persist.riak_manager import RiakManager, flatten_generator
from vumi.persist.tests.test_txriak_manager import CommonRiakManagerTests
class TestRiakManager(CommonRiakManagerTests, TestCase):
"""Most tests are inherited from the CommonRiakManagerTests mixin."""
def setUp(self):
self.manager = RiakManager.from_config({'bucket_prefix': 'test.'})
self.manager.purge_all()
def tearDown(self):
self.manager.purge_all()
def test_call_decorator(self):
self.assertEqual(RiakManager.call_decorator, flatten_generator)
def test_flatten_generator(self):
results = []
counter = count()
@flatten_generator
def f():
for i in range(3):
a = yield counter.next()
results.append(a)
ret = f()
self.assertEqual(ret, None)
self.assertEqual(results, list(range(3)))
def test_flatter_generator_with_return_value(self):
@flatten_generator
def f():
yield None
returnValue("foo")
ret = f()
self.assertEqual(ret, "foo")
|
Add tests for (nottx)riak manager.
|
Add tests for (nottx)riak manager.
|
Python
|
bsd-3-clause
|
vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi
|
---
+++
@@ -1,9 +1,46 @@
"""Tests for vumi.persist.riak_manager."""
+from itertools import count
+
from twisted.trial.unittest import TestCase
+from twisted.internet.defer import returnValue
-from vumi.persist.riak_manager import RiakManager
+from vumi.persist.riak_manager import RiakManager, flatten_generator
+from vumi.persist.tests.test_txriak_manager import CommonRiakManagerTests
-class TestRiakManager(TestCase):
- pass
+class TestRiakManager(CommonRiakManagerTests, TestCase):
+ """Most tests are inherited from the CommonRiakManagerTests mixin."""
+
+ def setUp(self):
+ self.manager = RiakManager.from_config({'bucket_prefix': 'test.'})
+ self.manager.purge_all()
+
+ def tearDown(self):
+ self.manager.purge_all()
+
+ def test_call_decorator(self):
+ self.assertEqual(RiakManager.call_decorator, flatten_generator)
+
+ def test_flatten_generator(self):
+ results = []
+ counter = count()
+
+ @flatten_generator
+ def f():
+ for i in range(3):
+ a = yield counter.next()
+ results.append(a)
+
+ ret = f()
+ self.assertEqual(ret, None)
+ self.assertEqual(results, list(range(3)))
+
+ def test_flatter_generator_with_return_value(self):
+ @flatten_generator
+ def f():
+ yield None
+ returnValue("foo")
+
+ ret = f()
+ self.assertEqual(ret, "foo")
|
c4ea39ab8666a2872b25c9b8619f1b0feb823d9f
|
server.py
|
server.py
|
import os
from app import create_app, db
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
manager.add_command("runserver", Server(host="0.0.0.0"))
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
|
import os
from app import create_app, db
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
manager.add_command("runserver", Server(host="0.0.0.0"))
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
successful = unittest.TextTestRunner(verbosity=2).run(tests).wasSuccessful()
import sys
sys.exit(successful is False)
if __name__ == '__main__':
manager.run()
|
Change system return exit on failed tests
|
Change system return exit on failed tests
|
Python
|
mit
|
luisfcofv/Superhero
|
---
+++
@@ -20,7 +20,10 @@
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
- unittest.TextTestRunner(verbosity=2).run(tests)
+ successful = unittest.TextTestRunner(verbosity=2).run(tests).wasSuccessful()
+
+ import sys
+ sys.exit(successful is False)
if __name__ == '__main__':
|
b80b781b8f446b8149b948a6ec4aeff63fd728ce
|
Orange/widgets/utils/plot/__init__.py
|
Orange/widgets/utils/plot/__init__.py
|
"""
*************************
Plot classes and tools for use in Orange widgets
*************************
The main class of this module is :obj:`.OWPlot`, from which all plots
in visualization widgets should inherit.
This module also contains plot elements, which are normally used by the :obj:`.OWPlot`,
but can also be used directly or subclassed
"""
from .owplotgui import *
from .owpalette import *
from .owconstants import *
try:
from .owcurve import *
from .owpoint import *
from .owlegend import *
from .owaxis import *
from .owplot import *
from .owtools import *
except ImportError:
pass
|
"""
*************************
Plot classes and tools for use in Orange widgets
*************************
The main class of this module is :obj:`.OWPlot`, from which all plots
in visualization widgets should inherit.
This module also contains plot elements, which are normally used by the :obj:`.OWPlot`,
but can also be used directly or subclassed
"""
from .owplotgui import *
from .owpalette import *
from .owconstants import *
try:
from .owcurve import *
from .owpoint import *
from .owlegend import *
from .owaxis import *
from .owplot import *
from .owtools import *
except (ImportError, RuntimeError):
pass
|
Handle PyQt 5.3 raising RuntimeError on incompatible orangeqt import
|
Handle PyQt 5.3 raising RuntimeError on incompatible orangeqt import
|
Python
|
bsd-2-clause
|
cheral/orange3,cheral/orange3,cheral/orange3,cheral/orange3,cheral/orange3,cheral/orange3
|
---
+++
@@ -23,5 +23,5 @@
from .owaxis import *
from .owplot import *
from .owtools import *
-except ImportError:
+except (ImportError, RuntimeError):
pass
|
59651470489a4479db6d9a79de3aacee6b9d7cd8
|
travis/wait-until-cluster-initialised.py
|
travis/wait-until-cluster-initialised.py
|
#!/usr/bin/env python3
import json
import sys
import time
from urllib.request import urlopen
STATS_URL = "http://localhost:18001/stats"
MAXIMUM_TIME_SECONDS = 2 * 60
SLEEPING_INTERVAL_SECONDS = 1
STATUS_CODE_OK = 200
def is_initialised():
try:
response = urlopen(STATS_URL)
if (response.getcode() == STATUS_CODE_OK):
encoding = response.info().get_content_charset('utf-8')
content = response.read().decode(encoding)
return json.loads(content)['initialised']
else:
return False
except Exception as e:
return False
def wait_until_cluster_initialised():
start = time.time()
elapsed = 0.0
while elapsed < MAXIMUM_TIME_SECONDS:
if is_initialised():
print("Cluster initialised!")
break
elapsed = time.time() - start
print("Cluster not initialised... keep waiting... elapsed time: {1:.2f} seconds.".format(
SLEEPING_INTERVAL_SECONDS, elapsed))
time.sleep(SLEEPING_INTERVAL_SECONDS)
elapsed = time.time() - start
else:
sys.exit("Cluster not initialised after {} seconds. I give up!".format(MAXIMUM_TIME_SECONDS))
if __name__ == "__main__":
wait_until_cluster_initialised()
|
#!/usr/bin/env python3
import json
import sys
import time
from urllib.request import urlopen
STATS_URL = "http://localhost:18001/stats"
MAXIMUM_TIME_SECONDS = 2 * 60
SLEEPING_INTERVAL_SECONDS = 1
STATUS_CODE_OK = 200
def is_initialised():
try:
response = urlopen(STATS_URL)
if (response.getcode() == STATUS_CODE_OK):
encoding = response.info().get_content_charset('utf-8')
content = response.read().decode(encoding)
return json.loads(content)['initialised']
else:
return False
except Exception as e:
return False
def wait_until_cluster_initialised():
start = time.time()
elapsed = 0.0
while elapsed < MAXIMUM_TIME_SECONDS:
if is_initialised():
print("Cluster initialised!")
break
elapsed = time.time() - start
print("Cluster not initialised... keep waiting... elapsed time: {0:.2f} seconds.".format(elapsed))
time.sleep(SLEEPING_INTERVAL_SECONDS)
elapsed = time.time() - start
else:
sys.exit("Cluster not initialised after {} seconds. I give up!".format(MAXIMUM_TIME_SECONDS))
if __name__ == "__main__":
wait_until_cluster_initialised()
|
Remove unused left over parameter
|
Remove unused left over parameter
|
Python
|
apache-2.0
|
codiply/barrio,codiply/barrio
|
---
+++
@@ -31,8 +31,7 @@
print("Cluster initialised!")
break
elapsed = time.time() - start
- print("Cluster not initialised... keep waiting... elapsed time: {1:.2f} seconds.".format(
- SLEEPING_INTERVAL_SECONDS, elapsed))
+ print("Cluster not initialised... keep waiting... elapsed time: {0:.2f} seconds.".format(elapsed))
time.sleep(SLEEPING_INTERVAL_SECONDS)
elapsed = time.time() - start
else:
|
c1af56026da9669ff76908e4d89982b1c88fd30d
|
examples/custom_xmlrpc_client/server.py
|
examples/custom_xmlrpc_client/server.py
|
import random
import time
from SimpleXMLRPCServer import SimpleXMLRPCServer
def get_time():
time.sleep(random.random())
return time.time()
def get_random_number(low, high):
time.sleep(random.random())
return random.randint(low, high)
server = SimpleXMLRPCServer(("localhost", 8877))
print "Listening on port 8877..."
server.register_function(get_time, "get_time")
server.register_function(get_random_number, "get_random_number")
server.serve_forever()
|
import random
import time
from SimpleXMLRPCServer import SimpleXMLRPCServer
def get_time():
time.sleep(random.random())
return time.time()
def get_random_number(low, high):
time.sleep(random.random())
return random.randint(low, high)
server = SimpleXMLRPCServer(("localhost", 8877))
print("Listening on port 8877...")
server.register_function(get_time, "get_time")
server.register_function(get_random_number, "get_random_number")
server.serve_forever()
|
Use print() function in both Python 2 and Python 3
|
Use print() function in both Python 2 and Python 3
Discovered via: __flake8 . --count --select=E9,F63,F72,F82 --show-source --statistics__
Legacy __print__ statements are syntax errors in Python 3 but __print()__ function works as expected in both Python 2 and Python 3.
|
Python
|
mit
|
locustio/locust,mbeacom/locust,mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust,heyman/locust,mbeacom/locust,locustio/locust
|
---
+++
@@ -12,7 +12,7 @@
return random.randint(low, high)
server = SimpleXMLRPCServer(("localhost", 8877))
-print "Listening on port 8877..."
+print("Listening on port 8877...")
server.register_function(get_time, "get_time")
server.register_function(get_random_number, "get_random_number")
server.serve_forever()
|
d81dbd7b25cd44f730e979efe03eb6e5e1d87f1b
|
admin/commandRunner.py
|
admin/commandRunner.py
|
import configparser
import sys
import os
parser = configparser.ConfigParser()
parser.read("../halite.ini")
WORKERS = dict(parser.items("workerIPs"))
command = sys.argv[1]
print(command)
for name in WORKERS:
print("########"+name+"########")
print(WORKERS[name])
os.system("ssh root@"+WORKERS[name]+" '"+command+"'")
print("################\n")
|
import pymysql
import configparser
import sys
import os
import os.path
parser = configparser.ConfigParser()
parser.read("../halite.ini")
DB_CONFIG = parser["database"]
keyPath = os.path.join("../", parser["aws"]["keyfilepath"])
db = pymysql.connect(host=DB_CONFIG["hostname"], user=DB_CONFIG['username'], passwd=DB_CONFIG['password'], db=DB_CONFIG['name'], cursorclass=pymysql.cursors.DictCursor)
cursor = db.cursor()
cursor.execute("select * from Worker")
workers = cursor.fetchall()
command = sys.argv[1]
for worker in workers:
print("########"+worker['ipAddress']+"########")
os.system("ssh -i \""+keyPath+"\" ubuntu@"+worker['ipAddress']+" '"+command+"'")
print("################\n")
|
Switch command runner to using db
|
Switch command runner to using db
|
Python
|
mit
|
HaliteChallenge/Halite,HaliteChallenge/Halite,yangle/HaliteIO,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,yangle/HaliteIO,yangle/HaliteIO,lanyudhy/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite,HaliteChallenge/Halite,HaliteChallenge/Halite,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II
|
---
+++
@@ -1,15 +1,24 @@
+import pymysql
import configparser
import sys
import os
+import os.path
parser = configparser.ConfigParser()
parser.read("../halite.ini")
-WORKERS = dict(parser.items("workerIPs"))
+DB_CONFIG = parser["database"]
+
+keyPath = os.path.join("../", parser["aws"]["keyfilepath"])
+
+db = pymysql.connect(host=DB_CONFIG["hostname"], user=DB_CONFIG['username'], passwd=DB_CONFIG['password'], db=DB_CONFIG['name'], cursorclass=pymysql.cursors.DictCursor)
+cursor = db.cursor()
+
+cursor.execute("select * from Worker")
+workers = cursor.fetchall()
+
command = sys.argv[1]
-print(command)
-for name in WORKERS:
- print("########"+name+"########")
- print(WORKERS[name])
- os.system("ssh root@"+WORKERS[name]+" '"+command+"'")
+for worker in workers:
+ print("########"+worker['ipAddress']+"########")
+ os.system("ssh -i \""+keyPath+"\" ubuntu@"+worker['ipAddress']+" '"+command+"'")
print("################\n")
|
cba8bd7d3440cc643823e93036bc3b9ac938a412
|
pinboard_linkrot.py
|
pinboard_linkrot.py
|
#!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.get(link, headers = headers)
return r.status_code
except (SSLError, InvalidSchema, ConnectionError):
return 409
def is_valid_link(status_code):
if status_code == 200:
return True
else:
return False
def process_links(links):
bad_links = 0
try:
for link in links:
status_code = get_link_status_code(link['href'])
if not is_valid_link(status_code):
print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href'])
bad_links += 1
except KeyboardInterrupt:
pass
linkrot = int(bad_links/len(links)*100)
print '\n%s%% linkrot\n' % linkrot
def process_bookmarks_file(filename):
with open(filename) as f:
bookmarks = json.load(f)
process_links(bookmarks)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'Usage: pinboard_linkrot.py <bookmarks.json>'
exit(1)
process_bookmarks_file(sys.argv[1])
|
#!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.head(link, headers=headers, allow_redirects=True)
return r.status_code
except (SSLError, InvalidSchema, ConnectionError):
return 409
def is_valid_link(status_code):
if status_code == 200:
return True
else:
return False
def process_links(links):
bad_links = 0
try:
for link in links:
status_code = get_link_status_code(link['href'])
if not is_valid_link(status_code):
print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href'])
bad_links += 1
except KeyboardInterrupt:
pass
linkrot = int(bad_links/len(links)*100)
print '\n%s%% linkrot\n' % linkrot
def process_bookmarks_file(filename):
with open(filename) as f:
bookmarks = json.load(f)
process_links(bookmarks)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'Usage: pinboard_linkrot.py <bookmarks.json>'
exit(1)
process_bookmarks_file(sys.argv[1])
|
Switch to head requests rather than get requests.
|
Switch to head requests rather than get requests.
|
Python
|
mit
|
edgauthier/pinboard_linkrot
|
---
+++
@@ -9,7 +9,7 @@
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
- r = requests.get(link, headers = headers)
+ r = requests.head(link, headers=headers, allow_redirects=True)
return r.status_code
except (SSLError, InvalidSchema, ConnectionError):
return 409
|
4efbc87a912b62db062da0c277baf2ea007e29e2
|
feedthefox/users/models.py
|
feedthefox/users/models.py
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class User(AbstractUser):
"""Basic Mozillian user profile."""
ircname = models.CharField(max_length=50, default='', blank=True)
avatar_url = models.URLField(max_length=400, default='', blank=True)
city = models.CharField(max_length=50, default='', blank=True)
country = models.CharField(max_length=50, default='', blank=True)
mozillians_url = models.URLField()
def __str__(self):
return self.user.get_full_name()
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class User(AbstractUser):
"""Basic Mozillian user profile."""
ircname = models.CharField(max_length=50, default='', blank=True)
avatar_url = models.URLField(max_length=400, default='', blank=True)
city = models.CharField(max_length=50, default='', blank=True)
country = models.CharField(max_length=50, default='', blank=True)
mozillians_url = models.URLField()
def __str__(self):
return self.get_full_name()
|
Fix str method for custom User model.
|
Fix str method for custom User model.
|
Python
|
mpl-2.0
|
mozilla/feedthefox,akatsoulas/feedthefox,mozilla/feedthefox,akatsoulas/feedthefox,akatsoulas/feedthefox,akatsoulas/feedthefox,mozilla/feedthefox,mozilla/feedthefox
|
---
+++
@@ -14,4 +14,4 @@
mozillians_url = models.URLField()
def __str__(self):
- return self.user.get_full_name()
+ return self.get_full_name()
|
91f107ef2ebdaf7ff210b9f36e2c810441f389e7
|
services/rdio.py
|
services/rdio.py
|
from werkzeug.urls import url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
# URLs to interact with the API
request_token_url = 'http://api.rdio.com/oauth/request_token'
authorize_url = None # Provided when the request token is granted
access_token_url = 'http://api.rdio.com/oauth/access_token'
api_domain = 'api.rdio.com'
available_permissions = [
(None, 'access and manage your music'),
]
https = False
signature_type = SIGNATURE_TYPE_BODY
def parse_token(self, content):
# Override standard token request to also get the authorization URL
data = url_decode(content)
if 'login_url' in data:
self.authorize_url = data['login_url']
return super(Rdio, self).parse_token(content)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/1/', method='POST', data={
'method': 'currentUser',
})
return unicode(r.json[u'result'][u'key'])
|
from werkzeug.urls import url_decode
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
# URLs to interact with the API
request_token_url = 'http://api.rdio.com/oauth/request_token'
authorize_url = None # Provided when the request token is granted
access_token_url = 'http://api.rdio.com/oauth/access_token'
api_domain = 'api.rdio.com'
available_permissions = [
(None, 'access and manage your music'),
]
https = False
def parse_token(self, content):
# Override standard token request to also get the authorization URL
data = url_decode(content)
if 'login_url' in data:
self.authorize_url = data['login_url']
return super(Rdio, self).parse_token(content)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/1/', method='POST', data={
'method': 'currentUser',
})
return unicode(r.json[u'result'][u'key'])
|
Allow Rdio to use default signature handling
|
Allow Rdio to use default signature handling
|
Python
|
bsd-3-clause
|
foauth/oauth-proxy,foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
|
---
+++
@@ -1,5 +1,4 @@
from werkzeug.urls import url_decode
-from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
@@ -21,7 +20,6 @@
]
https = False
- signature_type = SIGNATURE_TYPE_BODY
def parse_token(self, content):
# Override standard token request to also get the authorization URL
|
7dcda004fb2cc61b075e7ef67c8c33ebfd70786c
|
bashhub/view/status.py
|
bashhub/view/status.py
|
import dateutil.parser
import datetime
import humanize
status_view ="""\
=== Bashhub Status
http://bashhub.com/u/{0}
Total Commands: {1}
Total Sessions: {2}
Total Systems: {3}
===
Session PID {4} Started {5}
Commands In Session: {6}
Commands Today: {7}
"""
def build_status_view(model):
date = datetime.datetime.fromtimestamp(model.session_start_time/1000.0)
date_str = humanize.naturaltime(date)
return status_view.format(model.username, model.total_commands,
model.total_sessions, model.total_systems, model.session_name,
date_str, model.session_total_commands, model.total_commands_today)
|
import dateutil.parser
import datetime
import humanize
status_view ="""\
=== Bashhub Status
https://bashhub.com/u/{0}
Total Commands: {1}
Total Sessions: {2}
Total Systems: {3}
===
Session PID {4} Started {5}
Commands In Session: {6}
Commands Today: {7}
"""
def build_status_view(model):
date = datetime.datetime.fromtimestamp(model.session_start_time/1000.0)
date_str = humanize.naturaltime(date)
return status_view.format(model.username, model.total_commands,
model.total_sessions, model.total_systems, model.session_name,
date_str, model.session_total_commands, model.total_commands_today)
|
Change http url to https
|
Change http url to https
|
Python
|
apache-2.0
|
rcaloras/bashhub-client,rcaloras/bashhub-client
|
---
+++
@@ -4,7 +4,7 @@
status_view ="""\
=== Bashhub Status
-http://bashhub.com/u/{0}
+https://bashhub.com/u/{0}
Total Commands: {1}
Total Sessions: {2}
Total Systems: {3}
|
7959c38d82090db6a66c7d81a4adba089c9a884f
|
brains/orders/views.py
|
brains/orders/views.py
|
import math
from django.shortcuts import render
from django.template import RequestContext
from django.http import HttpResponseRedirect
from orders.models import Order
def index(request, x, y):
if request.META['HTTP_REFERER'] not in ('http://www.urbandead.com/map.cgi', 'http://urbandead.com/map.cgi'):
return HttpResponseRedirect('http://www.youtube.com/watch?v=lWKQiZVBtu4')
x = int(x)
y = int(y)
# Fetch the orders
fresh_order = list(Order.objects.all().order_by('-date'))
fresh_order.sort(key=lambda o: user_coord_dist(x, y, o.x, o.y))
# Return orders sorted by distance
return render(request, 'orders/orders.html', dict(orders=fresh_order))
def user_coord_dist(x1, y1, x2, y2):
# Pythagoras
return math.sqrt(math.pow(x2-x1,2)+math.pow(y2-y1,2))
|
import math
from django.shortcuts import render
from django.template import RequestContext
from django.http import HttpResponseRedirect
from orders.models import Order
def index(request, x, y):
if request.META.get('HTTP_REFERER', None) not in ('http://www.urbandead.com/map.cgi', 'http://urbandead.com/map.cgi'):
return HttpResponseRedirect('http://www.youtube.com/watch?v=lWKQiZVBtu4')
x = int(x)
y = int(y)
# Fetch the orders
fresh_order = list(Order.objects.all().order_by('-date'))
fresh_order.sort(key=lambda o: user_coord_dist(x, y, o.x, o.y))
# Return orders sorted by distance
return render(request, 'orders/orders.html', dict(orders=fresh_order))
def user_coord_dist(x1, y1, x2, y2):
# Pythagoras
return math.sqrt(math.pow(x2-x1,2)+math.pow(y2-y1,2))
|
Test things first you big dummy
|
Test things first you big dummy
|
Python
|
bsd-3-clause
|
crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains
|
---
+++
@@ -6,7 +6,7 @@
def index(request, x, y):
- if request.META['HTTP_REFERER'] not in ('http://www.urbandead.com/map.cgi', 'http://urbandead.com/map.cgi'):
+ if request.META.get('HTTP_REFERER', None) not in ('http://www.urbandead.com/map.cgi', 'http://urbandead.com/map.cgi'):
return HttpResponseRedirect('http://www.youtube.com/watch?v=lWKQiZVBtu4')
x = int(x)
|
81489c115704c5df83ef7607121c8c20ab2ab2b0
|
packages/mono-llvm.py
|
packages/mono-llvm.py
|
GitHubTarballPackage ('mono', 'llvm', '3.0', '292aa8712c3120b03f9aa1d201b2e7949adf35c3',
configure = './configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0',
override_properties = { 'make': 'make' }
)
|
GitHubTarballPackage ('mono', 'llvm', '3.0', '292aa8712c3120b03f9aa1d201b2e7949adf35c3',
configure = './configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --build=i386-apple-darwin10.8.0',
override_properties = { 'make': 'make' }
)
|
Set --build instead of --target.
|
Set --build instead of --target.
|
Python
|
mit
|
mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild
|
---
+++
@@ -1,4 +1,4 @@
GitHubTarballPackage ('mono', 'llvm', '3.0', '292aa8712c3120b03f9aa1d201b2e7949adf35c3',
- configure = './configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0',
+ configure = './configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --build=i386-apple-darwin10.8.0',
override_properties = { 'make': 'make' }
)
|
9a7c84cab0931f2998af990200c4412f23cc2034
|
scripts/run_unit_test.py
|
scripts/run_unit_test.py
|
#!/usr/bin/env python
import serial
import os
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.system("cd " + FILE_LOCATION + " ../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("\nPlease press the phsyical reset button on the STM32F4Discovery board and then press enter to continue...")
# Open a serial port
ser = serial.Serial("/dev/serial/by-id/usb-PopaGator_Toad-if00", 115200)
# Send data to start USB OTG
ser.write("start")
# Read until we see the finished text
result = ''
try:
while True:
num_chars = ser.inWaiting()
if num_chars:
result += ser.read(num_chars)
if result.find("Finished") != -1:
break
finally:
# Print the result so the user can see and close the serial port
print result
ser.close()
|
#!/usr/bin/env python
import serial
import os
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("\nPlease press the phsyical reset button on the STM32F4Discovery board and then press enter to continue...")
# Open a serial port
ser = serial.Serial("/dev/serial/by-id/usb-PopaGator_Toad-if00", 115200)
# Send data to start USB OTG
ser.write("start")
# Read until we see the finished text
result = ''
try:
while True:
num_chars = ser.inWaiting()
if num_chars:
result += ser.read(num_chars)
if result.find("Finished") != -1:
break
finally:
# Print the result so the user can see and close the serial port
print result
ser.close()
|
Add ability to run unit test script from anywhere
|
UNIT_TEST: Add ability to run unit test script from anywhere
|
Python
|
mit
|
fnivek/Pop-a-Gator,fnivek/Pop-a-Gator,fnivek/Pop-a-Gator
|
---
+++
@@ -5,7 +5,7 @@
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
-os.system("cd " + FILE_LOCATION + " ../")
+os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
|
e2c3c9f50f3bdb537ef863d7cff80d4fd5e27911
|
test/test_api.py
|
test/test_api.py
|
import unittest
import sys
import appdirs
if sys.version_info[0] < 3:
STRING_TYPE = basestring
else:
STRING_TYPE = str
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertIsInstance(
appdirs.user_data_dir('MyApp', 'MyCompany'), STRING_TYPE)
self.assertIsInstance(
appdirs.site_data_dir('MyApp', 'MyCompany'), STRING_TYPE)
self.assertIsInstance(
appdirs.user_cache_dir('MyApp', 'MyCompany'), STRING_TYPE)
self.assertIsInstance(
appdirs.user_log_dir('MyApp', 'MyCompany'), STRING_TYPE)
def test_dirs(self):
dirs = appdirs.AppDirs('MyApp', 'MyCompany', version='1.0')
self.assertIsInstance(dirs.user_data_dir, STRING_TYPE)
self.assertIsInstance(dirs.site_data_dir, STRING_TYPE)
self.assertIsInstance(dirs.user_cache_dir, STRING_TYPE)
self.assertIsInstance(dirs.user_log_dir, STRING_TYPE)
if __name__ == "__main__":
unittest.main()
|
import sys
import appdirs
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
if sys.version_info[0] < 3:
STRING_TYPE = basestring
else:
STRING_TYPE = str
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertIsInstance(
appdirs.user_data_dir('MyApp', 'MyCompany'), STRING_TYPE)
self.assertIsInstance(
appdirs.site_data_dir('MyApp', 'MyCompany'), STRING_TYPE)
self.assertIsInstance(
appdirs.user_cache_dir('MyApp', 'MyCompany'), STRING_TYPE)
self.assertIsInstance(
appdirs.user_log_dir('MyApp', 'MyCompany'), STRING_TYPE)
def test_dirs(self):
dirs = appdirs.AppDirs('MyApp', 'MyCompany', version='1.0')
self.assertIsInstance(dirs.user_data_dir, STRING_TYPE)
self.assertIsInstance(dirs.site_data_dir, STRING_TYPE)
self.assertIsInstance(dirs.user_cache_dir, STRING_TYPE)
self.assertIsInstance(dirs.user_log_dir, STRING_TYPE)
if __name__ == "__main__":
unittest.main()
|
Use unittest2 for Python < 2.7.
|
Use unittest2 for Python < 2.7.
|
Python
|
mit
|
platformdirs/platformdirs
|
---
+++
@@ -1,6 +1,10 @@
-import unittest
import sys
import appdirs
+
+if sys.version_info < (2, 7):
+ import unittest2 as unittest
+else:
+ import unittest
if sys.version_info[0] < 3:
STRING_TYPE = basestring
|
53fa37b1e8a97c214a0a3c1f95be53dbe4d3d442
|
comics/comics/wumovg.py
|
comics/comics/wumovg.py
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = 'Wulffmorgenthaler (vg.no)'
language = 'no'
url = 'http://heltnormalt.no/wumo'
rights = 'Mikael Wulff & Anders Morgenthaler'
class Crawler(CrawlerBase):
history_capable_date = '2013-01-26'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = 'Europe/Oslo'
def crawl(self, pub_date):
url = 'http://heltnormalt.no/img/wumo/%s.jpg' % (
pub_date.strftime('%Y/%m/%d'))
return CrawlerImage(url)
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = 'Wumo (vg.no)'
language = 'no'
url = 'http://heltnormalt.no/wumo'
rights = 'Mikael Wulff & Anders Morgenthaler'
class Crawler(CrawlerBase):
history_capable_date = '2013-01-26'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = 'Europe/Oslo'
def crawl(self, pub_date):
url = 'http://heltnormalt.no/img/wumo/%s.jpg' % (
pub_date.strftime('%Y/%m/%d'))
return CrawlerImage(url)
|
Update title of 'Wumo' crawlers, part two
|
Update title of 'Wumo' crawlers, part two
|
Python
|
agpl-3.0
|
jodal/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics
|
---
+++
@@ -3,7 +3,7 @@
class ComicData(ComicDataBase):
- name = 'Wulffmorgenthaler (vg.no)'
+ name = 'Wumo (vg.no)'
language = 'no'
url = 'http://heltnormalt.no/wumo'
rights = 'Mikael Wulff & Anders Morgenthaler'
|
534066b1228bb0070c1d62445155afa696a37921
|
contrail_provisioning/config/templates/contrail_plugin_ini.py
|
contrail_provisioning/config/templates/contrail_plugin_ini.py
|
import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
#use_ssl = False
#insecure = False
#certfile=$__contrail_api_server_cert_file__
#keyfile=$__contrail_api_server_key_file__
#cafile=$__contrail_api_server_ca_file__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None
[COLLECTOR]
analytics_api_ip = $__contrail_analytics_server_ip__
analytics_api_port = $__contrail_analytics_server_port__
[KEYSTONE]
auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0
admin_user=$__contrail_admin_user__
admin_password=$__contrail_admin_password__
admin_tenant_name=$__contrail_admin_tenant_name__
""")
|
import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
#use_ssl = False
#insecure = False
#certfile=$__contrail_api_server_cert_file__
#keyfile=$__contrail_api_server_key_file__
#cafile=$__contrail_api_server_ca_file__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None
[COLLECTOR]
analytics_api_ip = $__contrail_analytics_server_ip__
analytics_api_port = $__contrail_analytics_server_port__
[KEYSTONE]
auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0
admin_user=$__contrail_admin_user__
admin_password=$__contrail_admin_password__
admin_tenant_name=$__contrail_admin_tenant_name__
""")
|
Enable service-interface and vf-binding extensions by default in contrail based provisioning.
|
Enable service-interface and vf-binding extensions by default in
contrail based provisioning.
Change-Id: I5916f41cdf12ad54e74c0f76de244ed60f57aea5
Partial-Bug: 1556336
|
Python
|
apache-2.0
|
Juniper/contrail-provisioning,Juniper/contrail-provisioning
|
---
+++
@@ -10,7 +10,7 @@
#certfile=$__contrail_api_server_cert_file__
#keyfile=$__contrail_api_server_key_file__
#cafile=$__contrail_api_server_ca_file__
-contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None
+contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None
[COLLECTOR]
analytics_api_ip = $__contrail_analytics_server_ip__
|
eb987c4ca71ec53db46c0a8afa4265f70671330d
|
geotrek/settings/env_tests.py
|
geotrek/settings/env_tests.py
|
#
# Django Tests
# ..........................
TEST = True
CELERY_ALWAYS_EAGER = True
TEST_EXCLUDE = ('django',)
INSTALLED_APPS += (
'geotrek.diving',
'geotrek.sensitivity',
'geotrek.outdoor',
)
LOGGING['handlers']['console']['level'] = 'CRITICAL'
LANGUAGE_CODE = 'en'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
MODELTRANSLATION_LANGUAGES = ('en', 'es', 'fr', 'it')
LAND_BBOX_AREAS_ENABLED = True
class DisableMigrations():
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
ADMINS = (
('test', 'test@test.com'),
)
MANAGERS = ADMINS
TEST_RUNNER = 'geotrek.test_runner.TestRunner'
|
#
# Django Tests
# ..........................
TEST = True
CELERY_ALWAYS_EAGER = True
TEST_EXCLUDE = ('django',)
INSTALLED_APPS += (
'geotrek.diving',
'geotrek.sensitivity',
'geotrek.outdoor',
'drf_yasg',
)
LOGGING['handlers']['console']['level'] = 'CRITICAL'
LANGUAGE_CODE = 'en'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
MODELTRANSLATION_LANGUAGES = ('en', 'es', 'fr', 'it')
LAND_BBOX_AREAS_ENABLED = True
class DisableMigrations():
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
ADMINS = (
('test', 'test@test.com'),
)
MANAGERS = ADMINS
TEST_RUNNER = 'geotrek.test_runner.TestRunner'
|
Enable drf_yasg in test settings
|
Enable drf_yasg in test settings
|
Python
|
bsd-2-clause
|
GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek
|
---
+++
@@ -12,6 +12,7 @@
'geotrek.diving',
'geotrek.sensitivity',
'geotrek.outdoor',
+ 'drf_yasg',
)
LOGGING['handlers']['console']['level'] = 'CRITICAL'
|
456de4b1184780b9179ee9e6572a3f62cf22550a
|
tests/test_tools/simple_project.py
|
tests/test_tools/simple_project.py
|
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768']
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
|
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768'],
'linker_file': ['linker_script'],
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
|
Test - add linker script for tools project
|
Test - add linker script for tools project
|
Python
|
apache-2.0
|
molejar/project_generator,hwfwgrp/project_generator,0xc0170/project_generator,sarahmarshy/project_generator,ohagendorf/project_generator,project-generator/project_generator
|
---
+++
@@ -2,7 +2,8 @@
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
- 'target': ['mbed-lpc1768']
+ 'target': ['mbed-lpc1768'],
+ 'linker_file': ['linker_script'],
}
}
|
eca27464cc2c23a84e56e1d432a080ca663d04fb
|
src/dicomweb_client/__init__.py
|
src/dicomweb_client/__init__.py
|
__version__ = '0.9.1'
from dicomweb_client.api import DICOMwebClient
|
__version__ = '0.9.2'
from dicomweb_client.api import DICOMwebClient
|
Increase version to 0.9.2 for release
|
Increase version to 0.9.2 for release
|
Python
|
mit
|
MGHComputationalPathology/dicomweb-client
|
---
+++
@@ -1,3 +1,3 @@
-__version__ = '0.9.1'
+__version__ = '0.9.2'
from dicomweb_client.api import DICOMwebClient
|
47aeeaad68ea0c9246ec68b7a49f385a4b7fe9cf
|
socketio/policyserver.py
|
socketio/policyserver.py
|
from gevent.server import StreamServer
__all__ = ['FlashPolicyServer']
class FlashPolicyServer(StreamServer):
policy = """<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>"""
def __init__(self, listener=None, backlog=None):
if listener is None:
listener = ('0.0.0.0', 10843)
StreamServer.__init__(self, listener=listener, backlog=backlog)
def handle(self, socket, address):
socket.sendall(self.policy)
|
from gevent.server import StreamServer
__all__ = ['FlashPolicyServer']
class FlashPolicyServer(StreamServer):
policy = """<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>"""
def __init__(self, listener=None, backlog=None):
if listener is None:
listener = ('0.0.0.0', 10843)
StreamServer.__init__(self, listener=listener, backlog=backlog)
def handle(self, sock, address):
# send and read functions should not wait longer than three seconds
sock.settimeout(3)
try:
# try to receive at most 128 bytes (`POLICYREQUEST` is shorter)
# Interestingly if we dont do this and we write to the spcket directly
# I am getting strange errors.
input = sock.recv(128)
if input.startswith(FlashPolicyServer.policyrequest):
sock.sendall(FlashPolicyServer.policy)
except socket.timeout:
pass
sock.close()
|
Fix to make sure we dont get errors in gevent socket write call when we are writing the policy file back
|
Fix to make sure we dont get errors in gevent socket write call when we are writing the policy file back
Conflicts:
socketio/policyserver.py
|
Python
|
bsd-3-clause
|
abourget/gevent-socketio,arnuschky/gevent-socketio,bobvandevijver/gevent-socketio,Eugeny/gevent-socketio,hzruandd/gevent-socketio,gutomaia/gevent-socketio,gutomaia/gevent-socketio,yacneyac/gevent-socketio,smurfix/gevent-socketio,gutomaia/gevent-socketio,smurfix/gevent-socketio,Eugeny/gevent-socketio,kazmiruk/gevent-socketio,arnuschky/gevent-socketio,kazmiruk/gevent-socketio,abourget/gevent-socketio,smurfix/gevent-socketio,theskumar-archive/gevent-socketio,theskumar-archive/gevent-socketio,bobvandevijver/gevent-socketio,hzruandd/gevent-socketio,yacneyac/gevent-socketio
|
---
+++
@@ -12,5 +12,16 @@
listener = ('0.0.0.0', 10843)
StreamServer.__init__(self, listener=listener, backlog=backlog)
- def handle(self, socket, address):
- socket.sendall(self.policy)
+ def handle(self, sock, address):
+ # send and read functions should not wait longer than three seconds
+ sock.settimeout(3)
+ try:
+ # try to receive at most 128 bytes (`POLICYREQUEST` is shorter)
+ # Interestingly if we dont do this and we write to the spcket directly
+ # I am getting strange errors.
+ input = sock.recv(128)
+ if input.startswith(FlashPolicyServer.policyrequest):
+ sock.sendall(FlashPolicyServer.policy)
+ except socket.timeout:
+ pass
+ sock.close()
|
fc04d8f2629e5fef10cf62749e7c91e6b7d2d557
|
cms/djangoapps/contentstore/views/session_kv_store.py
|
cms/djangoapps/contentstore/views/session_kv_store.py
|
"""
An :class:`~xblock.runtime.KeyValueStore` that stores data in the django session
"""
from __future__ import absolute_import
from xblock.runtime import KeyValueStore
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request):
self._session = request.session
def get(self, key):
return self._session[tuple(key)]
def set(self, key, value):
self._session[tuple(key)] = value
def delete(self, key):
del self._session[tuple(key)]
def has(self, key):
return tuple(key) in self._session
|
"""
An :class:`~xblock.runtime.KeyValueStore` that stores data in the django session
"""
from __future__ import absolute_import
from xblock.runtime import KeyValueStore
def stringify(key):
return repr(tuple(key))
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request):
self._session = request.session
def get(self, key):
return self._session[stringify(key)]
def set(self, key, value):
self._session[stringify(key)] = value
def delete(self, key):
del self._session[stringify(key)]
def has(self, key):
return stringify(key) in self._session
|
Use strings instead of tuples as keys in SessionKeyValueStore
|
Use strings instead of tuples as keys in SessionKeyValueStore
Some Django packages expect only strings as keys in the user session,
and it is also a recommended practice in the Django manual.
|
Python
|
agpl-3.0
|
ESOedX/edx-platform,B-MOOC/edx-platform,jswope00/griffinx,openfun/edx-platform,MakeHer/edx-platform,benpatterson/edx-platform,stvstnfrd/edx-platform,AkA84/edx-platform,Softmotions/edx-platform,IONISx/edx-platform,kmoocdev2/edx-platform,nanolearningllc/edx-platform-cypress,unicri/edx-platform,romain-li/edx-platform,xinjiguaike/edx-platform,mbareta/edx-platform-ft,RPI-OPENEDX/edx-platform,simbs/edx-platform,msegado/edx-platform,4eek/edx-platform,longmen21/edx-platform,cognitiveclass/edx-platform,eduNEXT/edx-platform,hastexo/edx-platform,openfun/edx-platform,eestay/edx-platform,shurihell/testasia,DNFcode/edx-platform,hamzehd/edx-platform,iivic/BoiseStateX,jruiperezv/ANALYSE,atsolakid/edx-platform,arifsetiawan/edx-platform,leansoft/edx-platform,chauhanhardik/populo,B-MOOC/edx-platform,doismellburning/edx-platform,Edraak/edraak-platform,nanolearningllc/edx-platform-cypress-2,simbs/edx-platform,tanmaykm/edx-platform,Edraak/circleci-edx-platform,Shrhawk/edx-platform,kmoocdev/edx-platform,devs1991/test_edx_docmode,martynovp/edx-platform,shubhdev/edx-platform,chauhanhardik/populo_2,kmoocdev2/edx-platform,inares/edx-platform,AkA84/edx-platform,jazkarta/edx-platform-for-isc,chand3040/cloud_that,romain-li/edx-platform,zhenzhai/edx-platform,nttks/edx-platform,zerobatu/edx-platform,gymnasium/edx-platform,cyanna/edx-platform,beni55/edx-platform,chudaol/edx-platform,shubhdev/edxOnBaadal,sameetb-cuelogic/edx-platform-test,atsolakid/edx-platform,cyanna/edx-platform,CourseTalk/edx-platform,rue89-tech/edx-platform,DNFcode/edx-platform,wwj718/edx-platform,ahmadio/edx-platform,mitocw/edx-platform,unicri/edx-platform,cognitiveclass/edx-platform,Edraak/edx-platform,andyzsf/edx,shashank971/edx-platform,nikolas/edx-platform,antoviaque/edx-platform,pabloborrego93/edx-platform,Endika/edx-platform,leansoft/edx-platform,devs1991/test_edx_docmode,shashank971/edx-platform,waheedahmed/edx-platform,xuxiao19910803/edx,halvertoluke/edx-platform,unicri/edx-platform,EDUlib/edx-platform,franosincic/edx-platform,appliedx/edx-platform,Stanford-Online/edx-platform,jazkarta/edx-platform-for-isc,DNFcode/edx-platform,wwj718/ANALYSE,wwj718/edx-platform,kmoocdev/edx-platform,jelugbo/tundex,kxliugang/edx-platform,gymnasium/edx-platform,jazkarta/edx-platform,EDUlib/edx-platform,teltek/edx-platform,MSOpenTech/edx-platform,angelapper/edx-platform,jazkarta/edx-platform,xuxiao19910803/edx,jamesblunt/edx-platform,TeachAtTUM/edx-platform,chudaol/edx-platform,halvertoluke/edx-platform,kamalx/edx-platform,cselis86/edx-platform,jelugbo/tundex,J861449197/edx-platform,etzhou/edx-platform,zerobatu/edx-platform,chauhanhardik/populo,AkA84/edx-platform,nttks/jenkins-test,proversity-org/edx-platform,jelugbo/tundex,chand3040/cloud_that,ubc/edx-platform,JCBarahona/edX,franosincic/edx-platform,OmarIthawi/edx-platform,philanthropy-u/edx-platform,cpennington/edx-platform,nanolearningllc/edx-platform-cypress,deepsrijit1105/edx-platform,sameetb-cuelogic/edx-platform-test,tiagochiavericosta/edx-platform,atsolakid/edx-platform,etzhou/edx-platform,fintech-circle/edx-platform,kursitet/edx-platform,devs1991/test_edx_docmode,rue89-tech/edx-platform,zerobatu/edx-platform,valtech-mooc/edx-platform,Endika/edx-platform,doismellburning/edx-platform,a-parhom/edx-platform,edx/edx-platform,mushtaqak/edx-platform,pomegranited/edx-platform,ferabra/edx-platform,cecep-edu/edx-platform,iivic/BoiseStateX,Shrhawk/edx-platform,jazkarta/edx-platform-for-isc,jbassen/edx-platform,dsajkl/123,arifsetiawan/edx-platform,xuxiao19910803/edx-platform,openfun/edx-platform,JCBarahona/edX,beni55/edx-platform,EDUlib/edx-platform,cyanna/edx-platform,cyanna/edx-platform,vismartltd/edx-platform,kxliugang/edx-platform,louyihua/edx-platform,jbassen/edx-platform,motion2015/a3,zofuthan/edx-platform,raccoongang/edx-platform,mtlchun/edx,analyseuc3m/ANALYSE-v1,eemirtekin/edx-platform,devs1991/test_edx_docmode,CredoReference/edx-platform,antonve/s4-project-mooc,ak2703/edx-platform,appsembler/edx-platform,beacloudgenius/edx-platform,cpennington/edx-platform,itsjeyd/edx-platform,ubc/edx-platform,hamzehd/edx-platform,UXE/local-edx,Kalyzee/edx-platform,alu042/edx-platform,jzoldak/edx-platform,naresh21/synergetics-edx-platform,edx-solutions/edx-platform,benpatterson/edx-platform,vasyarv/edx-platform,vikas1885/test1,Edraak/edx-platform,SravanthiSinha/edx-platform,bitifirefly/edx-platform,tiagochiavericosta/edx-platform,eduNEXT/edx-platform,y12uc231/edx-platform,alu042/edx-platform,sameetb-cuelogic/edx-platform-test,caesar2164/edx-platform,benpatterson/edx-platform,Ayub-Khan/edx-platform,leansoft/edx-platform,edry/edx-platform,DNFcode/edx-platform,jazkarta/edx-platform,valtech-mooc/edx-platform,Lektorium-LLC/edx-platform,dsajkl/reqiop,nagyistoce/edx-platform,ahmadio/edx-platform,rismalrv/edx-platform,ovnicraft/edx-platform,ahmadio/edx-platform,Livit/Livit.Learn.EdX,ahmadiga/min_edx,ampax/edx-platform-backup,beni55/edx-platform,TeachAtTUM/edx-platform,ak2703/edx-platform,kamalx/edx-platform,mitocw/edx-platform,AkA84/edx-platform,louyihua/edx-platform,JioEducation/edx-platform,chand3040/cloud_that,mjirayu/sit_academy,peterm-itr/edx-platform,jjmiranda/edx-platform,Kalyzee/edx-platform,dsajkl/reqiop,SravanthiSinha/edx-platform,edry/edx-platform,teltek/edx-platform,doismellburning/edx-platform,appliedx/edx-platform,pomegranited/edx-platform,Endika/edx-platform,nagyistoce/edx-platform,dkarakats/edx-platform,wwj718/ANALYSE,Livit/Livit.Learn.EdX,cognitiveclass/edx-platform,jolyonb/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,vikas1885/test1,bitifirefly/edx-platform,TeachAtTUM/edx-platform,marcore/edx-platform,waheedahmed/edx-platform,bigdatauniversity/edx-platform,playm2mboy/edx-platform,jonathan-beard/edx-platform,pabloborrego93/edx-platform,dcosentino/edx-platform,jazkarta/edx-platform,RPI-OPENEDX/edx-platform,ovnicraft/edx-platform,kamalx/edx-platform,chand3040/cloud_that,ampax/edx-platform-backup,waheedahmed/edx-platform,IndonesiaX/edx-platform,kmoocdev/edx-platform,RPI-OPENEDX/edx-platform,defance/edx-platform,nttks/edx-platform,shabab12/edx-platform,longmen21/edx-platform,gsehub/edx-platform,Semi-global/edx-platform,marcore/edx-platform,dsajkl/123,appsembler/edx-platform,jzoldak/edx-platform,shashank971/edx-platform,etzhou/edx-platform,nagyistoce/edx-platform,MSOpenTech/edx-platform,CourseTalk/edx-platform,mahendra-r/edx-platform,rue89-tech/edx-platform,ampax/edx-platform-backup,beni55/edx-platform,chrisndodge/edx-platform,motion2015/a3,IONISx/edx-platform,SravanthiSinha/edx-platform,Shrhawk/edx-platform,alexthered/kienhoc-platform,mitocw/edx-platform,proversity-org/edx-platform,vikas1885/test1,mcgachey/edx-platform,jbzdak/edx-platform,BehavioralInsightsTeam/edx-platform,devs1991/test_edx_docmode,ahmadiga/min_edx,motion2015/a3,appliedx/edx-platform,bigdatauniversity/edx-platform,solashirai/edx-platform,UXE/local-edx,jonathan-beard/edx-platform,iivic/BoiseStateX,OmarIthawi/edx-platform,4eek/edx-platform,Kalyzee/edx-platform,jazkarta/edx-platform-for-isc,Edraak/edx-platform,nanolearningllc/edx-platform-cypress,vismartltd/edx-platform,angelapper/edx-platform,playm2mboy/edx-platform,fintech-circle/edx-platform,bigdatauniversity/edx-platform,nagyistoce/edx-platform,Lektorium-LLC/edx-platform,bigdatauniversity/edx-platform,don-github/edx-platform,zubair-arbi/edx-platform,ubc/edx-platform,prarthitm/edxplatform,SravanthiSinha/edx-platform,fintech-circle/edx-platform,ferabra/edx-platform,antoviaque/edx-platform,marcore/edx-platform,proversity-org/edx-platform,chudaol/edx-platform,tiagochiavericosta/edx-platform,jbassen/edx-platform,rismalrv/edx-platform,cselis86/edx-platform,shubhdev/edxOnBaadal,ferabra/edx-platform,ubc/edx-platform,rismalrv/edx-platform,doismellburning/edx-platform,cognitiveclass/edx-platform,rhndg/openedx,utecuy/edx-platform,ahmadiga/min_edx,doganov/edx-platform,nttks/jenkins-test,andyzsf/edx,defance/edx-platform,chudaol/edx-platform,mjirayu/sit_academy,halvertoluke/edx-platform,CourseTalk/edx-platform,MakeHer/edx-platform,Softmotions/edx-platform,DefyVentures/edx-platform,Softmotions/edx-platform,arifsetiawan/edx-platform,xingyepei/edx-platform,zadgroup/edx-platform,jruiperezv/ANALYSE,proversity-org/edx-platform,JioEducation/edx-platform,pabloborrego93/edx-platform,don-github/edx-platform,edry/edx-platform,pepeportela/edx-platform,utecuy/edx-platform,nagyistoce/edx-platform,MSOpenTech/edx-platform,arbrandes/edx-platform,utecuy/edx-platform,Kalyzee/edx-platform,J861449197/edx-platform,synergeticsedx/deployment-wipro,eestay/edx-platform,ovnicraft/edx-platform,SivilTaram/edx-platform,eestay/edx-platform,Ayub-Khan/edx-platform,SivilTaram/edx-platform,BehavioralInsightsTeam/edx-platform,UXE/local-edx,antonve/s4-project-mooc,zadgroup/edx-platform,fly19890211/edx-platform,longmen21/edx-platform,chauhanhardik/populo_2,mbareta/edx-platform-ft,philanthropy-u/edx-platform,hamzehd/edx-platform,nanolearningllc/edx-platform-cypress-2,ampax/edx-platform,UOMx/edx-platform,cecep-edu/edx-platform,dsajkl/reqiop,jswope00/griffinx,ahmadiga/min_edx,don-github/edx-platform,shashank971/edx-platform,10clouds/edx-platform,IndonesiaX/edx-platform,mjirayu/sit_academy,unicri/edx-platform,shabab12/edx-platform,valtech-mooc/edx-platform,miptliot/edx-platform,UOMx/edx-platform,zofuthan/edx-platform,alu042/edx-platform,xinjiguaike/edx-platform,xuxiao19910803/edx,edry/edx-platform,ak2703/edx-platform,doganov/edx-platform,mbareta/edx-platform-ft,shubhdev/edx-platform,chauhanhardik/populo,cecep-edu/edx-platform,louyihua/edx-platform,Semi-global/edx-platform,gsehub/edx-platform,Endika/edx-platform,shubhdev/openedx,ESOedX/edx-platform,stvstnfrd/edx-platform,Edraak/edx-platform,appliedx/edx-platform,mtlchun/edx,jelugbo/tundex,arifsetiawan/edx-platform,nikolas/edx-platform,amir-qayyum-khan/edx-platform,dcosentino/edx-platform,cecep-edu/edx-platform,adoosii/edx-platform,arbrandes/edx-platform,xingyepei/edx-platform,Lektorium-LLC/edx-platform,naresh21/synergetics-edx-platform,procangroup/edx-platform,mahendra-r/edx-platform,fly19890211/edx-platform,msegado/edx-platform,CredoReference/edx-platform,kxliugang/edx-platform,rue89-tech/edx-platform,dkarakats/edx-platform,benpatterson/edx-platform,stvstnfrd/edx-platform,romain-li/edx-platform,alu042/edx-platform,ampax/edx-platform,ampax/edx-platform-backup,valtech-mooc/edx-platform,motion2015/a3,caesar2164/edx-platform,tiagochiavericosta/edx-platform,bigdatauniversity/edx-platform,JCBarahona/edX,analyseuc3m/ANALYSE-v1,IONISx/edx-platform,xuxiao19910803/edx-platform,jazztpt/edx-platform,mushtaqak/edx-platform,atsolakid/edx-platform,eduNEXT/edunext-platform,mjirayu/sit_academy,xingyepei/edx-platform,itsjeyd/edx-platform,DefyVentures/edx-platform,antoviaque/edx-platform,10clouds/edx-platform,eemirtekin/edx-platform,shabab12/edx-platform,synergeticsedx/deployment-wipro,nikolas/edx-platform,edx/edx-platform,antoviaque/edx-platform,wwj718/edx-platform,bitifirefly/edx-platform,mcgachey/edx-platform,defance/edx-platform,alexthered/kienhoc-platform,vasyarv/edx-platform,lduarte1991/edx-platform,ZLLab-Mooc/edx-platform,jruiperezv/ANALYSE,chrisndodge/edx-platform,sameetb-cuelogic/edx-platform-test,iivic/BoiseStateX,sameetb-cuelogic/edx-platform-test,zerobatu/edx-platform,xuxiao19910803/edx,atsolakid/edx-platform,jbassen/edx-platform,cselis86/edx-platform,ZLLab-Mooc/edx-platform,wwj718/edx-platform,nanolearningllc/edx-platform-cypress-2,msegado/edx-platform,JCBarahona/edX,miptliot/edx-platform,chrisndodge/edx-platform,shubhdev/edxOnBaadal,knehez/edx-platform,Ayub-Khan/edx-platform,dkarakats/edx-platform,xuxiao19910803/edx-platform,SivilTaram/edx-platform,B-MOOC/edx-platform,adoosii/edx-platform,Edraak/edraak-platform,kursitet/edx-platform,beni55/edx-platform,Livit/Livit.Learn.EdX,kursitet/edx-platform,ahmadio/edx-platform,jbzdak/edx-platform,caesar2164/edx-platform,marcore/edx-platform,jruiperezv/ANALYSE,jamesblunt/edx-platform,kxliugang/edx-platform,mtlchun/edx,alexthered/kienhoc-platform,deepsrijit1105/edx-platform,fly19890211/edx-platform,edry/edx-platform,jamiefolsom/edx-platform,xingyepei/edx-platform,Shrhawk/edx-platform,beacloudgenius/edx-platform,appsembler/edx-platform,shubhdev/edxOnBaadal,motion2015/edx-platform,beacloudgenius/edx-platform,gymnasium/edx-platform,ESOedX/edx-platform,cyanna/edx-platform,jamesblunt/edx-platform,ampax/edx-platform-backup,beacloudgenius/edx-platform,devs1991/test_edx_docmode,vasyarv/edx-platform,IndonesiaX/edx-platform,olexiim/edx-platform,knehez/edx-platform,cecep-edu/edx-platform,arbrandes/edx-platform,dcosentino/edx-platform,arifsetiawan/edx-platform,Stanford-Online/edx-platform,cognitiveclass/edx-platform,IONISx/edx-platform,Edraak/edx-platform,vasyarv/edx-platform,iivic/BoiseStateX,DNFcode/edx-platform,chauhanhardik/populo_2,zadgroup/edx-platform,zubair-arbi/edx-platform,zofuthan/edx-platform,jjmiranda/edx-platform,procangroup/edx-platform,rismalrv/edx-platform,CourseTalk/edx-platform,olexiim/edx-platform,ak2703/edx-platform,mahendra-r/edx-platform,nttks/edx-platform,bitifirefly/edx-platform,shubhdev/openedx,franosincic/edx-platform,kmoocdev2/edx-platform,jswope00/griffinx,mushtaqak/edx-platform,synergeticsedx/deployment-wipro,solashirai/edx-platform,MakeHer/edx-platform,xuxiao19910803/edx-platform,antonve/s4-project-mooc,stvstnfrd/edx-platform,Edraak/circleci-edx-platform,polimediaupv/edx-platform,vasyarv/edx-platform,antonve/s4-project-mooc,jolyonb/edx-platform,ahmadiga/min_edx,arbrandes/edx-platform,procangroup/edx-platform,shubhdev/edx-platform,utecuy/edx-platform,chauhanhardik/populo,inares/edx-platform,devs1991/test_edx_docmode,BehavioralInsightsTeam/edx-platform,caesar2164/edx-platform,motion2015/edx-platform,ESOedX/edx-platform,nttks/jenkins-test,Lektorium-LLC/edx-platform,eduNEXT/edunext-platform,don-github/edx-platform,solashirai/edx-platform,martynovp/edx-platform,kmoocdev/edx-platform,CredoReference/edx-platform,msegado/edx-platform,IndonesiaX/edx-platform,polimediaupv/edx-platform,y12uc231/edx-platform,kursitet/edx-platform,jamesblunt/edx-platform,don-github/edx-platform,RPI-OPENEDX/edx-platform,jonathan-beard/edx-platform,jonathan-beard/edx-platform,angelapper/edx-platform,xinjiguaike/edx-platform,wwj718/ANALYSE,gsehub/edx-platform,antonve/s4-project-mooc,cpennington/edx-platform,adoosii/edx-platform,solashirai/edx-platform,EDUlib/edx-platform,longmen21/edx-platform,jazkarta/edx-platform-for-isc,mushtaqak/edx-platform,chudaol/edx-platform,MSOpenTech/edx-platform,pepeportela/edx-platform,mcgachey/edx-platform,philanthropy-u/edx-platform,jswope00/griffinx,lduarte1991/edx-platform,pomegranited/edx-platform,solashirai/edx-platform,rismalrv/edx-platform,tanmaykm/edx-platform,hastexo/edx-platform,eemirtekin/edx-platform,vismartltd/edx-platform,Edraak/circleci-edx-platform,zadgroup/edx-platform,jruiperezv/ANALYSE,eestay/edx-platform,edx/edx-platform,mitocw/edx-platform,Edraak/circleci-edx-platform,zhenzhai/edx-platform,J861449197/edx-platform,synergeticsedx/deployment-wipro,teltek/edx-platform,fintech-circle/edx-platform,beacloudgenius/edx-platform,romain-li/edx-platform,shubhdev/edxOnBaadal,raccoongang/edx-platform,a-parhom/edx-platform,4eek/edx-platform,JioEducation/edx-platform,rhndg/openedx,tiagochiavericosta/edx-platform,waheedahmed/edx-platform,nttks/edx-platform,philanthropy-u/edx-platform,JioEducation/edx-platform,pepeportela/edx-platform,doganov/edx-platform,ovnicraft/edx-platform,shubhdev/edx-platform,waheedahmed/edx-platform,chauhanhardik/populo,jswope00/griffinx,shubhdev/edx-platform,teltek/edx-platform,cselis86/edx-platform,lduarte1991/edx-platform,kamalx/edx-platform,Ayub-Khan/edx-platform,alexthered/kienhoc-platform,lduarte1991/edx-platform,ZLLab-Mooc/edx-platform,alexthered/kienhoc-platform,xinjiguaike/edx-platform,jamiefolsom/edx-platform,UXE/local-edx,Edraak/circleci-edx-platform,raccoongang/edx-platform,shurihell/testasia,jazztpt/edx-platform,prarthitm/edxplatform,10clouds/edx-platform,motion2015/edx-platform,andyzsf/edx,xingyepei/edx-platform,wwj718/edx-platform,edx-solutions/edx-platform,msegado/edx-platform,naresh21/synergetics-edx-platform,shubhdev/openedx,ubc/edx-platform,Kalyzee/edx-platform,kamalx/edx-platform,shurihell/testasia,nanolearningllc/edx-platform-cypress,AkA84/edx-platform,zadgroup/edx-platform,inares/edx-platform,CredoReference/edx-platform,fly19890211/edx-platform,Semi-global/edx-platform,OmarIthawi/edx-platform,Softmotions/edx-platform,shubhdev/openedx,deepsrijit1105/edx-platform,shurihell/testasia,Softmotions/edx-platform,miptliot/edx-platform,martynovp/edx-platform,mahendra-r/edx-platform,zhenzhai/edx-platform,ahmedaljazzar/edx-platform,ahmedaljazzar/edx-platform,knehez/edx-platform,Semi-global/edx-platform,hastexo/edx-platform,jjmiranda/edx-platform,mcgachey/edx-platform,hamzehd/edx-platform,nanolearningllc/edx-platform-cypress-2,4eek/edx-platform,jamesblunt/edx-platform,jbzdak/edx-platform,unicri/edx-platform,playm2mboy/edx-platform,cpennington/edx-platform,leansoft/edx-platform,naresh21/synergetics-edx-platform,SivilTaram/edx-platform,jonathan-beard/edx-platform,peterm-itr/edx-platform,amir-qayyum-khan/edx-platform,ovnicraft/edx-platform,mjirayu/sit_academy,UOMx/edx-platform,doganov/edx-platform,MSOpenTech/edx-platform,motion2015/a3,nanolearningllc/edx-platform-cypress,etzhou/edx-platform,ahmadio/edx-platform,jazztpt/edx-platform,jazztpt/edx-platform,playm2mboy/edx-platform,dsajkl/123,openfun/edx-platform,RPI-OPENEDX/edx-platform,raccoongang/edx-platform,motion2015/edx-platform,dsajkl/123,dsajkl/123,leansoft/edx-platform,louyihua/edx-platform,mahendra-r/edx-platform,chauhanhardik/populo_2,adoosii/edx-platform,y12uc231/edx-platform,valtech-mooc/edx-platform,dkarakats/edx-platform,rhndg/openedx,franosincic/edx-platform,Shrhawk/edx-platform,nttks/edx-platform,mtlchun/edx,kmoocdev/edx-platform,longmen21/edx-platform,edx-solutions/edx-platform,cselis86/edx-platform,zubair-arbi/edx-platform,eestay/edx-platform,gsehub/edx-platform,inares/edx-platform,jamiefolsom/edx-platform,4eek/edx-platform,analyseuc3m/ANALYSE-v1,amir-qayyum-khan/edx-platform,peterm-itr/edx-platform,rue89-tech/edx-platform,ak2703/edx-platform,jbzdak/edx-platform,ampax/edx-platform,DefyVentures/edx-platform,jzoldak/edx-platform,ferabra/edx-platform,adoosii/edx-platform,prarthitm/edxplatform,dcosentino/edx-platform,jjmiranda/edx-platform,deepsrijit1105/edx-platform,eduNEXT/edx-platform,jolyonb/edx-platform,polimediaupv/edx-platform,pomegranited/edx-platform,y12uc231/edx-platform,franosincic/edx-platform,Edraak/edraak-platform,vismartltd/edx-platform,xuxiao19910803/edx-platform,openfun/edx-platform,eemirtekin/edx-platform,doismellburning/edx-platform,miptliot/edx-platform,eduNEXT/edunext-platform,itsjeyd/edx-platform,zerobatu/edx-platform,simbs/edx-platform,a-parhom/edx-platform,andyzsf/edx,10clouds/edx-platform,fly19890211/edx-platform,zubair-arbi/edx-platform,jelugbo/tundex,etzhou/edx-platform,hastexo/edx-platform,rhndg/openedx,zhenzhai/edx-platform,eemirtekin/edx-platform,edx/edx-platform,jamiefolsom/edx-platform,procangroup/edx-platform,jbzdak/edx-platform,SivilTaram/edx-platform,polimediaupv/edx-platform,SravanthiSinha/edx-platform,itsjeyd/edx-platform,analyseuc3m/ANALYSE-v1,TeachAtTUM/edx-platform,bitifirefly/edx-platform,DefyVentures/edx-platform,mbareta/edx-platform-ft,wwj718/ANALYSE,Stanford-Online/edx-platform,shurihell/testasia,J861449197/edx-platform,Stanford-Online/edx-platform,ZLLab-Mooc/edx-platform,olexiim/edx-platform,jbassen/edx-platform,chauhanhardik/populo_2,dsajkl/reqiop,nikolas/edx-platform,appsembler/edx-platform,shashank971/edx-platform,prarthitm/edxplatform,vikas1885/test1,simbs/edx-platform,tanmaykm/edx-platform,jamiefolsom/edx-platform,ZLLab-Mooc/edx-platform,romain-li/edx-platform,nanolearningllc/edx-platform-cypress-2,IndonesiaX/edx-platform,peterm-itr/edx-platform,shubhdev/openedx,jazkarta/edx-platform,olexiim/edx-platform,knehez/edx-platform,dkarakats/edx-platform,zhenzhai/edx-platform,B-MOOC/edx-platform,BehavioralInsightsTeam/edx-platform,motion2015/edx-platform,devs1991/test_edx_docmode,martynovp/edx-platform,vikas1885/test1,chand3040/cloud_that,ahmedaljazzar/edx-platform,tanmaykm/edx-platform,UOMx/edx-platform,mcgachey/edx-platform,a-parhom/edx-platform,utecuy/edx-platform,kmoocdev2/edx-platform,playm2mboy/edx-platform,DefyVentures/edx-platform,shabab12/edx-platform,inares/edx-platform,edx-solutions/edx-platform,JCBarahona/edX,zubair-arbi/edx-platform,ahmedaljazzar/edx-platform,Ayub-Khan/edx-platform,y12uc231/edx-platform,simbs/edx-platform,kursitet/edx-platform,mushtaqak/edx-platform,appliedx/edx-platform,ferabra/edx-platform,eduNEXT/edx-platform,chrisndodge/edx-platform,martynovp/edx-platform,dcosentino/edx-platform,jazztpt/edx-platform,xinjiguaike/edx-platform,IONISx/edx-platform,pomegranited/edx-platform,knehez/edx-platform,hamzehd/edx-platform,halvertoluke/edx-platform,ampax/edx-platform,xuxiao19910803/edx,MakeHer/edx-platform,Semi-global/edx-platform,nttks/jenkins-test,MakeHer/edx-platform,Livit/Livit.Learn.EdX,OmarIthawi/edx-platform,jolyonb/edx-platform,rhndg/openedx,B-MOOC/edx-platform,kmoocdev2/edx-platform,halvertoluke/edx-platform,zofuthan/edx-platform,jzoldak/edx-platform,amir-qayyum-khan/edx-platform,benpatterson/edx-platform,defance/edx-platform,polimediaupv/edx-platform,kxliugang/edx-platform,pepeportela/edx-platform,gymnasium/edx-platform,Edraak/edraak-platform,olexiim/edx-platform,J861449197/edx-platform,nttks/jenkins-test,zofuthan/edx-platform,pabloborrego93/edx-platform,nikolas/edx-platform,wwj718/ANALYSE,doganov/edx-platform,mtlchun/edx,vismartltd/edx-platform
|
---
+++
@@ -5,18 +5,23 @@
from xblock.runtime import KeyValueStore
+
+def stringify(key):
+ return repr(tuple(key))
+
+
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request):
self._session = request.session
def get(self, key):
- return self._session[tuple(key)]
+ return self._session[stringify(key)]
def set(self, key, value):
- self._session[tuple(key)] = value
+ self._session[stringify(key)] = value
def delete(self, key):
- del self._session[tuple(key)]
+ del self._session[stringify(key)]
def has(self, key):
- return tuple(key) in self._session
+ return stringify(key) in self._session
|
5eb3f2c61c2b61e1bad7faa006e5503bd9a20edf
|
uni_form/util.py
|
uni_form/util.py
|
from django import forms
from django.forms.widgets import Input
class SubmitButtonWidget(Input):
"""
A widget that handles a submit button.
"""
input_type = 'submit'
def render(self, name, value, attrs=None):
return super(SubmitButtonWidget, self).render(name,
self.attrs['value'], attrs)
class BaseInput(forms.Field):
"""
An base Input class to reduce the amount of code in the Input classes.
"""
widget = SubmitButtonWidget
def __init__(self, **kwargs):
if not 'label' in kwargs:
kwargs['label'] = ''
if not 'required' in kwargs:
kwargs['required'] = False
if 'value' in kwargs:
self._widget_attrs = {'value': kwargs['value']}
del kwargs['value']
else:
self._widget_attrs = {'value': 'Submit'}
super(BaseInput, self).__init__(**kwargs)
def widget_attrs(self, widget):
return self._widget_attrs
class Toggle(object):
"""
A container for holder toggled items such as fields and buttons.
"""
fields = []
|
class BaseInput(object):
"""
An base Input class to reduce the amount of code in the Input classes.
"""
def __init__(self,name,value):
self.name = name
self.value = value
class Toggle(object):
"""
A container for holder toggled items such as fields and buttons.
"""
fields = []
|
Revert "Made BaseInput inherit from forms.Field so inputs can be used in layouts. Added a SubmitButtonWidget."
|
Revert "Made BaseInput inherit from forms.Field so inputs can be used in layouts. Added a SubmitButtonWidget."
This reverts commit aa571b2e1fd177491895cc263b192467431b90c2.
|
Python
|
mit
|
HungryCloud/django-crispy-forms,spectras/django-crispy-forms,iris-edu-int/django-crispy-forms,scuml/django-crispy-forms,ngenovictor/django-crispy-forms,CashStar/django-uni-form,PetrDlouhy/django-crispy-forms,RamezIssac/django-crispy-forms,jcomeauictx/django-crispy-forms,tarunlnmiit/django-crispy-forms,CashStar/django-uni-form,pydanny/django-uni-form,avsd/django-crispy-forms,agepoly/django-crispy-forms,django-crispy-forms/django-crispy-forms,carltongibson/django-crispy-forms,pjdelport/django-crispy-forms,iris-edu/django-crispy-forms,IanLee1521/django-crispy-forms,dzhuang/django-crispy-forms,IanLee1521/django-crispy-forms,zixan/django-crispy-forms,ionelmc/django-uni-form,spectras/django-crispy-forms,dessibelle/django-crispy-forms,bouttier/django-crispy-forms,HungryCloud/django-crispy-forms,jcomeauictx/django-crispy-forms,tarunlnmiit/django-crispy-forms,eykanal/django-crispy-forms,HungryCloud/django-crispy-forms,maraujop/django-crispy-forms,iedparis8/django-crispy-forms,VishvajitP/django-crispy-forms,damienjones/django-crispy-forms,saydulk/django-crispy-forms,impulse-cloud/django-crispy-forms,VishvajitP/django-crispy-forms,saydulk/django-crispy-forms,scuml/django-crispy-forms,carltongibson/django-crispy-forms,alanwj/django-crispy-forms,rfleschenberg/django-crispy-forms,eykanal/django-crispy-forms,alanwj/django-crispy-forms,uranusjr/django-crispy-forms-ng,iris-edu-int/django-crispy-forms,zixan/django-crispy-forms,treyhunner/django-crispy-forms,maraujop/django-crispy-forms,davidszotten/django-crispy-forms,iedparis8/django-crispy-forms,avsd/django-crispy-forms,ngenovictor/django-crispy-forms,jtyoung/django-crispy-forms,davidszotten/django-crispy-forms,Stranger6667/django-crispy-forms,dessibelle/django-crispy-forms,PetrDlouhy/django-crispy-forms,dzhuang/django-crispy-forms,treyhunner/django-crispy-forms,agepoly/django-crispy-forms,uranusjr/django-crispy-forms-ng,django-crispy-forms/django-crispy-forms,RamezIssac/django-crispy-forms,damienjones/django-crispy-forms,bouttier/django-crispy-forms,rfleschenberg/django-crispy-forms,smirolo/django-crispy-forms,jtyoung/django-crispy-forms,iris-edu/django-crispy-forms,schrd/django-crispy-forms,Stranger6667/django-crispy-forms,pydanny/django-uni-form,impulse-cloud/django-crispy-forms,smirolo/django-crispy-forms,schrd/django-crispy-forms
|
---
+++
@@ -1,37 +1,12 @@
-from django import forms
-from django.forms.widgets import Input
-
-class SubmitButtonWidget(Input):
- """
- A widget that handles a submit button.
- """
- input_type = 'submit'
-
- def render(self, name, value, attrs=None):
- return super(SubmitButtonWidget, self).render(name,
- self.attrs['value'], attrs)
-
-
-class BaseInput(forms.Field):
+class BaseInput(object):
"""
An base Input class to reduce the amount of code in the Input classes.
"""
- widget = SubmitButtonWidget
-
- def __init__(self, **kwargs):
- if not 'label' in kwargs:
- kwargs['label'] = ''
- if not 'required' in kwargs:
- kwargs['required'] = False
- if 'value' in kwargs:
- self._widget_attrs = {'value': kwargs['value']}
- del kwargs['value']
- else:
- self._widget_attrs = {'value': 'Submit'}
- super(BaseInput, self).__init__(**kwargs)
-
- def widget_attrs(self, widget):
- return self._widget_attrs
+
+ def __init__(self,name,value):
+ self.name = name
+ self.value = value
+
class Toggle(object):
"""
|
c306f6963e53b971674421eddca7f6b5c913281e
|
core/data/DataWriter.py
|
core/data/DataWriter.py
|
"""
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
super(DataWriter, self).__init__()
self.supportedExtensions = [DataReader.TypeMHD,
DataReader.TypeVTI]
def WriteToFile(self, imageData, exportFileName, fileType):
if fileType == DataReader.TypeMHA:
if not exportFileName.endswith(".mhd"):
exportFileName = exportFileName + ".mhd"
writer = vtkMetaImageWriter()
writer.SetFileName(exportFileName)
writer.SetInputData(imageData)
writer.Write()
elif fileType == DataReader.TypeVTI:
writer = vtkXMLImageDataWriter()
writer.SetFileName(exportFileName)
writer.SetInputData(imageData)
writer.Write()
else:
raise NotImplementedError("No writing support for type " + str(fileType))
|
"""
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
super(DataWriter, self).__init__()
self.supportedExtensions = [DataReader.TypeMHD,
DataReader.TypeVTI]
def WriteToFile(self, imageData, exportFileName, fileType):
if fileType == DataReader.TypeMHD:
if not exportFileName.endswith(".mhd"):
exportFileName = exportFileName + ".mhd"
writer = vtkMetaImageWriter()
writer.SetFileName(exportFileName)
writer.SetInputData(imageData)
writer.Write()
elif fileType == DataReader.TypeVTI:
writer = vtkXMLImageDataWriter()
writer.SetFileName(exportFileName)
writer.SetInputData(imageData)
writer.Write()
else:
raise NotImplementedError("No writing support for type " + str(fileType))
|
Fix for comparing with the wrong data type.
|
Fix for comparing with the wrong data type.
|
Python
|
mit
|
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
|
---
+++
@@ -20,7 +20,7 @@
DataReader.TypeVTI]
def WriteToFile(self, imageData, exportFileName, fileType):
- if fileType == DataReader.TypeMHA:
+ if fileType == DataReader.TypeMHD:
if not exportFileName.endswith(".mhd"):
exportFileName = exportFileName + ".mhd"
writer = vtkMetaImageWriter()
|
bfe884723d06252648cb95fdfc0f9dd0f804795f
|
proxyswitch/driver.py
|
proxyswitch/driver.py
|
from flask import Flask
class Driver:
'''
Holds the driver state so the flasked script can change behaviour based
on what the user injects via HTTP
'''
name = 'nobody'
def start(self, name):
self.name = name
return self.name
def stop(self):
self.name = 'nobody'
return self.name
app = Flask('proxapp')
driver = Driver()
def register(context):
context.app_registry.add(app, 'proxapp', 5000)
return context
@app.route('/')
def index():
return 'Try /start/:driver or /stop/:driver instead'
@app.route('/stop')
def stop_driver():
driver.stop()
return 'No drivers running\n'
@app.route('/<driver_name>/start')
def start_driver(driver_name):
print(driver.start(driver_name))
return '{} driver started\n'.format(driver_name)
|
from flask import Flask
class Driver:
'''
Holds the driver state so the flasked script can change behaviour based
on what the user injects via HTTP
'''
name = 'nobody'
def start(self, name):
self.name = name
return self.name
def stop(self):
self.name = 'nobody'
return self.name
app = Flask('proxapp')
app.host = '0.0.0.0'
driver = Driver()
def register(context):
context.app_registry.add(app, 'proxapp', 5000)
return context
@app.route('/')
def index():
return 'Try /start/:driver or /stop/:driver instead'
@app.route('/stop')
def stop_driver():
driver.stop()
return 'No drivers running\n'
@app.route('/<driver_name>/start')
def start_driver(driver_name):
print(driver.start(driver_name))
return '{} driver started\n'.format(driver_name)
|
Change Flask interface to 0.0.0.0
|
Change Flask interface to 0.0.0.0
|
Python
|
mit
|
ustwo/mastermind,ustwo/mastermind
|
---
+++
@@ -16,6 +16,7 @@
return self.name
app = Flask('proxapp')
+app.host = '0.0.0.0'
driver = Driver()
def register(context):
|
323f897e3550f41edc139352a6ac9d95ddf7228d
|
seriesly/helper/context_processors.py
|
seriesly/helper/context_processors.py
|
from django.conf import settings
def site_info(request):
return {'DOMAIN_URL': settings.DOMAIN_URL,
'SECURE_DOMAIN_URL': settings.SECURE_DOMAIN_URL,
'DEBUG': settings.DEBUG}
|
from django.conf import settings
def site_info(request):
return {'DOMAIN_URL': settings.DOMAIN_URL,
'SECURE_DOMAIN_URL': settings.SECURE_DOMAIN_URL,
'DEFAULT_FROM_EMAIL': settings.DEFAULT_FROM_EMAIL,
'DEBUG': settings.DEBUG}
|
Add DEFAULT_FROM_EMAIL to default template context
|
Add DEFAULT_FROM_EMAIL to default template context
|
Python
|
agpl-3.0
|
maxgraser/seriesly,maxgraser/seriesly,stefanw/seriesly,stefanw/seriesly,maxgraser/seriesly
|
---
+++
@@ -3,4 +3,5 @@
def site_info(request):
return {'DOMAIN_URL': settings.DOMAIN_URL,
'SECURE_DOMAIN_URL': settings.SECURE_DOMAIN_URL,
+ 'DEFAULT_FROM_EMAIL': settings.DEFAULT_FROM_EMAIL,
'DEBUG': settings.DEBUG}
|
fd054790ce32c3918f6edbe824540c09d7efce59
|
stagehand/providers/__init__.py
|
stagehand/providers/__init__.py
|
import asyncio
from ..utils import load_plugins, invoke_plugins
from .base import ProviderError
plugins, broken_plugins = load_plugins('providers', ['thetvdb', 'tvrage'])
@asyncio.coroutine
def start(manager):
"""
Called when the manager is starting.
"""
yield from invoke_plugins(plugins, 'start', manager)
for name, error in broken_plugins.items():
log.warning('failed to load provider plugin %s: %s', name, error)
|
import asyncio
from ..utils import load_plugins, invoke_plugins
from .base import ProviderError
plugins, broken_plugins = load_plugins('providers', ['thetvdb'])
@asyncio.coroutine
def start(manager):
"""
Called when the manager is starting.
"""
yield from invoke_plugins(plugins, 'start', manager)
for name, error in broken_plugins.items():
log.warning('failed to load provider plugin %s: %s', name, error)
|
Remove tvrage from active providers as site is shut down
|
Remove tvrage from active providers as site is shut down
|
Python
|
mit
|
jtackaberry/stagehand,jtackaberry/stagehand
|
---
+++
@@ -3,7 +3,7 @@
from ..utils import load_plugins, invoke_plugins
from .base import ProviderError
-plugins, broken_plugins = load_plugins('providers', ['thetvdb', 'tvrage'])
+plugins, broken_plugins = load_plugins('providers', ['thetvdb'])
@asyncio.coroutine
def start(manager):
|
22b5f7ecc6057252ec77d037522b5783c5f86c1f
|
mcmodfixes.py
|
mcmodfixes.py
|
#!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
))
DEP_ADDITIONS = {
"gregtech": ["IC2"],
"MineFactoryReloaded": ["PowerCrystalsCore"],
"NetherOres": ["PowerCrystalsCore"],
"PowerConverters": ["PowerCrystalsCore"],
"FlatBedrock": ["PowerCrystalsCore"],
"immibis-microblocks": ["ImmibisCore"],
}
def getExtraDeps(mod):
for k, v in DEP_ADDITIONS.iteritems():
if mod.startswith(k):
return set(v)
return set()
def fixDeps(mod, deps):
deps = set(deps)
deps -= DEP_BLACKLIST
deps |= getExtraDeps(mod)
return deps
MOD_IDS = {
"PowerCrystalsCore": ["PowerCrystalsCore"],
}
def fixModIDs(mod, ids):
for k, v in MOD_IDS.iteritems():
if mod.startswith(k):
return v
return ids
COREMODS = ["PowerCrystalsCore", "immibis-microblocks"]
def isCoremod(fn):
for k in COREMODS:
if fn.startswith(k):
return True
return False
|
#!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
"EurysCore", # replaced by SlimevoidLib?
))
DEP_ADDITIONS = {
"gregtech": ["IC2"],
"MineFactoryReloaded": ["PowerCrystalsCore"],
"NetherOres": ["PowerCrystalsCore"],
"PowerConverters": ["PowerCrystalsCore"],
"FlatBedrock": ["PowerCrystalsCore"],
"immibis-microblocks": ["ImmibisCore"],
"SlopesAndCorners": ["SlimevoidLib"],
}
def getExtraDeps(mod):
for k, v in DEP_ADDITIONS.iteritems():
if mod.startswith(k):
return set(v)
return set()
def fixDeps(mod, deps):
deps = set(deps)
deps -= DEP_BLACKLIST
deps |= getExtraDeps(mod)
return deps
MOD_IDS = {
"PowerCrystalsCore": ["PowerCrystalsCore"],
}
def fixModIDs(mod, ids):
for k, v in MOD_IDS.iteritems():
if mod.startswith(k):
return v
return ids
COREMODS = ["PowerCrystalsCore", "immibis-microblocks"]
def isCoremod(fn):
for k in COREMODS:
if fn.startswith(k):
return True
return False
|
Add mcmod.info fix for SlopesAndCorners SlimevoidLib dependency
|
Add mcmod.info fix for SlopesAndCorners SlimevoidLib dependency
|
Python
|
bsd-3-clause
|
agaricusb/ModAnalyzer,agaricusb/ModAnalyzer
|
---
+++
@@ -8,6 +8,7 @@
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
+ "EurysCore", # replaced by SlimevoidLib?
))
@@ -18,6 +19,7 @@
"PowerConverters": ["PowerCrystalsCore"],
"FlatBedrock": ["PowerCrystalsCore"],
"immibis-microblocks": ["ImmibisCore"],
+ "SlopesAndCorners": ["SlimevoidLib"],
}
def getExtraDeps(mod):
|
60a90722fbd5fc047fee5e9f7377f03e11f6a654
|
examples/root_finding/test_funcs.py
|
examples/root_finding/test_funcs.py
|
import math
def f1(x):
"""
Test function 1
"""
return x*x*x - math.pi*x + math.e/100
|
import numpy as npy
def f1(x):
"""
Test function 1
"""
return x*x*x - npy.pi*x + npy.e/100
def f2(x):
"""
Test function 2
"""
return -1.13 + npy.tanh(x-2) + 4*npy.exp(-x)*npy.sin((1/8.)*x**3) \
*x + .1*npy.exp((1/35.)*x)
|
Use numpy instead of math to allow vectorization
|
Use numpy instead of math to allow vectorization
|
Python
|
bsd-3-clause
|
robclewley/fovea,akuefler/fovea
|
---
+++
@@ -1,7 +1,14 @@
-import math
+import numpy as npy
def f1(x):
"""
Test function 1
"""
- return x*x*x - math.pi*x + math.e/100
+ return x*x*x - npy.pi*x + npy.e/100
+
+def f2(x):
+ """
+ Test function 2
+ """
+ return -1.13 + npy.tanh(x-2) + 4*npy.exp(-x)*npy.sin((1/8.)*x**3) \
+ *x + .1*npy.exp((1/35.)*x)
|
cd030a1ed2c3c7f0bf7d9a5d86f9cc81f802fcba
|
corehq/mobile_flags.py
|
corehq/mobile_flags.py
|
from collections import namedtuple
TAG_DIMAGI_ONLY = 'Dimagi Only'
MobileFlag = namedtuple('MobileFlag', 'slug label tags')
SUPERUSER = MobileFlag(
'superuser',
'Enable superuser-only features',
tags=(TAG_DIMAGI_ONLY,)
)
|
from collections import namedtuple
MobileFlag = namedtuple('MobileFlag', 'slug label')
SUPERUSER = MobileFlag(
'superuser',
'Enable superuser-only features'
)
|
Add tags for mobile flags when you need them
|
Add tags for mobile flags when you need them
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
|
---
+++
@@ -1,14 +1,10 @@
from collections import namedtuple
-TAG_DIMAGI_ONLY = 'Dimagi Only'
-
-
-MobileFlag = namedtuple('MobileFlag', 'slug label tags')
+MobileFlag = namedtuple('MobileFlag', 'slug label')
SUPERUSER = MobileFlag(
'superuser',
- 'Enable superuser-only features',
- tags=(TAG_DIMAGI_ONLY,)
+ 'Enable superuser-only features'
)
|
54bb12bdeec33e98451451837dce90665413bd67
|
mgsv_names.py
|
mgsv_names.py
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
for _ in range(20):
print(generate_name())
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
print(generate_name())
|
Print one name at a time.
|
Print one name at a time.
|
Python
|
unlicense
|
rotated8/mgsv_names
|
---
+++
@@ -27,5 +27,4 @@
return ' '.join((adj, anim))
if __name__ == '__main__':
- for _ in range(20):
- print(generate_name())
+ print(generate_name())
|
ba16b14203af704f1fa0a6eb3111d0537e0cc399
|
mail_inline_css/models/mail_template.py
|
mail_inline_css/models/mail_template.py
|
# Copyright 2017 David BEAL @ Akretion
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
try:
from premailer import Premailer
except (ImportError, IOError) as err: # pragma: no cover
import logging
_logger = logging.getLogger(__name__)
_logger.debug(err)
class MailTemplate(models.Model):
_inherit = "mail.template"
def generate_email(self, res_ids, fields=None):
"""Use `premailer` to convert styles to inline styles."""
result = super().generate_email(res_ids, fields=fields)
if isinstance(res_ids, int):
result["body_html"] = self._premailer_apply_transform(result["body_html"])
else:
for __, data in result.items():
data["body_html"] = self._premailer_apply_transform(data["body_html"])
return result
def _premailer_apply_transform(self, data_html):
premailer = Premailer(html=data_html, **self._get_premailer_options())
return premailer.transform()
def _get_premailer_options(self):
return {}
|
# Copyright 2017 David BEAL @ Akretion
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
try:
from premailer import Premailer
except (ImportError, IOError) as err: # pragma: no cover
import logging
_logger = logging.getLogger(__name__)
_logger.debug(err)
class MailTemplate(models.Model):
_inherit = "mail.template"
def generate_email(self, res_ids, fields=None):
"""Use `premailer` to convert styles to inline styles."""
result = super().generate_email(res_ids, fields=fields)
if isinstance(res_ids, int):
result["body_html"] = self._premailer_apply_transform(result["body_html"])
else:
for __, data in result.items():
data["body_html"] = self._premailer_apply_transform(data["body_html"])
return result
def _premailer_apply_transform(self, data_html):
if not data_html:
return data_html
premailer = Premailer(html=data_html, **self._get_premailer_options())
return premailer.transform()
def _get_premailer_options(self):
return {}
|
Fix issue on empty template with premailer
|
Fix issue on empty template with premailer
If premailer receives an empty value, such as an empty string,
on parsing, it returns None and fails when trying to call
'etree.fromstring()' on this None result.
We should avoid to call premailer on an empty string, as the result
will anyway not change.
We may have an empty template for instance when a template could not
compile due to a mistake.
|
Python
|
agpl-3.0
|
OCA/social,OCA/social,OCA/social
|
---
+++
@@ -28,6 +28,8 @@
return result
def _premailer_apply_transform(self, data_html):
+ if not data_html:
+ return data_html
premailer = Premailer(html=data_html, **self._get_premailer_options())
return premailer.transform()
|
0298e8b6abcd7cea99df4cb235c73a49e340521a
|
tests/query_test/test_decimal_queries.py
|
tests/query_test/test_decimal_queries.py
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
(v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none') or
v.get_value('table_format').file_format == 'parquet')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
(v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none') or
v.get_value('table_format').file_format == 'parquet')
def test_queries(self, vector):
if os.environ.get('ASAN_OPTIONS') == 'handle_segv=0':
pytest.xfail(reason="IMPALA-959: Sum on a decimal column fails ASAN")
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
Fix the ASAN build by xfailing test_decimal when ASAN_OPTIONS is set.
|
Fix the ASAN build by xfailing test_decimal when ASAN_OPTIONS is set.
Adding decimal columns crashes an ASAN built impalad. This change skips the test.
Change-Id: Ic94055a3f0d00f89354177de18bc27d2f4cecec2
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2532
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: jenkins
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2594
|
Python
|
apache-2.0
|
cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala
|
---
+++
@@ -29,6 +29,8 @@
v.get_value('table_format').file_format == 'parquet')
def test_queries(self, vector):
+ if os.environ.get('ASAN_OPTIONS') == 'handle_segv=0':
+ pytest.xfail(reason="IMPALA-959: Sum on a decimal column fails ASAN")
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.