commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
cfa77bed245d80d453f7b463ea35473bbc29cc50 | toolkits/rdk.py | toolkits/rdk.py | import numpy as np
from cinfony import rdk
from cinfony.rdk import *
class Fingerprint(rdk.Fingerprint):
@property
def raw(self):
return np.array(self.fp, dtype=bool)
rdk.Fingerprint = Fingerprint
| import numpy as np
from cinfony import rdk
from cinfony.rdk import *
class Fingerprint(rdk.Fingerprint):
@property
def raw(self):
return np.array(self.fp, dtype=bool)
rdk.Fingerprint = Fingerprint
# Patch reader not to return None as molecules
def _readfile(format, filename):
for mol in rdk.readfile(format, filename):
if mol is not None:
yield mol
rdk.readfile = _readfile
| Patch readfile not to return mols | Patch readfile not to return mols
| Python | bsd-3-clause | mwojcikowski/opendrugdiscovery |
e6c774c13a01f2cbe09947c39c1dac7b4989bebc | jason2/project.py | jason2/project.py | class Project(object):
"""Holds project configuration parameters, such as data directory."""
def __init__(self, data_directory):
self.data_directory = data_directory
| import ConfigParser
class Project(object):
"""Holds project configuration parameters, such as data directory."""
@classmethod
def from_config(cls, filename):
config = ConfigParser.RawConfigParser()
config.read(filename)
return cls(config.get("data", "directory"))
def __init__(self, data_directory):
self.data_directory = data_directory
| Add from_configfile method to Project | Add from_configfile method to Project
| Python | mit | gadomski/jason2 |
686406781af00d93e4d70049499068037d72be74 | geotrek/core/tests/test_forms.py | geotrek/core/tests/test_forms.py | from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
| from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
class PathFormTest(TestCase):
def test_overlapping_path(self):
user = UserFactory()
PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
# Just intersecting
form1 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
)
self.assertTrue(form1.is_valid(), str(form1.errors))
# Overlapping
form2 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
)
self.assertFalse(form2.is_valid(), str(form2.errors))
| Add tests for path overlapping check | Add tests for path overlapping check
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek |
4b26066a6f3b666ec107621334ddbcceec6a819a | micro/read_code.py | micro/read_code.py | import fileinput
def read_code():
return ''.join([line for line in fileinput.input()])
if __name__ == '__main__':
code = read_code()
print(code)
| import fileinput
def read_code(filename='-'):
return ''.join([line for line in fileinput.input(filename)])
if __name__ == '__main__':
import sys
filename = sys.argv[1] if len(sys.argv) > 1 else '-'
code = read_code(filename)
print(code)
| Correct a reading of a code | Correct a reading of a code
| Python | mit | thewizardplusplus/micro,thewizardplusplus/micro,thewizardplusplus/micro |
9be37b96450780b41f5a5443568ca41a18e06d22 | lcapy/sequence.py | lcapy/sequence.py | """This module handles sequences.
Copyright 2020 Michael Hayes, UCECE
"""
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
for v1, n1 in zip(self.n, self):
s = v.latex()
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
return '\left{%s\right\}' % ', '.join(items)
| """This module handles sequences.
Copyright 2020 Michael Hayes, UCECE
"""
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.latex()
except:
s = str(v1)
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
return r'\left\{%s\right\}' % ', '.join(items)
def pretty(self):
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.pretty()
except:
s = str(v1)
if n1 == 0:
s = '_%s_' % v1
items.append(s)
return r'{%s}' % ', '.join(items)
| Add pretty and latex for Sequence | Add pretty and latex for Sequence
| Python | lgpl-2.1 | mph-/lcapy |
4559e01646010e1ed260d77e612774778a0c1359 | lib/rfk/site/forms/login.py | lib/rfk/site/forms/login.py | from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \
PasswordField, IntegerField, FieldList, FormField, validators
class LoginForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required()])
remember = BooleanField('Remember me')
def login_form(rform):
return LoginForm(rform)
class RegisterForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required(),
validators.Length(min=5, message='Password too short.'),
validators.EqualTo('password_retype', message='Passwords must match.')])
password_retype = PasswordField('Password (verification)', [validators.Required()])
email = TextField('E-Mail', [validators.Optional(), validators.Email()])
def register_form(rform):
return RegisterForm(rform)
| from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \
PasswordField, IntegerField, FieldList, FormField, validators
class LoginForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required()])
remember = BooleanField('Remember me')
def login_form(rform):
return LoginForm(rform)
class RegisterForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required(),
validators.Length(min=5, message='Password too short.'),
validators.EqualTo('password_retype', message='Passwords must match.')])
password_retype = PasswordField('Password (verification)', [validators.Required()])
email = TextField('E-Mail (optional)', [validators.Optional(), validators.Email()])
def register_form(rform):
return RegisterForm(rform)
| Make it clear that the E-Mail address is optional. | Make it clear that the E-Mail address is optional.
| Python | bsd-3-clause | buckket/weltklang,buckket/weltklang,krautradio/PyRfK,krautradio/PyRfK,krautradio/PyRfK,buckket/weltklang,buckket/weltklang,krautradio/PyRfK |
3d9bf8afd912ccb0d1df72353a9c306c59773007 | swf/exceptions.py | swf/exceptions.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.split(':')
def __repr__(self):
msg = self.message
if self.kind and self.details:
msg += '\nReason: {}, {}'.format(self.kind, self.details)
return msg
def __str__(self):
msg = self.message
if self.kind and self.details:
msg += '\nReason: {}, {}'.format(self.kind, self.details)
return msg
class PollTimeout(SWFError):
pass
class InvalidCredentialsError(SWFError):
pass
class ResponseError(SWFError):
pass
class DoesNotExistError(SWFError):
pass
class AlreadyExistsError(SWFError):
pass
class InvalidKeywordArgumentError(SWFError):
pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.split(':')
self.type_ = self.kind.lower().strip().replace(' ', '_') if self.kind else None
def __repr__(self):
msg = self.message
if self.kind and self.details:
msg += '\nReason: {}, {}'.format(self.kind, self.details)
return msg
def __str__(self):
msg = self.message
if self.kind and self.details:
msg += '\nReason: {}, {}'.format(self.kind, self.details)
return msg
class PollTimeout(SWFError):
pass
class InvalidCredentialsError(SWFError):
pass
class ResponseError(SWFError):
pass
class DoesNotExistError(SWFError):
pass
class AlreadyExistsError(SWFError):
pass
class InvalidKeywordArgumentError(SWFError):
pass
| Update SWFError with a formatted type | Update SWFError with a formatted type
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow |
5a9f027bb3e660cd0146c4483c70e54a76332048 | makerscience_profile/api.py | makerscience_profile/api.py | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
| Enable full location for profile | Enable full location for profile
| Python | agpl-3.0 | atiberghien/makerscience-server,atiberghien/makerscience-server |
58f982d01a7c47a12a7ae600c2ca17cb6c5c7ed9 | monitor/runner.py | monitor/runner.py | from time import sleep
from monitor.camera import Camera
from monitor.plotter_pygame import PyGamePlotter
def run(plotter, camera):
while True:
plotter.show(camera.get_image_data())
sleep(1.0)
if __name__ == "main":
cam_ioc = "X1-CAM"
plo = PyGamePlotter()
cam = Camera(cam_ioc)
run(plo, cam)
| import sys
from time import sleep
from camera import Camera
from plotter_pygame import PyGamePlotter
def run(plotter, camera):
old_timestamp = -1
while True:
data, timestamp = camera.get_image_data()
if timestamp != old_timestamp:
plotter.show(data)
old_timestamp = timestamp
sleep(1.0)
if __name__ == "__main__":
cam_ioc = sys.argv[1] # "X1-CAM"
cam = Camera(cam_ioc)
plo = PyGamePlotter()
plo.set_screensize(cam.xsize, cam.ysize)
run(plo, cam)
| Update to set screensize and take camera IOC as arg | Update to set screensize and take camera IOC as arg
| Python | apache-2.0 | nickbattam/picamon,nickbattam/picamon,nickbattam/picamon,nickbattam/picamon |
2917f396f52eb042f2354f0a7e1d05dd59b819e3 | aids/strings/reverse_string.py | aids/strings/reverse_string.py | '''
Reverse a string
'''
def reverse_string_iterative(string):
pass
def reverse_string_recursive(string):
pass
def reverse_string_pythonic(string):
return string[::-1] | '''
Reverse a string
'''
def reverse_string_iterative(string):
result = ''
for char in range(len(string) - 1, -1 , -1):
result += char
return result
def reverse_string_recursive(string):
if string:
return reverse_string_recursive(string[1:]) + string[0]
return ''
def reverse_string_pythonic(string):
return string[::-1] | Add iterative and recursive solutions to reverse strings | Add iterative and recursive solutions to reverse strings
| Python | mit | ueg1990/aids |
8af5aaee0aad575c9f1039a2943aff986a501747 | tests/manage.py | tests/manage.py | #!/usr/bin/env python
import channels.log
import logging
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
def get_channels_logger(*args, **kwargs):
"""Return logger for channels."""
return logging.getLogger("django.channels")
# Force channels to respect logging configurations from settings:
# https://github.com/django/channels/issues/520
channels.log.setup_logger = get_channels_logger
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import logging
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Fix logging compatibility with the latest Channels | Fix logging compatibility with the latest Channels
| Python | apache-2.0 | genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio |
f4695f43e9eae5740efc303374c892850dfea1a2 | trade_server.py | trade_server.py | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
response = ''
if data:
response += handle_data(data)
cur_thread = threading.current_thread()
response += "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| Fix bugs occuring when no response is given. | Fix bugs occuring when no response is given.
| Python | mit | Tribler/decentral-market |
e98eeadb9d5906bf65efc7a17658ae498cfcf27d | chainer/utils/__init__.py | chainer/utils/__init__.py | import contextlib
import shutil
import tempfile
import numpy
from chainer.utils import walker_alias # NOQA
# import class and function
from chainer.utils.conv import get_conv_outsize # NOQA
from chainer.utils.conv import get_deconv_outsize # NOQA
from chainer.utils.experimental import experimental # NOQA
from chainer.utils.walker_alias import WalkerAlias # NOQA
def force_array(x, dtype=None):
# numpy returns a float value (scalar) when a return value of an operator
# is a 0-dimension array.
# We need to convert such a value to a 0-dimension array because `Function`
# object needs to return an `numpy.ndarray`.
if numpy.isscalar(x):
if dtype is None:
return numpy.array(x)
else:
return numpy.array(x, dtype)
else:
if dtype is None:
return x
else:
return x.astype(dtype, copy=False)
def force_type(dtype, value):
if numpy.isscalar(value):
return dtype.type(value)
elif value.dtype != dtype:
return value.astype(dtype, copy=False)
else:
return value
@contextlib.contextmanager
def tempdir(**kwargs):
# A context manager that defines a lifetime of a temporary directory.
temp_dir = tempfile.mkdtemp(**kwargs)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
| import contextlib
import shutil
import tempfile
import numpy
from chainer.utils import walker_alias # NOQA
# import class and function
from chainer.utils.conv import get_conv_outsize # NOQA
from chainer.utils.conv import get_deconv_outsize # NOQA
from chainer.utils.experimental import experimental # NOQA
from chainer.utils.walker_alias import WalkerAlias # NOQA
def force_array(x, dtype=None):
# numpy returns a float value (scalar) when a return value of an operator
# is a 0-dimension array.
# We need to convert such a value to a 0-dimension array because `Function`
# object needs to return an `numpy.ndarray`.
if numpy.isscalar(x):
if dtype is None:
return numpy.array(x)
else:
return numpy.array(x, dtype)
else:
if dtype is None:
return x
else:
return x.astype(dtype, copy=False)
def force_type(dtype, value):
if numpy.isscalar(value):
return dtype.type(value)
elif value.dtype != dtype:
return value.astype(dtype, copy=False)
else:
return value
@contextlib.contextmanager
def tempdir(**kwargs):
# A context manager that defines a lifetime of a temporary directory.
ignore_errors = kwargs.pop('ignore_errors', False)
temp_dir = tempfile.mkdtemp(**kwargs)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir, ignore_errors=ignore_errors)
| Make ignore_errors False by default | Make ignore_errors False by default
| Python | mit | ronekko/chainer,chainer/chainer,okuta/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,okuta/chainer,niboshi/chainer,chainer/chainer,hvy/chainer,chainer/chainer,rezoo/chainer,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,hvy/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,jnishi/chainer,pfnet/chainer,tkerola/chainer,hvy/chainer,jnishi/chainer,wkentaro/chainer,okuta/chainer,niboshi/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,ktnyt/chainer |
b423e73ec440d10ff80110c998d13ea8c2b5a764 | stock_request_picking_type/models/stock_request_order.py | stock_request_picking_type/models/stock_request_order.py | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picking.type'].search([
('code', '=', 'stock_request_order'),
('warehouse_id.company_id', 'in',
[self.env.context.get('company_id', self.env.user.company_id.id),
False])],
limit=1).id
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type',
default=_get_default_picking_type, required=True)
| # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picking.type'].search([
('code', '=', 'stock_request_order'),
('warehouse_id.company_id', 'in',
[self.env.context.get('company_id', self.env.user.company_id.id),
False])],
limit=1).id
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type',
default=_get_default_picking_type, required=True)
@api.onchange('warehouse_id')
def onchange_warehouse_picking_id(self):
if self.warehouse_id:
picking_type_id = self.env['stock.picking.type'].\
search([('code', '=', 'stock_request_order'),
('warehouse_id', '=', self.warehouse_id.id)], limit=1)
if picking_type_id:
self._origin.write({'picking_type_id': picking_type_id.id})
| Synchronize Picking Type and Warehouse | [IMP] Synchronize Picking Type and Warehouse
[IMP] User write()
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse |
8fd395e1085f0508da401186b09f7487b3f9ae64 | odbc2csv.py | odbc2csv.py | import pypyodbc
import csv
conn = pypyodbc.connect("DSN=")
cur = conn.cursor()
tables = []
cur.tables("%", "", "")
for row in cur.fetchall():
tables.append(row[2])
for table in tables:
cur.execute("select * from %s" % table)
column_names = []
for d in cur.description:
column_names.append(d[0])
file = open("%s.csv" % table, "w")
writer = csv.writer(file)
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| import pypyodbc
import csv
conn = pypyodbc.connect("DSN=")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
cur.execute("select * from %s" % table)
column_names = []
for d in cur.description:
column_names.append(d[0])
file = open("%s.csv" % table, "w")
writer = csv.writer(file)
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| Fix to fetching tables from MS SQL Server. | Fix to fetching tables from MS SQL Server. | Python | isc | wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts |
6a8fadc2d607adaf89e6ea15fca65136fac651c6 | src/auspex/instruments/utils.py | src/auspex/instruments/utils.py | from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| Move QGL import inside function | Move QGL import inside function
A channel library is not always available
| Python | apache-2.0 | BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex |
89ee95bf33ce504377087de383f56e8582623738 | pylab/website/tests/test_comments.py | pylab/website/tests/test_comments.py | import datetime
from django_webtest import WebTest
from django.contrib.auth.models import User
from django_comments.models import Comment
from pylab.core.models import Project
class CommentsTests(WebTest):
def setUp(self):
self.user = User.objects.create_user('u1')
self.project = Project.objects.create(
author=self.user,
title='Test project',
description='Description',
created='2015-08-13'
)
def test_add_comment(self):
resp = self.app.get('/projects/test-project/', user=self.user)
now = datetime.datetime.now()
comment = Comment.objects.create(
user=self.user,
comment='new comment',
submit_date=now,
object_pk=self.project.id,
content_type_id=self.project.id,
site_id=1,
)
comment.save()
resp = self.app.get('/projects/test-project/', user=self.user)
self.assertEqual(resp.status_int, 200)
self.assertEqual(
list(Comment.objects.values_list('comment')),
[('new comment',)]
)
| from django_webtest import WebTest
from django.contrib.auth.models import User
from django_comments.models import Comment
from pylab.core.models import Project
class CommentsTests(WebTest):
def setUp(self):
self.user = User.objects.create_user('u1', email='test@example.com')
self.project = Project.objects.create(
author=self.user,
title='Test project',
description='Description',
created='2015-08-13'
)
def test_add_comment(self):
resp = self.app.get('/projects/test-project/', user=self.user)
resp.form['comment'] = 'new comment'
resp = resp.form.submit()
resp = self.app.get('/projects/test-project/', user=self.user)
self.assertEqual(resp.status_int, 200)
self.assertEqual(
list(Comment.objects.values_list('comment')),
[('new comment',)]
)
| Add email parameter for creating test user | Add email parameter for creating test user
| Python | agpl-3.0 | python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website |
11d9225871fa4980c7782a849c3ecd425edbe806 | git_helper.py | git_helper.py | import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.path.exists(os.path.join(directory, '.git')):
return directory
else:
parent = os.path.realpath(os.path.join(directory, os.path.pardir))
if parent == directory:
# we have reached root dir
return False
else:
return git_root(parent)
def git_tree(view):
full_file_path = view.file_name()
file_parent_dir = os.path.realpath(os.path.dirname(full_file_path))
return git_root(file_parent_dir)
def git_dir(directory):
return os.path.join(directory, '.git')
| import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.path.exists(os.path.join(directory, '.git')):
return directory
else:
parent = os.path.realpath(os.path.join(directory, os.path.pardir))
if parent == directory:
# we have reached root dir
return False
else:
return git_root(parent)
def git_tree(view):
full_file_path = view.file_name()
file_parent_dir = os.path.realpath(os.path.dirname(full_file_path))
return git_root(file_parent_dir)
def git_dir(directory):
if not directory:
return False
return os.path.join(directory, '.git')
| Fix error when there is no git | Fix error when there is no git
| Python | mit | bradsokol/VcsGutter,biodamasceno/GitGutter,biodamasceno/GitGutter,bradsokol/VcsGutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,robfrawley/sublime-git-gutter,biodamasceno/GitGutter,akpersad/GitGutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,robfrawley/sublime-git-gutter,tushortz/GitGutter,akpersad/GitGutter,jisaacks/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,natecavanaugh/GitGutter,michaelhogg/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,akpersad/GitGutter,natecavanaugh/GitGutter,natecavanaugh/GitGutter,ariofrio/VcsGutter,ariofrio/VcsGutter |
d7a77380ad95e316efb73a7be485d9b882fd64e9 | Core/models.py | Core/models.py | from django.db import models
##
# Location Types
##
class World(models.Model):
name = models.CharField(max_length=30)
homes = models.ManyToManyField(Home)
class Home(models.Model):
name = models.CharField(max_length=30)
rooms = models.ManyToManyField(Room)
class Room(models.Model):
name = models.CharField(max_length=30)
##
# Device Types
##
class Device(models.Model):
name = models.CharField(max_length=30)
class Meta:
abstract = True
class OutputDevice(Device):
actions = models.ManyToManyField(Action)
class Meta:
abstract = True
class InputDevice(Device):
events = models.ManyToManyField(Event)
class Meta:
abstract = True
##
# Input/Output
##
class Action(models.Model):
name = models.CharField(max_length=30)
def run()
class Meta:
abstract = True
class Event(models.Model):
name = models.CharField(max_length=30)
actions = models.ManyToMany(Action)
def call():
for (action in self.actions):
action.run()
class Meta:
abstract = True
| from django.db import models
##
# Location Types
##
class World(models.Model):
name = models.CharField(max_length=30)
homes = models.ManyToManyField(Home)
class Meta:
db_table = u'Worlds'
class Home(models.Model):
name = models.CharField(max_length=30)
rooms = models.ManyToManyField(Room)
class Meta:
db_table = u'Homes'
class Room(models.Model):
name = models.CharField(max_length=30)
class Meta:
db_table = u'Rooms'
##
# Device Types
##
class Device(models.Model):
name = models.CharField(max_length=30)
class Meta:
abstract = True
class OutputDevice(Device):
actions = models.ManyToManyField(Action)
class Meta:
abstract = True
class InputDevice(Device):
events = models.ManyToManyField(Event)
class Meta:
abstract = True
##
# Input/Output
##
class Action(models.Model):
name = models.CharField(max_length=30)
def run()
class Meta:
abstract = True
class Event(models.Model):
name = models.CharField(max_length=30)
actions = models.ManyToMany(Action)
def call():
for (action in self.actions):
action.run()
class Meta:
abstract = True
| Add table names to core model items | Add table names to core model items
| Python | mit | Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation |
6a856e613248e32bd7fc8027adfb9df4d74b2357 | candidates/management/commands/candidates_make_party_sets_lookup.py | candidates/management/commands/candidates_make_party_sets_lookup.py | import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_root = realpath(join(dirname(__file__), '..', '..', '..'))
output_filename = join(
repo_root,
'elections',
settings.ELECTION_APP,
'static',
'js',
'post-to-party-set.js',
)
with open(output_filename, 'w') as f:
f.write('var postIDToPartySet = ')
mapping = {
post['id']: AREA_POST_DATA.post_id_to_party_set(post['id'])
for election, election_data in settings.ELECTIONS_CURRENT
for post in get_all_posts(election_data['for_post_role'])
}
unknown_post_ids = [
k for k, v in mapping.items()
if v is None
]
f.write(json.dumps(mapping))
f.write(';\n')
if unknown_post_ids:
print "Warning: no party set could be found for these post IDs:"
print unknown_post_ids
| import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_root = realpath(join(dirname(__file__), '..', '..', '..'))
output_filename = join(
repo_root,
'elections',
settings.ELECTION_APP,
'static',
'js',
'post-to-party-set.js',
)
with open(output_filename, 'w') as f:
f.write('var postIDToPartySet = ')
mapping = {
post['id']: AREA_POST_DATA.post_id_to_party_set(post['id'])
for election, election_data in settings.ELECTIONS_CURRENT
for post in get_all_posts(election_data['for_post_role'])
}
unknown_post_ids = [
k for k, v in mapping.items()
if v is None
]
f.write(json.dumps(mapping, sort_keys=True))
f.write(';\n')
if unknown_post_ids:
print "Warning: no party set could be found for these post IDs:"
print unknown_post_ids
| Make the party set JS generator output keys in a predictable order | Make the party set JS generator output keys in a predictable order
This makes it easier to check with "git diff" if there have been any
changes.
| Python | agpl-3.0 | neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit |
c126b7a6b060a30e5d5c698dfa3210786f169b92 | camoco/cli/commands/remove.py | camoco/cli/commands/remove.py | import camoco as co
def remove(args):
print(co.del_dataset(args.type,args.name,safe=args.force))
| import camoco as co
def remove(args):
co.del_dataset(args.type,args.name,safe=args.force)
print('Done')
| Make stderr messages more interpretable | Make stderr messages more interpretable
| Python | mit | schae234/Camoco,schae234/Camoco |
fab561da9c54e278e7762380bf043a2fe03e39da | xerox/darwin.py | xerox/darwin.py | # -*- coding: utf-8 -*-
""" Copy + Paste in OS X
"""
import subprocess
import commands
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
return unicode(commands.getoutput('pbpaste'))
except OSError as why:
raise XcodeNotFound
| # -*- coding: utf-8 -*-
""" Copy + Paste in OS X
"""
import subprocess
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
return unicode(subprocess.check_output('pbpaste'))
except OSError as why:
raise XcodeNotFound
| Use `subprocess.check_output` rather than `commands.getoutput`. | Use `subprocess.check_output` rather than `commands.getoutput`.
`commands` is deprecated.
| Python | mit | solarce/xerox,kennethreitz/xerox |
7816cf0562435176a33add229942ac3ee8e7b94c | yolodex/urls.py | yolodex/urls.py | from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from .views import (
RealmView,
RealmCorrectionsView,
EntitySearchView,
EntityListView,
EntityDetailView,
EntityDetailNetworkEmbedView,
)
from .api_views import (
YolodexRouter,
EntityViewSet,
EntityTypeViewSet
)
router = YolodexRouter()
router.register(r'api/entity', EntityViewSet, 'entity')
router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype')
entity_urls = [
url(r'^$', RealmView.as_view(), name='overview'),
url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'),
url(_(r'^search/$'), EntitySearchView.as_view(), name='search'),
url(r'^(?P<type>[\w-]+)/$',
EntityListView.as_view(),
name='entity_list'),
url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$',
EntityDetailView.as_view(),
name='entity_detail'),
url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$',
EntityDetailNetworkEmbedView.as_view(),
name='entity_detail_embed'),
]
urlpatterns = router.urls
urlpatterns += patterns('', *entity_urls)
| from django.conf.urls import url
from django.utils.translation import ugettext_lazy as _
from .views import (
RealmView,
RealmCorrectionsView,
EntitySearchView,
EntityListView,
EntityDetailView,
EntityDetailNetworkEmbedView,
)
from .api_views import (
YolodexRouter,
EntityViewSet,
EntityTypeViewSet
)
router = YolodexRouter()
router.register(r'api/entity', EntityViewSet, 'entity')
router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype')
entity_urls = [
url(r'^$', RealmView.as_view(), name='overview'),
url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'),
url(_(r'^search/$'), EntitySearchView.as_view(), name='search'),
url(r'^(?P<type>[\w-]+)/$',
EntityListView.as_view(),
name='entity_list'),
url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$',
EntityDetailView.as_view(),
name='entity_detail'),
url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$',
EntityDetailNetworkEmbedView.as_view(),
name='entity_detail_embed'),
]
urlpatterns = router.urls
urlpatterns += entity_urls
| Update urlpatterns and remove old patterns pattern | Update urlpatterns and remove old patterns pattern | Python | mit | correctiv/django-yolodex,correctiv/django-yolodex,correctiv/django-yolodex |
57810d41ac50284341c42217cfa6ea0917d10f21 | zephyr/forms.py | zephyr/forms.py | from django import forms
class RegistrationForm(forms.Form):
full_name = forms.CharField(max_length=100)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput, max_length=100)
| from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
def is_unique(value):
try:
print "foo + " + value
User.objects.get(email=value)
raise ValidationError(u'%s is already registered' % value)
except User.DoesNotExist:
pass
class UniqueEmailField(forms.EmailField):
default_validators = [validators.validate_email, is_unique]
class RegistrationForm(forms.Form):
full_name = forms.CharField(max_length=100)
email = UniqueEmailField()
password = forms.CharField(widget=forms.PasswordInput, max_length=100)
domain = forms.CharField(max_length=100)
| Add a custom validator to ensure email uniqueness, include ommitted fields. | Add a custom validator to ensure email uniqueness, include ommitted fields.
Previously no check was performed to ensure that the same email wasn't used
to register twice. Here we add a validator to perform that check.
We also noted that the domain field was omitted, but checked by a client of
this class. Therefore, we add it directly.
(imported from commit 1411bf0adeb3cd048278376b059a26a0da4c54df)
| Python | apache-2.0 | umkay/zulip,jeffcao/zulip,hafeez3000/zulip,dawran6/zulip,RobotCaleb/zulip,bastianh/zulip,brockwhittaker/zulip,hustlzp/zulip,littledogboy/zulip,aliceriot/zulip,MariaFaBella85/zulip,m1ssou/zulip,Gabriel0402/zulip,JanzTam/zulip,bitemyapp/zulip,amyliu345/zulip,alliejones/zulip,hayderimran7/zulip,dwrpayne/zulip,bastianh/zulip,isht3/zulip,krtkmj/zulip,ericzhou2008/zulip,TigorC/zulip,alliejones/zulip,ryansnowboarder/zulip,he15his/zulip,jphilipsen05/zulip,shaunstanislaus/zulip,akuseru/zulip,adnanh/zulip,alliejones/zulip,itnihao/zulip,yuvipanda/zulip,xuanhan863/zulip,kokoar/zulip,verma-varsha/zulip,PaulPetring/zulip,bowlofstew/zulip,Jianchun1/zulip,luyifan/zulip,xuxiao/zulip,Gabriel0402/zulip,hackerkid/zulip,shaunstanislaus/zulip,ryanbackman/zulip,saitodisse/zulip,bowlofstew/zulip,praveenaki/zulip,bowlofstew/zulip,Qgap/zulip,mahim97/zulip,yuvipanda/zulip,tommyip/zulip,peguin40/zulip,armooo/zulip,sonali0901/zulip,kokoar/zulip,easyfmxu/zulip,seapasulli/zulip,joshisa/zulip,EasonYi/zulip,lfranchi/zulip,souravbadami/zulip,ashwinirudrappa/zulip,so0k/zulip,niftynei/zulip,KingxBanana/zulip,ryansnowboarder/zulip,saitodisse/zulip,bowlofstew/zulip,bssrdf/zulip,jrowan/zulip,EasonYi/zulip,showell/zulip,deer-hope/zulip,wangdeshui/zulip,RobotCaleb/zulip,bluesea/zulip,m1ssou/zulip,TigorC/zulip,zachallaun/zulip,aps-sids/zulip,ufosky-server/zulip,zacps/zulip,Jianchun1/zulip,pradiptad/zulip,easyfmxu/zulip,ipernet/zulip,wdaher/zulip,jainayush975/zulip,tdr130/zulip,shaunstanislaus/zulip,ApsOps/zulip,reyha/zulip,kou/zulip,sup95/zulip,thomasboyt/zulip,gigawhitlocks/zulip,zorojean/zulip,LeeRisk/zulip,hafeez3000/zulip,babbage/zulip,eastlhu/zulip,karamcnair/zulip,grave-w-grave/zulip,eastlhu/zulip,lfranchi/zulip,zhaoweigg/zulip,jessedhillon/zulip,zhaoweigg/zulip,noroot/zulip,christi3k/zulip,joshisa/zulip,noroot/zulip,atomic-labs/zulip,dwrpayne/zulip,bluesea/zulip,verma-varsha/zulip,jimmy54/zulip,arpitpanwar/zulip,ashwinirudrappa/zulip,KingxBanana/zulip,LAndreas/zulip,TigorC/zulip,yuvipanda/zulip,synicalsyntax/zulip,proliming/zulip,pradiptad/zulip,dnmfarrell/zulip,Juanvulcano/zulip,tiansiyuan/zulip,zacps/zulip,shaunstanislaus/zulip,levixie/zulip,lfranchi/zulip,yocome/zulip,mdavid/zulip,shrikrishnaholla/zulip,PaulPetring/zulip,hustlzp/zulip,wweiradio/zulip,andersk/zulip,wweiradio/zulip,jonesgithub/zulip,aliceriot/zulip,jonesgithub/zulip,bssrdf/zulip,LeeRisk/zulip,Batterfii/zulip,christi3k/zulip,SmartPeople/zulip,yuvipanda/zulip,dwrpayne/zulip,jeffcao/zulip,jphilipsen05/zulip,vikas-parashar/zulip,rishig/zulip,hayderimran7/zulip,blaze225/zulip,natanovia/zulip,ApsOps/zulip,punchagan/zulip,ericzhou2008/zulip,Drooids/zulip,rishig/zulip,Qgap/zulip,dattatreya303/zulip,ashwinirudrappa/zulip,m1ssou/zulip,mahim97/zulip,jerryge/zulip,adnanh/zulip,glovebx/zulip,dwrpayne/zulip,amyliu345/zulip,peiwei/zulip,jessedhillon/zulip,susansls/zulip,arpith/zulip,Galexrt/zulip,ashwinirudrappa/zulip,RobotCaleb/zulip,ericzhou2008/zulip,voidException/zulip,lfranchi/zulip,ApsOps/zulip,shubhamdhama/zulip,levixie/zulip,yuvipanda/zulip,timabbott/zulip,zachallaun/zulip,mansilladev/zulip,bitemyapp/zulip,natanovia/zulip,itnihao/zulip,dnmfarrell/zulip,dwrpayne/zulip,andersk/zulip,aliceriot/zulip,codeKonami/zulip,Suninus/zulip,vaidap/zulip,moria/zulip,amyliu345/zulip,MariaFaBella85/zulip,shaunstanislaus/zulip,punchagan/zulip,levixie/zulip,niftynei/zulip,ufosky-server/zulip,mdavid/zulip,umkay/zulip,guiquanz/zulip,Jianchun1/zulip,Drooids/zulip,praveenaki/zulip,dawran6/zulip,bitemyapp/zulip,noroot/zulip,Frouk/zulip,glovebx/zulip,kokoar/zulip,schatt/zulip,wangdeshui/zulip,hafeez3000/zulip,wangdeshui/zulip,zorojean/zulip,aakash-cr7/zulip,dotcool/zulip,paxapy/zulip,atomic-labs/zulip,PaulPetring/zulip,dxq-git/zulip,hafeez3000/zulip,wweiradio/zulip,saitodisse/zulip,SmartPeople/zulip,guiquanz/zulip,ApsOps/zulip,esander91/zulip,blaze225/zulip,ipernet/zulip,paxapy/zulip,zwily/zulip,Frouk/zulip,bowlofstew/zulip,calvinleenyc/zulip,Diptanshu8/zulip,eeshangarg/zulip,KJin99/zulip,Juanvulcano/zulip,amanharitsh123/zulip,luyifan/zulip,yocome/zulip,adnanh/zulip,blaze225/zulip,tommyip/zulip,aps-sids/zulip,susansls/zulip,willingc/zulip,jackrzhang/zulip,Suninus/zulip,JanzTam/zulip,Juanvulcano/zulip,suxinde2009/zulip,dhcrzf/zulip,lfranchi/zulip,gigawhitlocks/zulip,SmartPeople/zulip,aakash-cr7/zulip,paxapy/zulip,littledogboy/zulip,punchagan/zulip,akuseru/zulip,bastianh/zulip,MariaFaBella85/zulip,adnanh/zulip,so0k/zulip,vaidap/zulip,technicalpickles/zulip,m1ssou/zulip,rishig/zulip,shubhamdhama/zulip,rishig/zulip,noroot/zulip,krtkmj/zulip,bastianh/zulip,JanzTam/zulip,Gabriel0402/zulip,KingxBanana/zulip,jeffcao/zulip,zachallaun/zulip,glovebx/zulip,johnnygaddarr/zulip,eastlhu/zulip,aakash-cr7/zulip,KJin99/zulip,amanharitsh123/zulip,aliceriot/zulip,adnanh/zulip,mohsenSy/zulip,KingxBanana/zulip,samatdav/zulip,bluesea/zulip,joyhchen/zulip,zofuthan/zulip,EasonYi/zulip,wangdeshui/zulip,sonali0901/zulip,zofuthan/zulip,bssrdf/zulip,nicholasbs/zulip,gkotian/zulip,esander91/zulip,fw1121/zulip,karamcnair/zulip,hustlzp/zulip,johnnygaddarr/zulip,xuxiao/zulip,eeshangarg/zulip,guiquanz/zulip,hj3938/zulip,blaze225/zulip,Gabriel0402/zulip,souravbadami/zulip,pradiptad/zulip,jackrzhang/zulip,littledogboy/zulip,sup95/zulip,Drooids/zulip,andersk/zulip,Diptanshu8/zulip,bastianh/zulip,tdr130/zulip,mdavid/zulip,dattatreya303/zulip,hafeez3000/zulip,lfranchi/zulip,eeshangarg/zulip,bitemyapp/zulip,sharmaeklavya2/zulip,grave-w-grave/zulip,andersk/zulip,glovebx/zulip,hengqujushi/zulip,jessedhillon/zulip,dhcrzf/zulip,mdavid/zulip,Galexrt/zulip,praveenaki/zulip,jonesgithub/zulip,hafeez3000/zulip,ahmadassaf/zulip,JPJPJPOPOP/zulip,stamhe/zulip,Diptanshu8/zulip,Juanvulcano/zulip,jeffcao/zulip,hayderimran7/zulip,qq1012803704/zulip,aps-sids/zulip,jphilipsen05/zulip,vakila/zulip,arpitpanwar/zulip,qq1012803704/zulip,ipernet/zulip,itnihao/zulip,PaulPetring/zulip,stamhe/zulip,niftynei/zulip,AZtheAsian/zulip,johnnygaddarr/zulip,hj3938/zulip,samatdav/zulip,sup95/zulip,vakila/zulip,Qgap/zulip,dotcool/zulip,deer-hope/zulip,sharmaeklavya2/zulip,armooo/zulip,swinghu/zulip,vakila/zulip,vikas-parashar/zulip,eastlhu/zulip,vabs22/zulip,alliejones/zulip,jainayush975/zulip,zofuthan/zulip,joyhchen/zulip,developerfm/zulip,swinghu/zulip,RobotCaleb/zulip,johnnygaddarr/zulip,tbutter/zulip,vaidap/zulip,nicholasbs/zulip,voidException/zulip,ikasumiwt/zulip,MariaFaBella85/zulip,praveenaki/zulip,ahmadassaf/zulip,Batterfii/zulip,noroot/zulip,zwily/zulip,PaulPetring/zulip,andersk/zulip,j831/zulip,Drooids/zulip,firstblade/zulip,stamhe/zulip,sonali0901/zulip,jainayush975/zulip,tommyip/zulip,EasonYi/zulip,mohsenSy/zulip,dnmfarrell/zulip,niftynei/zulip,ashwinirudrappa/zulip,DazWorrall/zulip,JanzTam/zulip,brockwhittaker/zulip,luyifan/zulip,Qgap/zulip,sharmaeklavya2/zulip,jimmy54/zulip,jimmy54/zulip,umkay/zulip,stamhe/zulip,kokoar/zulip,Cheppers/zulip,zorojean/zulip,qq1012803704/zulip,vabs22/zulip,jonesgithub/zulip,firstblade/zulip,xuanhan863/zulip,hayderimran7/zulip,rht/zulip,karamcnair/zulip,joshisa/zulip,glovebx/zulip,paxapy/zulip,akuseru/zulip,jerryge/zulip,armooo/zulip,PhilSk/zulip,eeshangarg/zulip,calvinleenyc/zulip,EasonYi/zulip,aps-sids/zulip,jessedhillon/zulip,dhcrzf/zulip,timabbott/zulip,zulip/zulip,RobotCaleb/zulip,avastu/zulip,bowlofstew/zulip,atomic-labs/zulip,mansilladev/zulip,yuvipanda/zulip,jimmy54/zulip,dwrpayne/zulip,voidException/zulip,glovebx/zulip,rht/zulip,samatdav/zulip,souravbadami/zulip,brockwhittaker/zulip,yuvipanda/zulip,kou/zulip,aakash-cr7/zulip,ahmadassaf/zulip,wdaher/zulip,umkay/zulip,seapasulli/zulip,wavelets/zulip,babbage/zulip,LAndreas/zulip,yocome/zulip,hustlzp/zulip,ikasumiwt/zulip,jerryge/zulip,krtkmj/zulip,vikas-parashar/zulip,moria/zulip,jackrzhang/zulip,MayB/zulip,sonali0901/zulip,tommyip/zulip,mdavid/zulip,tdr130/zulip,hackerkid/zulip,ryansnowboarder/zulip,peiwei/zulip,luyifan/zulip,voidException/zulip,zofuthan/zulip,pradiptad/zulip,synicalsyntax/zulip,grave-w-grave/zulip,ahmadassaf/zulip,adnanh/zulip,jainayush975/zulip,mohsenSy/zulip,johnnygaddarr/zulip,technicalpickles/zulip,JanzTam/zulip,huangkebo/zulip,babbage/zulip,punchagan/zulip,he15his/zulip,hj3938/zulip,kou/zulip,showell/zulip,vakila/zulip,verma-varsha/zulip,johnny9/zulip,moria/zulip,tbutter/zulip,johnnygaddarr/zulip,ipernet/zulip,stamhe/zulip,armooo/zulip,showell/zulip,deer-hope/zulip,eeshangarg/zulip,babbage/zulip,christi3k/zulip,TigorC/zulip,gkotian/zulip,esander91/zulip,swinghu/zulip,ericzhou2008/zulip,saitodisse/zulip,shubhamdhama/zulip,peguin40/zulip,AZtheAsian/zulip,udxxabp/zulip,qq1012803704/zulip,willingc/zulip,umkay/zulip,ashwinirudrappa/zulip,tiansiyuan/zulip,souravbadami/zulip,eastlhu/zulip,saitodisse/zulip,bssrdf/zulip,jonesgithub/zulip,joyhchen/zulip,Galexrt/zulip,ryanbackman/zulip,vabs22/zulip,xuanhan863/zulip,Cheppers/zulip,voidException/zulip,amanharitsh123/zulip,Jianchun1/zulip,tdr130/zulip,kaiyuanheshang/zulip,gkotian/zulip,arpitpanwar/zulip,codeKonami/zulip,willingc/zulip,armooo/zulip,suxinde2009/zulip,shubhamdhama/zulip,Frouk/zulip,dnmfarrell/zulip,shrikrishnaholla/zulip,Batterfii/zulip,kaiyuanheshang/zulip,avastu/zulip,natanovia/zulip,dattatreya303/zulip,deer-hope/zulip,akuseru/zulip,levixie/zulip,Galexrt/zulip,MayB/zulip,MariaFaBella85/zulip,mohsenSy/zulip,LeeRisk/zulip,dxq-git/zulip,zachallaun/zulip,firstblade/zulip,thomasboyt/zulip,reyha/zulip,hengqujushi/zulip,aliceriot/zulip,nicholasbs/zulip,cosmicAsymmetry/zulip,jimmy54/zulip,brockwhittaker/zulip,showell/zulip,shrikrishnaholla/zulip,johnny9/zulip,wweiradio/zulip,hafeez3000/zulip,zachallaun/zulip,ryanbackman/zulip,timabbott/zulip,cosmicAsymmetry/zulip,voidException/zulip,tommyip/zulip,proliming/zulip,jessedhillon/zulip,dattatreya303/zulip,hustlzp/zulip,Cheppers/zulip,johnny9/zulip,jerryge/zulip,DazWorrall/zulip,blaze225/zulip,brockwhittaker/zulip,luyifan/zulip,ipernet/zulip,themass/zulip,dotcool/zulip,zulip/zulip,thomasboyt/zulip,wdaher/zulip,MayB/zulip,vabs22/zulip,developerfm/zulip,huangkebo/zulip,zofuthan/zulip,JPJPJPOPOP/zulip,grave-w-grave/zulip,zorojean/zulip,arpith/zulip,Batterfii/zulip,arpith/zulip,Frouk/zulip,AZtheAsian/zulip,easyfmxu/zulip,kaiyuanheshang/zulip,levixie/zulip,willingc/zulip,tbutter/zulip,ApsOps/zulip,itnihao/zulip,pradiptad/zulip,developerfm/zulip,dattatreya303/zulip,PhilSk/zulip,MayB/zulip,shrikrishnaholla/zulip,LAndreas/zulip,MayB/zulip,codeKonami/zulip,reyha/zulip,SmartPeople/zulip,pradiptad/zulip,Qgap/zulip,synicalsyntax/zulip,AZtheAsian/zulip,zwily/zulip,pradiptad/zulip,praveenaki/zulip,ufosky-server/zulip,wdaher/zulip,easyfmxu/zulip,paxapy/zulip,zhaoweigg/zulip,Galexrt/zulip,huangkebo/zulip,mahim97/zulip,amyliu345/zulip,peguin40/zulip,xuanhan863/zulip,Suninus/zulip,johnny9/zulip,synicalsyntax/zulip,niftynei/zulip,ahmadassaf/zulip,ikasumiwt/zulip,PhilSk/zulip,yocome/zulip,udxxabp/zulip,dhcrzf/zulip,so0k/zulip,calvinleenyc/zulip,JPJPJPOPOP/zulip,codeKonami/zulip,vakila/zulip,seapasulli/zulip,tiansiyuan/zulip,MariaFaBella85/zulip,umkay/zulip,zulip/zulip,LeeRisk/zulip,zacps/zulip,hayderimran7/zulip,PhilSk/zulip,susansls/zulip,ryansnowboarder/zulip,SmartPeople/zulip,kou/zulip,wweiradio/zulip,technicalpickles/zulip,krtkmj/zulip,proliming/zulip,littledogboy/zulip,zofuthan/zulip,punchagan/zulip,gigawhitlocks/zulip,j831/zulip,ryansnowboarder/zulip,xuanhan863/zulip,brainwane/zulip,saitodisse/zulip,calvinleenyc/zulip,DazWorrall/zulip,amallia/zulip,hengqujushi/zulip,jessedhillon/zulip,mahim97/zulip,sonali0901/zulip,moria/zulip,vaidap/zulip,atomic-labs/zulip,so0k/zulip,ericzhou2008/zulip,hj3938/zulip,Batterfii/zulip,firstblade/zulip,yocome/zulip,hackerkid/zulip,willingc/zulip,isht3/zulip,zacps/zulip,alliejones/zulip,Batterfii/zulip,KingxBanana/zulip,brainwane/zulip,sup95/zulip,sup95/zulip,shaunstanislaus/zulip,wangdeshui/zulip,vaidap/zulip,rht/zulip,thomasboyt/zulip,wangdeshui/zulip,shubhamdhama/zulip,m1ssou/zulip,bluesea/zulip,LAndreas/zulip,huangkebo/zulip,dxq-git/zulip,zulip/zulip,aakash-cr7/zulip,ufosky-server/zulip,alliejones/zulip,gigawhitlocks/zulip,zhaoweigg/zulip,ufosky-server/zulip,sharmaeklavya2/zulip,synicalsyntax/zulip,deer-hope/zulip,suxinde2009/zulip,j831/zulip,gigawhitlocks/zulip,luyifan/zulip,jeffcao/zulip,ikasumiwt/zulip,guiquanz/zulip,udxxabp/zulip,udxxabp/zulip,blaze225/zulip,bitemyapp/zulip,willingc/zulip,johnny9/zulip,nicholasbs/zulip,KingxBanana/zulip,AZtheAsian/zulip,he15his/zulip,zwily/zulip,so0k/zulip,avastu/zulip,ikasumiwt/zulip,tiansiyuan/zulip,jackrzhang/zulip,Drooids/zulip,suxinde2009/zulip,punchagan/zulip,levixie/zulip,themass/zulip,wweiradio/zulip,lfranchi/zulip,JPJPJPOPOP/zulip,shrikrishnaholla/zulip,cosmicAsymmetry/zulip,fw1121/zulip,zhaoweigg/zulip,amallia/zulip,guiquanz/zulip,EasonYi/zulip,levixie/zulip,xuxiao/zulip,developerfm/zulip,joyhchen/zulip,zachallaun/zulip,suxinde2009/zulip,huangkebo/zulip,krtkmj/zulip,so0k/zulip,codeKonami/zulip,Vallher/zulip,proliming/zulip,PhilSk/zulip,synicalsyntax/zulip,jeffcao/zulip,xuanhan863/zulip,thomasboyt/zulip,rishig/zulip,sup95/zulip,mdavid/zulip,PhilSk/zulip,wavelets/zulip,grave-w-grave/zulip,KJin99/zulip,peiwei/zulip,gkotian/zulip,jrowan/zulip,tiansiyuan/zulip,bowlofstew/zulip,vabs22/zulip,suxinde2009/zulip,ipernet/zulip,firstblade/zulip,tiansiyuan/zulip,wweiradio/zulip,tdr130/zulip,jimmy54/zulip,kokoar/zulip,souravbadami/zulip,Cheppers/zulip,so0k/zulip,DazWorrall/zulip,hengqujushi/zulip,zulip/zulip,jimmy54/zulip,armooo/zulip,timabbott/zulip,timabbott/zulip,stamhe/zulip,Suninus/zulip,jainayush975/zulip,Jianchun1/zulip,huangkebo/zulip,littledogboy/zulip,jainayush975/zulip,dawran6/zulip,souravbadami/zulip,bluesea/zulip,j831/zulip,zachallaun/zulip,zorojean/zulip,Gabriel0402/zulip,dattatreya303/zulip,fw1121/zulip,arpith/zulip,dnmfarrell/zulip,stamhe/zulip,avastu/zulip,krtkmj/zulip,xuxiao/zulip,peguin40/zulip,Galexrt/zulip,verma-varsha/zulip,tbutter/zulip,esander91/zulip,JanzTam/zulip,deer-hope/zulip,johnny9/zulip,showell/zulip,tdr130/zulip,KJin99/zulip,shubhamdhama/zulip,wavelets/zulip,ryanbackman/zulip,m1ssou/zulip,rishig/zulip,karamcnair/zulip,christi3k/zulip,aliceriot/zulip,glovebx/zulip,codeKonami/zulip,natanovia/zulip,developerfm/zulip,hackerkid/zulip,arpitpanwar/zulip,bssrdf/zulip,itnihao/zulip,verma-varsha/zulip,jphilipsen05/zulip,noroot/zulip,brockwhittaker/zulip,cosmicAsymmetry/zulip,Vallher/zulip,sonali0901/zulip,Diptanshu8/zulip,hengqujushi/zulip,natanovia/zulip,samatdav/zulip,JPJPJPOPOP/zulip,fw1121/zulip,dawran6/zulip,jonesgithub/zulip,tommyip/zulip,eastlhu/zulip,deer-hope/zulip,technicalpickles/zulip,Cheppers/zulip,dotcool/zulip,Juanvulcano/zulip,kokoar/zulip,Frouk/zulip,PaulPetring/zulip,Suninus/zulip,atomic-labs/zulip,mansilladev/zulip,dxq-git/zulip,tdr130/zulip,joyhchen/zulip,firstblade/zulip,dhcrzf/zulip,arpith/zulip,shaunstanislaus/zulip,PaulPetring/zulip,KJin99/zulip,ryanbackman/zulip,zwily/zulip,peguin40/zulip,moria/zulip,wavelets/zulip,dnmfarrell/zulip,calvinleenyc/zulip,jrowan/zulip,technicalpickles/zulip,jackrzhang/zulip,zorojean/zulip,tbutter/zulip,LAndreas/zulip,vikas-parashar/zulip,KJin99/zulip,natanovia/zulip,christi3k/zulip,kou/zulip,isht3/zulip,rht/zulip,Diptanshu8/zulip,easyfmxu/zulip,jerryge/zulip,samatdav/zulip,Qgap/zulip,susansls/zulip,udxxabp/zulip,DazWorrall/zulip,esander91/zulip,ikasumiwt/zulip,vikas-parashar/zulip,amallia/zulip,themass/zulip,joyhchen/zulip,dxq-git/zulip,shrikrishnaholla/zulip,vakila/zulip,luyifan/zulip,swinghu/zulip,seapasulli/zulip,JPJPJPOPOP/zulip,easyfmxu/zulip,schatt/zulip,themass/zulip,zofuthan/zulip,aps-sids/zulip,Gabriel0402/zulip,ericzhou2008/zulip,mohsenSy/zulip,developerfm/zulip,isht3/zulip,mahim97/zulip,tbutter/zulip,voidException/zulip,sharmaeklavya2/zulip,eeshangarg/zulip,peiwei/zulip,dawran6/zulip,reyha/zulip,andersk/zulip,kou/zulip,MayB/zulip,MariaFaBella85/zulip,amallia/zulip,technicalpickles/zulip,he15his/zulip,zacps/zulip,dotcool/zulip,RobotCaleb/zulip,bluesea/zulip,samatdav/zulip,wdaher/zulip,aakash-cr7/zulip,mdavid/zulip,saitodisse/zulip,schatt/zulip,j831/zulip,itnihao/zulip,bluesea/zulip,yocome/zulip,suxinde2009/zulip,zulip/zulip,praveenaki/zulip,bssrdf/zulip,grave-w-grave/zulip,peiwei/zulip,ahmadassaf/zulip,jrowan/zulip,easyfmxu/zulip,mahim97/zulip,littledogboy/zulip,Frouk/zulip,LAndreas/zulip,bitemyapp/zulip,Vallher/zulip,zwily/zulip,arpith/zulip,dxq-git/zulip,TigorC/zulip,shrikrishnaholla/zulip,avastu/zulip,dwrpayne/zulip,SmartPeople/zulip,schatt/zulip,Galexrt/zulip,tbutter/zulip,ApsOps/zulip,jeffcao/zulip,showell/zulip,jessedhillon/zulip,willingc/zulip,Jianchun1/zulip,joshisa/zulip,fw1121/zulip,schatt/zulip,gigawhitlocks/zulip,amanharitsh123/zulip,MayB/zulip,noroot/zulip,punchagan/zulip,kaiyuanheshang/zulip,cosmicAsymmetry/zulip,brainwane/zulip,seapasulli/zulip,babbage/zulip,dnmfarrell/zulip,showell/zulip,ufosky-server/zulip,fw1121/zulip,brainwane/zulip,LeeRisk/zulip,Drooids/zulip,moria/zulip,brainwane/zulip,nicholasbs/zulip,swinghu/zulip,kaiyuanheshang/zulip,ikasumiwt/zulip,isht3/zulip,bastianh/zulip,ashwinirudrappa/zulip,joshisa/zulip,wavelets/zulip,kou/zulip,ApsOps/zulip,rht/zulip,Vallher/zulip,Juanvulcano/zulip,joshisa/zulip,timabbott/zulip,he15his/zulip,hj3938/zulip,amyliu345/zulip,zhaoweigg/zulip,gigawhitlocks/zulip,avastu/zulip,alliejones/zulip,swinghu/zulip,proliming/zulip,Gabriel0402/zulip,Suninus/zulip,peiwei/zulip,calvinleenyc/zulip,ericzhou2008/zulip,guiquanz/zulip,niftynei/zulip,jphilipsen05/zulip,brainwane/zulip,mohsenSy/zulip,Vallher/zulip,johnnygaddarr/zulip,cosmicAsymmetry/zulip,yocome/zulip,paxapy/zulip,themass/zulip,ryanbackman/zulip,karamcnair/zulip,eeshangarg/zulip,KJin99/zulip,vabs22/zulip,zulip/zulip,arpitpanwar/zulip,themass/zulip,huangkebo/zulip,ryansnowboarder/zulip,amanharitsh123/zulip,dhcrzf/zulip,developerfm/zulip,bastianh/zulip,xuanhan863/zulip,amallia/zulip,gkotian/zulip,eastlhu/zulip,sharmaeklavya2/zulip,christi3k/zulip,xuxiao/zulip,Qgap/zulip,xuxiao/zulip,guiquanz/zulip,susansls/zulip,bitemyapp/zulip,themass/zulip,itnihao/zulip,jerryge/zulip,wangdeshui/zulip,thomasboyt/zulip,krtkmj/zulip,technicalpickles/zulip,susansls/zulip,zorojean/zulip,hayderimran7/zulip,kokoar/zulip,hackerkid/zulip,Frouk/zulip,JanzTam/zulip,arpitpanwar/zulip,mansilladev/zulip,proliming/zulip,wavelets/zulip,praveenaki/zulip,aliceriot/zulip,ryansnowboarder/zulip,johnny9/zulip,gkotian/zulip,dxq-git/zulip,verma-varsha/zulip,rht/zulip,hj3938/zulip,m1ssou/zulip,hustlzp/zulip,dotcool/zulip,vikas-parashar/zulip,mansilladev/zulip,DazWorrall/zulip,jackrzhang/zulip,ahmadassaf/zulip,schatt/zulip,synicalsyntax/zulip,qq1012803704/zulip,amyliu345/zulip,armooo/zulip,Suninus/zulip,aps-sids/zulip,aps-sids/zulip,seapasulli/zulip,LeeRisk/zulip,udxxabp/zulip,esander91/zulip,zacps/zulip,udxxabp/zulip,amallia/zulip,RobotCaleb/zulip,kaiyuanheshang/zulip,ufosky-server/zulip,hustlzp/zulip,Diptanshu8/zulip,j831/zulip,jphilipsen05/zulip,atomic-labs/zulip,vaidap/zulip,bssrdf/zulip,reyha/zulip,kaiyuanheshang/zulip,Cheppers/zulip,xuxiao/zulip,swinghu/zulip,hengqujushi/zulip,AZtheAsian/zulip,arpitpanwar/zulip,rht/zulip,jrowan/zulip,hj3938/zulip,wdaher/zulip,dotcool/zulip,mansilladev/zulip,wavelets/zulip,wdaher/zulip,akuseru/zulip,TigorC/zulip,qq1012803704/zulip,qq1012803704/zulip,LeeRisk/zulip,hengqujushi/zulip,shubhamdhama/zulip,schatt/zulip,thomasboyt/zulip,esander91/zulip,zhaoweigg/zulip,ipernet/zulip,he15his/zulip,adnanh/zulip,jerryge/zulip,dhcrzf/zulip,littledogboy/zulip,jonesgithub/zulip,nicholasbs/zulip,andersk/zulip,hackerkid/zulip,akuseru/zulip,avastu/zulip,LAndreas/zulip,vakila/zulip,brainwane/zulip,tommyip/zulip,karamcnair/zulip,amanharitsh123/zulip,codeKonami/zulip,amallia/zulip,joshisa/zulip,hayderimran7/zulip,umkay/zulip,tiansiyuan/zulip,rishig/zulip,reyha/zulip,isht3/zulip,he15his/zulip,babbage/zulip,jrowan/zulip,proliming/zulip,mansilladev/zulip,jackrzhang/zulip,moria/zulip,timabbott/zulip,Drooids/zulip,Vallher/zulip,hackerkid/zulip,Vallher/zulip,firstblade/zulip,fw1121/zulip,EasonYi/zulip,nicholasbs/zulip,akuseru/zulip,Cheppers/zulip,atomic-labs/zulip,peguin40/zulip,peiwei/zulip,natanovia/zulip,DazWorrall/zulip,dawran6/zulip,babbage/zulip,karamcnair/zulip,gkotian/zulip,zwily/zulip,seapasulli/zulip,Batterfii/zulip |
325fed2ef774e708e96d1b123672e1be238d7d21 | nailgun/nailgun/models.py | nailgun/nailgun/models.py | from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
class Environment(models.Model):
#user = models.ForeignKey(User, related_name='environments')
name = models.CharField(max_length=100)
class Role(models.Model):
id = models.CharField(max_length=30, primary_key=True)
name = models.CharField(max_length=50)
class Node(models.Model):
NODE_STATUSES = (
('online', 'online'),
('offline', 'offline'),
('busy', 'busy'),
)
environment = models.ForeignKey(Environment, related_name='nodes')
name = models.CharField(max_length=100, primary_key=True)
status = models.CharField(max_length=30, choices=NODE_STATUSES,
default='online')
metadata = JSONField()
roles = models.ManyToManyField(Role, related_name='nodes')
| from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
class Environment(models.Model):
#user = models.ForeignKey(User, related_name='environments')
name = models.CharField(max_length=100)
class Role(models.Model):
id = models.CharField(max_length=30, primary_key=True)
name = models.CharField(max_length=50)
class Node(models.Model):
NODE_STATUSES = (
('online', 'online'),
('offline', 'offline'),
('busy', 'busy'),
)
environment = models.ForeignKey(Environment, related_name='nodes',
null=True, blank=True, on_delete=models.SET_NULL)
name = models.CharField(max_length=100, primary_key=True)
status = models.CharField(max_length=30, choices=NODE_STATUSES,
default='online')
metadata = JSONField()
roles = models.ManyToManyField(Role, related_name='nodes')
| Allow nodes not to have related environment | Allow nodes not to have related environment
| Python | apache-2.0 | SmartInfrastructures/fuel-main-dev,nebril/fuel-web,dancn/fuel-main-dev,SergK/fuel-main,zhaochao/fuel-main,nebril/fuel-web,prmtl/fuel-web,zhaochao/fuel-main,eayunstack/fuel-web,nebril/fuel-web,SmartInfrastructures/fuel-main-dev,SmartInfrastructures/fuel-main-dev,teselkin/fuel-main,Fiware/ops.Fuel-main-dev,teselkin/fuel-main,zhaochao/fuel-web,dancn/fuel-main-dev,eayunstack/fuel-web,stackforge/fuel-web,huntxu/fuel-web,SmartInfrastructures/fuel-web-dev,prmtl/fuel-web,eayunstack/fuel-web,zhaochao/fuel-main,teselkin/fuel-main,SmartInfrastructures/fuel-web-dev,SmartInfrastructures/fuel-web-dev,stackforge/fuel-web,Fiware/ops.Fuel-main-dev,AnselZhangGit/fuel-main,nebril/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,dancn/fuel-main-dev,zhaochao/fuel-web,dancn/fuel-main-dev,koder-ua/nailgun-fcert,zhaochao/fuel-main,AnselZhangGit/fuel-main,teselkin/fuel-main,prmtl/fuel-web,huntxu/fuel-web,koder-ua/nailgun-fcert,SergK/fuel-main,huntxu/fuel-main,koder-ua/nailgun-fcert,huntxu/fuel-main,huntxu/fuel-main,stackforge/fuel-main,eayunstack/fuel-main,SmartInfrastructures/fuel-main-dev,ddepaoli3/fuel-main-dev,Fiware/ops.Fuel-main-dev,AnselZhangGit/fuel-main,stackforge/fuel-web,SergK/fuel-main,zhaochao/fuel-web,ddepaoli3/fuel-main-dev,SmartInfrastructures/fuel-web-dev,ddepaoli3/fuel-main-dev,AnselZhangGit/fuel-main,huntxu/fuel-web,nebril/fuel-web,prmtl/fuel-web,huntxu/fuel-web,eayunstack/fuel-main,huntxu/fuel-web,zhaochao/fuel-main,zhaochao/fuel-web,stackforge/fuel-main,ddepaoli3/fuel-main-dev,prmtl/fuel-web,zhaochao/fuel-web,stackforge/fuel-main,koder-ua/nailgun-fcert,eayunstack/fuel-web,eayunstack/fuel-main,Fiware/ops.Fuel-main-dev |
23456a32038f13c6219b6af5ff9fff7e1daae242 | abusehelper/core/tests/test_utils.py | abusehelper/core/tests/test_utils.py | import pickle
import unittest
from .. import utils
class TestCompressedCollection(unittest.TestCase):
def test_collection_can_be_pickled_and_unpickled(self):
original = utils.CompressedCollection()
original.append("ab")
original.append("cd")
unpickled = pickle.loads(pickle.dumps(original))
self.assertEqual(["ab", "cd"], list(unpickled))
def test_objects_can_be_appended_to_an_unpickled_collection(self):
original = utils.CompressedCollection()
original.append("ab")
unpickled = pickle.loads(pickle.dumps(original))
self.assertEqual(["ab"], list(unpickled))
unpickled.append("cd")
self.assertEqual(["ab", "cd"], list(unpickled))
def test_objects_can_be_appended_a_collection_after_pickling(self):
original = utils.CompressedCollection()
original.append("ab")
pickle.dumps(original)
original.append("cd")
self.assertEqual(["ab", "cd"], list(original))
| import socket
import pickle
import urllib2
import unittest
import idiokit
from .. import utils
class TestFetchUrl(unittest.TestCase):
def test_should_raise_TypeError_when_passing_in_an_opener(self):
sock = socket.socket()
try:
sock.bind(("localhost", 0))
sock.listen(1)
_, port = sock.getsockname()
opener = urllib2.build_opener()
fetch = utils.fetch_url("http://localhost:{0}".format(port), opener=opener)
self.assertRaises(TypeError, idiokit.main_loop, fetch)
finally:
sock.close()
class TestCompressedCollection(unittest.TestCase):
def test_collection_can_be_pickled_and_unpickled(self):
original = utils.CompressedCollection()
original.append("ab")
original.append("cd")
unpickled = pickle.loads(pickle.dumps(original))
self.assertEqual(["ab", "cd"], list(unpickled))
def test_objects_can_be_appended_to_an_unpickled_collection(self):
original = utils.CompressedCollection()
original.append("ab")
unpickled = pickle.loads(pickle.dumps(original))
self.assertEqual(["ab"], list(unpickled))
unpickled.append("cd")
self.assertEqual(["ab", "cd"], list(unpickled))
def test_objects_can_be_appended_a_collection_after_pickling(self):
original = utils.CompressedCollection()
original.append("ab")
pickle.dumps(original)
original.append("cd")
self.assertEqual(["ab", "cd"], list(original))
| Add a test for utils.fetch_url(..., opener=...) | Add a test for utils.fetch_url(..., opener=...)
Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com>
| Python | mit | abusesa/abusehelper |
567925c770f965c7440b13b63b11b5615bf3c141 | src/connection.py | src/connection.py | from . import output
import json
import sys
import urllib.parse
import http.client
def getRequest(id, conf):
db = conf['db']
headers = conf['headers']
test = db[id]
method = test['method'].upper()
fullpath = conf['path'] + test['path']
desc = test['desc']
params = ''
server = conf['domain'] + ':' + conf['port']
try:
conn = http.client.HTTPConnection(server)
except IOError as err:
conf['errors'].append("Server " + server + " not found!")
output.validationError(conf)
sys.exit(1)
if method == 'GET':
conn.request(method, fullpath)
else:
params = urllib.parse.urlencode(test['data'])
res = conn.request(method, fullpath, params, headers)
res = conn.getresponse()
data = res.read().decode("utf-8").strip()
if len(data) > 60:
data = data[0:60] + '...'
output.printRequest(method,
conf['domain'],
fullpath,
params,
desc,
data,
res.status)
result = {}
result['status'] = res.status
result['header'] = res.getheaders()
try:
result['data'] = json.loads(data)
except ValueError:
print("Invalid JSON outout")
# finally:
# result['data'] = None
return result
| from . import output
import json
import sys
import urllib.parse
import http.client
def getRequest(id, conf):
db = conf['db']
headers = conf['headers']
test = db[id]
method = test['method'].upper()
fullpath = conf['path'] + test['path']
desc = test['desc']
params = ''
server = conf['domain'] + ':' + conf['port']
try:
conn = http.client.HTTPConnection(server)
except IOError as err:
conf['errors'].append("Server " + server + " not found!")
output.validationError(conf)
sys.exit(1)
if method == 'GET':
conn.request(method, fullpath)
else:
params = urllib.parse.urlencode(test['data'])
res = conn.request(method, fullpath, params, headers)
res = conn.getresponse()
data = res.read().decode("utf-8").strip()
if len(data) > 60:
output_data = data.replace("\n", '')
output_data = output_data[0:60] + '...'
else:
output_data = data
output.printRequest(method,
conf['domain'],
fullpath,
params,
desc,
output_data,
res.status)
result = {}
result['status'] = res.status
result['header'] = res.getheaders()
try:
result['data'] = json.loads(data)
except ValueError:
print("Invalid JSON outout")
# finally:
# result['data'] = None
return result
| Add a properly string for outputing | Add a properly string for outputing
| Python | mit | manoelhc/restafari,manoelhc/restafari |
a81f78385f8ec9a94d0d511805801d1f0a6f17ed | drogher/shippers/fedex.py | drogher/shippers/fedex.py | from .base import Shipper
class FedEx(Shipper):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:].lstrip('0')
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
total = 0
for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)):
total += int(char) * digit
return total % 11 % 10 == int(check_digit)
class FedExGround96(FedEx):
barcode_pattern = r'^96\d{20}$'
@property
def tracking_number(self):
return self.barcode[7:]
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
odd = even = 0
for i, char in enumerate(reversed(chars)):
if i & 0x1:
odd += int(char)
else:
even += int(char)
check = ((even * 3) + odd) % 10
if check != 0:
check = 10 - check
return check == int(check_digit)
| import itertools
from .base import Shipper
class FedEx(Shipper):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:].lstrip('0')
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
total = 0
for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)):
total += int(char) * digit
return total % 11 % 10 == int(check_digit)
class FedExGround96(FedEx):
barcode_pattern = r'^96\d{20}$'
@property
def tracking_number(self):
return self.barcode[7:]
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
odd = even = 0
for i, char in enumerate(reversed(chars)):
if i & 0x1:
odd += int(char)
else:
even += int(char)
check = ((even * 3) + odd) % 10
if check != 0:
check = 10 - check
return check == int(check_digit)
| Use itertools.cycle for repeating digits | Use itertools.cycle for repeating digits
| Python | bsd-3-clause | jbittel/drogher |
b7fcbc3a2117f00177ddd7a353eb6a4dee5bc777 | stat_retriever.py | stat_retriever.py | """
stat-retriever by Team-95
stat_retriever.py
"""
import requests
def main():
url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference="
"&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment="
"&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound="
"0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=2014-15&SeasonSegment="
"&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight="
if __name__ == "__main__":
main()
| """
stat-retriever by Team-95
stat_retriever.py
"""
import requests
import json
def main():
season = "2014-15"
url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference="
"&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment="
"&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound="
"0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=%s&SeasonSegment="
"&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference="
"&VsDivision=&Weight=") % season
response = requests.get(url)
stats = json.loads(response.text)
if __name__ == "__main__":
main()
| Fix formatting once more, added response parsing | Fix formatting once more, added response parsing
| Python | mit | Team-95/stat-retriever |
ce3249dea725d40d5e0916b344cdde53ab6d53dc | src/satosa/micro_services/processors/scope_extractor_processor.py | src/satosa/micro_services/processors/scope_extractor_processor.py | from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning
from .base_processor import BaseProcessor
CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute'
CONFIG_DEFAULT_MAPPEDATTRIBUTE = ''
class ScopeExtractorProcessor(BaseProcessor):
"""
Extracts the scope from a scoped attribute and maps that to
another attribute
Example configuration:
module: satosa.micro_services.attribute_processor.AttributeProcessor
name: AttributeProcessor
config:
process:
- attribute: scoped_affiliation
processors:
- name: ScopeExtractorProcessor
module: satosa.micro_services.processors.scope_extractor_processor
mapped_attribute: domain
"""
def process(self, internal_data, attribute, **kwargs):
mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE)
if mapped_attribute is None or mapped_attribute == '':
raise AttributeProcessorError("The mapped_attribute needs to be set")
attributes = internal_data.attributes
values = attributes.get(attribute, [])
if not values:
raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute))
if not any('@' in val for val in values):
raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute))
for value in values:
if '@' in value:
scope = value.split('@')[1]
attributes[mapped_attribute] = [scope]
break
| from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning
from .base_processor import BaseProcessor
CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute'
CONFIG_DEFAULT_MAPPEDATTRIBUTE = ''
class ScopeExtractorProcessor(BaseProcessor):
"""
Extracts the scope from a scoped attribute and maps that to
another attribute
Example configuration:
module: satosa.micro_services.attribute_processor.AttributeProcessor
name: AttributeProcessor
config:
process:
- attribute: scoped_affiliation
processors:
- name: ScopeExtractorProcessor
module: satosa.micro_services.processors.scope_extractor_processor
mapped_attribute: domain
"""
def process(self, internal_data, attribute, **kwargs):
mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE)
if mapped_attribute is None or mapped_attribute == '':
raise AttributeProcessorError("The mapped_attribute needs to be set")
attributes = internal_data.attributes
values = attributes.get(attribute, [])
if not values:
raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute))
if not isinstance(values, list):
values = [values]
if not any('@' in val for val in values):
raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute))
for value in values:
if '@' in value:
scope = value.split('@')[1]
attributes[mapped_attribute] = [scope]
break
| Make the ScopeExtractorProcessor usable for the Primary Identifier | Make the ScopeExtractorProcessor usable for the Primary Identifier
This patch adds support to use the ScopeExtractorProcessor on the Primary
Identifiert which is, in contrast to the other values, a string.
Closes #348
| Python | apache-2.0 | SUNET/SATOSA,SUNET/SATOSA,its-dirg/SATOSA |
8445d491030be7fb2fa1175140a4b022b2690425 | conman/cms/tests/test_urls.py | conman/cms/tests/test_urls.py | from incuna_test_utils.testcases.urls import URLTestCase
from .. import views
class TestCMSIndexURL(URLTestCase):
"""Make sure that the CMSIndex view has a URL"""
def test_url(self):
self.assert_url_matches_view(
views.CMSIndex,
'/cms/',
'cms:index',
)
| from unittest import mock
from django.test import TestCase
from incuna_test_utils.testcases.urls import URLTestCase
from .. import urls, views
class TestCMSIndexURL(URLTestCase):
"""Make sure that the CMSIndex view has a URL"""
def test_url(self):
self.assert_url_matches_view(
views.CMSIndex,
'/cms/',
'cms:index',
)
class TestCMSURLs(TestCase):
@mock.patch('conman.cms.urls.url')
@mock.patch('conman.cms.urls.include')
@mock.patch('django.apps.apps.get_app_config')
def test_urls(self, get_app_config, include, url):
fake_config = mock.Mock()
fake_config.cms_urls = 'example.path.to.urls'
fake_config.label = 'example'
fake_config.managed_apps = {fake_config}
get_app_config.return_value = fake_config
cms_urls = list(urls.urls())
expected = [
url(r'^$', views.CMSIndex.as_view, name='index'),
url(r'^example', include(fake_config.cms_urls))
]
self.assertSequenceEqual(cms_urls, expected)
| Add further tests of the cms urls | Add further tests of the cms urls
| Python | bsd-2-clause | meshy/django-conman,Ian-Foote/django-conman,meshy/django-conman |
748c9728b4de0d19b4e18e3c0e0763dc8d20ba37 | queue_job/tests/__init__.py | queue_job/tests/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_session
from . import test_event
from . import test_job
from . import test_queue
from . import test_worker
from . import test_backend
from . import test_producer
from . import test_connector
from . import test_mapper
from . import test_related_action
fast_suite = [
]
checks = [
test_session,
test_event,
test_job,
test_queue,
test_worker,
test_backend,
test_producer,
test_connector,
test_mapper,
test_related_action,
]
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_session
from . import test_event
from . import test_job
from . import test_queue
from . import test_worker
from . import test_backend
from . import test_producer
from . import test_connector
from . import test_mapper
from . import test_related_action
| Remove deprecated fast_suite and check list for unit tests | Remove deprecated fast_suite and check list for unit tests
| Python | agpl-3.0 | leorochael/queue |
23fa1c55ec9fcbc595260be1039a4b8481cb4f13 | api/comments/views.py | api/comments/views.py | from rest_framework import generics
from api.comments.serializers import CommentSerializer, CommentDetailSerializer
from website.project.model import Comment
from api.base.utils import get_object_or_error
class CommentMixin(object):
"""Mixin with convenience methods for retrieving the current comment based on the
current URL. By default, fetches the comment based on the comment_id kwarg.
"""
serializer_class = CommentSerializer
comment_lookup_url_kwarg = 'comment_id'
def get_comment(self, check_permissions=True):
comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg])
if check_permissions:
# May raise a permission denied
self.check_object_permissions(self.request, comment)
return comment
class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin):
"""Details about a specific comment.
"""
# permission classes
# required scopes
serializer_class = CommentDetailSerializer
# overrides RetrieveAPIView
def get_object(self):
return self.get_comment()
| from modularodm import Q
from modularodm.exceptions import NoResultsFound
from rest_framework import generics
from rest_framework.exceptions import NotFound
from api.comments.serializers import CommentSerializer, CommentDetailSerializer
from website.project.model import Comment
class CommentMixin(object):
"""Mixin with convenience methods for retrieving the current comment based on the
current URL. By default, fetches the comment based on the comment_id kwarg.
"""
serializer_class = CommentSerializer
comment_lookup_url_kwarg = 'comment_id'
def get_comment(self, check_permissions=True):
pk = self.kwargs[self.comment_lookup_url_kwarg]
query = Q('_id', 'eq', pk)
try:
comment = Comment.find_one(query)
except NoResultsFound:
raise NotFound
if check_permissions:
# May raise a permission denied
self.check_object_permissions(self.request, comment)
return comment
class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin):
"""Details about a specific comment.
"""
# permission classes
# required scopes
serializer_class = CommentDetailSerializer
# overrides RetrieveAPIView
def get_object(self):
return self.get_comment()
| Return deleted comments instead of throwing error | Return deleted comments instead of throwing error
| Python | apache-2.0 | kch8qx/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,acshi/osf.io,DanielSBrown/osf.io,GageGaskins/osf.io,icereval/osf.io,wearpants/osf.io,mfraezz/osf.io,acshi/osf.io,jnayak1/osf.io,crcresearch/osf.io,danielneis/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,samanehsan/osf.io,SSJohns/osf.io,samanehsan/osf.io,hmoco/osf.io,aaxelb/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,brandonPurvis/osf.io,ticklemepierce/osf.io,leb2dg/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,cwisecarver/osf.io,KAsante95/osf.io,felliott/osf.io,erinspace/osf.io,Nesiehr/osf.io,alexschiller/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,abought/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,samanehsan/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,emetsger/osf.io,rdhyee/osf.io,cslzchen/osf.io,ZobairAlijan/osf.io,abought/osf.io,alexschiller/osf.io,sloria/osf.io,doublebits/osf.io,KAsante95/osf.io,brianjgeiger/osf.io,jnayak1/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,mattclark/osf.io,mluo613/osf.io,GageGaskins/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,binoculars/osf.io,Nesiehr/osf.io,hmoco/osf.io,TomHeatwole/osf.io,doublebits/osf.io,caneruguz/osf.io,KAsante95/osf.io,mluo613/osf.io,kwierman/osf.io,crcresearch/osf.io,abought/osf.io,caseyrollins/osf.io,saradbowman/osf.io,saradbowman/osf.io,chrisseto/osf.io,danielneis/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,caneruguz/osf.io,mluo613/osf.io,mluo613/osf.io,amyshi188/osf.io,adlius/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,TomBaxter/osf.io,pattisdr/osf.io,Ghalko/osf.io,HalcyonChimera/osf.io,zamattiac/osf.io,mfraezz/osf.io,Nesiehr/osf.io,SSJohns/osf.io,caneruguz/osf.io,hmoco/osf.io,emetsger/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,abought/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,aaxelb/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,asanfilippo7/osf.io,ticklemepierce/osf.io,caseyrygt/osf.io,hmoco/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,caseyrollins/osf.io,wearpants/osf.io,leb2dg/osf.io,mluke93/osf.io,amyshi188/osf.io,zamattiac/osf.io,mfraezz/osf.io,mattclark/osf.io,RomanZWang/osf.io,wearpants/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,icereval/osf.io,amyshi188/osf.io,mattclark/osf.io,chennan47/osf.io,billyhunt/osf.io,wearpants/osf.io,alexschiller/osf.io,cslzchen/osf.io,KAsante95/osf.io,leb2dg/osf.io,billyhunt/osf.io,felliott/osf.io,erinspace/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,ZobairAlijan/osf.io,chennan47/osf.io,aaxelb/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,acshi/osf.io,binoculars/osf.io,kch8qx/osf.io,danielneis/osf.io,acshi/osf.io,erinspace/osf.io,alexschiller/osf.io,cslzchen/osf.io,adlius/osf.io,billyhunt/osf.io,laurenrevere/osf.io,GageGaskins/osf.io,mfraezz/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,crcresearch/osf.io,kwierman/osf.io,pattisdr/osf.io,asanfilippo7/osf.io,sloria/osf.io,samchrisinger/osf.io,doublebits/osf.io,asanfilippo7/osf.io,SSJohns/osf.io,mluo613/osf.io,brandonPurvis/osf.io,mluke93/osf.io,mluke93/osf.io,doublebits/osf.io,emetsger/osf.io,Ghalko/osf.io,caseyrygt/osf.io,chrisseto/osf.io,chennan47/osf.io,caseyrygt/osf.io,doublebits/osf.io,Ghalko/osf.io,zamattiac/osf.io,sloria/osf.io,Johnetordoff/osf.io,KAsante95/osf.io,pattisdr/osf.io,amyshi188/osf.io,asanfilippo7/osf.io,laurenrevere/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,billyhunt/osf.io,felliott/osf.io,rdhyee/osf.io,Ghalko/osf.io,ticklemepierce/osf.io,caseyrygt/osf.io,CenterForOpenScience/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,mluke93/osf.io,adlius/osf.io,danielneis/osf.io,billyhunt/osf.io,caneruguz/osf.io,kwierman/osf.io,zachjanicki/osf.io,chrisseto/osf.io,icereval/osf.io,felliott/osf.io,kwierman/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,zamattiac/osf.io,binoculars/osf.io,acshi/osf.io,emetsger/osf.io,rdhyee/osf.io,adlius/osf.io,TomBaxter/osf.io,jnayak1/osf.io |
10aab1c427a82b4cfef6b07ae1103260e14ca322 | geotrek/feedback/admin.py | geotrek/feedback/admin.py | from django.conf import settings
from django.contrib import admin
from geotrek.feedback import models as feedback_models
if 'modeltranslation' in settings.INSTALLED_APPS:
from modeltranslation.admin import TabbedTranslationAdmin
else:
from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin
class WorkflowManagerAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
# There can be only one manager
perms = super().has_add_permission(request)
if perms and feedback_models.WorkflowManager.objects.exists():
perms = False
return perms
admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportStatus)
admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
| from django.conf import settings
from django.contrib import admin
from geotrek.feedback import models as feedback_models
if 'modeltranslation' in settings.INSTALLED_APPS:
from modeltranslation.admin import TabbedTranslationAdmin
else:
from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin
class WorkflowManagerAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
# There can be only one manager
perms = super().has_add_permission(request)
if perms and feedback_models.WorkflowManager.objects.exists():
perms = False
return perms
admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin)
admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportStatus)
admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
| Fix deleted line during merge | Fix deleted line during merge
| Python | bsd-2-clause | makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek |
d7c4f0471271d104c0ff3500033e425547ca6c27 | notification/context_processors.py | notification/context_processors.py | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
}
else:
return {} | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
"notifications": Notice.objects.filter(user=request.user.id)
}
else:
return {} | Add user notifications to context processor | Add user notifications to context processor
| Python | mit | affan2/django-notification,affan2/django-notification |
7b681bfd34a24dc15b219dd355db2557914b7b49 | tests/conftest.py | tests/conftest.py | import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param)
| import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param, unsafe=True)
| Revert previous commit due to arrayfire-python bug. | Revert previous commit due to arrayfire-python bug.
| Python | bsd-2-clause | daurer/afnumpy,FilipeMaia/afnumpy |
a94a8f0e5c773995da710bb8e90839c7b697db96 | cobe/tokenizer.py | cobe/tokenizer.py | # Copyright (C) 2010 Peter Teichman
import re
class MegaHALTokenizer:
def split(self, phrase):
if len(phrase) == 0:
return []
# add ending punctuation if it is missing
if phrase[-1] not in ".!?":
phrase = phrase + "."
# megahal traditionally considers [a-z0-9] as word characters.
# Let's see what happens if we add [_']
words = re.findall("([\w']+|[^\w']+)", phrase.upper())
return words
| # Copyright (C) 2010 Peter Teichman
import re
class MegaHALTokenizer:
def split(self, phrase):
if len(phrase) == 0:
return []
# add ending punctuation if it is missing
if phrase[-1] not in ".!?":
phrase = phrase + "."
# megahal traditionally considers [a-z0-9] as word characters.
# Let's see what happens if we add [_']
words = re.findall("([\w']+|[^\w']+)", phrase.upper(), re.UNICODE)
return words
| Use the re.UNICODE flag (i.e., Python character tables) in findall() | Use the re.UNICODE flag (i.e., Python character tables) in findall()
| Python | mit | LeMagnesium/cobe,meska/cobe,wodim/cobe-ng,wodim/cobe-ng,LeMagnesium/cobe,pteichman/cobe,tiagochiavericosta/cobe,pteichman/cobe,meska/cobe,DarkMio/cobe,tiagochiavericosta/cobe,DarkMio/cobe |
b7c95f6eed786000278f5719fbf4ac037af20e50 | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/factories.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/factories.py | from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
password = (
extracted
if extracted
else Faker(
"password",
length=42,
special_chars=True,
digits=True,
upper_case=True,
lower_case=True,
).generate(params={"locale": None})
)
self.set_password(password)
class Meta:
model = get_user_model()
django_get_or_create = ["username"]
| from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
password = (
extracted
if extracted
else Faker(
"password",
length=42,
special_chars=True,
digits=True,
upper_case=True,
lower_case=True,
).evaluate(None, None, extra={"locale": None})
)
self.set_password(password)
class Meta:
model = get_user_model()
django_get_or_create = ["username"]
| Update factory-boy's .generate to evaluate | Update factory-boy's .generate to evaluate
Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com>
| Python | bsd-3-clause | pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django |
32b35f49c525d6b527de325ecc4837ab7c18b5ad | apiserver/alembic/versions/201711101357_451d4bb125cb_add_ranking_data_to_participants_table.py | apiserver/alembic/versions/201711101357_451d4bb125cb_add_ranking_data_to_participants_table.py | """Add ranking data to participants table
Revision ID: 451d4bb125cb
Revises: 49be2190c22d
Create Date: 2017-11-10 13:57:37.807238+00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '451d4bb125cb'
down_revision = '49be2190c22d'
branch_labels = None
depends_on = None
def upgrade():
op.add_column(
"game_participant",
sa.Column('mu', mysql.FLOAT(),
nullable=True),
)
op.add_column(
"game_participant",
sa.Column('sigma',
mysql.FLOAT(unsigned=True),
nullable=True),
)
op.add_column(
"game_participant",
sa.Column('rank',
mysql.SMALLINT(display_width=5),
autoincrement=False,
nullable=True),
)
def downgrade():
op.drop_column("game_participant", "mu")
op.drop_column("game_participant", "sigma")
op.drop_column("game_participant", "rank")
| """Add ranking data to participants table
Revision ID: 451d4bb125cb
Revises: 49be2190c22d
Create Date: 2017-11-10 13:57:37.807238+00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '451d4bb125cb'
down_revision = '49be2190c22d'
branch_labels = None
depends_on = None
def upgrade():
op.add_column(
"game_participant",
sa.Column('mu', mysql.FLOAT(),
nullable=True),
)
op.add_column(
"game_participant",
sa.Column('sigma',
mysql.FLOAT(unsigned=True),
nullable=True),
)
op.add_column(
"game_participant",
sa.Column('leaderboard_rank',
mysql.SMALLINT(display_width=5),
autoincrement=False,
nullable=True),
)
def downgrade():
op.drop_column("game_participant", "mu")
op.drop_column("game_participant", "sigma")
op.drop_column("game_participant", "leaderboard_rank")
| Rename rank field to avoid column name clash | Rename rank field to avoid column name clash
| Python | mit | HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II |
e9709abadb2daa1a0752fa12b8e017074f0fb098 | classes/person.py | classes/person.py | class Person(object):
def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"):
self.person_name = person_name
self.person_surname = person_surname
self.person_type = person_type
self.wants_accommodation = wants_accommodation
def full_name(self):
if not isinstance(self.person_name, str) or not isinstance(self.person_surname, str):
raise ValueError('Only strings are allowed as names')
else:
self.full_name = self.person_name + " " + self.person_surname
return self.full_name
| class Person(object):
def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"):
self.person_name = person_name
self.person_surname = person_surname
self.person_type = person_type
self.wants_accommodation = wants_accommodation
def full_name(self):
self.full_name = self.person_name + " " + self.person_surname
return self.full_name
| Change full name method to stop validating for str type which is repetitive and has been tested elsewhere | Change full name method to stop validating for str type which is repetitive and has been tested elsewhere
| Python | mit | peterpaints/room-allocator |
8d43061490c32b204505382ec7b77c18ddc32d9d | conf_site/apps.py | conf_site/apps.py | from django.apps import AppConfig as BaseAppConfig
from django.utils.importlib import import_module
class AppConfig(BaseAppConfig):
name = "conf_site"
def ready(self):
import_module("conf_site.receivers")
| from importlib import import_module
from django.apps import AppConfig as BaseAppConfig
class AppConfig(BaseAppConfig):
name = "conf_site"
def ready(self):
import_module("conf_site.receivers")
| Remove Django importlib in favor of stdlib. | Remove Django importlib in favor of stdlib.
Django's copy of importlib was deprecated in 1.7 and therefore removed
in Django 1.9:
https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib
This is okay, since we are using Python 2.7 and can rely on the copy in
the standard library.
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site |
858f993ceffb497bee12457d1d4102339af410a4 | typer/__init__.py | typer/__init__.py | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
BadArgumentUsage,
BadOptionUsage,
BadParameter,
ClickException,
FileError,
MissingParameter,
NoSuchOption,
UsageError,
)
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressbar,
prompt,
secho,
style,
unstyle,
)
from click.utils import ( # noqa
echo,
format_filename,
get_app_dir,
get_binary_stream,
get_os_args,
get_text_stream,
open_file,
)
from .main import Typer, run # noqa
from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa
from .params import Argument, Option # noqa
| """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
Exit,
)
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressbar,
prompt,
secho,
style,
unstyle,
)
from click.utils import ( # noqa
echo,
format_filename,
get_app_dir,
get_binary_stream,
get_text_stream,
open_file,
)
from .main import Typer, run # noqa
from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa
from .params import Argument, Option # noqa
| Clean exports from typer, remove unneeded Click components | :fire: Clean exports from typer, remove unneeded Click components
and add Exit exception
| Python | mit | tiangolo/typer,tiangolo/typer |
2833e2296cff6a52ab75c2c88563e81372902035 | src/heartbeat/checkers/build.py | src/heartbeat/checkers/build.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from pkg_resources import get_distribution, DistributionNotFound
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
try:
distro = get_distribution(package_name)
except DistributionNotFound:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
| from pkg_resources import Requirement, WorkingSet
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
sys_path_distros = WorkingSet()
package_req = Requirement.parse(package_name)
distro = sys_path_distros.find(package_req)
if not distro:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
| Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path. | Package name should be searched through the same distros list
we use for listing installed packages. get_distribution is using
the global working_set which may not contain the requested package
if the initialization(pkg_resources import time) happened before
the project name to appear in the sys.path.
| Python | mit | pbs/django-heartbeat |
fa776fc0d3c568bda7d84ccd9b345e34c3fcf312 | ideascube/mediacenter/tests/factories.py | ideascube/mediacenter/tests/factories.py | from django.conf import settings
import factory
from ..models import Document
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summary"
lang = settings.LANGUAGE_CODE
original = factory.django.FileField()
credits = "Document credits"
package_id = ""
@factory.post_generation
def tags(self, create, extracted, **kwargs):
if extracted:
self.tags.add(*extracted)
class Meta:
model = Document
| from django.conf import settings
import factory
from ..models import Document
class EmptyFileField(factory.django.FileField):
DEFAULT_FILENAME = None
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summary"
lang = settings.LANGUAGE_CODE
original = factory.django.FileField()
preview = EmptyFileField()
credits = "Document credits"
package_id = ""
@factory.post_generation
def tags(self, create, extracted, **kwargs):
if extracted:
self.tags.add(*extracted)
class Meta:
model = Document
| Allow DocumentFactory to handle preview field. | Allow DocumentFactory to handle preview field.
The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'.
It means that by default a FileField created by factoryboy is considered as a
True value.
Before this commit, we were not defining a Document.preview field in the
factory so factoryboy created a empty FileField.
To not break the API for other tests, we need to create a "False" FileField by
default.
To do so, we need to change the DEFAULT_FILENAME to None.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
e0607c27cf990f893d837af5717de684bb62aa63 | plugins/spark/__init__.py | plugins/spark/__init__.py | import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
def pyspark_run_cleanup(event):
if SC_KEY in event.info['kwargs']:
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
| import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
info['cleanup_spark'] = True
def pyspark_run_cleanup(event):
if event.info.get('cleanup_spark'):
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
| Fix spark mode (faulty shutdown conditional logic) | Fix spark mode (faulty shutdown conditional logic)
| Python | apache-2.0 | Kitware/romanesco,girder/girder_worker,girder/girder_worker,Kitware/romanesco,girder/girder_worker,Kitware/romanesco,Kitware/romanesco |
e771eeb4595197ae4c147f617c4cf7e5825f279c | object_extractor/named_object.py | object_extractor/named_object.py | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.items(), key=lambda x: x[1])[0]
def score(self):
return self._score
class NamedObject:
def __init__(self):
self._entities = []
def __bool__(self):
return bool(self._entities)
def add(self, object_type, score, normal_form):
self._entities.append((object_type, score, normal_form))
def calc_entities(self):
forms = defaultdict(EntityForm)
forms['object'] = self._make_global_entity()
for object_type, score, normal_form in self._entities:
forms[object_type].add_form(score, normal_form)
return forms
def _make_global_entity(self):
global_form = EntityForm()
for _, score, form in self._entities:
global_form.add_form(score, form)
return global_form
| from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.items(), key=lambda x: x[1])[0]
def score(self):
return self._score
class NamedObject:
def __init__(self):
self._entities = []
def __bool__(self):
return bool(self._entities)
def add(self, object_type, score, normal_form):
self._entities.append((object_type, score, normal_form))
def calc_entities(self):
forms = defaultdict(EntityForm)
for object_type, score, normal_form in self._entities:
forms[object_type].add_form(score, normal_form)
return forms
| Remove `objects' group as useless | Remove `objects' group as useless
| Python | mit | Lol4t0/named-objects-extractor |
c6427c035b9d1d38618ebfed33f729e3d10f270d | config.py | config.py | from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
s.merge(Guild(id=gid, **kwargs))
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
| from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
guild = await s.select(Guild).where(Guild.id == gid).first()
for key, value in kwargs.items():
setattr(guild, key, value)
s.merge(guild)
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
| Change set to merge correctly | Change set to merge correctly
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot |
dbda7d542c2f9353a57b63b7508afbf9bc2397cd | examples/address_validation.py | examples/address_validation.py | #!/usr/bin/env python
"""
This example shows how to validate addresses. Note that the validation
class can handle up to 100 addresses for validation.
"""
import logging
import binascii
from example_config import CONFIG_OBJ
from fedex.services.address_validation_service import FedexAddressValidationRequest
# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)
# This is the object that will be handling our tracking request.
# We're using the FedexConfig object from example_config.py in this dir.
address = FedexAddressValidationRequest(CONFIG_OBJ)
address1 = address.create_wsdl_object_of_type('AddressToValidate')
address1.CompanyName = 'International Paper'
address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103']
address1.Address.City = 'Clemson'
address1.Address.StateOrProvinceCode = 'SC'
address1.Address.PostalCode = 29631
address1.Address.CountryCode = 'US'
address1.Address.Residential = False
address.add_address(address1)
address.send_request()
print address.response
| #!/usr/bin/env python
"""
This example shows how to validate addresses. Note that the validation
class can handle up to 100 addresses for validation.
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.address_validation_service import FedexAddressValidationRequest
# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)
# This is the object that will be handling our tracking request.
# We're using the FedexConfig object from example_config.py in this dir.
address = FedexAddressValidationRequest(CONFIG_OBJ)
address1 = address.create_wsdl_object_of_type('AddressToValidate')
address1.CompanyName = 'International Paper'
address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103']
address1.Address.City = 'Clemson'
address1.Address.StateOrProvinceCode = 'SC'
address1.Address.PostalCode = 29631
address1.Address.CountryCode = 'US'
address1.Address.Residential = False
address.add_address(address1)
address.send_request()
print address.response
| Remove un-necessary binascii module import. | Remove un-necessary binascii module import.
| Python | bsd-3-clause | gtaylor/python-fedex,gtaylor/python-fedex,python-fedex-devs/python-fedex,AxiaCore/python-fedex,obr/python-fedex,python-fedex-devs/python-fedex,python-fedex-devs/python-fedex,obr/python-fedex,gtaylor/python-fedex,gtaylor/python-fedex,python-fedex-devs/python-fedex,AxiaCore/python-fedex |
0fe2cf6b03c6eb11a7cabed9302a1aa312a33b31 | django/projects/mysite/run-gevent.py | django/projects/mysite/run-gevent.py | #!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all(httplib=True)
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings
setup_environ(settings)
def runserver():
# Create the server
application = DjangoWSGIApp()
address = "127.0.0.1", 8080
server = WSGIServer( address, application )
# Run the server
try:
server.serve_forever()
except KeyboardInterrupt:
server.stop()
sys.exit(0)
if __name__ == '__main__':
runserver()
| #!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all(httplib=True)
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings
setup_environ(settings)
# Configure host and port for the WSGI server
host = getattr(settings, 'WSGI_HOST', '127.0.0.1')
port = getattr(settings, 'WSGI_PORT', 8080)
def runserver():
# Create the server
application = DjangoWSGIApp()
address = host, port
server = WSGIServer( address, application )
# Run the server
try:
server.serve_forever()
except KeyboardInterrupt:
server.stop()
sys.exit(0)
if __name__ == '__main__':
runserver()
| Allow host/port config in settings file for gevent run script | Allow host/port config in settings file for gevent run script
| Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID |
b1bb08a8ee246774b43e521e8f754cdcc88c418b | gasistafelice/gas/management.py | gasistafelice/gas/management.py | from django.db.models.signals import post_syncdb
from gasistafelice.gas.workflow_data import workflow_dict
def init_workflows(app, created_models, verbosity, **kwargs):
app_label = app.__name__.split('.')[-2]
if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time
# now that all necessary tables are in the DB, we can register our workflows
for name, w in workflow_dict.items():
w.register_workflow()
if verbosity == 2:
# give some feedback to the user
print "Workflow %s was successfully registered." % name
return
post_syncdb.connect(init_workflows)
| from django.db.models.signals import post_syncdb
from gasistafelice.gas.workflow_data import workflow_dict
def init_workflows(app, created_models, verbosity, **kwargs):
app_label = app.__name__.split('.')[-2]
if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for the first time
# now that all necessary tables are in the DB, we can register our workflows
for name, w in workflow_dict.items():
w.register_workflow()
if verbosity == 2:
# give some feedback to the user
print "Workflow %s was successfully registered." % name
return
post_syncdb.connect(init_workflows)
| Fix in post_syncdb workflow registration | Fix in post_syncdb workflow registration
| Python | agpl-3.0 | michelesr/gasistafelice,befair/gasistafelice,matteo88/gasistafelice,matteo88/gasistafelice,OrlyMar/gasistafelice,kobe25/gasistafelice,michelesr/gasistafelice,kobe25/gasistafelice,befair/gasistafelice,michelesr/gasistafelice,matteo88/gasistafelice,kobe25/gasistafelice,feroda/gasistafelice,OrlyMar/gasistafelice,michelesr/gasistafelice,OrlyMar/gasistafelice,feroda/gasistafelice,OrlyMar/gasistafelice,kobe25/gasistafelice,matteo88/gasistafelice,befair/gasistafelice,feroda/gasistafelice,befair/gasistafelice,feroda/gasistafelice |
7080057c9abc6e455222e057315055b3e9965cc9 | runtests.py | runtests.py | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'permissions',
'permissions.tests',
],
MIDDLEWARE_CLASSES=[],
PERMISSIONS={
'allow_staff': False,
},
ROOT_URLCONF='permissions.tests.urls',
TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
}],
TEST_RUNNER='django.test.runner.DiscoverRunner',
)
if django.VERSION[:2] >= (1, 7):
from django import setup
else:
setup = lambda: None
setup()
call_command("test")
| #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
TEST_SETTINGS = {
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
'ALLOWED_HOSTS': [
'testserver',
],
'INSTALLED_APPS': [
'django.contrib.auth',
'django.contrib.contenttypes',
'permissions',
'permissions.tests',
],
'PERMISSIONS': {
'allow_staff': False,
},
'ROOT_URLCONF': 'permissions.tests.urls',
'TEMPLATES': [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
}],
'TEST_RUNNER': 'django.test.runner.DiscoverRunner',
}
if django.VERSION < (1, 10):
TEST_SETTINGS['MIDDLEWARE_CLASSES'] = []
else:
TEST_SETTINGS['MIDDLEWARE'] = []
settings.configure(**TEST_SETTINGS)
if django.VERSION[:2] >= (1, 7):
from django import setup
else:
setup = lambda: None
setup()
call_command("test")
| Set middleware setting according to Django version in test settings | Set middleware setting according to Django version in test settings
Django 1.10 introduced new-style middleware and the corresponding
MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is
ignored on Django 2.
| Python | mit | wylee/django-perms |
4dbc42b0516578d59b315b1ac1fa6ccf3e262f1e | seo/escaped_fragment/app.py | seo/escaped_fragment/app.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
status = "500 Internal Server Error"
else:
url = "http://platformio.org/#!" + unquote(qs[19:])
try:
response = get_webcontent(url)
if "404 Not Found" in response:
status = "404 Not Found"
except Exception:
status = "500 Internal Server Error"
start_response(status, [("Content-Type", "text/html"),
("Content-Length", str(len(response)))])
return response
def get_webcontent(url):
retrynums = 0
while retrynums < 5:
try:
response = check_output([
"phantomjs", "--disk-cache=true", "--load-images=false",
"crawler.js", url
])
if 'class="ng-scope"' not in response:
raise CalledProcessError()
return response
except CalledProcessError:
retrynums += 1
raise Exception("Could not retrieve content from %s" % url)
| # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
status = "500 Internal Server Error"
else:
url = "http://platformio.org/#!" + unquote(qs[19:])
try:
response = get_webcontent(url)
if "404 Not Found" in response:
status = "404 Not Found"
except Exception:
status = "500 Internal Server Error"
start_response(status, [("Content-Type", "text/html"),
("Content-Length", str(len(response)))])
return response
def get_webcontent(url):
retrynums = 0
while retrynums < 5:
try:
response = check_output([
"phantomjs", "--disk-cache=true", "--load-images=false",
"crawler.js", url
])
if 'ng-view=' not in response:
raise CalledProcessError()
return response
except CalledProcessError:
retrynums += 1
raise Exception("Could not retrieve content from %s" % url)
| Fix broken content from PhJS | Fix broken content from PhJS | Python | apache-2.0 | platformio/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,platformio/platformio-web |
fd061738d025b5371c1415a1f5466bcf5f6476b7 | py2deb/config/__init__.py | py2deb/config/__init__.py | import os
config_dir = os.path.dirname(os.path.abspath(__file__))
# Destination of built packages.
PKG_REPO = '/tmp/'
| import os
config_dir = os.path.dirname(os.path.abspath(__file__))
# Destination of built packages.
if os.getuid() == 0:
PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb'
else:
PKG_REPO = '/tmp'
| Make it work out of the box on the build-server and locally | Make it work out of the box on the build-server and locally
| Python | mit | paylogic/py2deb,paylogic/py2deb |
8d9b50b2cd8b0235863c48a84ba5f23af4531765 | ynr/apps/parties/tests/test_models.py | ynr/apps/parties/tests/test_models.py | """
Test some of the basic model use cases
"""
from django.test import TestCase
from .factories import PartyFactory, PartyEmblemFactory
class TestPartyModels(TestCase):
def setUp(self):
PartyFactory.reset_sequence()
def test_party_str(self):
party = PartyFactory()
self.assertEqual(str(party), "Party 0 (PP0)")
def test_party_emblem(self):
party = PartyFactory()
PartyEmblemFactory.create_batch(3, party=party)
self.assertEqual(party.emblems.count(), 3)
self.assertTrue(
party.emblems.first().image.url.startswith(
"/media/emblems/PP0/0_example"
)
)
# Add a default image and assert it's the deafult on the party
PartyEmblemFactory(party=party, __sequence=99, default=True)
self.assertTrue(
party.default_emblem.image.url.startswith(
"/media/emblems/PP0/99_example"
)
)
| """
Test some of the basic model use cases
"""
from django.test import TestCase
from django.core.files.storage import DefaultStorage
from candidates.tests.helpers import TmpMediaRootMixin
from .factories import PartyFactory, PartyEmblemFactory
class TestPartyModels(TmpMediaRootMixin, TestCase):
def setUp(self):
self.storage = DefaultStorage()
PartyFactory.reset_sequence()
def test_party_str(self):
party = PartyFactory()
self.assertEqual(str(party), "Party 0 (PP0)")
def test_party_emblem(self):
party = PartyFactory()
PartyEmblemFactory.create_batch(3, party=party)
self.assertEqual(party.emblems.count(), 3)
self.assertTrue(
party.emblems.first().image.url.startswith(
"/media/emblems/PP0/0_example"
)
)
# Add a default image and assert it's the deafult on the party
PartyEmblemFactory(party=party, __sequence=99, default=True)
self.assertTrue(
party.default_emblem.image.url.startswith(
"/media/emblems/PP0/99_example"
)
)
| Test using tmp media root | Test using tmp media root
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
b6a2ba81c9ddd642cfa271cab809a5c2511f7204 | app/auth/forms.py | app/auth/forms.py | from flask_wtf import Form
from wtforms import (
StringField, PasswordField, BooleanField, SubmitField,
ValidationError,
)
from wtforms.validators import (
InputRequired, Length, Email, Regexp, EqualTo,
)
from app.models import User
class LoginForm(Form):
email = StringField('Email', validators=[
InputRequired(), Length(1, 64), Email()])
password = PasswordField('Senha', validators=[InputRequired()])
remember_me = BooleanField('Lembrar')
submit = SubmitField('Log In')
class RegistrationForm(Form):
email = StringField('Email', validators=[
InputRequired(), Length(1, 64), Email()])
username = StringField('Username', validators=[
InputRequired(), Length(1, 64)])
password = PasswordField('Senha', validators=[
InputRequired(), EqualTo('password2',
message='Senhas devem ser iguais')])
password2 = PasswordField('Confirmar senha', validators=[InputRequired()])
submit = SubmitField('Registrar')
def validate_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('Esse email já está em uso!')
def validate_username(self, field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('Esse usuário já está em uso!')
| from flask_wtf import FlaskForm
from wtforms import (
StringField, PasswordField, BooleanField, SubmitField,
ValidationError,
)
from wtforms.validators import (
InputRequired, Length, Email, Regexp, EqualTo,
)
from app.models import User
class LoginForm(FlaskForm):
email = StringField('Email', validators=[
InputRequired(), Length(1, 64), Email()])
password = PasswordField('Senha', validators=[InputRequired()])
remember_me = BooleanField('Lembrar')
submit = SubmitField('Log In')
class RegistrationForm(FlaskForm):
email = StringField('Email', validators=[
InputRequired(), Length(1, 64), Email()])
username = StringField('Username', validators=[
InputRequired(), Length(1, 64)])
password = PasswordField('Senha', validators=[
InputRequired(), EqualTo('password2',
message='Senhas devem ser iguais')])
password2 = PasswordField('Confirmar senha', validators=[InputRequired()])
submit = SubmitField('Registrar')
def validate_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('Esse email já está em uso!')
def validate_username(self, field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('Esse usuário já está em uso!')
| Change Form to FlaskForm (previous is deprecated) | :art: Change Form to FlaskForm (previous is deprecated)
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys |
58544043b8dee4e55bad0be5d889a40c0ae88960 | tests/__init__.py | tests/__init__.py | import logging
import os
import re
import unittest.mock
# Default to turning off all but critical logging messages
logging.basicConfig(level=logging.CRITICAL)
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None):
"""Open local files instead of URLs.
If it's a local file path, leave it alone; otherwise,
open as a file under ./files/
This is meant as a side effect for unittest.mock.Mock
"""
if re.match(r'https?:', url):
# Looks like a URL
filename = re.sub(r'^.*/([^/]+)$', '\\1', url)
path = resolve_path('files/mock/' + filename)
else:
# Assume it's a file
path = url
return (open(path, 'rb'), None, None, None)
def resolve_path(filename):
"""Resolve a pathname for a test input file."""
return os.path.join(os.path.dirname(__file__), filename)
# Target function to replace for mocking URL access.
URL_MOCK_TARGET = 'hxl.io.open_url_or_file'
# Mock object to replace hxl.io.make_stream
URL_MOCK_OBJECT = unittest.mock.Mock()
URL_MOCK_OBJECT.side_effect = mock_open_url
| import logging
import os
import re
import io
import unittest.mock
# Default to turning off all but critical logging messages
logging.basicConfig(level=logging.CRITICAL)
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None):
"""Open local files instead of URLs.
If it's a local file path, leave it alone; otherwise,
open as a file under ./files/
This is meant as a side effect for unittest.mock.Mock
"""
if re.match(r'https?:', url):
# Looks like a URL
filename = re.sub(r'^.*/([^/]+)$', '\\1', url)
path = resolve_path('files/mock/' + filename)
else:
# Assume it's a file
path = url
with open(path, 'rb') as input:
data = input.read()
return (io.BytesIO(data), None, None, None)
def resolve_path(filename):
"""Resolve a pathname for a test input file."""
return os.path.join(os.path.dirname(__file__), filename)
# Target function to replace for mocking URL access.
URL_MOCK_TARGET = 'hxl.io.open_url_or_file'
# Mock object to replace hxl.io.make_stream
URL_MOCK_OBJECT = unittest.mock.Mock()
URL_MOCK_OBJECT.side_effect = mock_open_url
| Fix intermittent errors during test runs. | Fix intermittent errors during test runs.
| Python | unlicense | HXLStandard/libhxl-python,HXLStandard/libhxl-python |
2f2b64321a54c93a109c0b65866d724227db9399 | tests/conftest.py | tests/conftest.py | from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="email@domain.com"):
user = MagicMock()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
| import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="email@domain.com"):
# create empty object, because Mock not included to python2
user = type('test', (object,), {})()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
| Remove Mock and create "empty" object on the fly | Remove Mock and create "empty" object on the fly
| Python | mit | jadolg/rocketchat_API |
00f1ff26fcd7d0398d057eee2c7c6f6b2002e959 | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture
def event_loop():
print("in event_loop")
try:
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
loop = asyncio.new_event_loop()
yield loop
loop.close()
| import pytest
@pytest.fixture
def event_loop():
try:
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
loop = asyncio.new_event_loop()
yield loop
loop.close()
| Remove accidentally left in print statement | Remove accidentally left in print statement
| Python | mit | kura/blackhole,kura/blackhole |
dcebceec83c31fc9b99cb5e232ae066ee229c3bf | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# type: ignore
"""Shared fixture functions."""
import pathlib
import pytest # pylint: disable=E0401
import spacy # pylint: disable=E0401
from spacy.language import Language # pylint: disable=E0401
from spacy.tokens import Doc # pylint: disable=E0401
@pytest.fixture(scope="session")
def nlp () -> Language:
"""
Language shared fixture.
"""
nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621
return nlp
@pytest.fixture(scope="session")
def doc (nlp: Language) -> Doc: # pylint: disable=W0621
"""
Doc shared fixture.
returns:
spaCy EN doc containing a piece of football news.
"""
text = pathlib.Path("dat/cfc.txt").read_text()
doc = nlp(text) # pylint: disable=W0621
return doc
@pytest.fixture(scope="session")
def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621
"""
Doc shared fixture.
returns:
spaCy EN doc containing a long text.
"""
text = pathlib.Path("dat/lee.txt").read_text()
doc = nlp(text) # pylint: disable=W0621
return doc
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# type: ignore
"""Shared fixture functions."""
import pathlib
import pytest # pylint: disable=E0401
import spacy # pylint: disable=E0401
from spacy.language import Language # pylint: disable=E0401
from spacy.tokens import Doc # pylint: disable=E0401
@pytest.fixture(scope="module")
def nlp () -> Language:
"""
Language shared fixture.
"""
nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621
return nlp
@pytest.fixture(scope="module")
def doc (nlp: Language) -> Doc: # pylint: disable=W0621
"""
Doc shared fixture.
returns:
spaCy EN doc containing a piece of football news.
"""
text = pathlib.Path("dat/cfc.txt").read_text()
doc = nlp(text) # pylint: disable=W0621
return doc
@pytest.fixture(scope="module")
def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621
"""
Doc shared fixture.
returns:
spaCy EN doc containing a long text.
"""
text = pathlib.Path("dat/lee.txt").read_text()
doc = nlp(text) # pylint: disable=W0621
return doc
| Set fixture scope to module, so that pipes from one file dont influence tests from another | Set fixture scope to module, so that pipes from one file dont influence tests from another
| Python | apache-2.0 | ceteri/pytextrank,ceteri/pytextrank |
6b148e4c98628e9ef60cc3ce70c7cdeb8a215c49 | scarplet/datasets/base.py | scarplet/datasets/base.py | """ Convenience functions to load example datasets """
import os
import scarplet as sl
EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'data/')
def load_carrizo():
path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif')
data = sl.load(path)
return data
def load_grandcanyon():
path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif')
data = sl.load(path)
return data
def load_synthetic():
path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif')
data = sl.load(path)
return data
| """ Convenience functions to load example datasets """
import os
import scarplet as sl
EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'data/')
def load_carrizo():
"""
Load sample dataset containing fault scarps along the San Andreas Fault
from the Wallace Creek section on the Carrizo Plain, California, USA
Data downloaded from OpenTopography and collected by the B4 Lidar Project:
https://catalog.data.gov/dataset/b4-project-southern-san-andreas-and-san-jacinto-faults
"""
path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif')
data = sl.load(path)
return data
def load_grandcanyon():
"""
Load sample dataset containing part of channel network in the Grand Canyon
Arizona, USA
Data downloaded from the Terrain Tile dataset, part of Amazon Earth on AWS
https://registry.opendata.aws/terrain-tiles/
"""
path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif')
data = sl.load(path)
return data
def load_synthetic():
"""
Load sample dataset of synthetic fault scarp of morphologic age 10 m2
"""
path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif')
data = sl.load(path)
return data
| Add docstrings for load functions | Add docstrings for load functions
| Python | mit | rmsare/scarplet,stgl/scarplet |
39acab842be6a82d687d4edf6c1d29e7bf293fae | udp_logger.py | udp_logger.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from socket import socket, AF_INET, SOCK_DGRAM
def create_udp_server_socket(endpoint):
skt = socket(AF_INET, SOCK_DGRAM)
skt.bind(endpoint)
return skt
if __name__ == '__main__':
ENDPOINT = ("", 3000) # empty string == INADDR_ANY
skt = create_udp_server_socket(ENDPOINT)
while True:
data, (host, port) = skt.recvfrom(1500)
print "(%s:%i) %s" % (host, port, data)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
from socket import socket, AF_INET, SOCK_DGRAM
from optparse import OptionParser
def create_udp_server_socket(endpoint):
skt = socket(AF_INET, SOCK_DGRAM)
skt.bind(endpoint)
return skt
def MakeOptionParser():
parser = OptionParser()
parser.add_option('-a', '--append', dest='append', metavar="FILE",
help="Append log data to this file")
return parser
if __name__ == '__main__':
parser = MakeOptionParser()
options, args = parser.parse_args()
append_file = None
if options.append:
append_file = open(options.append, 'a', 0)
ENDPOINT = ("", 3000) # empty string == INADDR_ANY
skt = create_udp_server_socket(ENDPOINT)
while True:
data, (host, port) = skt.recvfrom(1500)
log_line = "(%s:%i) %s\n" % (host, port, data)
print log_line,
if append_file:
append_file.write(log_line)
| Support for appending to a file | Support for appending to a file
| Python | mit | tmacam/remote_logging_cpp,tmacam/remote_logging_cpp |
3a74774a42521f4b68e484855d103495438095c3 | examples/schema/targetinfo.py | examples/schema/targetinfo.py | import jsl
class TargetInfo(jsl.Document):
docker = jsl.ArrayField(jsl.StringField(), max_items=2)
rsync = jsl.ArrayField(jsl.StringField(), max_items=2)
containers = jsl.ArrayField([
jsl.StringField(),
jsl.ArrayField(jsl.StringField())
])
| import jsl
class TargetInfo(jsl.Document):
docker = jsl.ArrayField([
jsl.StringField(),
jsl.OneOfField([jsl.StringField(), jsl.NullField()])
])
rsync = jsl.ArrayField([
jsl.StringField(),
jsl.OneOfField([jsl.StringField(), jsl.NullField()])
])
containers = jsl.ArrayField([
jsl.StringField(),
jsl.ArrayField(jsl.StringField())
])
| Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello. | Correct the target info schema: docker and rsync messages are Null in case of
success. Suggested by @vinzenz and corrected by @artmello.
| Python | apache-2.0 | leapp-to/snactor |
74260bc1b401d9ec500fba1eae72b99c2a2db147 | github.py | github.py | import requests
GITHUB_API_URL = "https://api.github.com/graphql"
QUERY = """
query($repository_owner:String!, $repository_name: String!, $count: Int!) {
repository(
owner: $repository_owner,
name: $repository_name) {
refs(last: $count,refPrefix:"refs/tags/") {
edges {
node{
name
}
}
}
releases(last: $count) {
edges {
node {
name
}
}
}
}
}
"""
class Github:
def __authorization_header(self):
return "token " + self.token
def __request_headers(self):
return {
'authorization': self.__authorization_header(),
}
def __init__(self, token):
self.token = token
def getTagsAndReleases(self, repository_owner, repository_name, count):
payload = {"query": QUERY,
"variables": {
"repository_owner": repository_owner,
"repository_name": repository_name,
"count": count
}}
print "Requesting for", repository_name
response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers())
print "Got status code for", repository_name, response.status_code
return response.json() | import requests
GITHUB_API_URL = "https://api.github.com/graphql"
QUERY = """
query($repository_owner:String!,
$repository_name: String!,
$count: Int!) {
repository(owner: $repository_owner,
name: $repository_name) {
refs(last: $count,refPrefix:"refs/tags/") {
nodes {
name
target {
commitUrl
}
}
}
releases(last: $count) {
nodes {
tag {
name
prefix
}
}
}
}
}
"""
class Github:
def __authorization_header(self):
return "token " + self.token
def __request_headers(self):
return {
'authorization': self.__authorization_header(),
}
def __init__(self, token):
self.token = token
def getTagsAndReleases(self, repository_owner, repository_name, count):
payload = {"query": QUERY,
"variables": {
"repository_owner": repository_owner,
"repository_name": repository_name,
"count": count
}}
print "Requesting for", repository_name
response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers())
print "Got status code for", repository_name, response.status_code
return response.json() | Update query to use nodes | Update query to use nodes
| Python | mit | ayushgoel/LongShot |
05e62b96cfa50934d98d78a86307d94239dd7a4b | Orange/__init__.py | Orange/__init__.py | from .misc.lazy_module import LazyModule
from .version import \
short_version as __version__, git_revision as __git_version__
ADDONS_ENTRY_POINT = 'orange.addons'
from Orange import data
for mod_name in ['classification', 'clustering', 'distance', 'evaluation',
'feature', 'misc', 'regression', 'statistics', 'widgets']:
globals()[mod_name] = LazyModule(mod_name)
del mod_name
del LazyModule
| from .misc.lazy_module import LazyModule
from .version import \
short_version as __version__, git_revision as __git_version__
ADDONS_ENTRY_POINT = 'orange.addons'
from Orange import data
for mod_name in ['classification', 'clustering', 'distance', 'evaluation',
'feature', 'misc', 'regression', 'statistics', 'widgets',
'preprocess']:
globals()[mod_name] = LazyModule(mod_name)
del mod_name
del LazyModule
| Add preprocess to the list of modules lazy-imported in Orange | Add preprocess to the list of modules lazy-imported in Orange
| Python | bsd-2-clause | cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,qusp/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,qusp/orange3,kwikadi/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3 |
896a9b3d116a6ac2d313c5ea8dbc16345a097138 | linguine/ops/StanfordCoreNLP.py | linguine/ops/StanfordCoreNLP.py | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
def __init__(self):
# I don't see anywhere to put properties like this path...
# For now it's hardcoded and would need to be changed when deployed...
coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar')
coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar')
self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath])
def run(self, data):
results = []
for corpus in data:
results.append(self.proc.parse_doc(corpus.contents))
return results
| #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
"""
When the JSON segments return from the CoreNLP library, they
separate the data acquired from each word into their own element.
For readability's sake, it would be nice to pair all of the information
for a given word with that word, making a list of words with their
part of speech tags
"""
def jsonCleanup(self, data):
for corpus in data:
res = self.proc.parse_doc(corpus.contents)
for sentence in res["sentences"]:
words = []
for index, token in enumerate(sentence["tokens"]):
word = {}
word["token"] = sentence["tokens"][index]
word["lemma"] = sentence["lemmas"][index]
word["part-of-speech"] = sentence["pos"][index]
words.append(word)
return words
def __init__(self):
coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar')
coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar')
self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath])
def run(self, data):
return self.jsonCleanup(data)
| Format JSON to be collections of tokens | Format JSON to be collections of tokens
When coreNLP returns the JSON payload, it is in an unmanageable format
where multiple arrays are made for all parts of speech, tokens, and
lemmas. It's much easier to manage when the response is formatted as a
list of objects:
{
"token": "Pineapple",
"lemma": "Pineapple",
"part-of-speech": "DT"
}
| Python | mit | rigatoni/linguine-python,Pastafarians/linguine-python |
f473cc24e0f2a41699ed9e684b400cb5cb562ce6 | go_contacts/backends/utils.py | go_contacts/backends/utils.py | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
contact_keys = yield model_proxy.index_keys_page(
'user_account', user_account_key, max_results=max_results,
continuation=cursor)
except VumiRiakError:
raise CollectionUsageError(
"Riak error, possible invalid cursor: %r" % (cursor,))
cursor = contact_keys.continuation
returnValue((cursor, contact_keys))
@inlineCallbacks
def _fill_queue(q, get_page, get_dict):
keys_deferred = get_page(None)
while True:
cursor, keys = yield keys_deferred
if cursor is not None:
# Get the next page of keys while we fetch the contacts
keys_deferred = get_page(cursor)
for key in keys:
contact = yield get_dict(key)
yield q.put(contact)
if cursor is None:
break
q.put(PausingQueueCloseMarker())
| from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
contact_keys = yield model_proxy.index_keys_page(
'user_account', user_account_key, max_results=max_results,
continuation=cursor)
except VumiRiakError:
raise CollectionUsageError(
"Riak error, possible invalid cursor: %r" % (cursor,))
cursor = contact_keys.continuation
returnValue((cursor, contact_keys))
@inlineCallbacks
def _fill_queue(q, get_page, get_dict):
keys_deferred = get_page(None)
while True:
cursor, keys = yield keys_deferred
if cursor is not None:
# Get the next page of keys while we fetch the objects
keys_deferred = get_page(cursor)
for key in keys:
obj = yield get_dict(key)
yield q.put(obj)
if cursor is None:
break
q.put(PausingQueueCloseMarker())
| Change to more generic variable names in _fill_queue | Change to more generic variable names in _fill_queue
| Python | bsd-3-clause | praekelt/go-contacts-api,praekelt/go-contacts-api |
b7b41a160294edd987f73be7817c8b08aa8ed70e | herders/templatetags/utils.py | herders/templatetags/utils.py | from django import template
register = template.Library()
@register.filter
def get_range(value):
return range(value)
@register.filter
def absolute(value):
return abs(value)
@register.filter
def subtract(value, arg):
return value - arg
@register.filter
def multiply(value, arg):
return value * arg
@register.filter
def remove_extension(string):
return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
| from django import template
register = template.Library()
@register.filter
def get_range(value):
if value:
return range(value)
else:
return 0
@register.filter
def absolute(value):
return abs(value)
@register.filter
def subtract(value, arg):
return value - arg
@register.filter
def multiply(value, arg):
return value * arg
@register.filter
def remove_extension(string):
return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
| Return 0 with the get_range filter if value is invalid instead of raise exception | Return 0 with the get_range filter if value is invalid instead of raise exception
| Python | apache-2.0 | porksmash/swarfarm,PeteAndersen/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm |
6d018ef0ac8bc020b38dab1dd29dd6e383be2e8e | src/sentry_heroku/plugin.py | src/sentry_heroku/plugin.py | """
sentry_heroku.plugin
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Sentry Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
"""
import sentry_heroku
from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin
class HerokuReleaseHook(ReleaseHook):
def handle(self, request):
self.finish_release(
version=request.POST['head_long'],
)
class HerokuPlugin(ReleaseTrackingPlugin):
author = 'Sentry Team'
author_url = 'https://github.com/getsentry'
resource_links = (
('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'),
('Source', 'https://github.com/getsentry/sentry-heroku'),
)
title = 'Heroku'
slug = 'heroku'
description = 'Integrate Heroku release tracking.'
version = sentry_heroku.VERSION
def get_release_doc_html(self, hook_url):
return """
<p>Add Sentry as a deploy hook to automatically track new releases.</p>
<pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre>
""".format(hook_url=hook_url)
def get_release_hook(self):
return HerokuReleaseHook
| """
sentry_heroku.plugin
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Sentry Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
"""
import sentry_heroku
from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin
class HerokuReleaseHook(ReleaseHook):
def handle(self, request):
self.finish_release(
version=request.POST['head_long'],
url=request.POST['url'],
environment=request.POST['app'],
)
class HerokuPlugin(ReleaseTrackingPlugin):
author = 'Sentry Team'
author_url = 'https://github.com/getsentry'
resource_links = (
('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'),
('Source', 'https://github.com/getsentry/sentry-heroku'),
)
title = 'Heroku'
slug = 'heroku'
description = 'Integrate Heroku release tracking.'
version = sentry_heroku.VERSION
def get_release_doc_html(self, hook_url):
return """
<p>Add Sentry as a deploy hook to automatically track new releases.</p>
<pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre>
""".format(hook_url=hook_url)
def get_release_hook(self):
return HerokuReleaseHook
| Add url and environment to payload | Add url and environment to payload
| Python | apache-2.0 | getsentry/sentry-heroku |
400289449e164ff168372d9df286acba35926e61 | map_points/oauth2/decorators.py | map_points/oauth2/decorators.py | import httplib2
from decorator import decorator
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from googleapiclient import discovery
from oauth2client.client import OAuth2Credentials
@decorator
def auth_required(f, request, *args, **kwargs):
if 'credentials' not in request.session:
return redirect(reverse('oauth2callback'))
credentials = OAuth2Credentials.from_json(request.session['credentials'])
if credentials.access_token_expired:
return redirect(reverse('oauth2callback'))
http_auth = credentials.authorize(httplib2.Http())
client = discovery.build('fusiontables', 'v1', http=http_auth)
request.gapi_client = client
return f(request, *args, **kwargs)
| import httplib2
from decorator import decorator
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from googleapiclient import discovery
from oauth2client.client import OAuth2Credentials
@decorator
def auth_required(f, request, *args, **kwargs):
"""
Verify if request is authorized to communicate with Google's API. If so
assign authorized Fusion Tables client to it as gapi attribute.
"""
if 'credentials' not in request.session:
return redirect(reverse('oauth2callback'))
credentials = OAuth2Credentials.from_json(request.session['credentials'])
if credentials.access_token_expired:
return redirect(reverse('oauth2callback'))
http_auth = credentials.authorize(httplib2.Http())
client = discovery.build('fusiontables', 'v1', http=http_auth)
request.gapi_client = client
return f(request, *args, **kwargs)
| Add docstr to auth_required decorator. | Add docstr to auth_required decorator.
| Python | mit | nihn/map-points,nihn/map-points,nihn/map-points,nihn/map-points |
2d0b44d65a8167a105cbc63e704735b1c360e0c4 | api/core/urls.py | api/core/urls.py | from django.urls import path, re_path
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [
path('go/<path:path>', views.redirector, name='redirector'),
re_path('^', views.index, name='index'),
]
| from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import logout
from django.urls import path, re_path
from . import views
urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [
path('go/<path:path>', views.redirector, name='redirector'),
path('logout', logout, {'next_page': '/'}),
re_path('^', views.index, name='index'),
]
| Handle logout on the backend | Handle logout on the backend
| Python | mit | citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement |
e6ae7fc2c30aa8af087b803408359189ece58f30 | keystone/common/policies/revoke_event.py | keystone/common/policies/revoke_event.py | # 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 oslo_policy import policy
from keystone.common.policies import base
revoke_event_policies = [
policy.RuleDefault(
name=base.IDENTITY % 'list_revoke_events',
check_str=base.RULE_SERVICE_OR_ADMIN)
]
def list_rules():
return revoke_event_policies
| # 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 oslo_policy import policy
from keystone.common.policies import base
revoke_event_policies = [
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'list_revoke_events',
check_str=base.RULE_SERVICE_OR_ADMIN,
description='List revocation events.',
operations=[{'path': '/v3/OS-REVOKE/events',
'method': 'GET'}])
]
def list_rules():
return revoke_event_policies
| Move revoke events to DocumentedRuleDefault | Move revoke events to DocumentedRuleDefault
The overall goal is to define a richer policy for deployers
and operators[0]. To achieve that goal a new policy
class was introduce that requires additional parameters
when defining policy objects.
This patch switches our revoke events policy object to
the policy.DocumentedRuleDefault and fills the
required policy parameters as needed.
[0] I2b59f92545c5ead2a883d358f72f3ad3b3dfe1a6
Change-Id: Idfa3e5cd373c560035d03dfdef4ea303e28a92fc
Partially-Implements: bp policy-docs
| Python | apache-2.0 | rajalokan/keystone,mahak/keystone,rajalokan/keystone,ilay09/keystone,openstack/keystone,rajalokan/keystone,openstack/keystone,openstack/keystone,mahak/keystone,ilay09/keystone,mahak/keystone,ilay09/keystone |
5cb8d2a4187d867111b32491df6e53983f124d73 | rawkit/raw.py | rawkit/raw.py | from rawkit.libraw import libraw
class Raw(object):
def __init__(self, filename=None):
self.data = libraw.libraw_init(0)
libraw.libraw_open_file(self.data, bytes(filename, 'utf-8'))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
libraw.libraw_close(self.data)
def process(self, options=None):
libraw.libraw_unpack(self.data)
libraw.libraw_dcraw_process(self.data)
def save(self, filename=None):
libraw.libraw_dcraw_ppm_tiff_writer(
self.data, bytes(filename, 'utf-8'))
| from rawkit.libraw import libraw
class Raw(object):
def __init__(self, filename=None):
self.data = libraw.libraw_init(0)
libraw.libraw_open_file(self.data, bytes(filename, 'utf-8'))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Clean up after ourselves when leaving the context manager."""
self.close()
def close(self):
"""Free the underlying raw representation."""
libraw.libraw_close(self.data)
def process(self, options=None):
"""
Unpack and process the raw data into something more usable.
"""
libraw.libraw_unpack(self.data)
libraw.libraw_dcraw_process(self.data)
def save(self, filename=None):
libraw.libraw_dcraw_ppm_tiff_writer(
self.data, bytes(filename, 'utf-8'))
| Add close method to Raw class | Add close method to Raw class
Fixes #10
| Python | mit | nagyistoce/rawkit,SamWhited/rawkit,photoshell/rawkit |
abd5fcac1fa585daa73910273adf429baf671de3 | contrib/runners/windows_runner/windows_runner/__init__.py | contrib/runners/windows_runner/windows_runner/__init__.py | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
# Note: This is here for backward compatibility - in the past, runners were single module
# packages, but now they are full blown Python packages.
# This means you can either do "from runner_name import RunnerClass" (old way, don't do that)
# or "from runner_name.runner_name import RunnerClass"
from __future__ import absolute_import
from .windows_command_runner import * # noqa
from .windows_script_runner import * # noqa
| # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
| Remove code we dont need anymore. | Remove code we dont need anymore.
| Python | apache-2.0 | nzlosh/st2,StackStorm/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2 |
6e874375ee1d371a3e6ecb786ade4e1b16d84da5 | wafer/kv/views.py | wafer/kv/views.py | from rest_framework import viewsets
from wafer.kv.models import KeyValue
from wafer.kv.serializers import KeyValueSerializer
from wafer.kv.permissions import KeyValueGroupPermission
class KeyValueViewSet(viewsets.ModelViewSet):
"""API endpoint that allows key-value pairs to be viewed or edited."""
queryset = KeyValue.objects.none() # Needed for the REST Permissions
serializer_class = KeyValueSerializer
permission_classes = (KeyValueGroupPermission, )
def get_queryset(self):
# Restrict the list to only those that match the user's
# groups
if self.request.user.id is not None:
grp_ids = [x.id for x in self.request.user.groups.all()]
return KeyValue.objects.filter(group_id__in=grp_ids)
return KeyValue.objects.none()
| from rest_framework import viewsets
from wafer.kv.models import KeyValue
from wafer.kv.serializers import KeyValueSerializer
from wafer.kv.permissions import KeyValueGroupPermission
from wafer.utils import order_results_by
class KeyValueViewSet(viewsets.ModelViewSet):
"""API endpoint that allows key-value pairs to be viewed or edited."""
queryset = KeyValue.objects.none() # Needed for the REST Permissions
serializer_class = KeyValueSerializer
permission_classes = (KeyValueGroupPermission, )
@order_results_by('key', 'id')
def get_queryset(self):
# Restrict the list to only those that match the user's
# groups
if self.request.user.id is not None:
grp_ids = [x.id for x in self.request.user.groups.all()]
return KeyValue.objects.filter(group_id__in=grp_ids)
return KeyValue.objects.none()
| Order paginated KV API results. | Order paginated KV API results.
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
d8872865cc7159ffeeae45a860b97cd241f95c6e | vispy/visuals/tests/test_arrows.py | vispy/visuals/tests/test_arrows.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main, raises)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_line_draw():
"""Test drawing arrows without transforms"""
vertices = np.array([
[25, 25],
[25, 75],
[50, 25],
[50, 75],
[75, 25],
[75, 75]
]).astype('f32')
arrows = np.array([
vertices[:2],
vertices[3:1:-1],
vertices[4:],
vertices[-1:-3:-1]
]).reshape((4, 4))
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type,
arrows=arrows, arrow_size=10, color='red',
connect="segments", antialias=True,
parent=c.scene)
assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' %
arrow_type)
arrow.parent = None
run_tests_if_main()
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main, raises)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_line_draw():
"""Test drawing arrows without transforms"""
vertices = np.array([
[25, 25],
[25, 75],
[50, 25],
[50, 75],
[75, 25],
[75, 75]
]).astype('f32')
arrows = np.array([
vertices[:2],
vertices[3:1:-1],
vertices[4:],
vertices[-1:-3:-1]
]).reshape((4, 4))
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type,
arrows=arrows, arrow_size=10, color='red',
connect="segments", parent=c.scene)
assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' %
arrow_type)
arrow.parent = None
run_tests_if_main()
| Disable antialias for GL drawing lines | Disable antialias for GL drawing lines
| Python | bsd-3-clause | inclement/vispy,michaelaye/vispy,srinathv/vispy,jay3sh/vispy,julienr/vispy,QuLogic/vispy,jay3sh/vispy,julienr/vispy,ghisvail/vispy,drufat/vispy,Eric89GXL/vispy,inclement/vispy,RebeccaWPerry/vispy,michaelaye/vispy,kkuunnddaannkk/vispy,Eric89GXL/vispy,jdreaver/vispy,sbtlaarzc/vispy,srinathv/vispy,Eric89GXL/vispy,drufat/vispy,dchilds7/Deysha-Star-Formation,ghisvail/vispy,jay3sh/vispy,jdreaver/vispy,kkuunnddaannkk/vispy,drufat/vispy,inclement/vispy,QuLogic/vispy,ghisvail/vispy,sbtlaarzc/vispy,dchilds7/Deysha-Star-Formation,dchilds7/Deysha-Star-Formation,michaelaye/vispy,sbtlaarzc/vispy,srinathv/vispy,RebeccaWPerry/vispy,julienr/vispy,QuLogic/vispy,bollu/vispy,bollu/vispy,jdreaver/vispy,RebeccaWPerry/vispy,kkuunnddaannkk/vispy,bollu/vispy |
a1be6021c4d13b1212dff74dc981a602951994fb | erpnext/patches/v4_0/customer_discount_to_pricing_rule.py | erpnext/patches/v4_0/customer_discount_to_pricing_rule.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import get_root_of
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.auto_commit_on_many_writes = True
default_item_group = get_root_of("Item Group")
for d in frappe.db.sql("""select * from `tabCustomer Discount`
where ifnull(parent, '') != ''""", as_dict=1):
if not d.discount:
continue
frappe.get_doc({
"doctype": "Pricing Rule",
"apply_on": "Item Group",
"item_group": d.item_group or default_item_group,
"applicable_for": "Customer",
"customer": d.parent,
"price_or_discount": "Discount Percentage",
"discount_percentage": d.discount
}).insert()
frappe.db.auto_commit_on_many_writes = False
frappe.delete_doc("DocType", "Customer Discount")
| # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import get_root_of
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.auto_commit_on_many_writes = True
default_item_group = get_root_of("Item Group")
for d in frappe.db.sql("""select * from `tabCustomer Discount`
where ifnull(parent, '') != ''""", as_dict=1):
if not d.discount:
continue
frappe.get_doc({
"doctype": "Pricing Rule",
"apply_on": "Item Group",
"item_group": d.item_group or default_item_group,
"applicable_for": "Customer",
"customer": d.parent,
"price_or_discount": "Discount Percentage",
"discount_percentage": d.discount,
"selling": 1
}).insert()
frappe.db.auto_commit_on_many_writes = False
frappe.delete_doc("DocType", "Customer Discount")
| Fix in pricing rule patch | Fix in pricing rule patch
| Python | agpl-3.0 | mbauskar/omnitech-erpnext,indictranstech/internal-erpnext,pawaranand/phrerp,SPKian/Testing,indictranstech/reciphergroup-erpnext,Drooids/erpnext,suyashphadtare/gd-erp,shft117/SteckerApp,hernad/erpnext,pawaranand/phrerp,pombredanne/erpnext,rohitwaghchaure/digitales_erpnext,Tejal011089/trufil-erpnext,suyashphadtare/sajil-final-erp,gangadhar-kadam/latestchurcherp,netfirms/erpnext,gangadharkadam/saloon_erp_install,treejames/erpnext,indictranstech/trufil-erpnext,indictranstech/phrerp,geekroot/erpnext,sagar30051991/ozsmart-erp,Drooids/erpnext,indictranstech/focal-erpnext,gangadhar-kadam/laganerp,gangadharkadam/v4_erp,sheafferusa/erpnext,indictranstech/focal-erpnext,tmimori/erpnext,gangadharkadam/contributionerp,rohitwaghchaure/New_Theme_Erp,Tejal011089/digitales_erpnext,Suninus/erpnext,mbauskar/helpdesk-erpnext,mbauskar/helpdesk-erpnext,indictranstech/phrerp,gangadhar-kadam/helpdesk-erpnext,gangadharkadam/saloon_erp_install,Tejal011089/huntercamp_erpnext,hatwar/Das_erpnext,pombredanne/erpnext,ShashaQin/erpnext,indictranstech/internal-erpnext,aruizramon/alec_erpnext,Tejal011089/fbd_erpnext,indictranstech/fbd_erpnext,indictranstech/phrerp,mahabuber/erpnext,rohitwaghchaure/GenieManager-erpnext,SPKian/Testing,Tejal011089/huntercamp_erpnext,meisterkleister/erpnext,BhupeshGupta/erpnext,Tejal011089/digitales_erpnext,sheafferusa/erpnext,Tejal011089/digitales_erpnext,gangadhar-kadam/verve-erp,mbauskar/sapphire-erpnext,pawaranand/phrerp,hatwar/focal-erpnext,shitolepriya/test-erp,ThiagoGarciaAlves/erpnext,gangadharkadam/saloon_erp_install,gangadharkadam/sher,suyashphadtare/test,gangadhar-kadam/verve_live_erp,gangadharkadam/verveerp,gangadharkadam/saloon_erp,rohitwaghchaure/erpnext-receipher,ShashaQin/erpnext,suyashphadtare/test,gangadharkadam/v5_erp,indictranstech/phrerp,rohitwaghchaure/digitales_erpnext,mbauskar/Das_Erpnext,gangadharkadam/smrterp,rohitwaghchaure/New_Theme_Erp,MartinEnder/erpnext-de,Tejal011089/paypal_erpnext,gangadharkadam/saloon_erp,gsnbng/erpnext,hatwar/buyback-erpnext,gangadharkadam/contributionerp,gsnbng/erpnext,anandpdoshi/erpnext,indictranstech/Das_Erpnext,indictranstech/trufil-erpnext,indictranstech/osmosis-erpnext,suyashphadtare/gd-erp,mahabuber/erpnext,rohitwaghchaure/erpnext_smart,shft117/SteckerApp,Tejal011089/paypal_erpnext,rohitwaghchaure/erpnext_smart,gangadhar-kadam/verve_test_erp,mbauskar/alec_frappe5_erpnext,MartinEnder/erpnext-de,ShashaQin/erpnext,suyashphadtare/vestasi-erp-1,hatwar/Das_erpnext,indictranstech/erpnext,Tejal011089/digitales_erpnext,njmube/erpnext,gangadharkadam/saloon_erp,susuchina/ERPNEXT,gangadhar-kadam/helpdesk-erpnext,fuhongliang/erpnext,gangadharkadam/vlinkerp,gangadharkadam/saloon_erp,indictranstech/erpnext,hatwar/focal-erpnext,suyashphadtare/vestasi-erp-jan-end,Suninus/erpnext,SPKian/Testing2,gmarke/erpnext,gangadharkadam/letzerp,fuhongliang/erpnext,njmube/erpnext,mahabuber/erpnext,pombredanne/erpnext,indictranstech/osmosis-erpnext,shitolepriya/test-erp,gangadhar-kadam/helpdesk-erpnext,tmimori/erpnext,gangadharkadam/office_erp,gangadhar-kadam/verve_erp,hanselke/erpnext-1,gangadharkadam/letzerp,susuchina/ERPNEXT,indictranstech/Das_Erpnext,hatwar/buyback-erpnext,indictranstech/buyback-erp,gangadharkadam/johnerp,indictranstech/focal-erpnext,gangadharkadam/verveerp,BhupeshGupta/erpnext,hatwar/focal-erpnext,netfirms/erpnext,gangadharkadam/sterp,netfirms/erpnext,indictranstech/focal-erpnext,suyashphadtare/sajil-erp,suyashphadtare/vestasi-erp-final,Tejal011089/osmosis_erpnext,Tejal011089/trufil-erpnext,suyashphadtare/test,sagar30051991/ozsmart-erp,indictranstech/osmosis-erpnext,gangadharkadam/tailorerp,suyashphadtare/gd-erp,mbauskar/sapphire-erpnext,gangadharkadam/sher,gangadhar-kadam/laganerp,indictranstech/fbd_erpnext,Tejal011089/huntercamp_erpnext,Aptitudetech/ERPNext,tmimori/erpnext,Drooids/erpnext,sagar30051991/ozsmart-erp,gmarke/erpnext,indictranstech/internal-erpnext,shft117/SteckerApp,ShashaQin/erpnext,susuchina/ERPNEXT,mbauskar/phrerp,mbauskar/alec_frappe5_erpnext,mbauskar/helpdesk-erpnext,suyashphadtare/sajil-final-erp,indictranstech/internal-erpnext,MartinEnder/erpnext-de,Tejal011089/fbd_erpnext,gangadharkadam/sterp,fuhongliang/erpnext,suyashphadtare/sajil-erp,mbauskar/Das_Erpnext,BhupeshGupta/erpnext,dieface/erpnext,rohitwaghchaure/GenieManager-erpnext,saurabh6790/test-erp,gangadhar-kadam/verve_test_erp,mbauskar/omnitech-demo-erpnext,gangadharkadam/v5_erp,gangadhar-kadam/smrterp,suyashphadtare/sajil-final-erp,suyashphadtare/vestasi-erp-1,gsnbng/erpnext,4commerce-technologies-AG/erpnext,mbauskar/omnitech-demo-erpnext,meisterkleister/erpnext,aruizramon/alec_erpnext,hatwar/Das_erpnext,ThiagoGarciaAlves/erpnext,mbauskar/omnitech-erpnext,indictranstech/reciphergroup-erpnext,gangadhar-kadam/latestchurcherp,gangadhar-kadam/verve_erp,SPKian/Testing2,indictranstech/Das_Erpnext,shft117/SteckerApp,indictranstech/osmosis-erpnext,rohitwaghchaure/erpnext-receipher,indictranstech/erpnext,gangadharkadam/letzerp,rohitwaghchaure/erpnext_smart,tmimori/erpnext,sagar30051991/ozsmart-erp,gangadharkadam/contributionerp,suyashphadtare/vestasi-erp-final,mbauskar/sapphire-erpnext,indictranstech/vestasi-erpnext,mbauskar/Das_Erpnext,gangadharkadam/vlinkerp,gangadhar-kadam/verve_erp,saurabh6790/test-erp,njmube/erpnext,Suninus/erpnext,suyashphadtare/vestasi-erp-1,Tejal011089/fbd_erpnext,mbauskar/sapphire-erpnext,mbauskar/phrerp,dieface/erpnext,mbauskar/omnitech-demo-erpnext,indictranstech/buyback-erp,suyashphadtare/vestasi-erp-jan-end,pawaranand/phrerp,pombredanne/erpnext,hatwar/buyback-erpnext,rohitwaghchaure/New_Theme_Erp,4commerce-technologies-AG/erpnext,gangadharkadam/saloon_erp_install,suyashphadtare/vestasi-update-erp,SPKian/Testing,gangadharkadam/v4_erp,indictranstech/biggift-erpnext,indictranstech/trufil-erpnext,saurabh6790/test-erp,suyashphadtare/vestasi-erp-jan-end,anandpdoshi/erpnext,rohitwaghchaure/erpnext-receipher,mbauskar/alec_frappe5_erpnext,rohitwaghchaure/New_Theme_Erp,mbauskar/omnitech-erpnext,gangadhar-kadam/verve_live_erp,geekroot/erpnext,gangadharkadam/v4_erp,gangadharkadam/letzerp,dieface/erpnext,netfirms/erpnext,gangadharkadam/verveerp,anandpdoshi/erpnext,SPKian/Testing2,suyashphadtare/vestasi-update-erp,Tejal011089/osmosis_erpnext,gangadharkadam/verveerp,meisterkleister/erpnext,mbauskar/alec_frappe5_erpnext,Tejal011089/paypal_erpnext,suyashphadtare/gd-erp,indictranstech/tele-erpnext,gangadhar-kadam/verve_erp,susuchina/ERPNEXT,BhupeshGupta/erpnext,saurabh6790/test-erp,hernad/erpnext,indictranstech/biggift-erpnext,gmarke/erpnext,indictranstech/biggift-erpnext,hatwar/focal-erpnext,suyashphadtare/vestasi-erp-jan-end,rohitwaghchaure/erpnext-receipher,gangadhar-kadam/verve-erp,indictranstech/vestasi-erpnext,SPKian/Testing2,dieface/erpnext,indictranstech/trufil-erpnext,indictranstech/tele-erpnext,gangadharkadam/office_erp,mbauskar/phrerp,Drooids/erpnext,Tejal011089/huntercamp_erpnext,hanselke/erpnext-1,treejames/erpnext,indictranstech/vestasi-erpnext,indictranstech/erpnext,treejames/erpnext,gmarke/erpnext,aruizramon/alec_erpnext,sheafferusa/erpnext,gsnbng/erpnext,aruizramon/alec_erpnext,mahabuber/erpnext,mbauskar/helpdesk-erpnext,gangadharkadam/v5_erp,indictranstech/biggift-erpnext,hatwar/Das_erpnext,gangadharkadam/v6_erp,gangadharkadam/v6_erp,mbauskar/omnitech-erpnext,Tejal011089/paypal_erpnext,gangadhar-kadam/verve_test_erp,indictranstech/Das_Erpnext,njmube/erpnext,treejames/erpnext,ThiagoGarciaAlves/erpnext,indictranstech/fbd_erpnext,indictranstech/reciphergroup-erpnext,rohitwaghchaure/GenieManager-erpnext,gangadharkadam/v6_erp,gangadhar-kadam/helpdesk-erpnext,gangadhar-kadam/verve-erp,Suninus/erpnext,Tejal011089/trufil-erpnext,gangadhar-kadam/verve_live_erp,mbauskar/phrerp,gangadhar-kadam/laganerp,gangadharkadam/smrterp,gangadhar-kadam/latestchurcherp,gangadhar-kadam/smrterp,hernad/erpnext,Tejal011089/osmosis_erpnext,rohitwaghchaure/digitales_erpnext,ThiagoGarciaAlves/erpnext,Tejal011089/trufil-erpnext,gangadharkadam/vlinkerp,gangadhar-kadam/verve_test_erp,suyashphadtare/vestasi-erp-final,indictranstech/vestasi-erpnext,fuhongliang/erpnext,mbauskar/omnitech-demo-erpnext,sheafferusa/erpnext,gangadharkadam/office_erp,meisterkleister/erpnext,gangadhar-kadam/verve_live_erp,rohitwaghchaure/digitales_erpnext,shitolepriya/test-erp,gangadharkadam/tailorerp,indictranstech/buyback-erp,gangadharkadam/v4_erp,Tejal011089/osmosis_erpnext,indictranstech/tele-erpnext,4commerce-technologies-AG/erpnext,gangadharkadam/contributionerp,hanselke/erpnext-1,SPKian/Testing,rohitwaghchaure/GenieManager-erpnext,Tejal011089/fbd_erpnext,hernad/erpnext,gangadharkadam/johnerp,geekroot/erpnext,shitolepriya/test-erp,indictranstech/fbd_erpnext,hatwar/buyback-erpnext,suyashphadtare/sajil-erp,geekroot/erpnext,mbauskar/Das_Erpnext,indictranstech/tele-erpnext,hanselke/erpnext-1,anandpdoshi/erpnext,MartinEnder/erpnext-de,gangadharkadam/vlinkerp,suyashphadtare/vestasi-update-erp,gangadhar-kadam/latestchurcherp,indictranstech/reciphergroup-erpnext,gangadharkadam/v6_erp,gangadharkadam/v5_erp,indictranstech/buyback-erp |
701d312815fe6f193e1e555abe9fc65f9cee0567 | core/management/commands/send_tweets.py | core/management/commands/send_tweets.py | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
if tweet.user:
user_tokens = tweet.user.social_auth.all()[0].tokens
access_token = user_tokens['oauth_token']
access_token_secret = user_tokens['oauth_token_secret']
elif tweet.access:
access_token = tweet.access.access_token
access_token_secret = tweet.access.access_token_secret
api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY,
consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
access_token_key=access_token,
access_token_secret=access_token_secret,)
try:
if tweet.media_path:
status = api.PostUpdate(tweet.text, media=tweet.media_path)
else:
status = api.PostUpdate(tweet.text)
except twitter.TwitterError, e:
print "Something went wrong with #{}: ".format(tweet.pk), e
tweet.failed_trials += 1
tweet.save()
continue
tweet.tweet_id = status.id
tweet.was_sent = True
tweet.save()
| import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
if tweet.user:
user_tokens = tweet.user.social_auth.all()[0].tokens
consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY
consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET
access_token = user_tokens['oauth_token']
access_token_secret = user_tokens['oauth_token_secret']
elif tweet.access:
consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY
consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET
access_token = tweet.access.access_token
access_token_secret = tweet.access.access_token_secret
api = twitter.Api(consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token_key=access_token,
access_token_secret=access_token_secret,)
try:
if tweet.media_path:
status = api.PostUpdate(tweet.text, media=tweet.media_path)
else:
status = api.PostUpdate(tweet.text)
except twitter.TwitterError, e:
print "Something went wrong with #{}: ".format(tweet.pk), e
tweet.failed_trials += 1
tweet.save()
continue
tweet.tweet_id = status.id
tweet.was_sent = True
tweet.save()
| Use ENJAZACESSS when is access is provided | Use ENJAZACESSS when is access is provided
| Python | agpl-3.0 | enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,osamak/student-portal |
d324b27e41aee52b044e5647a4a13aecc9130c3e | tests/conftest.py | tests/conftest.py | import pytest
from utils import *
from pgcli.pgexecute import PGExecute
@pytest.yield_fixture(scope="function")
def connection():
create_db('_test_db')
connection = db_connection('_test_db')
yield connection
drop_tables(connection)
connection.close()
@pytest.fixture
def cursor(connection):
with connection.cursor() as cur:
return cur
@pytest.fixture
def executor(connection):
return PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST,
password=None, port=None)
| import pytest
from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection,
drop_tables)
import pgcli.pgexecute
@pytest.yield_fixture(scope="function")
def connection():
create_db('_test_db')
connection = db_connection('_test_db')
yield connection
drop_tables(connection)
connection.close()
@pytest.fixture
def cursor(connection):
with connection.cursor() as cur:
return cur
@pytest.fixture
def executor(connection):
return pgcli.pgexecute.PGExecute(database='_test_db', user=POSTGRES_USER,
host=POSTGRES_HOST, password=None, port=None)
| Replace splat import in tests. | Replace splat import in tests.
| Python | bsd-3-clause | koljonen/pgcli,darikg/pgcli,n-someya/pgcli,thedrow/pgcli,dbcli/vcli,joewalnes/pgcli,zhiyuanshi/pgcli,thedrow/pgcli,darikg/pgcli,janusnic/pgcli,bitemyapp/pgcli,dbcli/pgcli,MattOates/pgcli,suzukaze/pgcli,bitmonk/pgcli,bitmonk/pgcli,johshoff/pgcli,nosun/pgcli,d33tah/pgcli,johshoff/pgcli,koljonen/pgcli,lk1ngaa7/pgcli,zhiyuanshi/pgcli,w4ngyi/pgcli,TamasNo1/pgcli,suzukaze/pgcli,lk1ngaa7/pgcli,j-bennet/pgcli,TamasNo1/pgcli,yx91490/pgcli,nosun/pgcli,MattOates/pgcli,yx91490/pgcli,joewalnes/pgcli,dbcli/vcli,janusnic/pgcli,w4ngyi/pgcli,j-bennet/pgcli,dbcli/pgcli,n-someya/pgcli,d33tah/pgcli,bitemyapp/pgcli |
e5beaabc66cbb87f63e2648b277bada72ddec7dc | tests/conftest.py | tests/conftest.py | import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param)
| import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param, unsafe=True)
| Allow unsafe change of backend for testing | Allow unsafe change of backend for testing
| Python | bsd-2-clause | FilipeMaia/afnumpy,daurer/afnumpy |
c5a617db987fda0302cf5963bbc41e8d0887347d | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture
def observe(monkeypatch):
def patch(module, func):
original_func = getattr(module, func)
def wrapper(*args, **kwargs):
result = original_func(*args, **kwargs)
self.calls[self.last_call] = (args, kwargs, result)
self.last_call += 1
return result
self = wrapper
self.calls = {}
self.last_call = 0
monkeypatch.setattr(module, func, wrapper)
return wrapper
return patch
| import pytest
@pytest.fixture
def observe(monkeypatch):
"""
Wrap a function so its call history can be inspected.
Example:
# foo.py
def func(bar):
return 2 * bar
# test.py
import pytest
import foo
def test_func(observe):
observer = observe(foo, "func")
assert foo.func(3) == 6
assert foo.func(-5) == -10
assert len(observer.calls) == 2
"""
class ObserverFactory:
def __init__(self, module, func):
self.original_func = getattr(module, func)
self.calls = []
monkeypatch.setattr(module, func, self)
def __call__(self, *args, **kwargs):
result = self.original_func(*args, **kwargs)
self.calls.append((args, kwargs, result))
return result
return ObserverFactory
| Clean up test helper, add example | Clean up test helper, add example
| Python | mit | numberoverzero/pyservice |
dec3ec25739e78c465fd5e31a161a674331edbed | serpent/cv.py | serpent/cv.py | import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = None
for root, directories, files in os.walk(image_region_path):
for file in files:
if not file.endswith(".png"):
continue
image = skimage.io.imread(f"{root}/{file}")
image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2)
if result_image is None:
result_image = image
else:
height, width, rgba = image.shape
for i in range(height):
for ii in range(width):
if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]):
result_image[i, ii, 3] = 0
skimage.io.imsave(output_file_path, result_image)
def scale_range(n, minimum, maximum):
n += -(np.min(n))
n /= np.max(n) / (maximum - minimum)
n += minimum
return n
| import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = None
for root, directories, files in os.walk(image_region_path):
for file in files:
if not file.endswith(".png"):
continue
image = skimage.io.imread(f"{root}/{file}")
image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2)
if result_image is None:
result_image = image
else:
height, width, rgba = image.shape
for i in range(height):
for ii in range(width):
if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]):
result_image[i, ii, 3] = 0
skimage.io.imsave(output_file_path, result_image)
def normalize(n, source_min, source_max, target_min=0, target_max=1):
return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
| Change scale range to normalization with source and target min max | Change scale range to normalization with source and target min max
| Python | mit | SerpentAI/SerpentAI |
7157843c2469fd837cb30df182ad69583790b9eb | makeaface/makeaface/urls.py | makeaface/makeaface/urls.py | from django.conf.urls.defaults import *
from motion.feeds import PublicEventsFeed
urlpatterns = patterns('',
url(r'^$', 'makeaface.views.home', name='home'),
url(r'^$', 'makeaface.views.home', name='group_events'),
url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'),
url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to',
{'url': r'/photo/%(id)s'}),
url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'),
url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'),
url(r'^favorite$', 'makeaface.views.favorite', name='favorite'),
url(r'^flag$', 'makeaface.views.flag', name='flag'),
url(r'^delete$', 'makeaface.views.delete', name='delete'),
url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'),
url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'),
)
urlpatterns += patterns('',
url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed',
{'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'),
)
| from django.conf.urls.defaults import *
from motion.feeds import PublicEventsFeed
urlpatterns = patterns('',
url(r'^$', 'makeaface.views.home', name='home'),
url(r'^$', 'makeaface.views.home', name='group_events'),
url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'),
url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to',
{'url': r'/photo/%(id)s'}),
url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'),
url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'),
url(r'^favorite$', 'makeaface.views.favorite', name='favorite'),
url(r'^flag$', 'makeaface.views.flag', name='flag'),
url(r'^delete$', 'makeaface.views.delete', name='delete'),
url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'),
url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'),
url(r'^grid\.$', 'django.views.generic.simple.redirect_to',
{'url': r'/grid'}),
)
urlpatterns += patterns('',
url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed',
{'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'),
)
| Handle when /grid ends with a period, since Twitter let apgwoz link to it that way | Handle when /grid ends with a period, since Twitter let apgwoz link to it that way
| Python | mit | markpasc/make-a-face,markpasc/make-a-face |
fedf1df20418169a377012c22bf81f758e2978e8 | tests/test_dbg.py | tests/test_dbg.py | import pytest
from boink.dbg_tests import (_test_add_single_kmer,
_test_add_two_kmers,
_test_kmer_degree,
_test_kmer_in_degree,
_test_kmer_out_degree)
def test_add_single_kmer():
_test_add_single_kmer()
def test_add_two_kmers():
_test_add_two_kmers()
def test_kmer_degree():
_test_kmer_degree()
def test_kmer_in_degree():
_test_kmer_in_degree()
def test_kmer_out_degree():
_test_kmer_out_degree()
| import pytest
from utils import *
from boink.dbg_tests import (_test_add_single_kmer,
_test_add_two_kmers,
_test_kmer_degree,
_test_kmer_in_degree,
_test_kmer_out_degree,
_test_kmer_count,
_test_add_loop)
from boink.dbg import ExactDBG, kmers
@pytest.fixture
def G(K):
return ExactDBG(K)
def test_add_single_kmer():
_test_add_single_kmer()
def test_add_two_kmers():
_test_add_two_kmers()
def test_kmer_degree():
_test_kmer_degree()
def test_kmer_in_degree():
_test_kmer_in_degree()
def test_kmer_out_degree():
_test_kmer_out_degree()
def test_kmer_count():
_test_kmer_count()
def test_add_loop(random_sequence, K):
seq = random_sequence()
seq += seq[:K]
_test_add_loop(seq, K)
def test_right_tip(right_tip_structure, G, K):
(sequence, tip), S = right_tip_structure
G.add_sequence(sequence)
for kmer in kmers(sequence[1:-1], K):
assert G.kmer_count(kmer) == 1
assert G.kmer_degree(kmer) == 2
assert G.kmer_degree(sequence[:K]) == 1
assert G.kmer_degree(sequence[-K:]) == 1
G.add_sequence(tip)
assert G.kmer_out_degree(sequence[S-K:S]) == 2
assert G.kmer_in_degree(sequence[S-K:S]) == 1
assert G.kmer_in_degree(tip[-K:]) == 1
assert G.kmer_out_degree(tip[S-K:S]) == 2
for kmer in kmers(tip[1:-2], K):
assert G.kmer_count(kmer) == 2
assert G.kmer_degree(kmer) == 2
| Add right tip structure tests | Add right tip structure tests
| Python | mit | camillescott/boink,camillescott/boink,camillescott/boink,camillescott/boink |
568c3466844ec9b27fbe7e3a4e1bae772203923d | touch/__init__.py | touch/__init__.py | from pelican import signals
import logging
import os
import time
logger = logging.getLogger(__name__)
def set_file_utime(path, datetime):
mtime = time.mktime(datetime.timetuple())
logger.info('touching %s', path)
os.utime(path, (mtime, mtime))
def touch_file(path, context):
content = context.get('article', context.get('page'))
page = context.get('articles_page')
dates = context.get('dates')
if content and hasattr(content, 'date'):
set_file_utime(path, content.date)
elif page:
set_file_utime(path, max(x.date for x in page.object_list))
elif dates:
set_file_utime(path, max(x.date for x in dates))
def register():
signals.content_written.connect(touch_file)
| from pelican import signals
import logging
import os
import time
logger = logging.getLogger(__name__)
def set_file_utime(path, datetime):
mtime = time.mktime(datetime.timetuple())
logger.info('touching %s', path)
os.utime(path, (mtime, mtime))
def touch_file(path, context):
content = context.get('article', context.get('page'))
page = context.get('articles_page')
dates = context.get('dates')
if content and hasattr(content, 'date'):
set_file_utime(path, content.date)
elif page:
set_file_utime(path, max(x.date for x in page.object_list))
elif dates:
set_file_utime(path, max(x.date for x in dates))
def touch_feed(path, context, feed):
set_file_utime(path, max(x['pubdate'] for x in feed.items))
def register():
signals.content_written.connect(touch_file)
signals.feed_written.connect(touch_feed)
| Update timestamps of generated feeds as well | Update timestamps of generated feeds as well
| Python | agpl-3.0 | frickp/pelican-plugins,UHBiocomputation/pelican-plugins,xsteadfastx/pelican-plugins,mikitex70/pelican-plugins,jantman/pelican-plugins,proteansec/pelican-plugins,lindzey/pelican-plugins,farseerfc/pelican-plugins,davidmarquis/pelican-plugins,UHBiocomputation/pelican-plugins,makefu/pelican-plugins,mwcz/pelican-plugins,goerz/pelican-plugins,ingwinlu/pelican-plugins,xsteadfastx/pelican-plugins,gw0/pelican-plugins,ingwinlu/pelican-plugins,joachimneu/pelican-plugins,ziaa/pelican-plugins,phrawzty/pelican-plugins,davidmarquis/pelican-plugins,mortada/pelican-plugins,MarkusH/pelican-plugins,olgabot/pelican-plugins,doctorwidget/pelican-plugins,karya0/pelican-plugins,wilsonfreitas/pelican-plugins,jprine/pelican-plugins,makefu/pelican-plugins,jfosorio/pelican-plugins,jakevdp/pelican-plugins,gw0/pelican-plugins,pestrickland/pelican-plugins,M157q/pelican-plugins,andreas-h/pelican-plugins,joachimneu/pelican-plugins,proteansec/pelican-plugins,samueljohn/pelican-plugins,clokep/pelican-plugins,florianjacob/pelican-plugins,shireenrao/pelican-plugins,benjaminabel/pelican-plugins,xsteadfastx/pelican-plugins,wilsonfreitas/pelican-plugins,davidmarquis/pelican-plugins,cmacmackin/pelican-plugins,Neurita/pelican-plugins,amitsaha/pelican-plugins,doctorwidget/pelican-plugins,M157q/pelican-plugins,rlaboiss/pelican-plugins,jcdubacq/pelican-plugins,lindzey/pelican-plugins,joachimneu/pelican-plugins,pxquim/pelican-plugins,makefu/pelican-plugins,jcdubacq/pelican-plugins,gjreda/pelican-plugins,lindzey/pelican-plugins,M157q/pelican-plugins,phrawzty/pelican-plugins,jantman/pelican-plugins,mwcz/pelican-plugins,Neurita/pelican-plugins,cctags/pelican-plugins,frickp/pelican-plugins,andreas-h/pelican-plugins,frickp/pelican-plugins,pelson/pelican-plugins,Xion/pelican-plugins,barrysteyn/pelican-plugins,samueljohn/pelican-plugins,mortada/pelican-plugins,benjaminabel/pelican-plugins,lele1122/pelican-plugins,ziaa/pelican-plugins,kdheepak89/pelican-plugins,kdheepak89/pelican-plugins,florianjacob/pelican-plugins,pxquim/pelican-plugins,wilsonfreitas/pelican-plugins,talha131/pelican-plugins,howthebodyworks/pelican-plugins,pestrickland/pelican-plugins,pestrickland/pelican-plugins,prisae/pelican-plugins,lazycoder-ru/pelican-plugins,goerz/pelican-plugins,barrysteyn/pelican-plugins,publicus/pelican-plugins,FuzzJunket/pelican-plugins,talha131/pelican-plugins,Samael500/pelican-plugins,cmacmackin/pelican-plugins,cctags/pelican-plugins,Xion/pelican-plugins,FuzzJunket/pelican-plugins,olgabot/pelican-plugins,clokep/pelican-plugins,talha131/pelican-plugins,lazycoder-ru/pelican-plugins,jfosorio/pelican-plugins,jfosorio/pelican-plugins,seandavi/pelican-plugins,karya0/pelican-plugins,lele1122/pelican-plugins,mikitex70/pelican-plugins,yuanboshe/pelican-plugins,pelson/pelican-plugins,jakevdp/pelican-plugins,FuzzJunket/pelican-plugins,prisae/pelican-plugins,shireenrao/pelican-plugins,talha131/pelican-plugins,olgabot/pelican-plugins,mwcz/pelican-plugins,samueljohn/pelican-plugins,mwcz/pelican-plugins,howthebodyworks/pelican-plugins,andreas-h/pelican-plugins,goerz/pelican-plugins,davidmarquis/pelican-plugins,Samael500/pelican-plugins,pxquim/pelican-plugins,benjaminabel/pelican-plugins,mortada/pelican-plugins,seandavi/pelican-plugins,phrawzty/pelican-plugins,pxquim/pelican-plugins,prisae/pelican-plugins,publicus/pelican-plugins,talha131/pelican-plugins,Xion/pelican-plugins,barrysteyn/pelican-plugins,gjreda/pelican-plugins,FuzzJunket/pelican-plugins,karya0/pelican-plugins,howthebodyworks/pelican-plugins,danmackinlay/pelican-plugins,joachimneu/pelican-plugins,proteansec/pelican-plugins,cmacmackin/pelican-plugins,MarkusH/pelican-plugins,mitchins/pelican-plugins,doctorwidget/pelican-plugins,farseerfc/pelican-plugins,jantman/pelican-plugins,ziaa/pelican-plugins,cctags/pelican-plugins,olgabot/pelican-plugins,phrawzty/pelican-plugins,cctags/pelican-plugins,florianjacob/pelican-plugins,lele1122/pelican-plugins,goerz/pelican-plugins,yuanboshe/pelican-plugins,mikitex70/pelican-plugins,amitsaha/pelican-plugins,shireenrao/pelican-plugins,mitchins/pelican-plugins,frickp/pelican-plugins,ziaa/pelican-plugins,danmackinlay/pelican-plugins,yuanboshe/pelican-plugins,if1live/pelican-plugins,doctorwidget/pelican-plugins,mortada/pelican-plugins,wilsonfreitas/pelican-plugins,MarkusH/pelican-plugins,Samael500/pelican-plugins,publicus/pelican-plugins,benjaminabel/pelican-plugins,prisae/pelican-plugins,makefu/pelican-plugins,howthebodyworks/pelican-plugins,if1live/pelican-plugins,shireenrao/pelican-plugins,M157q/pelican-plugins,proteansec/pelican-plugins,farseerfc/pelican-plugins,xsteadfastx/pelican-plugins,Samael500/pelican-plugins,cmacmackin/pelican-plugins,samueljohn/pelican-plugins,farseerfc/pelican-plugins,clokep/pelican-plugins,Neurita/pelican-plugins,farseerfc/pelican-plugins,publicus/pelican-plugins,ingwinlu/pelican-plugins,danmackinlay/pelican-plugins,mikitex70/pelican-plugins,amitsaha/pelican-plugins,rlaboiss/pelican-plugins,jprine/pelican-plugins,lele1122/pelican-plugins,MarkusH/pelican-plugins,lazycoder-ru/pelican-plugins,mitchins/pelican-plugins,lindzey/pelican-plugins,yuanboshe/pelican-plugins,amitsaha/pelican-plugins,clokep/pelican-plugins,mortada/pelican-plugins,rlaboiss/pelican-plugins,seandavi/pelican-plugins,pelson/pelican-plugins,UHBiocomputation/pelican-plugins,gjreda/pelican-plugins,andreas-h/pelican-plugins,MarkusH/pelican-plugins,if1live/pelican-plugins,jantman/pelican-plugins,gjreda/pelican-plugins,lazycoder-ru/pelican-plugins,mitchins/pelican-plugins,barrysteyn/pelican-plugins,karya0/pelican-plugins,kdheepak89/pelican-plugins,if1live/pelican-plugins,seandavi/pelican-plugins,kdheepak89/pelican-plugins,pelson/pelican-plugins,jfosorio/pelican-plugins,florianjacob/pelican-plugins,jakevdp/pelican-plugins,danmackinlay/pelican-plugins,rlaboiss/pelican-plugins,jakevdp/pelican-plugins,ingwinlu/pelican-plugins,UHBiocomputation/pelican-plugins,Xion/pelican-plugins,pestrickland/pelican-plugins,Neurita/pelican-plugins |
394262effa690eda51ba9ee29aa86d98c683e17d | foundry/tests.py | foundry/tests.py | from django.core import management
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from post.models import Post
from foundry.models import Member, Listing
class TestCase(TestCase):
def setUp(self):
# Post-syncdb steps
management.call_command('migrate', interactive=False)
management.call_command('load_photosizes', interactive=False)
# Editor
self.editor, dc = Member.objects.get_or_create(
username='editor',
email='editor@test.com'
)
# Posts
for i in range(1, 5):
post = Post.objects.create(
title='Post %s' % i, content='<b>aaa</b>',
owner=self.editor, state='published',
)
post.sites = [1]
post.save()
setattr(self, 'post%s' % i, post)
def test_listing(self):
content_type = ContentType.objects.get(app_label='post', model='post')
posts = Listing.objects.create(
title='Posts', count=0, style='VerticalThumbnail',
)
posts.content_type = [content_type]
posts.sites = [1]
posts.save()
self.failUnless(self.post1.modelbase_obj in posts.queryset.all())
| from django.core import management
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from django.test.client import Client
from post.models import Post
from foundry.models import Member, Listing
class TestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
# Post-syncdb steps
management.call_command('migrate', interactive=False)
management.call_command('load_photosizes', interactive=False)
# Editor
self.editor, dc = Member.objects.get_or_create(
username='editor',
email='editor@test.com'
)
# Posts
for i in range(1, 5):
post = Post.objects.create(
title='Post %s' % i, content='<b>aaa</b>',
owner=self.editor, state='published',
)
post.sites = [1]
post.save()
setattr(self, 'post%s' % i, post)
def test_listing(self):
content_type = ContentType.objects.get(app_label='post', model='post')
posts = Listing.objects.create(
title='Posts', count=0, style='VerticalThumbnail',
)
posts.content_type = [content_type]
posts.sites = [1]
posts.save()
self.failUnless(self.post1.modelbase_obj in posts.queryset.all())
def test_pages(self):
response =self.client.get('/login')
self.assertEqual(response.status_code, 200)
self.failIf(response.content.find('<form') == -1)
| Add test to show login form is broken | Add test to show login form is broken
| Python | bsd-3-clause | praekelt/jmbo-foundry,praekelt/jmbo-foundry,praekelt/jmbo-foundry |
332452cf7ccd6d3ee583be9a6aac27b14771263f | source/services/omdb_service.py | source/services/omdb_service.py | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
ratings = []
ratings.append(movie_info['tomatoMeter'])
ratings.append(movie_info['tomatoUserMeter'])
return RTRating(ratings)
| import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
scores = []
scores.append(movie_info['tomatoMeter'])
scores.append(movie_info['tomatoUserMeter'])
rt_rating = RTRating(scores)
rt_rating.link = movie_info['tomatoURL']
return rt_rating
| Add url to RTRating object | Add url to RTRating object
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu |
a27d3f76f194a9767022e37c83d5d18861552cfd | all-domains/tutorials/cracking-the-coding-interview/linked-lists-detect-a-cycle/solution.py | all-domains/tutorials/cracking-the-coding-interview/linked-lists-detect-a-cycle/solution.py | # https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
"""
def has_cycle(node):
if hasattr(node, 'visited'):
return True
node.visited = True
if node.next is None:
return False
return has_cycle(node.next)
# TEST CODE
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
first_case = Node(1)
three = Node(3)
two = Node(2, three)
one = Node(1, two)
three.next = two
second_case = one
x = Node('x')
y = Node('y', x)
third_case = Node('third_case', y)
# print('has_cycle(first_case): {}'.format(has_cycle(first_case)))
print('has_cycle(second_case): {}'.format(has_cycle(second_case)))
# print('has_cycle(second_case): {}'.format(has_cycle(third_case)))
| # https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
"""
def has_cycle(node):
c = node
n = node.next
while n is not None:
if hasattr(c, 'visited'):
return True
c.visited = True
c = n.next
n = c.next
return False
# TEST CODE
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
first_case = Node(1)
three = Node(3)
two = Node(2, three)
one = Node(1, two)
three.next = two
second_case = one
x = Node('x')
y = Node('y', x)
third_case = Node('third_case', y)
print('has_cycle(first_case): {}'.format(has_cycle(first_case)))
print('has_cycle(second_case): {}'.format(has_cycle(second_case)))
print('has_cycle(second_case): {}'.format(has_cycle(third_case)))
| Solve problem to detect linked list cycle | Solve problem to detect linked list cycle
https://www.hackerrank.com/challenges/ctci-linked-list-cycle
| Python | mit | arvinsim/hackerrank-solutions |
0be3b5bf33a3e0254297eda664c85fd249bce2fe | amostra/tests/test_jsonschema.py | amostra/tests/test_jsonschema.py | import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
| from operator import itemgetter
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
| Use itemgetter instead of lambda | TST: Use itemgetter instead of lambda
| Python | bsd-3-clause | NSLS-II/amostra |
d0ac312de9b48a78f92f9eb09e048131578483f5 | giles/utils.py | giles/utils.py | # Giles: utils.py
# Copyright 2012 Phil Bordelon
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def booleanize(msg):
# This returns:
# -1 for False
# 1 for True
# 0 for invalid input.
if type(msg) != str:
return 0
msg = msg.strip().lower()
if (msg == "on" or msg == "true" or msg == "yes" or msg == "y"
or msg == "t" or msg == "1"):
return 1
elif (msg == "off" or msg == "false" or msg == "no" or msg == "n"
or msg == "f" or msg == "0"):
return -1
return 0
| # Giles: utils.py
# Copyright 2012 Phil Bordelon
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Struct(object):
# Empty class, useful for making "structs."
pass
def booleanize(msg):
# This returns:
# -1 for False
# 1 for True
# 0 for invalid input.
if type(msg) != str:
return 0
msg = msg.strip().lower()
if (msg == "on" or msg == "true" or msg == "yes" or msg == "y"
or msg == "t" or msg == "1"):
return 1
elif (msg == "off" or msg == "false" or msg == "no" or msg == "n"
or msg == "f" or msg == "0"):
return -1
return 0
| Add my classic Struct "class." | Add my classic Struct "class."
That's right, I embrace the lazy.
| Python | agpl-3.0 | sunfall/giles |
b26ce5b5ff778208314bfd21014f88ee24917d7a | ideas/views.py | ideas/views.py | from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
def vote(request):
if request.method == 'POST':
idea = Idea.objects.get(pk=request.data)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
| from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def idea(request, pk):
if request.method == 'GET':
idea = Idea.objects.get(pk=pk)
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
def vote(request, pk):
if request.method == 'POST':
idea = Idea.objects.get(pk=pk)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
| Add GET for idea and refactor vote | Add GET for idea and refactor vote
| Python | mit | neosergio/vote_hackatrix_backend |
6464c3ed7481e347dc6ca93ccfcad6964456e769 | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "capomastro.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
# This bootstraps the virtualenv so that the system Python can use it
app_root = os.path.dirname(os.path.realpath(__file__))
activate_this = os.path.join(app_root, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "capomastro.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Add temporary bootstrapping to get the service working with how the charm presently expects to run the app. | Add temporary bootstrapping to get the service working with how the charm presently expects to run the app.
| Python | mit | timrchavez/capomastro,timrchavez/capomastro |
8318bae21bd5cb716a4cbf2cd2dfe46ea8cadbcf | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development')
import dotenv
dotenv.read_dotenv('.env')
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development')
if os.environ['DJANGO_CONFIGURATION'] == 'Development':
import dotenv
dotenv.read_dotenv('.env')
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Hide .env behind a development environment. | Hide .env behind a development environment.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
e9c7b17ccd9709eb90f38bec9d59c48dc6f793b2 | calico_containers/tests/st/utils.py | calico_containers/tests/st/utils.py | import sh
from sh import docker
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
intf = sh.ifconfig.eth0()
return sh.perl(intf, "-ne", 's/dr:(\S+)/print $1/e')
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.
"""
docker("exec", "-t", name, "bash", "-c",
"docker rm -f $(docker ps -qa) ; docker rmi $(docker images -qa)",
_ok_code=[0, 1, 255]) # 255 is; "bash": executable file not found in $PATH
def delete_container(name):
"""
Cleanly delete a container.
"""
# We *must* remove all inner containers and images before removing the outer
# container. Otherwise the inner images will stick around and fill disk.
# https://github.com/jpetazzo/dind#important-warning-about-disk-usage
cleanup_inside(name)
sh.docker.rm("-f", name, _ok_code=[0, 1])
| import sh
from sh import docker
import socket
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.
"""
docker("exec", "-t", name, "bash", "-c",
"docker rm -f $(docker ps -qa) ; docker rmi $(docker images -qa)",
_ok_code=[0, 1, 255]) # 255 is; "bash": executable file not found in $PATH
def delete_container(name):
"""
Cleanly delete a container.
"""
# We *must* remove all inner containers and images before removing the outer
# container. Otherwise the inner images will stick around and fill disk.
# https://github.com/jpetazzo/dind#important-warning-about-disk-usage
cleanup_inside(name)
sh.docker.rm("-f", name, _ok_code=[0, 1])
| Use socket connection to get own IP. | Use socket connection to get own IP.
Former-commit-id: ebec31105582235c8aa74e9bbfd608b9bf103ad1 | Python | apache-2.0 | robbrockbank/libcalico,tomdee/libnetwork-plugin,TrimBiggs/libcalico,plwhite/libcalico,tomdee/libcalico,projectcalico/libnetwork-plugin,L-MA/libcalico,projectcalico/libcalico,djosborne/libcalico,Symmetric/libcalico,TrimBiggs/libnetwork-plugin,alexhersh/libcalico,insequent/libcalico,caseydavenport/libcalico,TrimBiggs/libnetwork-plugin |
4a827bfff24758677e9c1d9d3b186fc14f23e0bb | lib/oeqa/runtime/cases/parselogs_rpi.py | lib/oeqa/runtime/cases/parselogs_rpi.py | from oeqa.runtime.cases.parselogs import *
rpi_errors = [
'bcmgenet fd580000.genet: failed to get enet-eee clock',
'bcmgenet fd580000.genet: failed to get enet-wol clock',
'bcmgenet fd580000.genet: failed to get enet clock',
'bcmgenet fd580000.ethernet: failed to get enet-eee clock',
'bcmgenet fd580000.ethernet: failed to get enet-wol clock',
'bcmgenet fd580000.ethernet: failed to get enet clock',
]
ignore_errors['raspberrypi4'] = rpi_errors + common_errors
ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors
ignore_errors['raspberrypi3'] = rpi_errors + common_errors
ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors
class ParseLogsTestRpi(ParseLogsTest):
pass
| from oeqa.runtime.cases.parselogs import *
rpi_errors = [
]
ignore_errors['raspberrypi4'] = rpi_errors + common_errors
ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors
ignore_errors['raspberrypi3'] = rpi_errors + common_errors
ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors
class ParseLogsTestRpi(ParseLogsTest):
pass
| Update the error regexps to 5.10 kernel | parselogs: Update the error regexps to 5.10 kernel
The old messages are no longer necessary
Signed-off-by: Khem Raj <729d64b6f67515e258459a5f6d20ec88b2caf8df@gmail.com>
| Python | mit | agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi |
b1781b8c82979ee3765197084a9c8e372cb68cf8 | jazzband/hooks.py | jazzband/hooks.py | import json
import uuid
from flask_hookserver import Hooks
from .db import redis
from .members.models import User
from .projects.tasks import update_project_by_hook
from .tasks import spinach
hooks = Hooks()
@hooks.hook("ping")
def ping(data, guid):
return "pong"
@hooks.hook("membership")
def membership(data, guid):
if data["scope"] != "team":
return
member = User.query.filter_by(id=data["member"]["id"]).first()
if member is None:
return
if data["action"] == "added":
member.is_member = True
member.save()
elif data["action"] == "removed":
member.is_member = False
member.save()
return "Thanks"
@hooks.hook("member")
def member(data, guid):
# only if the action is to add a member and if there is repo data
if data.get("action") == "added" and "repository" in data:
hook_id = f"repo-added-{uuid.uuid4()}"
redis.setex(
hook_id, 60 * 5, json.dumps(data) # expire the hook hash in 5 minutes
)
spinach.schedule(update_project_by_hook, hook_id)
return hook_id
return "Thanks"
| import json
import uuid
from flask_hookserver import Hooks
from .db import redis
from .members.models import User
from .projects.tasks import update_project_by_hook
from .tasks import spinach
hooks = Hooks()
@hooks.hook("ping")
def ping(data, guid):
return "pong"
@hooks.hook("membership")
def membership(data, guid):
if data["scope"] != "team":
return
member = User.query.filter_by(id=data["member"]["id"]).first()
if member is None:
return
if data["action"] == "added":
member.is_member = True
member.save()
elif data["action"] == "removed":
member.is_member = False
member.save()
return "Thanks"
@hooks.hook("repository")
def repository(data, guid):
# only if the action is to add a member and if there is repo data
if data.get("action") == "transferred" and "repository" in data:
hook_id = f"repo-added-{uuid.uuid4()}"
redis.setex(
hook_id, 60 * 5, json.dumps(data) # expire the hook hash in 5 minutes
)
spinach.schedule(update_project_by_hook, hook_id)
return hook_id
return "Thanks"
| Use new (?) repository transferred hook. | Use new (?) repository transferred hook.
| Python | mit | jazzband/jazzband-site,jazzband/website,jazzband/website,jazzband/website,jazzband/website,jazzband/site,jazzband/jazzband-site,jazzband/site |
6e6c60613180bb3d7e2d019129e57d1a2c33286d | backend/backend/models.py | backend/backend/models.py | from django.db import models
class Animal(models.Model):
MALE = 'male'
FEMALE = 'female'
GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female'))
father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father")
mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother")
name = models.CharField(max_length = 100)
dob = models.IntegerField()
gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE)
active = models.BooleanField()
own = models.BooleanField()
class Meta:
unique_together = ("name", "dob")
| from django.db import models
from django.core.validators import MaxValueValidator, MaxLengthValidator
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime
def current_year():
return datetime.now().year
class Animal(models.Model):
MALE = 'male'
FEMALE = 'female'
GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female'))
father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father")
mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother")
name = models.CharField(max_length = 100, validators = [MaxLengthValidator(100)])
dob = models.IntegerField(validators = [MaxValueValidator(current_year())])
gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE)
active = models.BooleanField()
own = models.BooleanField()
class Meta:
unique_together = ("name", "dob")
| Add length validator to name. Add dob validator can't be higher than current year. | Add length validator to name.
Add dob validator can't be higher than current year.
| Python | apache-2.0 | mmlado/animal_pairing,mmlado/animal_pairing |
a1897464b7974589723790f946fed0c1a5bdb475 | chef/fabric.py | chef/fabric.py | from chef import Search
from chef.api import ChefAPI, autoconfigure
from chef.exceptions import ChefError
class Roledef(object):
def __init__(self, name, api, hostname_attr):
self.name = name
self.api = api
self.hostname_attr = hostname_attr
def __call__(self):
for row in Search('node', 'roles:'+self.name, api=self.api):
yield row.object.attributes.get_dotted(self.hostname_attr)
def chef_roledefs(api=None, hostname_attr = 'fqdn'):
"""Build a Fabric roledef dictionary from a Chef server.
Example:
from fabric.api import env, run, roles
from chef.fabric import chef_roledefs
env.roledefs = chef_roledefs()
@roles('web_app')
def mytask():
run('uptime')
hostname_attr is the attribute in the chef node that holds the real hostname.
to refer to a nested attribute, separate the levels with '.'.
for example 'ec2.public_hostname'
"""
api = api or ChefAPI.get_global() or autoconfigure()
if not api:
raise ChefError('Unable to load Chef API configuration')
roledefs = {}
for row in Search('role', api=api):
name = row['name']
roledefs[name] = Roledef(name, api, hostname_attr)
return roledefs
| from chef import Search
from chef.api import ChefAPI, autoconfigure
from chef.exceptions import ChefError
class Roledef(object):
def __init__(self, name, api, hostname_attr):
self.name = name
self.api = api
self.hostname_attr = hostname_attr
def __call__(self):
for row in Search('node', 'roles:'+self.name, api=self.api):
fqdn = ""
if row.object.attributes.has_dotted(self.hostname_attr):
fqdn = row.object.attributes.get_dotted(self.hostname_attr)
else if row.object.attributes.has_dotted("ec2.hostname"):
fqdn = row.object.attributes.get_dotted("ec2.hostname")
yield fqdn
def chef_roledefs(api=None, hostname_attr = 'fqdn'):
"""Build a Fabric roledef dictionary from a Chef server.
Example:
from fabric.api import env, run, roles
from chef.fabric import chef_roledefs
env.roledefs = chef_roledefs()
@roles('web_app')
def mytask():
run('uptime')
hostname_attr is the attribute in the chef node that holds the real hostname.
to refer to a nested attribute, separate the levels with '.'.
for example 'ec2.public_hostname'
"""
api = api or ChefAPI.get_global() or autoconfigure()
if not api:
raise ChefError('Unable to load Chef API configuration')
roledefs = {}
for row in Search('role', api=api):
name = row['name']
roledefs[name] = Roledef(name, api, hostname_attr)
return roledefs
| Work around when fqdn is not defined for a node. | Work around when fqdn is not defined for a node.
| Python | apache-2.0 | Scalr/pychef,jarosser06/pychef,cread/pychef,coderanger/pychef,Scalr/pychef,jarosser06/pychef,dipakvwarade/pychef,dipakvwarade/pychef,coderanger/pychef,cread/pychef |
1ce39741886cdce69e3801a1d0afb25c39a8b844 | fitbit/models.py | fitbit/models.py | from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
| from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
def __repr__(self):
return '<Token %s>' % self.fitbit_id
def __str__(self):
return self.fitbit_id
| Add repr and str to our token model | Add repr and str to our token model
| Python | apache-2.0 | Bachmann1234/fitbitSlackBot,Bachmann1234/fitbitSlackBot |
0420ed666f8a2cd5cd6c2055b13a5d26cc5d3792 | output.py | output.py | def summarizeECG(instHR, avgHR, brady, tachy):
"""Create txt file summarizing ECG analysis
:param instHR: (int)
:param avgHR: (int)
:param brady: (int)
:param tachy: (int)
"""
#Calls hrdetector() to get instantaneous heart rate
#instHR = findInstHR()
#Calls findAvgHR() to get average heart rate
#avgHR = findAvgHR()
#Calls bradyTimes() to get times when bradycardia occurred
#brady = bradyTimes()
#Calls tachtimes() to get times when tachycardia occurred
#tachy = tachyTimes()
#Writes the output of the ECG analysis to an output file named ecgOutput.txt
ecgResults = open('ecgOutput.txt','w')
instHRstr = "Estimated instantaneous heart rate: %s" % str(instHR)
avgHRstr = "Estimated average heart rate: %s" % str(avgHR)
bradystr = "Bradycardia occurred at: %s" % str(brady)
tachystr = "Tachycardia occurred at: %s" % str(tachy)
ecgResults.write(instHRstr + ' BPM\n' + avgHRstr + ' BPM\n' + bradystr + '\n' + tachystr)
ecgResults.close()
| def summarizeECG(instHR, avgHR, brady, tachy):
"""Create txt file summarizing ECG analysis
:param instHR: (int)
:param avgHR: (int)
:param brady: (int)
:param tachy: (int)
"""
#Calls hrdetector() to get instantaneous heart rate
#instHR = findInstHR()
#Calls findAvgHR() to get average heart rate
#avgHR = findAvgHR()
#Calls bradyTimes() to get times when bradycardia occurred
#brady = bradyTimes()
#Calls tachtimes() to get times when tachycardia occurred
#tachy = tachyTimes()
#Writes the output of the ECG analysis to an output file named ecgOutput.txt
ecgResults = open('ecgOutput.txt','w')
instHRstr = "Estimated instantaneous heart rate: %s" % str(instHR)
avgHRstr = "Estimated average heart rate: %s" % str(avgHR)
bradystr = "Bradycardia occurred at: %s" % str(brady)
tachystr = "Tachycardia occurred at: %s" % str(tachy)
ecgResults.write(instHRstr + ' BPM\n' + avgHRstr + ' BPM\n' + bradystr + ' sec\n' + tachystr + ' sec')
ecgResults.close()
| Add units to brady and tachy strings. | Add units to brady and tachy strings.
| Python | mit | raspearsy/bme590hrm |
93f9bb4115c4259dd38962229947b87e952a25a7 | completion/levenshtein.py | completion/levenshtein.py | def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
| def levenshtein(top_string, bot_string):
if len(top_string) < len(bot_string):
return levenshtein(bot_string, top_string)
# len(s1) >= len(s2)
if len(bot_string) == 0:
return len(top_string)
previous_row = range(len(bot_string) + 1)
for i, top_char in enumerate(top_string):
current_row = [i + 1]
for j, bot_char in enumerate(bot_string):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than bot_string
substitutions = previous_row[j] + (top_char != bot_char)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
| Use better variable names for algorithmic determination | Use better variable names for algorithmic determination
| Python | mit | thatsIch/sublime-rainmeter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.