commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5217075d20c9b707dba191f4e7efdc9f66dcfaa
|
am_workout_assistant.py
|
am_workout_assistant.py
|
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
|
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}! Sum for the day is {}."
.format(msg_checker.get_num_catch_ups(), res))
|
Return summary for the day on success
|
Return summary for the day on success
This implements #2
|
Python
|
mit
|
amaslenn/AMWorkoutAssist
|
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
- res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
+ res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
- bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
+ bot.send_reply("Successfully added {}! Sum for the day is {}."
+ .format(msg_checker.get_num_catch_ups(), res))
|
Return summary for the day on success
|
## Code Before:
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
## Instruction:
Return summary for the day on success
## Code After:
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}! Sum for the day is {}."
.format(msg_checker.get_num_catch_ups(), res))
|
# ... existing code ...
res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
# ... modified code ...
# success!
bot.send_reply("Successfully added {}! Sum for the day is {}."
.format(msg_checker.get_num_catch_ups(), res))
# ... rest of the code ...
|
8ab254490dac4f4ebfed1f43d615c321b5890e29
|
xmlrpclib_to/__init__.py
|
xmlrpclib_to/__init__.py
|
try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, timeout=None):
if timeout is not None:
transport = TimeoutTransport(use_datetime, timeout)
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose,
allow_none, use_datetime)
class TimeoutTransport(xmlrpclib.Transport):
def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
xmlrpclib.Transport.__init__(self, use_datetime)
self.timeout = timeout
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
chost, self._extra_headers, x509 = self.get_host_info(host)
self._connection = host, httplib.HTTPConnection(
chost, timeout=self.timeout
)
return self._connection[1]
|
try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, timeout=None):
if timeout is not None:
if uri.startswith('http://'):
secure = False
elif uri.startswith('https://'):
secure = True
transport = TimeoutTransport(use_datetime, timeout, secure=secure)
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose,
allow_none, use_datetime)
class TimeoutTransport(xmlrpclib.Transport):
def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
secure=False):
xmlrpclib.Transport.__init__(self, use_datetime)
self.timeout = timeout
self.secure = secure
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
chost, self._extra_headers, x509 = self.get_host_info(host)
if self.secure:
self._connection = host, httplib.HTTPSConnection(
chost, None, timeout=self.timeout, **(x509 or {})
)
else:
self._connection = host, httplib.HTTPConnection(
chost, timeout=self.timeout
)
return self._connection[1]
|
FIX working with HTTPS correctly
|
FIX working with HTTPS correctly
|
Python
|
mit
|
gisce/xmlrpclib-to
|
try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, timeout=None):
if timeout is not None:
+ if uri.startswith('http://'):
+ secure = False
+ elif uri.startswith('https://'):
+ secure = True
- transport = TimeoutTransport(use_datetime, timeout)
+ transport = TimeoutTransport(use_datetime, timeout, secure=secure)
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose,
allow_none, use_datetime)
class TimeoutTransport(xmlrpclib.Transport):
- def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
+ def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
+ secure=False):
xmlrpclib.Transport.__init__(self, use_datetime)
self.timeout = timeout
+ self.secure = secure
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
+ chost, self._extra_headers, x509 = self.get_host_info(host)
+ if self.secure:
+ self._connection = host, httplib.HTTPSConnection(
+ chost, None, timeout=self.timeout, **(x509 or {})
+ )
+ else:
+ self._connection = host, httplib.HTTPConnection(
+ chost, timeout=self.timeout
+ )
+
- chost, self._extra_headers, x509 = self.get_host_info(host)
- self._connection = host, httplib.HTTPConnection(
- chost, timeout=self.timeout
- )
return self._connection[1]
|
FIX working with HTTPS correctly
|
## Code Before:
try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, timeout=None):
if timeout is not None:
transport = TimeoutTransport(use_datetime, timeout)
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose,
allow_none, use_datetime)
class TimeoutTransport(xmlrpclib.Transport):
def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
xmlrpclib.Transport.__init__(self, use_datetime)
self.timeout = timeout
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
chost, self._extra_headers, x509 = self.get_host_info(host)
self._connection = host, httplib.HTTPConnection(
chost, timeout=self.timeout
)
return self._connection[1]
## Instruction:
FIX working with HTTPS correctly
## Code After:
try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, timeout=None):
if timeout is not None:
if uri.startswith('http://'):
secure = False
elif uri.startswith('https://'):
secure = True
transport = TimeoutTransport(use_datetime, timeout, secure=secure)
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose,
allow_none, use_datetime)
class TimeoutTransport(xmlrpclib.Transport):
def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
secure=False):
xmlrpclib.Transport.__init__(self, use_datetime)
self.timeout = timeout
self.secure = secure
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
chost, self._extra_headers, x509 = self.get_host_info(host)
if self.secure:
self._connection = host, httplib.HTTPSConnection(
chost, None, timeout=self.timeout, **(x509 or {})
)
else:
self._connection = host, httplib.HTTPConnection(
chost, timeout=self.timeout
)
return self._connection[1]
|
// ... existing code ...
if timeout is not None:
if uri.startswith('http://'):
secure = False
elif uri.startswith('https://'):
secure = True
transport = TimeoutTransport(use_datetime, timeout, secure=secure)
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose,
// ... modified code ...
def __init__(self, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
secure=False):
xmlrpclib.Transport.__init__(self, use_datetime)
...
self.timeout = timeout
self.secure = secure
...
return self._connection[1]
chost, self._extra_headers, x509 = self.get_host_info(host)
if self.secure:
self._connection = host, httplib.HTTPSConnection(
chost, None, timeout=self.timeout, **(x509 or {})
)
else:
self._connection = host, httplib.HTTPConnection(
chost, timeout=self.timeout
)
return self._connection[1]
// ... rest of the code ...
|
66c0b220188499a5871ee1fbe5b79f0a57db4ec9
|
feder/tasks/filters.py
|
feder/tasks/filters.py
|
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Task
class TaskFilter(CrispyFilterMixin, django_filters.FilterSet):
case = AutocompleteChoiceFilter('CaseAutocomplete')
questionary = AutocompleteChoiceFilter('QuestionaryAutocomplete')
case__institution = AutocompleteChoiceFilter('InstitutionAutocomplete')
case__monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete')
created = django_filters.DateRangeFilter(label=_("Creation date"))
form_class = None
def __init__(self, *args, **kwargs):
super(TaskFilter, self).__init__(*args, **kwargs)
self.filters['name'].lookup_type = 'icontains'
class Meta:
model = Task
fields = ['name', 'case', 'questionary', 'case__institution', ]
order_by = ['created', ]
|
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Task
class TaskFilter(CrispyFilterMixin, django_filters.FilterSet):
case = AutocompleteChoiceFilter('CaseAutocomplete')
questionary = AutocompleteChoiceFilter('QuestionaryAutocomplete')
case__institution = AutocompleteChoiceFilter('InstitutionAutocomplete')
case__monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete')
created = django_filters.DateRangeFilter(label=_("Creation date"))
done = django_filters.BooleanFilter(label=_("Is done?"),
action=lambda qs, v: qs.is_done(exclude=not v))
form_class = None
def __init__(self, *args, **kwargs):
super(TaskFilter, self).__init__(*args, **kwargs)
self.filters['name'].lookup_type = 'icontains'
class Meta:
model = Task
fields = ['name', 'case', 'questionary', 'case__institution', ]
order_by = ['created', ]
|
Add is_done filter for task
|
Add is_done filter for task
|
Python
|
mit
|
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
|
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Task
class TaskFilter(CrispyFilterMixin, django_filters.FilterSet):
case = AutocompleteChoiceFilter('CaseAutocomplete')
questionary = AutocompleteChoiceFilter('QuestionaryAutocomplete')
case__institution = AutocompleteChoiceFilter('InstitutionAutocomplete')
case__monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete')
created = django_filters.DateRangeFilter(label=_("Creation date"))
+ done = django_filters.BooleanFilter(label=_("Is done?"),
+ action=lambda qs, v: qs.is_done(exclude=not v))
form_class = None
def __init__(self, *args, **kwargs):
super(TaskFilter, self).__init__(*args, **kwargs)
self.filters['name'].lookup_type = 'icontains'
class Meta:
model = Task
fields = ['name', 'case', 'questionary', 'case__institution', ]
order_by = ['created', ]
|
Add is_done filter for task
|
## Code Before:
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Task
class TaskFilter(CrispyFilterMixin, django_filters.FilterSet):
case = AutocompleteChoiceFilter('CaseAutocomplete')
questionary = AutocompleteChoiceFilter('QuestionaryAutocomplete')
case__institution = AutocompleteChoiceFilter('InstitutionAutocomplete')
case__monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete')
created = django_filters.DateRangeFilter(label=_("Creation date"))
form_class = None
def __init__(self, *args, **kwargs):
super(TaskFilter, self).__init__(*args, **kwargs)
self.filters['name'].lookup_type = 'icontains'
class Meta:
model = Task
fields = ['name', 'case', 'questionary', 'case__institution', ]
order_by = ['created', ]
## Instruction:
Add is_done filter for task
## Code After:
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Task
class TaskFilter(CrispyFilterMixin, django_filters.FilterSet):
case = AutocompleteChoiceFilter('CaseAutocomplete')
questionary = AutocompleteChoiceFilter('QuestionaryAutocomplete')
case__institution = AutocompleteChoiceFilter('InstitutionAutocomplete')
case__monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete')
created = django_filters.DateRangeFilter(label=_("Creation date"))
done = django_filters.BooleanFilter(label=_("Is done?"),
action=lambda qs, v: qs.is_done(exclude=not v))
form_class = None
def __init__(self, *args, **kwargs):
super(TaskFilter, self).__init__(*args, **kwargs)
self.filters['name'].lookup_type = 'icontains'
class Meta:
model = Task
fields = ['name', 'case', 'questionary', 'case__institution', ]
order_by = ['created', ]
|
// ... existing code ...
created = django_filters.DateRangeFilter(label=_("Creation date"))
done = django_filters.BooleanFilter(label=_("Is done?"),
action=lambda qs, v: qs.is_done(exclude=not v))
form_class = None
// ... rest of the code ...
|
da39bc268e3fe94af348690262fc116e3e0b2c9c
|
attachments/admin.py
|
attachments/admin.py
|
from attachments.models import Attachment
from django.contrib.contenttypes import generic
class AttachmentInlines(generic.GenericStackedInline):
model = Attachment
extra = 1
|
from attachments.models import Attachment
from django.contrib.contenttypes import admin
class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1
|
Fix deprecated modules for content types
|
Fix deprecated modules for content types
|
Python
|
bsd-3-clause
|
leotrubach/django-attachments,leotrubach/django-attachments
|
from attachments.models import Attachment
- from django.contrib.contenttypes import generic
+ from django.contrib.contenttypes import admin
- class AttachmentInlines(generic.GenericStackedInline):
+ class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1
|
Fix deprecated modules for content types
|
## Code Before:
from attachments.models import Attachment
from django.contrib.contenttypes import generic
class AttachmentInlines(generic.GenericStackedInline):
model = Attachment
extra = 1
## Instruction:
Fix deprecated modules for content types
## Code After:
from attachments.models import Attachment
from django.contrib.contenttypes import admin
class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1
|
# ... existing code ...
from attachments.models import Attachment
from django.contrib.contenttypes import admin
# ... modified code ...
class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
# ... rest of the code ...
|
d8cde079d6e8dd0dcd5a13a36a0bca9685ba7b1c
|
api/BucketListAPI.py
|
api/BucketListAPI.py
|
from flask import Flask, jsonify
from modals.modals import User, Bucket, Item
from api.__init__ import create_app, db
app = create_app('DevelopmentEnv')
@app.errorhandler(404)
def page_not_found(e):
response = jsonify({'error': 'The request can not be completed'})
response.status_code = 404
return response
if __name__ == '__main__':
app.run()
|
from flask import Flask, jsonify
from modals.modals import User, Bucket, Item
from api.__init__ import create_app, db
app = create_app('DevelopmentEnv')
@app.errorhandler(404)
def page_not_found(e):
response = jsonify({'error': 'The request can not be completed'})
response.status_code = 404
return response
@app.errorhandler(401)
def invalid_token(e):
response = jsonify({'error': 'Invalid Token'})
response.status_code = 401
return response
if __name__ == '__main__':
app.run()
|
Add error handler for invalid token
|
Add error handler for invalid token
|
Python
|
mit
|
patlub/BucketListAPI,patlub/BucketListAPI
|
from flask import Flask, jsonify
from modals.modals import User, Bucket, Item
from api.__init__ import create_app, db
app = create_app('DevelopmentEnv')
@app.errorhandler(404)
def page_not_found(e):
response = jsonify({'error': 'The request can not be completed'})
response.status_code = 404
return response
+ @app.errorhandler(401)
+ def invalid_token(e):
+ response = jsonify({'error': 'Invalid Token'})
+ response.status_code = 401
+ return response
+
if __name__ == '__main__':
app.run()
|
Add error handler for invalid token
|
## Code Before:
from flask import Flask, jsonify
from modals.modals import User, Bucket, Item
from api.__init__ import create_app, db
app = create_app('DevelopmentEnv')
@app.errorhandler(404)
def page_not_found(e):
response = jsonify({'error': 'The request can not be completed'})
response.status_code = 404
return response
if __name__ == '__main__':
app.run()
## Instruction:
Add error handler for invalid token
## Code After:
from flask import Flask, jsonify
from modals.modals import User, Bucket, Item
from api.__init__ import create_app, db
app = create_app('DevelopmentEnv')
@app.errorhandler(404)
def page_not_found(e):
response = jsonify({'error': 'The request can not be completed'})
response.status_code = 404
return response
@app.errorhandler(401)
def invalid_token(e):
response = jsonify({'error': 'Invalid Token'})
response.status_code = 401
return response
if __name__ == '__main__':
app.run()
|
// ... existing code ...
@app.errorhandler(401)
def invalid_token(e):
response = jsonify({'error': 'Invalid Token'})
response.status_code = 401
return response
// ... rest of the code ...
|
06ef7333ea7c584166b1a7361e1d41143a0c85c8
|
moveon/managers.py
|
moveon/managers.py
|
from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
|
from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
|
Add the query to get the near stations
|
Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box.
|
Python
|
agpl-3.0
|
SeGarVi/moveon-web,SeGarVi/moveon-web,SeGarVi/moveon-web
|
from django.db import models
+ from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
+
+ def get_near_stations(self, left, bottom, right, top):
+ stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
+ Q(latitude__lte=right) & Q(longitude__lte=top))
+ return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
|
Add the query to get the near stations
|
## Code Before:
from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
## Instruction:
Add the query to get the near stations
## Code After:
from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
|
# ... existing code ...
from django.db import models
from django.db.models import Q
# ... modified code ...
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
# ... rest of the code ...
|
881222a49c6b3e8792adf5754c61992bd12c7b28
|
tests/test_conduction.py
|
tests/test_conduction.py
|
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
self.conduction = pymongo.MongoClient(self.mockup.uri).test
def test_bad_command_name(self):
with self.assertRaises(OperationFailure):
self.conduction.command('foo')
if __name__ == '__main__':
unittest.main()
|
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
# Any database name will do.
self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
def test_root_uri(self):
reply = self.conduction.command('get', '/')
self.assertIn('links', reply)
self.assertIn('service', reply)
def test_bad_command_name(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
self.assertIn('unrecognized: {"foo": 1}',
str(context.exception))
def test_server_id_404(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command({'post': '/v1/servers/'})
self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main()
|
Test root URI and 404s.
|
Test root URI and 404s.
|
Python
|
apache-2.0
|
ajdavis/mongo-conduction
|
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
+ # Any database name will do.
- self.conduction = pymongo.MongoClient(self.mockup.uri).test
+ self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
+
+ def test_root_uri(self):
+ reply = self.conduction.command('get', '/')
+ self.assertIn('links', reply)
+ self.assertIn('service', reply)
def test_bad_command_name(self):
- with self.assertRaises(OperationFailure):
+ with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
+
+ self.assertIn('unrecognized: {"foo": 1}',
+ str(context.exception))
+
+ def test_server_id_404(self):
+ with self.assertRaises(OperationFailure) as context:
+ self.conduction.command({'post': '/v1/servers/'})
+
+ self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main()
|
Test root URI and 404s.
|
## Code Before:
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
self.conduction = pymongo.MongoClient(self.mockup.uri).test
def test_bad_command_name(self):
with self.assertRaises(OperationFailure):
self.conduction.command('foo')
if __name__ == '__main__':
unittest.main()
## Instruction:
Test root URI and 404s.
## Code After:
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
# Any database name will do.
self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
def test_root_uri(self):
reply = self.conduction.command('get', '/')
self.assertIn('links', reply)
self.assertIn('service', reply)
def test_bad_command_name(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
self.assertIn('unrecognized: {"foo": 1}',
str(context.exception))
def test_server_id_404(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command({'post': '/v1/servers/'})
self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main()
|
# ... existing code ...
# Any database name will do.
self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
def test_root_uri(self):
reply = self.conduction.command('get', '/')
self.assertIn('links', reply)
self.assertIn('service', reply)
# ... modified code ...
def test_bad_command_name(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
self.assertIn('unrecognized: {"foo": 1}',
str(context.exception))
def test_server_id_404(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command({'post': '/v1/servers/'})
self.assertIn('404 Not Found', str(context.exception))
# ... rest of the code ...
|
64db9a503322ce1ee61c64afbdc38f367c3d6627
|
guardian/testapp/tests/management_test.py
|
guardian/testapp/tests/management_test.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.management import create_anonymous_user
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(SimpleTestCase):
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
|
from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
|
Use unit test.TestCase instead of SimpleTestCase
|
Use unit test.TestCase instead of SimpleTestCase
|
Python
|
bsd-2-clause
|
calvinpy/django-guardian,vovanbo/django-guardian,loop0/django-guardian,frwickst/django-guardian,thedrow/django-guardian,emperorcezar/django-guardian,alexshin/django-guardian,calvinpy/django-guardian,flisky/django-guardian,vitan/django-guardian,sustainingtechnologies/django-guardian,rfleschenberg/django-guardian,frwickst/django-guardian,alexshin/django-guardian,RDXT/django-guardian,lukaszb/django-guardian,benkonrath/django-guardian,brianmay/django-guardian,flisky/django-guardian,rmgorman/django-guardian,vitan/django-guardian,rmgorman/django-guardian,onaio/django-guardian,thedrow/django-guardian,alexshin/django-guardian,kostko/django-guardian,EnHatch/django-guardian,TailorDev/django-guardian,calvinpy/django-guardian,rfleschenberg/django-guardian,EnHatch/django-guardian,giocalitri/django-guardian,hunter007/django-guardian,sustainingtechnologies/django-guardian,brianmay/django-guardian,sindrig/django-guardian,RDXT/django-guardian,denilsonsa/django-guardian,sindrig/django-guardian,patgmiller/django-guardian,loop0/django-guardian,EnHatch/django-guardian,benkonrath/django-guardian,vovanbo/django-guardian,kostko/django-guardian,thedrow/django-guardian,EnHatch/django-guardian,benkonrath/django-guardian,loop0/django-guardian,vovanbo/django-guardian,giocalitri/django-guardian,onaio/django-guardian,TailorDev/django-guardian,patgmiller/django-guardian,patgmiller/django-guardian,vitan/django-guardian,sustainingtechnologies/django-guardian,haxo/django-guardian,frwickst/django-guardian,haxo/django-guardian,flisky/django-guardian,haxo/django-guardian,infoxchange/django-guardian,emperorcezar/django-guardian,denilsonsa/django-guardian,lukaszb/django-guardian,brianmay/django-guardian,thedrow/django-guardian,flisky/django-guardian,TailorDev/django-guardian,infoxchange/django-guardian,sustainingtechnologies/django-guardian,lukaszb/django-guardian,hunter007/django-guardian,onaio/django-guardian,emperorcezar/django-guardian,giocalitri/django-guardian,denilsonsa/django-guardian,infoxchange/django-guardian,emperorcezar/django-guardian,rmgorman/django-guardian,sindrig/django-guardian,kostko/django-guardian,rfleschenberg/django-guardian,loop0/django-guardian,kostko/django-guardian,RDXT/django-guardian,vitan/django-guardian,hunter007/django-guardian,denilsonsa/django-guardian,haxo/django-guardian
|
from __future__ import absolute_import
from __future__ import unicode_literals
- from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
+ from guardian.compat import unittest
from guardian.management import create_anonymous_user
+ import django
mocked_get_init_anon = mock.Mock()
- class TestGetAnonymousUser(SimpleTestCase):
+ class TestGetAnonymousUser(unittest.TestCase):
+ @unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
|
Use unit test.TestCase instead of SimpleTestCase
|
## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.management import create_anonymous_user
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(SimpleTestCase):
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
## Instruction:
Use unit test.TestCase instead of SimpleTestCase
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
|
# ... existing code ...
from guardian.compat import get_user_model
# ... modified code ...
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
...
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
# ... rest of the code ...
|
747af88d56dc274638f515825405f58b0e59b8d7
|
invoice/views.py
|
invoice/views.py
|
from django.shortcuts import get_object_or_404
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
def pdf_user_view(request, invoice_id):
invoice = get_object_or_404(Invoice, invoice_id=invoice_id, user=request.user)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
|
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
@login_required
def pdf_user_view(request, invoice_id):
invoice = get_object_or_404(Invoice, invoice_id=invoice_id, user=request.user)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
|
Make sure user in logged in for showing invoice
|
Make sure user in logged in for showing invoice
|
Python
|
bsd-3-clause
|
Chris7/django-invoice,Chris7/django-invoice,simonluijk/django-invoice
|
from django.shortcuts import get_object_or_404
+ from django.contrib.auth.decorators import login_required
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
+ @login_required
def pdf_user_view(request, invoice_id):
invoice = get_object_or_404(Invoice, invoice_id=invoice_id, user=request.user)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
|
Make sure user in logged in for showing invoice
|
## Code Before:
from django.shortcuts import get_object_or_404
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
def pdf_user_view(request, invoice_id):
invoice = get_object_or_404(Invoice, invoice_id=invoice_id, user=request.user)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
## Instruction:
Make sure user in logged in for showing invoice
## Code After:
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
@login_required
def pdf_user_view(request, invoice_id):
invoice = get_object_or_404(Invoice, invoice_id=invoice_id, user=request.user)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
|
...
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from invoice.models import Invoice
...
@login_required
def pdf_user_view(request, invoice_id):
...
|
6decf1f48e56832b1d15d3fc26d92f9813d13353
|
coop_cms/moves.py
|
coop_cms/moves.py
|
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
from HTMLParser import HTMLParser
from StringIO import StringIO
else:
# Python 3
from html.parser import HTMLParser
from io import BytesIO as StringIO
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
if VERSION >= (1, 9, 0):
from wsgiref.util import FileWrapper
else:
from django.core.servers.basehttp import FileWrapper
if VERSION >= (1, 8, 0):
from unittest import SkipTest
else:
# Deprecated in Django 1.9
from django.utils.unittest import SkipTest
def make_context(request, context_dict):
""""""
if VERSION >= (1, 9, 0):
context = dict(context_dict)
if request:
context['request'] = request
else:
from django.template import RequestContext, Context
if request:
context = RequestContext(request, context_dict)
else:
context = Context(context_dict)
return context
|
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
from StringIO import StringIO
from HTMLParser import HTMLParser
else:
# Python 3
from io import BytesIO as StringIO
from html.parser import HTMLParser as BaseHTMLParser
class HTMLParser(BaseHTMLParser):
def __init__(self):
BaseHTMLParser.__init__(self, convert_charrefs=False)
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
if VERSION >= (1, 9, 0):
from wsgiref.util import FileWrapper
else:
from django.core.servers.basehttp import FileWrapper
if VERSION >= (1, 8, 0):
from unittest import SkipTest
else:
# Deprecated in Django 1.9
from django.utils.unittest import SkipTest
def make_context(request, context_dict):
""""""
if VERSION >= (1, 9, 0):
context = dict(context_dict)
if request:
context['request'] = request
else:
from django.template import RequestContext, Context
if request:
context = RequestContext(request, context_dict)
else:
context = Context(context_dict)
return context
|
Fix HTMLParser compatibility in Python 3
|
Fix HTMLParser compatibility in Python 3
|
Python
|
bsd-3-clause
|
ljean/coop_cms,ljean/coop_cms,ljean/coop_cms
|
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
+
+ from StringIO import StringIO
+
from HTMLParser import HTMLParser
- from StringIO import StringIO
+
+
+
else:
# Python 3
- from html.parser import HTMLParser
from io import BytesIO as StringIO
+
+ from html.parser import HTMLParser as BaseHTMLParser
+
+ class HTMLParser(BaseHTMLParser):
+ def __init__(self):
+ BaseHTMLParser.__init__(self, convert_charrefs=False)
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
if VERSION >= (1, 9, 0):
from wsgiref.util import FileWrapper
else:
from django.core.servers.basehttp import FileWrapper
if VERSION >= (1, 8, 0):
from unittest import SkipTest
else:
# Deprecated in Django 1.9
from django.utils.unittest import SkipTest
def make_context(request, context_dict):
""""""
if VERSION >= (1, 9, 0):
context = dict(context_dict)
if request:
context['request'] = request
else:
from django.template import RequestContext, Context
if request:
context = RequestContext(request, context_dict)
else:
context = Context(context_dict)
return context
|
Fix HTMLParser compatibility in Python 3
|
## Code Before:
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
from HTMLParser import HTMLParser
from StringIO import StringIO
else:
# Python 3
from html.parser import HTMLParser
from io import BytesIO as StringIO
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
if VERSION >= (1, 9, 0):
from wsgiref.util import FileWrapper
else:
from django.core.servers.basehttp import FileWrapper
if VERSION >= (1, 8, 0):
from unittest import SkipTest
else:
# Deprecated in Django 1.9
from django.utils.unittest import SkipTest
def make_context(request, context_dict):
""""""
if VERSION >= (1, 9, 0):
context = dict(context_dict)
if request:
context['request'] = request
else:
from django.template import RequestContext, Context
if request:
context = RequestContext(request, context_dict)
else:
context = Context(context_dict)
return context
## Instruction:
Fix HTMLParser compatibility in Python 3
## Code After:
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
from StringIO import StringIO
from HTMLParser import HTMLParser
else:
# Python 3
from io import BytesIO as StringIO
from html.parser import HTMLParser as BaseHTMLParser
class HTMLParser(BaseHTMLParser):
def __init__(self):
BaseHTMLParser.__init__(self, convert_charrefs=False)
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
if VERSION >= (1, 9, 0):
from wsgiref.util import FileWrapper
else:
from django.core.servers.basehttp import FileWrapper
if VERSION >= (1, 8, 0):
from unittest import SkipTest
else:
# Deprecated in Django 1.9
from django.utils.unittest import SkipTest
def make_context(request, context_dict):
""""""
if VERSION >= (1, 9, 0):
context = dict(context_dict)
if request:
context['request'] = request
else:
from django.template import RequestContext, Context
if request:
context = RequestContext(request, context_dict)
else:
context = Context(context_dict)
return context
|
// ... existing code ...
# Python 2
from StringIO import StringIO
from HTMLParser import HTMLParser
else:
// ... modified code ...
# Python 3
from io import BytesIO as StringIO
from html.parser import HTMLParser as BaseHTMLParser
class HTMLParser(BaseHTMLParser):
def __init__(self):
BaseHTMLParser.__init__(self, convert_charrefs=False)
// ... rest of the code ...
|
9d66600518ec05dae2be62da0bbe2c15ddccce9d
|
spicedham/__init__.py
|
spicedham/__init__.py
|
from pkg_resources import iter_entry_points
from spicedham.config import load_config
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
global _plugins
if _plugins == None:
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
_plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in _plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in _plugins:
value = plugin.classify(tag, classification_data)
# Skip _plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no _plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
|
from pkg_resources import iter_entry_points
from spicedham.config import load_config
from spicedham.backend import load_backend
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
global _plugins
if _plugins == None:
# In order to use the plugins config and backend must be loaded.
load_backend()
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
_plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in _plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in _plugins:
value = plugin.classify(tag, classification_data)
# Skip _plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no _plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
|
Make sure to load_backend as part of load_plugins
|
Make sure to load_backend as part of load_plugins
|
Python
|
mpl-2.0
|
mozilla/spicedham,mozilla/spicedham
|
from pkg_resources import iter_entry_points
from spicedham.config import load_config
+ from spicedham.backend import load_backend
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
global _plugins
if _plugins == None:
+ # In order to use the plugins config and backend must be loaded.
+ load_backend()
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
_plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in _plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in _plugins:
value = plugin.classify(tag, classification_data)
# Skip _plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no _plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
|
Make sure to load_backend as part of load_plugins
|
## Code Before:
from pkg_resources import iter_entry_points
from spicedham.config import load_config
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
global _plugins
if _plugins == None:
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
_plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in _plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in _plugins:
value = plugin.classify(tag, classification_data)
# Skip _plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no _plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
## Instruction:
Make sure to load_backend as part of load_plugins
## Code After:
from pkg_resources import iter_entry_points
from spicedham.config import load_config
from spicedham.backend import load_backend
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
global _plugins
if _plugins == None:
# In order to use the plugins config and backend must be loaded.
load_backend()
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
_plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in _plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in _plugins:
value = plugin.classify(tag, classification_data)
# Skip _plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no _plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
|
# ... existing code ...
from spicedham.config import load_config
from spicedham.backend import load_backend
# ... modified code ...
if _plugins == None:
# In order to use the plugins config and backend must be loaded.
load_backend()
load_config()
# ... rest of the code ...
|
f59852e0db6941ce0862545f552a2bc17081086a
|
schedule/tests/test_templatetags.py
|
schedule/tests/test_templatetags.py
|
import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
|
import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
|
Update unit test to use escaped ampersands in comparision.
|
Update unit test to use escaped ampersands in comparision.
|
Python
|
bsd-3-clause
|
Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-scheduler,nwaxiomatic/django-scheduler,mbrondani/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,nwaxiomatic/django-scheduler,sprightco/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,erezlife/django-scheduler,GrahamDigital/django-scheduler,llazzaro/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,mbrondani/django-scheduler,rowbot-dev/django-scheduler
|
import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
- self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
+ self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
+
|
Update unit test to use escaped ampersands in comparision.
|
## Code Before:
import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
## Instruction:
Update unit test to use escaped ampersands in comparision.
## Code After:
import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
|
...
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
...
|
25133d90fe267dba522c9b87eb0bd614ae8556dd
|
web_433Mhz/views.py
|
web_433Mhz/views.py
|
from web_433Mhz import app
from flask import render_template
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
|
from web_433Mhz import app
from flask import render_template, jsonify
import subprocess
import os
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/api/get_code', methods=['GET'])
def get_code():
proc = subprocess.Popen(os.path.abspath('../433Mhz'),\
stdout=subprocess.PIPE)
code = proc.communicate()[0].decode('utf-8') # Grab the stdout
return jsonify({'code': code})
|
Add api call to open binary and grab stdout
|
Add api call to open binary and grab stdout
|
Python
|
agpl-3.0
|
tuxxy/433Mhz_web,tuxxy/433Mhz_web,tuxxy/433Mhz_web,tuxxy/433Mhz_web
|
from web_433Mhz import app
- from flask import render_template
+ from flask import render_template, jsonify
+
+ import subprocess
+ import os
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
+ @app.route('/api/get_code', methods=['GET'])
+ def get_code():
+ proc = subprocess.Popen(os.path.abspath('../433Mhz'),\
+ stdout=subprocess.PIPE)
+ code = proc.communicate()[0].decode('utf-8') # Grab the stdout
+
+ return jsonify({'code': code})
+
|
Add api call to open binary and grab stdout
|
## Code Before:
from web_433Mhz import app
from flask import render_template
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
## Instruction:
Add api call to open binary and grab stdout
## Code After:
from web_433Mhz import app
from flask import render_template, jsonify
import subprocess
import os
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/api/get_code', methods=['GET'])
def get_code():
proc = subprocess.Popen(os.path.abspath('../433Mhz'),\
stdout=subprocess.PIPE)
code = proc.communicate()[0].decode('utf-8') # Grab the stdout
return jsonify({'code': code})
|
// ... existing code ...
from web_433Mhz import app
from flask import render_template, jsonify
import subprocess
import os
// ... modified code ...
return render_template('index.html')
@app.route('/api/get_code', methods=['GET'])
def get_code():
proc = subprocess.Popen(os.path.abspath('../433Mhz'),\
stdout=subprocess.PIPE)
code = proc.communicate()[0].decode('utf-8') # Grab the stdout
return jsonify({'code': code})
// ... rest of the code ...
|
5b892de6093de62615e327a805948b76ce806cb4
|
protoplot-test/test_options_resolving.py
|
protoplot-test/test_options_resolving.py
|
import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
class Series(Item):
pass
Series.options.register("color", True)
Series.options.register("lineWidth", False)
Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testOptionsResolving(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
# class Series(Item):
# pass
#
# Series.options.register("color", True)
# Series.options.register("lineWidth", False)
# Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testOptionsResolving(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
Disable code made for old engine model
|
Disable code made for old engine model
|
Python
|
agpl-3.0
|
deffi/protoplot
|
import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
- class Series(Item):
+ # class Series(Item):
- pass
+ # pass
-
+ #
- Series.options.register("color", True)
+ # Series.options.register("color", True)
- Series.options.register("lineWidth", False)
+ # Series.options.register("lineWidth", False)
- Series.options.register("lineStyle", False)
+ # Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testOptionsResolving(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
Disable code made for old engine model
|
## Code Before:
import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
class Series(Item):
pass
Series.options.register("color", True)
Series.options.register("lineWidth", False)
Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testOptionsResolving(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
## Instruction:
Disable code made for old engine model
## Code After:
import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
# class Series(Item):
# pass
#
# Series.options.register("color", True)
# Series.options.register("lineWidth", False)
# Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testOptionsResolving(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
// ... existing code ...
# class Series(Item):
# pass
#
# Series.options.register("color", True)
# Series.options.register("lineWidth", False)
# Series.options.register("lineStyle", False)
// ... rest of the code ...
|
25f26842b8371b13b3fc9f4abf12dfba0b0408bc
|
shapely/tests/__init__.py
|
shapely/tests/__init__.py
|
from test_doctests import test_suite
|
from unittest import TestSuite
import test_doctests, test_prepared
def test_suite():
suite = TestSuite()
suite.addTest(test_doctests.test_suite())
suite.addTest(test_prepared.test_suite())
return suite
|
Integrate tests of prepared geoms into main test suite.
|
Integrate tests of prepared geoms into main test suite.
git-svn-id: 1a8067f95329a7fca9bad502d13a880b95ac544b@1508 b426a367-1105-0410-b9ff-cdf4ab011145
|
Python
|
bsd-3-clause
|
mindw/shapely,mindw/shapely,mouadino/Shapely,mouadino/Shapely,abali96/Shapely,jdmcbr/Shapely,abali96/Shapely,jdmcbr/Shapely
|
- from test_doctests import test_suite
+ from unittest import TestSuite
+ import test_doctests, test_prepared
+
+ def test_suite():
+ suite = TestSuite()
+ suite.addTest(test_doctests.test_suite())
+ suite.addTest(test_prepared.test_suite())
+ return suite
+
+
|
Integrate tests of prepared geoms into main test suite.
|
## Code Before:
from test_doctests import test_suite
## Instruction:
Integrate tests of prepared geoms into main test suite.
## Code After:
from unittest import TestSuite
import test_doctests, test_prepared
def test_suite():
suite = TestSuite()
suite.addTest(test_doctests.test_suite())
suite.addTest(test_prepared.test_suite())
return suite
|
// ... existing code ...
from unittest import TestSuite
import test_doctests, test_prepared
def test_suite():
suite = TestSuite()
suite.addTest(test_doctests.test_suite())
suite.addTest(test_prepared.test_suite())
return suite
// ... rest of the code ...
|
f56ed1c14b87e4d28e8e853cf64d91cf756576d1
|
dashboard/tasks.py
|
dashboard/tasks.py
|
import json
import requests
from bitcoinmonitor.celeryconfig import app
from channels import Group
app.conf.beat_schedule = {
'add-every-30-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 6.0,
'args': ("dale",)
},
}
@app.task
def get_bitcoin_price(arg):
last_price = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=USDT-BTC").json().get("result").get("Last")
Group('btc-price').send({'text': json.dumps({
'last_price': last_price
})})
|
import json
from bitcoinmonitor.celeryconfig import app
from channels import Group
from .helpers import get_coin_price
app.conf.beat_schedule = {
'get-bitcoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 5.0,
},
'get-litecoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_litcoin_price',
'schedule': 5.0,
},
}
@app.task
def get_bitcoin_price():
data = get_coin_price('BTC')
Group('btc-price').send({'text': data})
@app.task
def get_litcoin_price():
data = get_coin_price('LTC')
Group('ltc-price').send({'text': data})
|
Create another task to get the litecoin price
|
Create another task to get the litecoin price
|
Python
|
mit
|
alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor
|
import json
- import requests
from bitcoinmonitor.celeryconfig import app
from channels import Group
+ from .helpers import get_coin_price
app.conf.beat_schedule = {
- 'add-every-30-seconds': {
+ 'get-bitcoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
- 'schedule': 6.0,
+ 'schedule': 5.0,
- 'args': ("dale",)
+ },
+ 'get-litecoin-price-every-five-seconds': {
+ 'task': 'dashboard.tasks.get_litcoin_price',
+ 'schedule': 5.0,
},
}
@app.task
- def get_bitcoin_price(arg):
+ def get_bitcoin_price():
+ data = get_coin_price('BTC')
- last_price = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=USDT-BTC").json().get("result").get("Last")
- Group('btc-price').send({'text': json.dumps({
- 'last_price': last_price
- })})
+ Group('btc-price').send({'text': data})
+
+
+ @app.task
+ def get_litcoin_price():
+ data = get_coin_price('LTC')
+
+ Group('ltc-price').send({'text': data})
+
|
Create another task to get the litecoin price
|
## Code Before:
import json
import requests
from bitcoinmonitor.celeryconfig import app
from channels import Group
app.conf.beat_schedule = {
'add-every-30-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 6.0,
'args': ("dale",)
},
}
@app.task
def get_bitcoin_price(arg):
last_price = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=USDT-BTC").json().get("result").get("Last")
Group('btc-price').send({'text': json.dumps({
'last_price': last_price
})})
## Instruction:
Create another task to get the litecoin price
## Code After:
import json
from bitcoinmonitor.celeryconfig import app
from channels import Group
from .helpers import get_coin_price
app.conf.beat_schedule = {
'get-bitcoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 5.0,
},
'get-litecoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_litcoin_price',
'schedule': 5.0,
},
}
@app.task
def get_bitcoin_price():
data = get_coin_price('BTC')
Group('btc-price').send({'text': data})
@app.task
def get_litcoin_price():
data = get_coin_price('LTC')
Group('ltc-price').send({'text': data})
|
...
import json
...
from channels import Group
from .helpers import get_coin_price
...
app.conf.beat_schedule = {
'get-bitcoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 5.0,
},
'get-litecoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_litcoin_price',
'schedule': 5.0,
},
...
@app.task
def get_bitcoin_price():
data = get_coin_price('BTC')
Group('btc-price').send({'text': data})
@app.task
def get_litcoin_price():
data = get_coin_price('LTC')
Group('ltc-price').send({'text': data})
...
|
e0e1b41c93fdb0c148638f6c2f33e3d47c3ec17b
|
slot/routes.py
|
slot/routes.py
|
from slot import basic_auth
from flask_login import login_required
from slot.main import app
from slot import controller as con
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_form():
return con.render_new_procedure_form()
@app.route('/sms', methods=['POST'])
@basic_auth.requires_auth
def receive_sms():
return con.receive_sms()
@app.route('/complete', methods=['POST'])
@login_required
def complete_procedure():
return con.complete_procedure()
|
from flask_login import login_required
from slot.main import app
from slot import controller as con
from slot import basic_auth
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_form():
return con.render_new_procedure_form()
@app.route('/sms', methods=['POST'])
@basic_auth.requires_auth
def receive_sms():
return con.receive_sms()
@app.route('/complete', methods=['POST'])
@login_required
def complete_procedure():
return con.complete_procedure()
|
Move import statement so that it was with other local imports
|
Move import statement so that it was with other local imports
|
Python
|
mit
|
nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT
|
- from slot import basic_auth
from flask_login import login_required
from slot.main import app
from slot import controller as con
+ from slot import basic_auth
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_form():
return con.render_new_procedure_form()
@app.route('/sms', methods=['POST'])
@basic_auth.requires_auth
def receive_sms():
return con.receive_sms()
@app.route('/complete', methods=['POST'])
@login_required
def complete_procedure():
return con.complete_procedure()
|
Move import statement so that it was with other local imports
|
## Code Before:
from slot import basic_auth
from flask_login import login_required
from slot.main import app
from slot import controller as con
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_form():
return con.render_new_procedure_form()
@app.route('/sms', methods=['POST'])
@basic_auth.requires_auth
def receive_sms():
return con.receive_sms()
@app.route('/complete', methods=['POST'])
@login_required
def complete_procedure():
return con.complete_procedure()
## Instruction:
Move import statement so that it was with other local imports
## Code After:
from flask_login import login_required
from slot.main import app
from slot import controller as con
from slot import basic_auth
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_form():
return con.render_new_procedure_form()
@app.route('/sms', methods=['POST'])
@basic_auth.requires_auth
def receive_sms():
return con.receive_sms()
@app.route('/complete', methods=['POST'])
@login_required
def complete_procedure():
return con.complete_procedure()
|
...
from flask_login import login_required
...
from slot import controller as con
from slot import basic_auth
...
|
3c0bc3c382b3abe693b3871ee0c3d40723cb8f28
|
comics/crawler/crawlers/bunny.py
|
comics/crawler/crawlers/bunny.py
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
rights = 'H. Davies, CC BY-NC-SA'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.parse_feed('http://www.bunny-comic.com/rss/bunny.xml')
for entry in self.feed.entries:
title = entry.title
pieces = entry.summary.split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
url = pieces[i + 1]
break
image_name = url.replace('http://bunny-comic.com/strips/', '')
if self.pub_date == self.string_to_date(image_name[:6], '%d%m%y'):
self.title = title
self.url = url
return
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
rights = 'H. Davies, CC BY-NC-SA'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.parse_feed('http://www.bunny-comic.com/rss/bunny.xml')
for entry in self.feed.entries:
title = entry.title
pieces = entry.summary.split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
url = pieces[i + 1]
break
image_name = url.replace('http://bunny-comic.com/strips/', '')
if (image_name[:6].isdigit()
and self.pub_date == self.string_to_date(
image_name[:6], '%d%m%y')):
self.title = title
self.url = url
return
|
Fix Bunny crawler crash on non-date image names
|
Fix Bunny crawler crash on non-date image names
|
Python
|
agpl-3.0
|
jodal/comics,klette/comics,datagutten/comics,datagutten/comics,klette/comics,klette/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
rights = 'H. Davies, CC BY-NC-SA'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.parse_feed('http://www.bunny-comic.com/rss/bunny.xml')
for entry in self.feed.entries:
title = entry.title
pieces = entry.summary.split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
url = pieces[i + 1]
break
image_name = url.replace('http://bunny-comic.com/strips/', '')
- if self.pub_date == self.string_to_date(image_name[:6], '%d%m%y'):
+ if (image_name[:6].isdigit()
+ and self.pub_date == self.string_to_date(
+ image_name[:6], '%d%m%y')):
self.title = title
self.url = url
return
|
Fix Bunny crawler crash on non-date image names
|
## Code Before:
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
rights = 'H. Davies, CC BY-NC-SA'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.parse_feed('http://www.bunny-comic.com/rss/bunny.xml')
for entry in self.feed.entries:
title = entry.title
pieces = entry.summary.split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
url = pieces[i + 1]
break
image_name = url.replace('http://bunny-comic.com/strips/', '')
if self.pub_date == self.string_to_date(image_name[:6], '%d%m%y'):
self.title = title
self.url = url
return
## Instruction:
Fix Bunny crawler crash on non-date image names
## Code After:
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
rights = 'H. Davies, CC BY-NC-SA'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.parse_feed('http://www.bunny-comic.com/rss/bunny.xml')
for entry in self.feed.entries:
title = entry.title
pieces = entry.summary.split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
url = pieces[i + 1]
break
image_name = url.replace('http://bunny-comic.com/strips/', '')
if (image_name[:6].isdigit()
and self.pub_date == self.string_to_date(
image_name[:6], '%d%m%y')):
self.title = title
self.url = url
return
|
# ... existing code ...
image_name = url.replace('http://bunny-comic.com/strips/', '')
if (image_name[:6].isdigit()
and self.pub_date == self.string_to_date(
image_name[:6], '%d%m%y')):
self.title = title
# ... rest of the code ...
|
cee60151acf606a4e22a92c51066b7fb720f35a3
|
application/models.py
|
application/models.py
|
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range (1,ll):
data = lines[i].split('\t')
year = data[0]
results.append(dict());
results[len(results)-1]["year"]=year;
results[len(results)-1]["userdata"]=list();
lw = len(data)
yeardata=dict()
for j in range(1,lw):
results[len(results)-1]["userdata"].append(dict())
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["user"]=names[j]
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["data"]=data[j]
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
|
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range(1,ll):
data = lines[i].split('\t')
ld = len(data)
for j in range (1,ld):
if(i==1):
results.append(dict())
results[j-1]["user"]=names[j].strip();
results[j-1]["userdata"]=list()
results[j-1]["userdata"].append(dict())
results[j-1]["userdata"][i-1]["year"]=data[0].strip()
results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
|
Update the API to make it more semantic.
|
Update the API to make it more semantic.
|
Python
|
mit
|
swvist/debmetrics,swvist/debmetrics
|
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
- for i in range (1,ll):
+ for i in range(1,ll):
- data = lines[i].split('\t')
+ data = lines[i].split('\t')
+ ld = len(data)
- year = data[0]
- results.append(dict());
- results[len(results)-1]["year"]=year;
- results[len(results)-1]["userdata"]=list();
- lw = len(data)
- yeardata=dict()
- for j in range(1,lw):
+ for j in range (1,ld):
+ if(i==1):
+ results.append(dict())
+ results[j-1]["user"]=names[j].strip();
+ results[j-1]["userdata"]=list()
- results[len(results)-1]["userdata"].append(dict())
+ results[j-1]["userdata"].append(dict())
- results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["user"]=names[j]
- results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["data"]=data[j]
+ results[j-1]["userdata"][i-1]["year"]=data[0].strip()
+ results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
-
|
Update the API to make it more semantic.
|
## Code Before:
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range (1,ll):
data = lines[i].split('\t')
year = data[0]
results.append(dict());
results[len(results)-1]["year"]=year;
results[len(results)-1]["userdata"]=list();
lw = len(data)
yeardata=dict()
for j in range(1,lw):
results[len(results)-1]["userdata"].append(dict())
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["user"]=names[j]
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["data"]=data[j]
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
## Instruction:
Update the API to make it more semantic.
## Code After:
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range(1,ll):
data = lines[i].split('\t')
ld = len(data)
for j in range (1,ld):
if(i==1):
results.append(dict())
results[j-1]["user"]=names[j].strip();
results[j-1]["userdata"]=list()
results[j-1]["userdata"].append(dict())
results[j-1]["userdata"][i-1]["year"]=data[0].strip()
results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
|
...
results = list()
for i in range(1,ll):
data = lines[i].split('\t')
ld = len(data)
for j in range (1,ld):
if(i==1):
results.append(dict())
results[j-1]["user"]=names[j].strip();
results[j-1]["userdata"]=list()
results[j-1]["userdata"].append(dict())
results[j-1]["userdata"][i-1]["year"]=data[0].strip()
results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
...
return metricresult
...
|
ab7c15b791f42f90fa41dfd0557172ce520933f8
|
LibCharm/IO/__init__.py
|
LibCharm/IO/__init__.py
|
try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
Load sequence from file in FASTA file_format
filename - Path and filename of input sequence file
"""
content = None
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
print('ERROR: {}'.format(e))
exit(1)
if content:
seq = content.seq
return seq
else:
return None
|
try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
Load sequence from file and returns sequence as Bio.Seq object
filename - String; Path and filename of input sequence file
file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta'
"""
content = None
try:
# assume sequence is DNA
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
# if this fails, try RNA instead
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
# if this fails, too, raise exception and exit with error code 1
print('ERROR: {}'.format(e))
exit(1)
# if some kind of data could be read, return the sequence object
if content:
seq = content.seq
return seq
# else return None
else:
return None
|
Prepare for tagging release 0.1: Add comments to LibCharm.IO
|
Prepare for tagging release 0.1: Add comments to LibCharm.IO
|
Python
|
mit
|
Athemis/charm
|
try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
- Load sequence from file in FASTA file_format
+ Load sequence from file and returns sequence as Bio.Seq object
- filename - Path and filename of input sequence file
+ filename - String; Path and filename of input sequence file
+ file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta'
"""
content = None
try:
+ # assume sequence is DNA
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
+ # if this fails, try RNA instead
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
+ # if this fails, too, raise exception and exit with error code 1
print('ERROR: {}'.format(e))
exit(1)
+ # if some kind of data could be read, return the sequence object
if content:
seq = content.seq
return seq
+ # else return None
else:
return None
|
Prepare for tagging release 0.1: Add comments to LibCharm.IO
|
## Code Before:
try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
Load sequence from file in FASTA file_format
filename - Path and filename of input sequence file
"""
content = None
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
print('ERROR: {}'.format(e))
exit(1)
if content:
seq = content.seq
return seq
else:
return None
## Instruction:
Prepare for tagging release 0.1: Add comments to LibCharm.IO
## Code After:
try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
Load sequence from file and returns sequence as Bio.Seq object
filename - String; Path and filename of input sequence file
file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta'
"""
content = None
try:
# assume sequence is DNA
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
# if this fails, try RNA instead
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
# if this fails, too, raise exception and exit with error code 1
print('ERROR: {}'.format(e))
exit(1)
# if some kind of data could be read, return the sequence object
if content:
seq = content.seq
return seq
# else return None
else:
return None
|
# ... existing code ...
"""
Load sequence from file and returns sequence as Bio.Seq object
filename - String; Path and filename of input sequence file
file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta'
"""
# ... modified code ...
try:
# assume sequence is DNA
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
...
except ValueError as e:
# if this fails, try RNA instead
print('ERROR: {}'.format(e))
...
except ValueError as e:
# if this fails, too, raise exception and exit with error code 1
print('ERROR: {}'.format(e))
...
# if some kind of data could be read, return the sequence object
if content:
...
return seq
# else return None
else:
# ... rest of the code ...
|
5d57c43ba7a01dc0f94ab41e4014484d1b78c1cb
|
django_polymorphic_auth/admin.py
|
django_polymorphic_auth/admin.py
|
from django.conf import settings
from django.contrib import admin
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
base_model = User
# base_form = forms.ProductAdminForm
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
|
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
base_fieldsets = (
('Meta', {
'classes': ('collapse', ),
'fields': ('last_login', )
}),
('Permissions', {
'fields': (
'is_active', 'is_staff', 'is_superuser', 'groups',
'user_permissions')
}),
)
base_form = UserChangeForm
base_model = User
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
|
Integrate `UserChangeForm` so we get nice password fields.
|
Integrate `UserChangeForm` so we get nice password fields.
|
Python
|
mit
|
whembed197923/django-polymorphic-auth,ixc/django-polymorphic-auth
|
from django.conf import settings
from django.contrib import admin
+ from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
+ base_fieldsets = (
+ ('Meta', {
+ 'classes': ('collapse', ),
+ 'fields': ('last_login', )
+ }),
+ ('Permissions', {
+ 'fields': (
+ 'is_active', 'is_staff', 'is_superuser', 'groups',
+ 'user_permissions')
+ }),
+ )
+ base_form = UserChangeForm
base_model = User
- # base_form = forms.ProductAdminForm
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
|
Integrate `UserChangeForm` so we get nice password fields.
|
## Code Before:
from django.conf import settings
from django.contrib import admin
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
base_model = User
# base_form = forms.ProductAdminForm
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
## Instruction:
Integrate `UserChangeForm` so we get nice password fields.
## Code After:
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
base_fieldsets = (
('Meta', {
'classes': ('collapse', ),
'fields': ('last_login', )
}),
('Permissions', {
'fields': (
'is_active', 'is_staff', 'is_superuser', 'groups',
'user_permissions')
}),
)
base_form = UserChangeForm
base_model = User
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
|
# ... existing code ...
from django.contrib import admin
from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
# ... modified code ...
class UserChildAdmin(PolymorphicChildModelAdmin):
base_fieldsets = (
('Meta', {
'classes': ('collapse', ),
'fields': ('last_login', )
}),
('Permissions', {
'fields': (
'is_active', 'is_staff', 'is_superuser', 'groups',
'user_permissions')
}),
)
base_form = UserChangeForm
base_model = User
# ... rest of the code ...
|
580868c63f61bb7f6576dc7b0029aa137e274a51
|
qnd/__init__.py
|
qnd/__init__.py
|
"""Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
|
"""Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
__all__ = ["add_flag", "add_required_flag", "FlagAdder", "def_run"]
|
Add __all__ variable to top level package
|
Add __all__ variable to top level package
|
Python
|
unlicense
|
raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd
|
"""Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
+ __all__ = ["add_flag", "add_required_flag", "FlagAdder", "def_run"]
+
|
Add __all__ variable to top level package
|
## Code Before:
"""Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
## Instruction:
Add __all__ variable to top level package
## Code After:
"""Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
__all__ = ["add_flag", "add_required_flag", "FlagAdder", "def_run"]
|
// ... existing code ...
from .run import def_run
__all__ = ["add_flag", "add_required_flag", "FlagAdder", "def_run"]
// ... rest of the code ...
|
5b3d26b6c9256f869d3bc08dfa00bf9b8de58f85
|
tests/test_cli_parse.py
|
tests/test_cli_parse.py
|
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.TemporaryDirectory() as d:
out_file = os.path.join(d, 'model_out.hdf5')
runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
|
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
|
Change from TemporaryDirectory to NamedTemporaryFile
|
Change from TemporaryDirectory to NamedTemporaryFile
|
Python
|
apache-2.0
|
Z2PackDev/TBmodels,Z2PackDev/TBmodels
|
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
- with tempfile.TemporaryDirectory() as d:
+ with tempfile.NamedTemporaryFile() as out_file:
- out_file = os.path.join(d, 'model_out.hdf5')
- runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
+ runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
- model_res = tbmodels.Model.from_hdf5_file(out_file)
+ model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
|
Change from TemporaryDirectory to NamedTemporaryFile
|
## Code Before:
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.TemporaryDirectory() as d:
out_file = os.path.join(d, 'model_out.hdf5')
runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
## Instruction:
Change from TemporaryDirectory to NamedTemporaryFile
## Code After:
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
|
# ... existing code ...
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
# ... rest of the code ...
|
f56d8b35aa7d1d2c06d5c98ef49696e829459042
|
log_request_id/tests.py
|
log_request_id/tests.py
|
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
|
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
def test_external_id_in_http_header(self):
with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
request = self.factory.get('/')
request.META['REQUEST_ID_HEADER'] = 'some_request_id'
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertEqual(request.id, 'some_request_id')
test_view(request)
self.assertTrue('some_request_id' in self.handler.messages[0])
|
Add test for externally-generated request IDs
|
Add test for externally-generated request IDs
|
Python
|
bsd-2-clause
|
dabapps/django-log-request-id
|
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
+ self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
+ def test_external_id_in_http_header(self):
+ with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
+ request = self.factory.get('/')
+ request.META['REQUEST_ID_HEADER'] = 'some_request_id'
+ middleware = RequestIDMiddleware()
+ middleware.process_request(request)
+ self.assertEqual(request.id, 'some_request_id')
+ test_view(request)
+ self.assertTrue('some_request_id' in self.handler.messages[0])
+
|
Add test for externally-generated request IDs
|
## Code Before:
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
## Instruction:
Add test for externally-generated request IDs
## Code After:
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
def test_external_id_in_http_header(self):
with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
request = self.factory.get('/')
request.META['REQUEST_ID_HEADER'] = 'some_request_id'
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertEqual(request.id, 'some_request_id')
test_view(request)
self.assertTrue('some_request_id' in self.handler.messages[0])
|
...
self.handler = logging.getLogger('testproject').handlers[0]
self.handler.messages = []
...
self.assertTrue(request.id in self.handler.messages[0])
def test_external_id_in_http_header(self):
with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
request = self.factory.get('/')
request.META['REQUEST_ID_HEADER'] = 'some_request_id'
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertEqual(request.id, 'some_request_id')
test_view(request)
self.assertTrue('some_request_id' in self.handler.messages[0])
...
|
d57844d1d6b2172fe196db4945517a5b3a68d343
|
satchless/process/__init__.py
|
satchless/process/__init__.py
|
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return not self.get_next_step()
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
|
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
|
Check explicit that next step is None
|
Check explicit that next step is None
|
Python
|
bsd-3-clause
|
taedori81/satchless
|
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
- return not self.get_next_step()
+ return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
|
Check explicit that next step is None
|
## Code Before:
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return not self.get_next_step()
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
## Instruction:
Check explicit that next step is None
## Code After:
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
|
// ... existing code ...
def is_complete(self):
return self.get_next_step() is None
// ... rest of the code ...
|
21ab4cb4bb50acd7598b09ebceec20c7302061da
|
scikits/learn/datasets/tests/test_20news.py
|
scikits/learn/datasets/tests/test_20news.py
|
"""Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.tools import assert_true
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=False,
shuffle=False)
except IOError:
raise SkipTest("Download 20 newsgroups to run this test")
# Extract a reduced dataset
data2cats = datasets.fetch_20newsgroups(subset='all',
categories=data.target_names[-1:-3:-1],
shuffle=False)
# Check that the ordering of the target_names is the same
# as the ordering in the full dataset
assert_equal(data2cats.target_names,
data.target_names[-2:])
# Assert that we have only 0 and 1 as labels
assert_equal(np.unique(data2cats.target).tolist(), [0, 1])
# Check that the first entry of the reduced dataset corresponds to
# the first entry of the corresponding category in the full dataset
entry1 = data2cats.data[0]
category = data2cats.target_names[data2cats.target[0]]
label = data.target_names.index(category)
entry2 = data.data[np.where(data.target == label)[0][0]]
assert_equal(entry1, entry2)
# check that the filenames are available too
assert_true(data.filenames[0].endswith(
"20news_home/20news-bydate-test/talk.politics.mideast/76560"))
|
"""Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=False,
shuffle=False)
except IOError:
raise SkipTest("Download 20 newsgroups to run this test")
# Extract a reduced dataset
data2cats = datasets.fetch_20newsgroups(subset='all',
categories=data.target_names[-1:-3:-1],
shuffle=False)
# Check that the ordering of the target_names is the same
# as the ordering in the full dataset
assert_equal(data2cats.target_names,
data.target_names[-2:])
# Assert that we have only 0 and 1 as labels
assert_equal(np.unique(data2cats.target).tolist(), [0, 1])
# Check that the first entry of the reduced dataset corresponds to
# the first entry of the corresponding category in the full dataset
entry1 = data2cats.data[0]
category = data2cats.target_names[data2cats.target[0]]
label = data.target_names.index(category)
entry2 = data.data[np.where(data.target == label)[0][0]]
assert_equal(entry1, entry2)
|
Fix a bug introduced in rebasing
|
BUG: Fix a bug introduced in rebasing
|
Python
|
bsd-3-clause
|
krez13/scikit-learn,ChanderG/scikit-learn,466152112/scikit-learn,ChanChiChoi/scikit-learn,belltailjp/scikit-learn,tdhopper/scikit-learn,krez13/scikit-learn,yyjiang/scikit-learn,schets/scikit-learn,TomDLT/scikit-learn,xubenben/scikit-learn,MohammedWasim/scikit-learn,0x0all/scikit-learn,mblondel/scikit-learn,aewhatley/scikit-learn,spallavolu/scikit-learn,abimannans/scikit-learn,yask123/scikit-learn,henrykironde/scikit-learn,sergeyf/scikit-learn,moutai/scikit-learn,amueller/scikit-learn,ankurankan/scikit-learn,kmike/scikit-learn,marcocaccin/scikit-learn,bhargav/scikit-learn,vshtanko/scikit-learn,ahoyosid/scikit-learn,lbishal/scikit-learn,mattilyra/scikit-learn,anntzer/scikit-learn,jseabold/scikit-learn,AnasGhrab/scikit-learn,glouppe/scikit-learn,pypot/scikit-learn,pompiduskus/scikit-learn,olologin/scikit-learn,aetilley/scikit-learn,mojoboss/scikit-learn,btabibian/scikit-learn,PrashntS/scikit-learn,thilbern/scikit-learn,macks22/scikit-learn,ishanic/scikit-learn,PatrickOReilly/scikit-learn,toastedcornflakes/scikit-learn,vshtanko/scikit-learn,ngoix/OCRF,kagayakidan/scikit-learn,russel1237/scikit-learn,mfjb/scikit-learn,sergeyf/scikit-learn,voxlol/scikit-learn,liberatorqjw/scikit-learn,ogrisel/scikit-learn,shenzebang/scikit-learn,shikhardb/scikit-learn,shahankhatch/scikit-learn,UNR-AERIAL/scikit-learn,heli522/scikit-learn,sumspr/scikit-learn,tdhopper/scikit-learn,hlin117/scikit-learn,frank-tancf/scikit-learn,mugizico/scikit-learn,petosegan/scikit-learn,wlamond/scikit-learn,stylianos-kampakis/scikit-learn,pythonvietnam/scikit-learn,B3AU/waveTree,joshloyal/scikit-learn,manashmndl/scikit-learn,hrjn/scikit-learn,thientu/scikit-learn,zihua/scikit-learn,aflaxman/scikit-learn,huobaowangxi/scikit-learn,dhruv13J/scikit-learn,nrhine1/scikit-learn,btabibian/scikit-learn,spallavolu/scikit-learn,glemaitre/scikit-learn,trankmichael/scikit-learn,zhenv5/scikit-learn,nomadcube/scikit-learn,xzh86/scikit-learn,henridwyer/scikit-learn,altairpearl/scikit-learn,LiaoPan/scikit-learn,thilbern/scikit-learn,DSLituiev/scikit-learn,kjung/scikit-learn,lucidfrontier45/scikit-learn,etkirsch/scikit-learn,h2educ/scikit-learn,rvraghav93/scikit-learn,yunfeilu/scikit-learn,clemkoa/scikit-learn,manhhomienbienthuy/scikit-learn,Srisai85/scikit-learn,AlexRobson/scikit-learn,yask123/scikit-learn,AIML/scikit-learn,ndingwall/scikit-learn,jmetzen/scikit-learn,r-mart/scikit-learn,shahankhatch/scikit-learn,shyamalschandra/scikit-learn,ilyes14/scikit-learn,toastedcornflakes/scikit-learn,vigilv/scikit-learn,poryfly/scikit-learn,mojoboss/scikit-learn,fbagirov/scikit-learn,lbishal/scikit-learn,IndraVikas/scikit-learn,arahuja/scikit-learn,anurag313/scikit-learn,mblondel/scikit-learn,tawsifkhan/scikit-learn,chrisburr/scikit-learn,tosolveit/scikit-learn,larsmans/scikit-learn,jorik041/scikit-learn,Vimos/scikit-learn,jorge2703/scikit-learn,moutai/scikit-learn,alexeyum/scikit-learn,toastedcornflakes/scikit-learn,schets/scikit-learn,nhejazi/scikit-learn,billy-inn/scikit-learn,evgchz/scikit-learn,samuel1208/scikit-learn,jmschrei/scikit-learn,procoder317/scikit-learn,manhhomienbienthuy/scikit-learn,huobaowangxi/scikit-learn,icdishb/scikit-learn,bnaul/scikit-learn,voxlol/scikit-learn,depet/scikit-learn,anirudhjayaraman/scikit-learn,samzhang111/scikit-learn,rahuldhote/scikit-learn,Nyker510/scikit-learn,liangz0707/scikit-learn,iismd17/scikit-learn,lucidfrontier45/scikit-learn,lenovor/scikit-learn,heli522/scikit-learn,frank-tancf/scikit-learn,aewhatley/scikit-learn,ishanic/scikit-learn,robbymeals/scikit-learn,JsNoNo/scikit-learn,jaidevd/scikit-learn,waterponey/scikit-learn,PatrickOReilly/scikit-learn,voxlol/scikit-learn,yanlend/scikit-learn,kagayakidan/scikit-learn,wzbozon/scikit-learn,jlegendary/scikit-learn,stylianos-kampakis/scikit-learn,abimannans/scikit-learn,Akshay0724/scikit-learn,sumspr/scikit-learn,loli/semisupervisedforests,IshankGulati/scikit-learn,ElDeveloper/scikit-learn,jorik041/scikit-learn,mehdidc/scikit-learn,JPFrancoia/scikit-learn,scikit-learn/scikit-learn,vshtanko/scikit-learn,trungnt13/scikit-learn,mjgrav2001/scikit-learn,jayflo/scikit-learn,Nyker510/scikit-learn,q1ang/scikit-learn,Djabbz/scikit-learn,zorojean/scikit-learn,tomlof/scikit-learn,icdishb/scikit-learn,jlegendary/scikit-learn,cainiaocome/scikit-learn,eickenberg/scikit-learn,andrewnc/scikit-learn,RPGOne/scikit-learn,shikhardb/scikit-learn,wlamond/scikit-learn,sanketloke/scikit-learn,marcocaccin/scikit-learn,JosmanPS/scikit-learn,jmetzen/scikit-learn,UNR-AERIAL/scikit-learn,jkarnows/scikit-learn,mwv/scikit-learn,iismd17/scikit-learn,nvoron23/scikit-learn,jblackburne/scikit-learn,xubenben/scikit-learn,gclenaghan/scikit-learn,andrewnc/scikit-learn,shahankhatch/scikit-learn,sgenoud/scikit-learn,liberatorqjw/scikit-learn,wanggang3333/scikit-learn,jm-begon/scikit-learn,ephes/scikit-learn,alexsavio/scikit-learn,nesterione/scikit-learn,scikit-learn/scikit-learn,0x0all/scikit-learn,rexshihaoren/scikit-learn,kagayakidan/scikit-learn,jorge2703/scikit-learn,Obus/scikit-learn,eg-zhang/scikit-learn,shyamalschandra/scikit-learn,samuel1208/scikit-learn,luo66/scikit-learn,jblackburne/scikit-learn,murali-munna/scikit-learn,rohanp/scikit-learn,JosmanPS/scikit-learn,pypot/scikit-learn,alvarofierroclavero/scikit-learn,nesterione/scikit-learn,plissonf/scikit-learn,jpautom/scikit-learn,tmhm/scikit-learn,zihua/scikit-learn,thientu/scikit-learn,zuku1985/scikit-learn,ilo10/scikit-learn,shahankhatch/scikit-learn,ClimbsRocks/scikit-learn,mjudsp/Tsallis,f3r/scikit-learn,mhdella/scikit-learn,RachitKansal/scikit-learn,DSLituiev/scikit-learn,arabenjamin/scikit-learn,DonBeo/scikit-learn,gclenaghan/scikit-learn,stylianos-kampakis/scikit-learn,PrashntS/scikit-learn,samuel1208/scikit-learn,rahuldhote/scikit-learn,0x0all/scikit-learn,zuku1985/scikit-learn,simon-pepin/scikit-learn,ycaihua/scikit-learn,sgenoud/scikit-learn,mikebenfield/scikit-learn,JPFrancoia/scikit-learn,kylerbrown/scikit-learn,Garrett-R/scikit-learn,amueller/scikit-learn,chrisburr/scikit-learn,loli/semisupervisedforests,glemaitre/scikit-learn,mojoboss/scikit-learn,kashif/scikit-learn,hainm/scikit-learn,jlegendary/scikit-learn,sonnyhu/scikit-learn,Achuth17/scikit-learn,xuewei4d/scikit-learn,qifeigit/scikit-learn,akionakamura/scikit-learn,eickenberg/scikit-learn,wazeerzulfikar/scikit-learn,zorroblue/scikit-learn,h2educ/scikit-learn,mhdella/scikit-learn,Vimos/scikit-learn,billy-inn/scikit-learn,JeanKossaifi/scikit-learn,abhishekgahlot/scikit-learn,maheshakya/scikit-learn,mayblue9/scikit-learn,ycaihua/scikit-learn,yyjiang/scikit-learn,xyguo/scikit-learn,fabianp/scikit-learn,vermouthmjl/scikit-learn,arabenjamin/scikit-learn,dingocuster/scikit-learn,abhishekkrthakur/scikit-learn,phdowling/scikit-learn,ZENGXH/scikit-learn,manashmndl/scikit-learn,maheshakya/scikit-learn,dhruv13J/scikit-learn,depet/scikit-learn,hsiaoyi0504/scikit-learn,yunfeilu/scikit-learn,cwu2011/scikit-learn,LiaoPan/scikit-learn,dsquareindia/scikit-learn,betatim/scikit-learn,pratapvardhan/scikit-learn,akionakamura/scikit-learn,bhargav/scikit-learn,NelisVerhoef/scikit-learn,harshaneelhg/scikit-learn,jjx02230808/project0223,ky822/scikit-learn,jjx02230808/project0223,ZENGXH/scikit-learn,stylianos-kampakis/scikit-learn,moutai/scikit-learn,kaichogami/scikit-learn,marcocaccin/scikit-learn,ycaihua/scikit-learn,altairpearl/scikit-learn,mlyundin/scikit-learn,joernhees/scikit-learn,terkkila/scikit-learn,LohithBlaze/scikit-learn,PatrickChrist/scikit-learn,joernhees/scikit-learn,kagayakidan/scikit-learn,shangwuhencc/scikit-learn,wazeerzulfikar/scikit-learn,pianomania/scikit-learn,Garrett-R/scikit-learn,mikebenfield/scikit-learn,fengzhyuan/scikit-learn,herilalaina/scikit-learn,jblackburne/scikit-learn,akionakamura/scikit-learn,treycausey/scikit-learn,arahuja/scikit-learn,petosegan/scikit-learn,ChanderG/scikit-learn,mrshu/scikit-learn,thilbern/scikit-learn,Lawrence-Liu/scikit-learn,dingocuster/scikit-learn,pianomania/scikit-learn,xyguo/scikit-learn,robbymeals/scikit-learn,PrashntS/scikit-learn,imaculate/scikit-learn,alvarofierroclavero/scikit-learn,huzq/scikit-learn,3manuek/scikit-learn,mattgiguere/scikit-learn,Lawrence-Liu/scikit-learn,rrohan/scikit-learn,cauchycui/scikit-learn,jakirkham/scikit-learn,h2educ/scikit-learn,Achuth17/scikit-learn,evgchz/scikit-learn,russel1237/scikit-learn,CforED/Machine-Learning,procoder317/scikit-learn,dsquareindia/scikit-learn,OshynSong/scikit-learn,victorbergelin/scikit-learn,ChanderG/scikit-learn,heli522/scikit-learn,mattilyra/scikit-learn,mwv/scikit-learn,Garrett-R/scikit-learn,zorroblue/scikit-learn,rsivapr/scikit-learn,rvraghav93/scikit-learn,mayblue9/scikit-learn,ZENGXH/scikit-learn,IssamLaradji/scikit-learn,waterponey/scikit-learn,wzbozon/scikit-learn,scikit-learn/scikit-learn,tmhm/scikit-learn,deepesch/scikit-learn,mhue/scikit-learn,theoryno3/scikit-learn,jaidevd/scikit-learn,robbymeals/scikit-learn,akionakamura/scikit-learn,themrmax/scikit-learn,RPGOne/scikit-learn,Aasmi/scikit-learn,ilo10/scikit-learn,pratapvardhan/scikit-learn,TomDLT/scikit-learn,espg/scikit-learn,terkkila/scikit-learn,cainiaocome/scikit-learn,alexsavio/scikit-learn,anntzer/scikit-learn,rexshihaoren/scikit-learn,vybstat/scikit-learn,h2educ/scikit-learn,xwolf12/scikit-learn,idlead/scikit-learn,lazywei/scikit-learn,ephes/scikit-learn,nmayorov/scikit-learn,roxyboy/scikit-learn,JsNoNo/scikit-learn,hsiaoyi0504/scikit-learn,LohithBlaze/scikit-learn,rohanp/scikit-learn,plissonf/scikit-learn,xwolf12/scikit-learn,khkaminska/scikit-learn,jkarnows/scikit-learn,Adai0808/scikit-learn,jm-begon/scikit-learn,kevin-intel/scikit-learn,IshankGulati/scikit-learn,glennq/scikit-learn,giorgiop/scikit-learn,michigraber/scikit-learn,rrohan/scikit-learn,Djabbz/scikit-learn,lbishal/scikit-learn,arjoly/scikit-learn,jayflo/scikit-learn,kylerbrown/scikit-learn,sergeyf/scikit-learn,rahuldhote/scikit-learn,rrohan/scikit-learn,wanggang3333/scikit-learn,mehdidc/scikit-learn,florian-f/sklearn,ogrisel/scikit-learn,PatrickOReilly/scikit-learn,hitszxp/scikit-learn,macks22/scikit-learn,PatrickChrist/scikit-learn,phdowling/scikit-learn,mattgiguere/scikit-learn,huzq/scikit-learn,IndraVikas/scikit-learn,vshtanko/scikit-learn,lin-credible/scikit-learn,nmayorov/scikit-learn,elkingtonmcb/scikit-learn,thilbern/scikit-learn,PatrickOReilly/scikit-learn,yunfeilu/scikit-learn,RomainBrault/scikit-learn,nmayorov/scikit-learn,ilo10/scikit-learn,equialgo/scikit-learn,ashhher3/scikit-learn,Sentient07/scikit-learn,gclenaghan/scikit-learn,fyffyt/scikit-learn,anirudhjayaraman/scikit-learn,PatrickChrist/scikit-learn,clemkoa/scikit-learn,jm-begon/scikit-learn,lesteve/scikit-learn,tosolveit/scikit-learn,untom/scikit-learn,DonBeo/scikit-learn,lesteve/scikit-learn,plissonf/scikit-learn,NelisVerhoef/scikit-learn,thientu/scikit-learn,vinayak-mehta/scikit-learn,vortex-ape/scikit-learn,glouppe/scikit-learn,simon-pepin/scikit-learn,jmschrei/scikit-learn,hainm/scikit-learn,AlexRobson/scikit-learn,qifeigit/scikit-learn,nesterione/scikit-learn,aminert/scikit-learn,alexsavio/scikit-learn,macks22/scikit-learn,arjoly/scikit-learn,zorojean/scikit-learn,cauchycui/scikit-learn,manhhomienbienthuy/scikit-learn,OshynSong/scikit-learn,mattgiguere/scikit-learn,Aasmi/scikit-learn,djgagne/scikit-learn,Jimmy-Morzaria/scikit-learn,ogrisel/scikit-learn,kashif/scikit-learn,vybstat/scikit-learn,fyffyt/scikit-learn,IndraVikas/scikit-learn,jm-begon/scikit-learn,f3r/scikit-learn,kjung/scikit-learn,YinongLong/scikit-learn,jpautom/scikit-learn,djgagne/scikit-learn,rahul-c1/scikit-learn,dingocuster/scikit-learn,pianomania/scikit-learn,aabadie/scikit-learn,jakobworldpeace/scikit-learn,mrshu/scikit-learn,tmhm/scikit-learn,AnasGhrab/scikit-learn,Obus/scikit-learn,appapantula/scikit-learn,anirudhjayaraman/scikit-learn,lazywei/scikit-learn,abhishekgahlot/scikit-learn,icdishb/scikit-learn,mjgrav2001/scikit-learn,PrashntS/scikit-learn,moutai/scikit-learn,sarahgrogan/scikit-learn,xuewei4d/scikit-learn,massmutual/scikit-learn,hsuantien/scikit-learn,vibhorag/scikit-learn,pratapvardhan/scikit-learn,vigilv/scikit-learn,chrsrds/scikit-learn,fredhusser/scikit-learn,ilyes14/scikit-learn,ChanderG/scikit-learn,0asa/scikit-learn,vybstat/scikit-learn,murali-munna/scikit-learn,cwu2011/scikit-learn,chrsrds/scikit-learn,devanshdalal/scikit-learn,anirudhjayaraman/scikit-learn,ky822/scikit-learn,RayMick/scikit-learn,tomlof/scikit-learn,etkirsch/scikit-learn,r-mart/scikit-learn,potash/scikit-learn,Clyde-fare/scikit-learn,manashmndl/scikit-learn,equialgo/scikit-learn,maheshakya/scikit-learn,saiwing-yeung/scikit-learn,MechCoder/scikit-learn,HolgerPeters/scikit-learn,JPFrancoia/scikit-learn,cainiaocome/scikit-learn,vinayak-mehta/scikit-learn,evgchz/scikit-learn,rohanp/scikit-learn,NunoEdgarGub1/scikit-learn,russel1237/scikit-learn,Akshay0724/scikit-learn,cl4rke/scikit-learn,vortex-ape/scikit-learn,yask123/scikit-learn,betatim/scikit-learn,xiaoxiamii/scikit-learn,theoryno3/scikit-learn,espg/scikit-learn,MohammedWasim/scikit-learn,ZenDevelopmentSystems/scikit-learn,Fireblend/scikit-learn,Srisai85/scikit-learn,RayMick/scikit-learn,terkkila/scikit-learn,lesteve/scikit-learn,sarahgrogan/scikit-learn,0asa/scikit-learn,elkingtonmcb/scikit-learn,samzhang111/scikit-learn,appapantula/scikit-learn,vinayak-mehta/scikit-learn,hainm/scikit-learn,sgenoud/scikit-learn,aflaxman/scikit-learn,mehdidc/scikit-learn,ankurankan/scikit-learn,luo66/scikit-learn,rsivapr/scikit-learn,themrmax/scikit-learn,zaxtax/scikit-learn,vigilv/scikit-learn,466152112/scikit-learn,abimannans/scikit-learn,Akshay0724/scikit-learn,shusenl/scikit-learn,sergeyf/scikit-learn,roxyboy/scikit-learn,jaidevd/scikit-learn,CVML/scikit-learn,belltailjp/scikit-learn,fbagirov/scikit-learn,cl4rke/scikit-learn,fzalkow/scikit-learn,NelisVerhoef/scikit-learn,ishanic/scikit-learn,trankmichael/scikit-learn,hdmetor/scikit-learn,massmutual/scikit-learn,LohithBlaze/scikit-learn,etkirsch/scikit-learn,rsivapr/scikit-learn,fredhusser/scikit-learn,rajat1994/scikit-learn,pypot/scikit-learn,gclenaghan/scikit-learn,f3r/scikit-learn,pythonvietnam/scikit-learn,hdmetor/scikit-learn,abhishekgahlot/scikit-learn,tawsifkhan/scikit-learn,fredhusser/scikit-learn,ishanic/scikit-learn,harshaneelhg/scikit-learn,wazeerzulfikar/scikit-learn,trankmichael/scikit-learn,alexsavio/scikit-learn,Fireblend/scikit-learn,treycausey/scikit-learn,idlead/scikit-learn,NelisVerhoef/scikit-learn,AlexanderFabisch/scikit-learn,jzt5132/scikit-learn,nrhine1/scikit-learn,mhue/scikit-learn,anurag313/scikit-learn,victorbergelin/scikit-learn,zhenv5/scikit-learn,eg-zhang/scikit-learn,xyguo/scikit-learn,walterreade/scikit-learn,cybernet14/scikit-learn,pv/scikit-learn,Sentient07/scikit-learn,smartscheduling/scikit-learn-categorical-tree,trungnt13/scikit-learn,JeanKossaifi/scikit-learn,DSLituiev/scikit-learn,HolgerPeters/scikit-learn,yonglehou/scikit-learn,adamgreenhall/scikit-learn,nvoron23/scikit-learn,andaag/scikit-learn,larsmans/scikit-learn,hlin117/scikit-learn,qifeigit/scikit-learn,huobaowangxi/scikit-learn,larsmans/scikit-learn,sonnyhu/scikit-learn,ankurankan/scikit-learn,elkingtonmcb/scikit-learn,Clyde-fare/scikit-learn,3manuek/scikit-learn,AlexRobson/scikit-learn,eickenberg/scikit-learn,arahuja/scikit-learn,gotomypc/scikit-learn,murali-munna/scikit-learn,abhishekgahlot/scikit-learn,cwu2011/scikit-learn,lesteve/scikit-learn,ClimbsRocks/scikit-learn,fengzhyuan/scikit-learn,nelson-liu/scikit-learn,jorik041/scikit-learn,Srisai85/scikit-learn,ChanChiChoi/scikit-learn,siutanwong/scikit-learn,0asa/scikit-learn,MartinSavc/scikit-learn,beepee14/scikit-learn,glennq/scikit-learn,shusenl/scikit-learn,tawsifkhan/scikit-learn,equialgo/scikit-learn,NunoEdgarGub1/scikit-learn,macks22/scikit-learn,mwv/scikit-learn,madjelan/scikit-learn,Aasmi/scikit-learn,ominux/scikit-learn,ahoyosid/scikit-learn,andaag/scikit-learn,shenzebang/scikit-learn,yonglehou/scikit-learn,xubenben/scikit-learn,fengzhyuan/scikit-learn,treycausey/scikit-learn,glouppe/scikit-learn,jereze/scikit-learn,sonnyhu/scikit-learn,arjoly/scikit-learn,glennq/scikit-learn,untom/scikit-learn,AlexandreAbraham/scikit-learn,phdowling/scikit-learn,elkingtonmcb/scikit-learn,giorgiop/scikit-learn,jseabold/scikit-learn,yonglehou/scikit-learn,ningchi/scikit-learn,idlead/scikit-learn,justincassidy/scikit-learn,marcocaccin/scikit-learn,0x0all/scikit-learn,tawsifkhan/scikit-learn,ivannz/scikit-learn,frank-tancf/scikit-learn,pompiduskus/scikit-learn,shenzebang/scikit-learn,ChanChiChoi/scikit-learn,robin-lai/scikit-learn,mlyundin/scikit-learn,ankurankan/scikit-learn,roxyboy/scikit-learn,ssaeger/scikit-learn,fbagirov/scikit-learn,shusenl/scikit-learn,murali-munna/scikit-learn,vortex-ape/scikit-learn,herilalaina/scikit-learn,appapantula/scikit-learn,xzh86/scikit-learn,imaculate/scikit-learn,vinayak-mehta/scikit-learn,mrshu/scikit-learn,IshankGulati/scikit-learn,yonglehou/scikit-learn,khkaminska/scikit-learn,theoryno3/scikit-learn,mjudsp/Tsallis,pkruskal/scikit-learn,schets/scikit-learn,lin-credible/scikit-learn,henridwyer/scikit-learn,mojoboss/scikit-learn,devanshdalal/scikit-learn,harshaneelhg/scikit-learn,pkruskal/scikit-learn,OshynSong/scikit-learn,chrsrds/scikit-learn,bhargav/scikit-learn,0asa/scikit-learn,mxjl620/scikit-learn,Barmaley-exe/scikit-learn,hsuantien/scikit-learn,abimannans/scikit-learn,MartinDelzant/scikit-learn,ltiao/scikit-learn,huobaowangxi/scikit-learn,costypetrisor/scikit-learn,appapantula/scikit-learn,kmike/scikit-learn,JosmanPS/scikit-learn,cdegroc/scikit-learn,chrisburr/scikit-learn,tmhm/scikit-learn,mayblue9/scikit-learn,ldirer/scikit-learn,RachitKansal/scikit-learn,yanlend/scikit-learn,clemkoa/scikit-learn,altairpearl/scikit-learn,MohammedWasim/scikit-learn,liangz0707/scikit-learn,Titan-C/scikit-learn,AlexandreAbraham/scikit-learn,altairpearl/scikit-learn,rahul-c1/scikit-learn,loli/sklearn-ensembletrees,MartinSavc/scikit-learn,jorge2703/scikit-learn,jaidevd/scikit-learn,MatthieuBizien/scikit-learn,joshloyal/scikit-learn,samzhang111/scikit-learn,aetilley/scikit-learn,CforED/Machine-Learning,r-mart/scikit-learn,imaculate/scikit-learn,manashmndl/scikit-learn,lin-credible/scikit-learn,nmayorov/scikit-learn,trankmichael/scikit-learn,anurag313/scikit-learn,nrhine1/scikit-learn,mattilyra/scikit-learn,ashhher3/scikit-learn,Windy-Ground/scikit-learn,mblondel/scikit-learn,rexshihaoren/scikit-learn,q1ang/scikit-learn,dhruv13J/scikit-learn,depet/scikit-learn,nomadcube/scikit-learn,alexeyum/scikit-learn,raghavrv/scikit-learn,waterponey/scikit-learn,sumspr/scikit-learn,jakobworldpeace/scikit-learn,MechCoder/scikit-learn,shangwuhencc/scikit-learn,ElDeveloper/scikit-learn,deepesch/scikit-learn,imaculate/scikit-learn,ngoix/OCRF,PatrickChrist/scikit-learn,mehdidc/scikit-learn,samzhang111/scikit-learn,ZenDevelopmentSystems/scikit-learn,nhejazi/scikit-learn,waterponey/scikit-learn,wzbozon/scikit-learn,jakirkham/scikit-learn,kaichogami/scikit-learn,bthirion/scikit-learn,olologin/scikit-learn,clemkoa/scikit-learn,hrjn/scikit-learn,jjx02230808/project0223,jpautom/scikit-learn,spallavolu/scikit-learn,justincassidy/scikit-learn,bikong2/scikit-learn,schets/scikit-learn,ilyes14/scikit-learn,mattilyra/scikit-learn,petosegan/scikit-learn,dsullivan7/scikit-learn,fbagirov/scikit-learn,xyguo/scikit-learn,madjelan/scikit-learn,florian-f/sklearn,xzh86/scikit-learn,xzh86/scikit-learn,sinhrks/scikit-learn,hlin117/scikit-learn,vivekmishra1991/scikit-learn,JeanKossaifi/scikit-learn,cdegroc/scikit-learn,belltailjp/scikit-learn,rajat1994/scikit-learn,TomDLT/scikit-learn,dsullivan7/scikit-learn,adamgreenhall/scikit-learn,potash/scikit-learn,olologin/scikit-learn,IssamLaradji/scikit-learn,yyjiang/scikit-learn,victorbergelin/scikit-learn,ningchi/scikit-learn,lin-credible/scikit-learn,IssamLaradji/scikit-learn,liyu1990/sklearn,pv/scikit-learn,wanggang3333/scikit-learn,aminert/scikit-learn,dsquareindia/scikit-learn,sgenoud/scikit-learn,jkarnows/scikit-learn,MatthieuBizien/scikit-learn,zuku1985/scikit-learn,wazeerzulfikar/scikit-learn,glouppe/scikit-learn,andrewnc/scikit-learn,LohithBlaze/scikit-learn,JosmanPS/scikit-learn,mhue/scikit-learn,Myasuka/scikit-learn,jjx02230808/project0223,iismd17/scikit-learn,yanlend/scikit-learn,fabianp/scikit-learn,davidgbe/scikit-learn,Nyker510/scikit-learn,madjelan/scikit-learn,zaxtax/scikit-learn,ngoix/OCRF,vibhorag/scikit-learn,untom/scikit-learn,jmetzen/scikit-learn,kashif/scikit-learn,mlyundin/scikit-learn,Obus/scikit-learn,loli/sklearn-ensembletrees,pnedunuri/scikit-learn,loli/sklearn-ensembletrees,Myasuka/scikit-learn,fabioticconi/scikit-learn,btabibian/scikit-learn,andrewnc/scikit-learn,ssaeger/scikit-learn,ephes/scikit-learn,kaichogami/scikit-learn,roxyboy/scikit-learn,devanshdalal/scikit-learn,ldirer/scikit-learn,robin-lai/scikit-learn,BiaDarkia/scikit-learn,ngoix/OCRF,raghavrv/scikit-learn,bigdataelephants/scikit-learn,rrohan/scikit-learn,hdmetor/scikit-learn,MartinDelzant/scikit-learn,ningchi/scikit-learn,michigraber/scikit-learn,yyjiang/scikit-learn,quheng/scikit-learn,lazywei/scikit-learn,pnedunuri/scikit-learn,mjudsp/Tsallis,davidgbe/scikit-learn,wanggang3333/scikit-learn,IndraVikas/scikit-learn,simon-pepin/scikit-learn,Myasuka/scikit-learn,ldirer/scikit-learn,vybstat/scikit-learn,gotomypc/scikit-learn,poryfly/scikit-learn,hlin117/scikit-learn,aetilley/scikit-learn,poryfly/scikit-learn,rvraghav93/scikit-learn,mlyundin/scikit-learn,davidgbe/scikit-learn,CforED/Machine-Learning,dsullivan7/scikit-learn,DonBeo/scikit-learn,henridwyer/scikit-learn,glennq/scikit-learn,trungnt13/scikit-learn,henrykironde/scikit-learn,rishikksh20/scikit-learn,Vimos/scikit-learn,RachitKansal/scikit-learn,Achuth17/scikit-learn,CforED/Machine-Learning,massmutual/scikit-learn,glemaitre/scikit-learn,q1ang/scikit-learn,RayMick/scikit-learn,saiwing-yeung/scikit-learn,jseabold/scikit-learn,rsivapr/scikit-learn,simon-pepin/scikit-learn,xubenben/scikit-learn,MartinDelzant/scikit-learn,sinhrks/scikit-learn,zhenv5/scikit-learn,jblackburne/scikit-learn,kashif/scikit-learn,nomadcube/scikit-learn,carrillo/scikit-learn,ominux/scikit-learn,TomDLT/scikit-learn,eickenberg/scikit-learn,ivannz/scikit-learn,nrhine1/scikit-learn,YinongLong/scikit-learn,nesterione/scikit-learn,liangz0707/scikit-learn,jorge2703/scikit-learn,mxjl620/scikit-learn,deepesch/scikit-learn,IssamLaradji/scikit-learn,hsuantien/scikit-learn,pianomania/scikit-learn,depet/scikit-learn,ClimbsRocks/scikit-learn,ashhher3/scikit-learn,vivekmishra1991/scikit-learn,treycausey/scikit-learn,nhejazi/scikit-learn,Fireblend/scikit-learn,Titan-C/scikit-learn,aabadie/scikit-learn,eg-zhang/scikit-learn,hitszxp/scikit-learn,hsuantien/scikit-learn,siutanwong/scikit-learn,JsNoNo/scikit-learn,equialgo/scikit-learn,andaag/scikit-learn,Windy-Ground/scikit-learn,lazywei/scikit-learn,bnaul/scikit-learn,cybernet14/scikit-learn,CVML/scikit-learn,aflaxman/scikit-learn,glemaitre/scikit-learn,icdishb/scikit-learn,chrsrds/scikit-learn,pv/scikit-learn,Fireblend/scikit-learn,zaxtax/scikit-learn,kmike/scikit-learn,466152112/scikit-learn,mjgrav2001/scikit-learn,ashhher3/scikit-learn,AnasGhrab/scikit-learn,rohanp/scikit-learn,costypetrisor/scikit-learn,wlamond/scikit-learn,meduz/scikit-learn,kylerbrown/scikit-learn,zorojean/scikit-learn,amueller/scikit-learn,bhargav/scikit-learn,fabianp/scikit-learn,bthirion/scikit-learn,tosolveit/scikit-learn,ZenDevelopmentSystems/scikit-learn,DSLituiev/scikit-learn,mugizico/scikit-learn,poryfly/scikit-learn,rishikksh20/scikit-learn,ssaeger/scikit-learn,sarahgrogan/scikit-learn,aflaxman/scikit-learn,LiaoPan/scikit-learn,dingocuster/scikit-learn,mxjl620/scikit-learn,lucidfrontier45/scikit-learn,Lawrence-Liu/scikit-learn,luo66/scikit-learn,mjgrav2001/scikit-learn,Clyde-fare/scikit-learn,carrillo/scikit-learn,mrshu/scikit-learn,rexshihaoren/scikit-learn,sumspr/scikit-learn,vermouthmjl/scikit-learn,rishikksh20/scikit-learn,MartinSavc/scikit-learn,RomainBrault/scikit-learn,hugobowne/scikit-learn,AIML/scikit-learn,xavierwu/scikit-learn,mfjb/scikit-learn,liyu1990/sklearn,wlamond/scikit-learn,anntzer/scikit-learn,Djabbz/scikit-learn,cl4rke/scikit-learn,AlexanderFabisch/scikit-learn,jzt5132/scikit-learn,djgagne/scikit-learn,tdhopper/scikit-learn,lbishal/scikit-learn,mjudsp/Tsallis,mattilyra/scikit-learn,cauchycui/scikit-learn,espg/scikit-learn,spallavolu/scikit-learn,mfjb/scikit-learn,etkirsch/scikit-learn,tomlof/scikit-learn,sarahgrogan/scikit-learn,aetilley/scikit-learn,vigilv/scikit-learn,ahoyosid/scikit-learn,JsNoNo/scikit-learn,jkarnows/scikit-learn,HolgerPeters/scikit-learn,AIML/scikit-learn,ephes/scikit-learn,kjung/scikit-learn,robin-lai/scikit-learn,MechCoder/scikit-learn,hsiaoyi0504/scikit-learn,liangz0707/scikit-learn,fredhusser/scikit-learn,jakirkham/scikit-learn,procoder317/scikit-learn,alvarofierroclavero/scikit-learn,BiaDarkia/scikit-learn,fzalkow/scikit-learn,dsullivan7/scikit-learn,fzalkow/scikit-learn,idlead/scikit-learn,xavierwu/scikit-learn,nelson-liu/scikit-learn,pratapvardhan/scikit-learn,hitszxp/scikit-learn,mikebenfield/scikit-learn,justincassidy/scikit-learn,walterreade/scikit-learn,B3AU/waveTree,billy-inn/scikit-learn,shyamalschandra/scikit-learn,hugobowne/scikit-learn,mwv/scikit-learn,vermouthmjl/scikit-learn,tomlof/scikit-learn,carrillo/scikit-learn,Nyker510/scikit-learn,cainiaocome/scikit-learn,NunoEdgarGub1/scikit-learn,Garrett-R/scikit-learn,tdhopper/scikit-learn,shikhardb/scikit-learn,ZenDevelopmentSystems/scikit-learn,ndingwall/scikit-learn,rahuldhote/scikit-learn,jayflo/scikit-learn,Jimmy-Morzaria/scikit-learn,f3r/scikit-learn,nhejazi/scikit-learn,procoder317/scikit-learn,giorgiop/scikit-learn,Myasuka/scikit-learn,pkruskal/scikit-learn,RayMick/scikit-learn,RPGOne/scikit-learn,nelson-liu/scikit-learn,cwu2011/scikit-learn,0x0all/scikit-learn,voxlol/scikit-learn,pompiduskus/scikit-learn,huzq/scikit-learn,DonBeo/scikit-learn,ominux/scikit-learn,herilalaina/scikit-learn,ycaihua/scikit-learn,pypot/scikit-learn,hrjn/scikit-learn,xiaoxiamii/scikit-learn,Obus/scikit-learn,kmike/scikit-learn,wzbozon/scikit-learn,AlexandreAbraham/scikit-learn,smartscheduling/scikit-learn-categorical-tree,loli/sklearn-ensembletrees,lenovor/scikit-learn,xuewei4d/scikit-learn,khkaminska/scikit-learn,lenovor/scikit-learn,saiwing-yeung/scikit-learn,jakirkham/scikit-learn,alexeyum/scikit-learn,potash/scikit-learn,AlexanderFabisch/scikit-learn,quheng/scikit-learn,jmetzen/scikit-learn,yanlend/scikit-learn,sanketloke/scikit-learn,jzt5132/scikit-learn,quheng/scikit-learn,fyffyt/scikit-learn,beepee14/scikit-learn,jmschrei/scikit-learn,gotomypc/scikit-learn,mayblue9/scikit-learn,frank-tancf/scikit-learn,florian-f/sklearn,pompiduskus/scikit-learn,ky822/scikit-learn,shangwuhencc/scikit-learn,pkruskal/scikit-learn,ahoyosid/scikit-learn,rsivapr/scikit-learn,maheshakya/scikit-learn,mrshu/scikit-learn,Adai0808/scikit-learn,joshloyal/scikit-learn,shangwuhencc/scikit-learn,mxjl620/scikit-learn,zorojean/scikit-learn,liberatorqjw/scikit-learn,jmschrei/scikit-learn,kylerbrown/scikit-learn,UNR-AERIAL/scikit-learn,vortex-ape/scikit-learn,quheng/scikit-learn,LiaoPan/scikit-learn,bigdataelephants/scikit-learn,mattgiguere/scikit-learn,fabianp/scikit-learn,Adai0808/scikit-learn,Lawrence-Liu/scikit-learn,aminert/scikit-learn,meduz/scikit-learn,ElDeveloper/scikit-learn,zihua/scikit-learn,trungnt13/scikit-learn,ky822/scikit-learn,fyffyt/scikit-learn,mhdella/scikit-learn,mikebenfield/scikit-learn,3manuek/scikit-learn,rajat1994/scikit-learn,bigdataelephants/scikit-learn,bikong2/scikit-learn,amueller/scikit-learn,zhenv5/scikit-learn,pnedunuri/scikit-learn,ltiao/scikit-learn,tosolveit/scikit-learn,rishikksh20/scikit-learn,MatthieuBizien/scikit-learn,Akshay0724/scikit-learn,michigraber/scikit-learn,bnaul/scikit-learn,aabadie/scikit-learn,zaxtax/scikit-learn,dsquareindia/scikit-learn,JPFrancoia/scikit-learn,siutanwong/scikit-learn,ltiao/scikit-learn,scikit-learn/scikit-learn,arabenjamin/scikit-learn,costypetrisor/scikit-learn,xuewei4d/scikit-learn,henrykironde/scikit-learn,BiaDarkia/scikit-learn,bikong2/scikit-learn,walterreade/scikit-learn,bthirion/scikit-learn,loli/semisupervisedforests,UNR-AERIAL/scikit-learn,CVML/scikit-learn,pv/scikit-learn,loli/sklearn-ensembletrees,costypetrisor/scikit-learn,AnasGhrab/scikit-learn,billy-inn/scikit-learn,hrjn/scikit-learn,hitszxp/scikit-learn,phdowling/scikit-learn,CVML/scikit-learn,larsmans/scikit-learn,sinhrks/scikit-learn,zorroblue/scikit-learn,justincassidy/scikit-learn,HolgerPeters/scikit-learn,zuku1985/scikit-learn,xavierwu/scikit-learn,Garrett-R/scikit-learn,henrykironde/scikit-learn,Titan-C/scikit-learn,ivannz/scikit-learn,mhdella/scikit-learn,B3AU/waveTree,nikitasingh981/scikit-learn,fabioticconi/scikit-learn,RachitKansal/scikit-learn,Barmaley-exe/scikit-learn,jzt5132/scikit-learn,Sentient07/scikit-learn,shenzebang/scikit-learn,ChanChiChoi/scikit-learn,jorik041/scikit-learn,toastedcornflakes/scikit-learn,qifeigit/scikit-learn,michigraber/scikit-learn,betatim/scikit-learn,eickenberg/scikit-learn,nikitasingh981/scikit-learn,MatthieuBizien/scikit-learn,ankurankan/scikit-learn,jereze/scikit-learn,loli/semisupervisedforests,shikhardb/scikit-learn,sonnyhu/scikit-learn,IshankGulati/scikit-learn,djgagne/scikit-learn,siutanwong/scikit-learn,yask123/scikit-learn,davidgbe/scikit-learn,zorroblue/scikit-learn,RPGOne/scikit-learn,cdegroc/scikit-learn,madjelan/scikit-learn,mjudsp/Tsallis,hsiaoyi0504/scikit-learn,rvraghav93/scikit-learn,cybernet14/scikit-learn,ivannz/scikit-learn,krez13/scikit-learn,adamgreenhall/scikit-learn,sinhrks/scikit-learn,meduz/scikit-learn,walterreade/scikit-learn,aewhatley/scikit-learn,AlexandreAbraham/scikit-learn,Vimos/scikit-learn,xwolf12/scikit-learn,vivekmishra1991/scikit-learn,AIML/scikit-learn,fengzhyuan/scikit-learn,joernhees/scikit-learn,mblondel/scikit-learn,shyamalschandra/scikit-learn,shusenl/scikit-learn,liyu1990/sklearn,0asa/scikit-learn,anurag313/scikit-learn,sgenoud/scikit-learn,ElDeveloper/scikit-learn,chrisburr/scikit-learn,YinongLong/scikit-learn,eg-zhang/scikit-learn,mhue/scikit-learn,466152112/scikit-learn,zihua/scikit-learn,arjoly/scikit-learn,raghavrv/scikit-learn,RomainBrault/scikit-learn,alvarofierroclavero/scikit-learn,henridwyer/scikit-learn,aewhatley/scikit-learn,cybernet14/scikit-learn,AlexanderFabisch/scikit-learn,ominux/scikit-learn,Jimmy-Morzaria/scikit-learn,giorgiop/scikit-learn,rajat1994/scikit-learn,kevin-intel/scikit-learn,betatim/scikit-learn,ndingwall/scikit-learn,ClimbsRocks/scikit-learn,sanketloke/scikit-learn,krez13/scikit-learn,jayflo/scikit-learn,jpautom/scikit-learn,smartscheduling/scikit-learn-categorical-tree,bikong2/scikit-learn,aabadie/scikit-learn,devanshdalal/scikit-learn,arabenjamin/scikit-learn,khkaminska/scikit-learn,rahul-c1/scikit-learn,abhishekkrthakur/scikit-learn,kevin-intel/scikit-learn,Titan-C/scikit-learn,ycaihua/scikit-learn,aminert/scikit-learn,treycausey/scikit-learn,lenovor/scikit-learn,joernhees/scikit-learn,hugobowne/scikit-learn,herilalaina/scikit-learn,Clyde-fare/scikit-learn,carrillo/scikit-learn,fabioticconi/scikit-learn,rahul-c1/scikit-learn,JeanKossaifi/scikit-learn,nikitasingh981/scikit-learn,alexeyum/scikit-learn,heli522/scikit-learn,huzq/scikit-learn,evgchz/scikit-learn,beepee14/scikit-learn,ilyes14/scikit-learn,petosegan/scikit-learn,jereze/scikit-learn,Srisai85/scikit-learn,Windy-Ground/scikit-learn,ltiao/scikit-learn,vermouthmjl/scikit-learn,bigdataelephants/scikit-learn,nelson-liu/scikit-learn,mfjb/scikit-learn,Windy-Ground/scikit-learn,evgchz/scikit-learn,xiaoxiamii/scikit-learn,r-mart/scikit-learn,ningchi/scikit-learn,depet/scikit-learn,smartscheduling/scikit-learn-categorical-tree,luo66/scikit-learn,pythonvietnam/scikit-learn,B3AU/waveTree,belltailjp/scikit-learn,terkkila/scikit-learn,hdmetor/scikit-learn,AlexRobson/scikit-learn,nvoron23/scikit-learn,olologin/scikit-learn,deepesch/scikit-learn,lucidfrontier45/scikit-learn,manhhomienbienthuy/scikit-learn,bthirion/scikit-learn,plissonf/scikit-learn,ngoix/OCRF,Adai0808/scikit-learn,ldirer/scikit-learn,massmutual/scikit-learn,raghavrv/scikit-learn,ngoix/OCRF,beepee14/scikit-learn,q1ang/scikit-learn,victorbergelin/scikit-learn,yunfeilu/scikit-learn,MartinDelzant/scikit-learn,iismd17/scikit-learn,MartinSavc/scikit-learn,liberatorqjw/scikit-learn,jereze/scikit-learn,cauchycui/scikit-learn,xwolf12/scikit-learn,kevin-intel/scikit-learn,jlegendary/scikit-learn,vivekmishra1991/scikit-learn,andaag/scikit-learn,jakobworldpeace/scikit-learn,nikitasingh981/scikit-learn,BiaDarkia/scikit-learn,potash/scikit-learn,lucidfrontier45/scikit-learn,espg/scikit-learn,mugizico/scikit-learn,dhruv13J/scikit-learn,harshaneelhg/scikit-learn,bnaul/scikit-learn,MechCoder/scikit-learn,ndingwall/scikit-learn,ssaeger/scikit-learn,samuel1208/scikit-learn,nomadcube/scikit-learn,Aasmi/scikit-learn,arahuja/scikit-learn,adamgreenhall/scikit-learn,hugobowne/scikit-learn,RomainBrault/scikit-learn,thientu/scikit-learn,fabioticconi/scikit-learn,vibhorag/scikit-learn,anntzer/scikit-learn,joshloyal/scikit-learn,ZENGXH/scikit-learn,B3AU/waveTree,Achuth17/scikit-learn,abhishekkrthakur/scikit-learn,saiwing-yeung/scikit-learn,fzalkow/scikit-learn,Sentient07/scikit-learn,cdegroc/scikit-learn,Djabbz/scikit-learn,3manuek/scikit-learn,kmike/scikit-learn,untom/scikit-learn,ogrisel/scikit-learn,xavierwu/scikit-learn,larsmans/scikit-learn,robbymeals/scikit-learn,jseabold/scikit-learn,jakobworldpeace/scikit-learn,robin-lai/scikit-learn,pythonvietnam/scikit-learn,liyu1990/sklearn,abhishekgahlot/scikit-learn,kjung/scikit-learn,pnedunuri/scikit-learn,hainm/scikit-learn,MohammedWasim/scikit-learn,themrmax/scikit-learn,YinongLong/scikit-learn,nvoron23/scikit-learn,Jimmy-Morzaria/scikit-learn,NunoEdgarGub1/scikit-learn,theoryno3/scikit-learn,maheshakya/scikit-learn,Barmaley-exe/scikit-learn,themrmax/scikit-learn,florian-f/sklearn,kaichogami/scikit-learn,ilo10/scikit-learn,abhishekkrthakur/scikit-learn,btabibian/scikit-learn,russel1237/scikit-learn,mugizico/scikit-learn,gotomypc/scikit-learn,xiaoxiamii/scikit-learn,sanketloke/scikit-learn,meduz/scikit-learn,hitszxp/scikit-learn,vibhorag/scikit-learn,OshynSong/scikit-learn,florian-f/sklearn,Barmaley-exe/scikit-learn,cl4rke/scikit-learn
|
"""Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
- from nose.tools import assert_true
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=False,
shuffle=False)
except IOError:
raise SkipTest("Download 20 newsgroups to run this test")
# Extract a reduced dataset
data2cats = datasets.fetch_20newsgroups(subset='all',
categories=data.target_names[-1:-3:-1],
shuffle=False)
# Check that the ordering of the target_names is the same
# as the ordering in the full dataset
assert_equal(data2cats.target_names,
data.target_names[-2:])
# Assert that we have only 0 and 1 as labels
assert_equal(np.unique(data2cats.target).tolist(), [0, 1])
# Check that the first entry of the reduced dataset corresponds to
# the first entry of the corresponding category in the full dataset
entry1 = data2cats.data[0]
category = data2cats.target_names[data2cats.target[0]]
label = data.target_names.index(category)
entry2 = data.data[np.where(data.target == label)[0][0]]
assert_equal(entry1, entry2)
- # check that the filenames are available too
- assert_true(data.filenames[0].endswith(
- "20news_home/20news-bydate-test/talk.politics.mideast/76560"))
|
Fix a bug introduced in rebasing
|
## Code Before:
"""Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.tools import assert_true
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=False,
shuffle=False)
except IOError:
raise SkipTest("Download 20 newsgroups to run this test")
# Extract a reduced dataset
data2cats = datasets.fetch_20newsgroups(subset='all',
categories=data.target_names[-1:-3:-1],
shuffle=False)
# Check that the ordering of the target_names is the same
# as the ordering in the full dataset
assert_equal(data2cats.target_names,
data.target_names[-2:])
# Assert that we have only 0 and 1 as labels
assert_equal(np.unique(data2cats.target).tolist(), [0, 1])
# Check that the first entry of the reduced dataset corresponds to
# the first entry of the corresponding category in the full dataset
entry1 = data2cats.data[0]
category = data2cats.target_names[data2cats.target[0]]
label = data.target_names.index(category)
entry2 = data.data[np.where(data.target == label)[0][0]]
assert_equal(entry1, entry2)
# check that the filenames are available too
assert_true(data.filenames[0].endswith(
"20news_home/20news-bydate-test/talk.politics.mideast/76560"))
## Instruction:
Fix a bug introduced in rebasing
## Code After:
"""Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=False,
shuffle=False)
except IOError:
raise SkipTest("Download 20 newsgroups to run this test")
# Extract a reduced dataset
data2cats = datasets.fetch_20newsgroups(subset='all',
categories=data.target_names[-1:-3:-1],
shuffle=False)
# Check that the ordering of the target_names is the same
# as the ordering in the full dataset
assert_equal(data2cats.target_names,
data.target_names[-2:])
# Assert that we have only 0 and 1 as labels
assert_equal(np.unique(data2cats.target).tolist(), [0, 1])
# Check that the first entry of the reduced dataset corresponds to
# the first entry of the corresponding category in the full dataset
entry1 = data2cats.data[0]
category = data2cats.target_names[data2cats.target[0]]
label = data.target_names.index(category)
entry2 = data.data[np.where(data.target == label)[0][0]]
assert_equal(entry1, entry2)
|
// ... existing code ...
from nose.tools import assert_equal
from nose.plugins.skip import SkipTest
// ... modified code ...
// ... rest of the code ...
|
7f3c086a953f91ec7f351c56a4f07f38dc0b9eb3
|
exampleCourse/elements/course_element/course_element.py
|
exampleCourse/elements/course_element/course_element.py
|
import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
import random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
Remove unneeded get_dependencies from course element
|
Remove unneeded get_dependencies from course element
|
Python
|
agpl-3.0
|
parasgithub/PrairieLearn,rbessick5/PrairieLearn,tbretl/PrairieLearn,parasgithub/PrairieLearn,jakebailey/PrairieLearn,parasgithub/PrairieLearn,tbretl/PrairieLearn,rbessick5/PrairieLearn,jakebailey/PrairieLearn,jakebailey/PrairieLearn,rbessick5/PrairieLearn,mwest1066/PrairieLearn,mwest1066/PrairieLearn,parasgithub/PrairieLearn,mwest1066/PrairieLearn,jakebailey/PrairieLearn,parasgithub/PrairieLearn,tbretl/PrairieLearn,mwest1066/PrairieLearn,rbessick5/PrairieLearn,mwest1066/PrairieLearn,tbretl/PrairieLearn,rbessick5/PrairieLearn,tbretl/PrairieLearn
|
import random
import chevron
-
- def get_dependencies(element_html, element_index, data):
- return {
- 'styles': ['course_element.css'],
- 'scripts': ['course_element.js']
- }
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
Remove unneeded get_dependencies from course element
|
## Code Before:
import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
## Instruction:
Remove unneeded get_dependencies from course element
## Code After:
import random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
// ... existing code ...
import chevron
// ... rest of the code ...
|
bd4506dc95ee7a778a5b0f062d6d0423ade5890c
|
alerts/lib/alert_plugin_set.py
|
alerts/lib/alert_plugin_set.py
|
from mozdef_util.plugin_set import PluginSet
from mozdef_util.utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summary' in message:
message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
logger.info(message_log_str)
return plugin_class.onMessage(message), metadata
|
from mozdef_util.plugin_set import PluginSet
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
return plugin_class.onMessage(message), metadata
|
Remove logger entry for alert plugins receiving alerts
|
Remove logger entry for alert plugins receiving alerts
|
Python
|
mpl-2.0
|
mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef
|
from mozdef_util.plugin_set import PluginSet
- from mozdef_util.utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
- if 'utctimestamp' in message and 'summary' in message:
- message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
- logger.info(message_log_str)
-
return plugin_class.onMessage(message), metadata
|
Remove logger entry for alert plugins receiving alerts
|
## Code Before:
from mozdef_util.plugin_set import PluginSet
from mozdef_util.utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summary' in message:
message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
logger.info(message_log_str)
return plugin_class.onMessage(message), metadata
## Instruction:
Remove logger entry for alert plugins receiving alerts
## Code After:
from mozdef_util.plugin_set import PluginSet
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
return plugin_class.onMessage(message), metadata
|
# ... existing code ...
from mozdef_util.plugin_set import PluginSet
# ... modified code ...
def send_message_to_plugin(self, plugin_class, message, metadata=None):
return plugin_class.onMessage(message), metadata
# ... rest of the code ...
|
2baed20067fed71987bf7582fa9c9a5e53a63cb5
|
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
|
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
|
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
|
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
sw = s.startswith # $f-:checks=s $f-:branch=true
if sw("safe"):
pass
|
Test false negative from review
|
Python: Test false negative from review
|
Python
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
+ sw = s.startswith # $f-:checks=s $f-:branch=true
+ if sw("safe"):
+ pass
+
|
Test false negative from review
|
## Code Before:
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
## Instruction:
Test false negative from review
## Code After:
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
sw = s.startswith # $f-:checks=s $f-:branch=true
if sw("safe"):
pass
|
...
pass
sw = s.startswith # $f-:checks=s $f-:branch=true
if sw("safe"):
pass
...
|
badddd6aa9533a01e07477174dc7422ee4941014
|
wsgi.py
|
wsgi.py
|
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
from raven.middleware import Sentry
application = loadapp('config:production.ini',
relative_to='yithlibraryserver/config-templates')
application = agent.WSGIApplicationWrapper(Sentry(application))
|
import os
import os.path
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
from pyramid.paster import setup_logging
from raven.middleware import Sentry
from waitress import serve
basedir= os.path.dirname(os.path.realpath(__file__))
conf_file = os.path.join(
basedir,
'yithlibraryserver', 'config-templates', 'production.ini'
)
application = loadapp('config:%s' % conf_file)
application = agent.WSGIApplicationWrapper(Sentry(application))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
scheme = os.environ.get("SCHEME", "https")
setup_logging(conf_file)
serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
|
Read the conf file using absolute paths
|
Read the conf file using absolute paths
|
Python
|
agpl-3.0
|
lorenzogil/yith-library-server,lorenzogil/yith-library-server,lorenzogil/yith-library-server
|
+
+ import os
+ import os.path
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
+ from pyramid.paster import setup_logging
from raven.middleware import Sentry
+ from waitress import serve
- application = loadapp('config:production.ini',
- relative_to='yithlibraryserver/config-templates')
+ basedir= os.path.dirname(os.path.realpath(__file__))
+ conf_file = os.path.join(
+ basedir,
+ 'yithlibraryserver', 'config-templates', 'production.ini'
+ )
+
+ application = loadapp('config:%s' % conf_file)
application = agent.WSGIApplicationWrapper(Sentry(application))
+ if __name__ == "__main__":
+ port = int(os.environ.get("PORT", 5000))
+ scheme = os.environ.get("SCHEME", "https")
+ setup_logging(conf_file)
+ serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
+
|
Read the conf file using absolute paths
|
## Code Before:
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
from raven.middleware import Sentry
application = loadapp('config:production.ini',
relative_to='yithlibraryserver/config-templates')
application = agent.WSGIApplicationWrapper(Sentry(application))
## Instruction:
Read the conf file using absolute paths
## Code After:
import os
import os.path
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
from pyramid.paster import setup_logging
from raven.middleware import Sentry
from waitress import serve
basedir= os.path.dirname(os.path.realpath(__file__))
conf_file = os.path.join(
basedir,
'yithlibraryserver', 'config-templates', 'production.ini'
)
application = loadapp('config:%s' % conf_file)
application = agent.WSGIApplicationWrapper(Sentry(application))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
scheme = os.environ.get("SCHEME", "https")
setup_logging(conf_file)
serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
|
// ... existing code ...
import os
import os.path
// ... modified code ...
from paste.deploy import loadapp
from pyramid.paster import setup_logging
from raven.middleware import Sentry
from waitress import serve
basedir= os.path.dirname(os.path.realpath(__file__))
conf_file = os.path.join(
basedir,
'yithlibraryserver', 'config-templates', 'production.ini'
)
application = loadapp('config:%s' % conf_file)
application = agent.WSGIApplicationWrapper(Sentry(application))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
scheme = os.environ.get("SCHEME", "https")
setup_logging(conf_file)
serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
// ... rest of the code ...
|
f35c6f989129d6298eb2f419ccb6fe8d4c734fd6
|
taskq/run.py
|
taskq/run.py
|
import time
import transaction
from taskq import models
from daemon import runner
class TaskRunner():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/task-runner.pid'
self.pidfile_timeout = 5
def run(self):
while True:
task = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).first()
if not task:
time.sleep(2)
continue
with transaction.manager:
task.status = models.TASK_STATUS_IN_PROGRESS
task.perform()
task.status = models.TASK_STATUS_FINISHED
models.DBSession.add(task)
time.sleep(2)
def main():
app = TaskRunner()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
if __name__ == '__main__':
main()
|
import time
import transaction
from daemon import runner
from taskq import models
class TaskDaemonRunner(runner.DaemonRunner):
def _status(self):
pid = self.pidfile.read_pid()
message = []
if pid:
message += ['Daemon started with pid %s' % pid]
else:
message += ['Daemon not running']
tasks = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).all()
message += ['Number of waiting tasks: %s' % len(tasks)]
runner.emit_message('\n'.join(message))
action_funcs = {
u'start': runner.DaemonRunner._start,
u'stop': runner.DaemonRunner._stop,
u'restart': runner.DaemonRunner._restart,
u'status': _status,
}
class TaskRunner():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/task-runner.pid'
self.pidfile_timeout = 5
def run(self):
while True:
task = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).first()
if not task:
time.sleep(2)
continue
with transaction.manager:
task.status = models.TASK_STATUS_IN_PROGRESS
task.perform()
task.status = models.TASK_STATUS_FINISHED
models.DBSession.add(task)
time.sleep(2)
def main():
app = TaskRunner()
daemon_runner = TaskDaemonRunner(app)
daemon_runner.do_action()
if __name__ == '__main__':
main()
|
Add status to the daemon
|
Add status to the daemon
|
Python
|
mit
|
LeResKP/sqla-taskq
|
import time
import transaction
+ from daemon import runner
from taskq import models
- from daemon import runner
+
+
+ class TaskDaemonRunner(runner.DaemonRunner):
+
+ def _status(self):
+ pid = self.pidfile.read_pid()
+ message = []
+ if pid:
+ message += ['Daemon started with pid %s' % pid]
+ else:
+ message += ['Daemon not running']
+
+ tasks = models.Task.query.filter_by(
+ status=models.TASK_STATUS_WAITING).all()
+ message += ['Number of waiting tasks: %s' % len(tasks)]
+ runner.emit_message('\n'.join(message))
+
+ action_funcs = {
+ u'start': runner.DaemonRunner._start,
+ u'stop': runner.DaemonRunner._stop,
+ u'restart': runner.DaemonRunner._restart,
+ u'status': _status,
+ }
class TaskRunner():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/task-runner.pid'
self.pidfile_timeout = 5
def run(self):
while True:
task = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).first()
if not task:
time.sleep(2)
continue
with transaction.manager:
task.status = models.TASK_STATUS_IN_PROGRESS
task.perform()
task.status = models.TASK_STATUS_FINISHED
models.DBSession.add(task)
time.sleep(2)
def main():
app = TaskRunner()
- daemon_runner = runner.DaemonRunner(app)
+ daemon_runner = TaskDaemonRunner(app)
daemon_runner.do_action()
if __name__ == '__main__':
main()
|
Add status to the daemon
|
## Code Before:
import time
import transaction
from taskq import models
from daemon import runner
class TaskRunner():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/task-runner.pid'
self.pidfile_timeout = 5
def run(self):
while True:
task = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).first()
if not task:
time.sleep(2)
continue
with transaction.manager:
task.status = models.TASK_STATUS_IN_PROGRESS
task.perform()
task.status = models.TASK_STATUS_FINISHED
models.DBSession.add(task)
time.sleep(2)
def main():
app = TaskRunner()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
if __name__ == '__main__':
main()
## Instruction:
Add status to the daemon
## Code After:
import time
import transaction
from daemon import runner
from taskq import models
class TaskDaemonRunner(runner.DaemonRunner):
def _status(self):
pid = self.pidfile.read_pid()
message = []
if pid:
message += ['Daemon started with pid %s' % pid]
else:
message += ['Daemon not running']
tasks = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).all()
message += ['Number of waiting tasks: %s' % len(tasks)]
runner.emit_message('\n'.join(message))
action_funcs = {
u'start': runner.DaemonRunner._start,
u'stop': runner.DaemonRunner._stop,
u'restart': runner.DaemonRunner._restart,
u'status': _status,
}
class TaskRunner():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/task-runner.pid'
self.pidfile_timeout = 5
def run(self):
while True:
task = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).first()
if not task:
time.sleep(2)
continue
with transaction.manager:
task.status = models.TASK_STATUS_IN_PROGRESS
task.perform()
task.status = models.TASK_STATUS_FINISHED
models.DBSession.add(task)
time.sleep(2)
def main():
app = TaskRunner()
daemon_runner = TaskDaemonRunner(app)
daemon_runner.do_action()
if __name__ == '__main__':
main()
|
// ... existing code ...
import transaction
from daemon import runner
from taskq import models
class TaskDaemonRunner(runner.DaemonRunner):
def _status(self):
pid = self.pidfile.read_pid()
message = []
if pid:
message += ['Daemon started with pid %s' % pid]
else:
message += ['Daemon not running']
tasks = models.Task.query.filter_by(
status=models.TASK_STATUS_WAITING).all()
message += ['Number of waiting tasks: %s' % len(tasks)]
runner.emit_message('\n'.join(message))
action_funcs = {
u'start': runner.DaemonRunner._start,
u'stop': runner.DaemonRunner._stop,
u'restart': runner.DaemonRunner._restart,
u'status': _status,
}
// ... modified code ...
app = TaskRunner()
daemon_runner = TaskDaemonRunner(app)
daemon_runner.do_action()
// ... rest of the code ...
|
4c12b100531597b2f6356b3512c9adf462122e3d
|
nova/scheduler/utils.py
|
nova/scheduler/utils.py
|
"""Utility methods for scheduling."""
from nova.compute import flavors
from nova.openstack.common import jsonutils
def build_request_spec(image, instances):
"""Build a request_spec for the scheduler.
The request_spec assumes that all instances to be scheduled are the same
type.
"""
instance = instances[0]
request_spec = {
'image': image,
'instance_properties': instance,
'instance_type': flavors.extract_flavor(instance),
'instance_uuids': [inst['uuid'] for inst in instances]}
return jsonutils.to_primitive(request_spec)
|
"""Utility methods for scheduling."""
from nova.compute import flavors
from nova import db
from nova.openstack.common import jsonutils
def build_request_spec(ctxt, image, instances):
"""Build a request_spec for the scheduler.
The request_spec assumes that all instances to be scheduled are the same
type.
"""
instance = instances[0]
instance_type = flavors.extract_flavor(instance)
# NOTE(comstud): This is a bit ugly, but will get cleaned up when
# we're passing an InstanceType internal object.
extra_specs = db.instance_type_extra_specs_get(ctxt,
instance_type['flavorid'])
instance_type['extra_specs'] = extra_specs
request_spec = {
'image': image,
'instance_properties': instance,
'instance_type': instance_type,
'instance_uuids': [inst['uuid'] for inst in instances]}
return jsonutils.to_primitive(request_spec)
|
Make sure instance_type has extra_specs
|
Make sure instance_type has extra_specs
Make sure that when scheduling, the instance_type used in filters
contains the 'extra_specs'. This is a bit ugly, but will get cleaned up
with objects.
Fixes bug 1192331
Change-Id: I3614f3a858840c9561b4e618fc30f3d3ae5ac689
|
Python
|
apache-2.0
|
n0ano/gantt,n0ano/gantt
|
"""Utility methods for scheduling."""
from nova.compute import flavors
+ from nova import db
from nova.openstack.common import jsonutils
- def build_request_spec(image, instances):
+ def build_request_spec(ctxt, image, instances):
"""Build a request_spec for the scheduler.
The request_spec assumes that all instances to be scheduled are the same
type.
"""
instance = instances[0]
+ instance_type = flavors.extract_flavor(instance)
+ # NOTE(comstud): This is a bit ugly, but will get cleaned up when
+ # we're passing an InstanceType internal object.
+ extra_specs = db.instance_type_extra_specs_get(ctxt,
+ instance_type['flavorid'])
+ instance_type['extra_specs'] = extra_specs
request_spec = {
'image': image,
'instance_properties': instance,
- 'instance_type': flavors.extract_flavor(instance),
+ 'instance_type': instance_type,
'instance_uuids': [inst['uuid'] for inst in instances]}
return jsonutils.to_primitive(request_spec)
|
Make sure instance_type has extra_specs
|
## Code Before:
"""Utility methods for scheduling."""
from nova.compute import flavors
from nova.openstack.common import jsonutils
def build_request_spec(image, instances):
"""Build a request_spec for the scheduler.
The request_spec assumes that all instances to be scheduled are the same
type.
"""
instance = instances[0]
request_spec = {
'image': image,
'instance_properties': instance,
'instance_type': flavors.extract_flavor(instance),
'instance_uuids': [inst['uuid'] for inst in instances]}
return jsonutils.to_primitive(request_spec)
## Instruction:
Make sure instance_type has extra_specs
## Code After:
"""Utility methods for scheduling."""
from nova.compute import flavors
from nova import db
from nova.openstack.common import jsonutils
def build_request_spec(ctxt, image, instances):
"""Build a request_spec for the scheduler.
The request_spec assumes that all instances to be scheduled are the same
type.
"""
instance = instances[0]
instance_type = flavors.extract_flavor(instance)
# NOTE(comstud): This is a bit ugly, but will get cleaned up when
# we're passing an InstanceType internal object.
extra_specs = db.instance_type_extra_specs_get(ctxt,
instance_type['flavorid'])
instance_type['extra_specs'] = extra_specs
request_spec = {
'image': image,
'instance_properties': instance,
'instance_type': instance_type,
'instance_uuids': [inst['uuid'] for inst in instances]}
return jsonutils.to_primitive(request_spec)
|
// ... existing code ...
from nova.compute import flavors
from nova import db
from nova.openstack.common import jsonutils
// ... modified code ...
def build_request_spec(ctxt, image, instances):
"""Build a request_spec for the scheduler.
...
instance = instances[0]
instance_type = flavors.extract_flavor(instance)
# NOTE(comstud): This is a bit ugly, but will get cleaned up when
# we're passing an InstanceType internal object.
extra_specs = db.instance_type_extra_specs_get(ctxt,
instance_type['flavorid'])
instance_type['extra_specs'] = extra_specs
request_spec = {
...
'instance_properties': instance,
'instance_type': instance_type,
'instance_uuids': [inst['uuid'] for inst in instances]}
// ... rest of the code ...
|
0ec01e1c5770c87faa5300b80c3b9d6bcb0df41b
|
tcxparser.py
|
tcxparser.py
|
"Simple parser for Garmin TCX files."
from lxml import objectify
__version__ = '0.3.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees
@property
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time
@property
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
|
"Simple parser for Garmin TCX files."
from lxml import objectify
__version__ = '0.4.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees.pyval
@property
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees.pyval
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time.pyval
@property
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters.pyval
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
|
Make sure to return python values, not lxml objects
|
Make sure to return python values, not lxml objects
Bump version to 0.4.0
|
Python
|
bsd-2-clause
|
vkurup/python-tcxparser,vkurup/python-tcxparser,SimonArnu/python-tcxparser
|
"Simple parser for Garmin TCX files."
from lxml import objectify
- __version__ = '0.3.0'
+ __version__ = '0.4.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
- return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees
+ return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees.pyval
@property
def longitude(self):
- return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees
+ return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees.pyval
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
- return self.activity.Lap[-1].Track.Trackpoint[-1].Time
+ return self.activity.Lap[-1].Track.Trackpoint[-1].Time.pyval
@property
def distance(self):
- return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters
+ return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters.pyval
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
|
Make sure to return python values, not lxml objects
|
## Code Before:
"Simple parser for Garmin TCX files."
from lxml import objectify
__version__ = '0.3.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees
@property
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time
@property
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
## Instruction:
Make sure to return python values, not lxml objects
## Code After:
"Simple parser for Garmin TCX files."
from lxml import objectify
__version__ = '0.4.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees.pyval
@property
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees.pyval
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time.pyval
@property
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters.pyval
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
|
...
__version__ = '0.4.0'
...
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees.pyval
...
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees.pyval
...
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time.pyval
...
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters.pyval
...
|
a3770920919f02f9609fe0a48789b70ec548cd3d
|
setup.py
|
setup.py
|
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"])
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='[email protected]',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
import sys
import numpy
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse",
sources=["src/nerven/epoc/_parse.pyx"],
include_dirs=[".", numpy.get_include()]),
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='[email protected]',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
Fix the numpy include path used by the Cython extension
|
Fix the numpy include path used by the Cython extension
Apparently this only worked because I had numpy installed system-wide
(broke on virtualenv-only installs).
|
Python
|
mit
|
olorin/nerven,fractalcat/nerven,fractalcat/nerven,olorin/nerven
|
import sys
+
+ import numpy
+
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
- Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"])
+ Extension("nerven.epoc._parse",
+ sources=["src/nerven/epoc/_parse.pyx"],
+ include_dirs=[".", numpy.get_include()]),
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='[email protected]',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
Fix the numpy include path used by the Cython extension
|
## Code Before:
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"])
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='[email protected]',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
## Instruction:
Fix the numpy include path used by the Cython extension
## Code After:
import sys
import numpy
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse",
sources=["src/nerven/epoc/_parse.pyx"],
include_dirs=[".", numpy.get_include()]),
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='[email protected]',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
# ... existing code ...
import sys
import numpy
from distutils.core import setup
# ... modified code ...
ext_modules = [
Extension("nerven.epoc._parse",
sources=["src/nerven/epoc/_parse.pyx"],
include_dirs=[".", numpy.get_include()]),
]
# ... rest of the code ...
|
2bd449678d34187efdf3e4ca92daa28ea1d9fa48
|
imagemodal/mixins/fragment.py
|
imagemodal/mixins/fragment.py
|
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
template = 'templates/' + template
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
|
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
template = 'templates/' + template
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
|
Fix bug to make template optional
|
Fix bug to make template optional
|
Python
|
agpl-3.0
|
Stanford-Online/xblock-image-modal,Stanford-Online/xblock-image-modal,Stanford-Online/xblock-image-modal
|
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
- template = 'templates/' + template
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
+ template = 'templates/' + template
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
|
Fix bug to make template optional
|
## Code Before:
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
template = 'templates/' + template
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
## Instruction:
Fix bug to make template optional
## Code After:
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
template = 'templates/' + template
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
|
// ... existing code ...
"""
context = context or {}
// ... modified code ...
if template:
template = 'templates/' + template
rendered_template = self.loader.render_django_template(
// ... rest of the code ...
|
49dc93d0fd2ab58815d91aba8afc6796cf45ce98
|
migrations/versions/0093_data_gov_uk.py
|
migrations/versions/0093_data_gov_uk.py
|
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
Revert "Remove name from organisation"
|
Revert "Remove name from organisation"
|
Python
|
mit
|
alphagov/notifications-api,alphagov/notifications-api
|
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
- '',
+ 'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
Revert "Remove name from organisation"
|
## Code Before:
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
## Instruction:
Revert "Remove name from organisation"
## Code After:
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
...
'',
'data_gov_uk_x2.png',
''
...
|
b575099c0d1f23916038172d46852a264a5f5a95
|
bluebottle/utils/staticfiles_finders.py
|
bluebottle/utils/staticfiles_finders.py
|
from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg
"""
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
local_path = safe_join(tenant_dir, tenant_path)
if os.path.exists(local_path):
return local_path
return
|
from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg
"""
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return []
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
local_path = safe_join(tenant_dir, tenant_path)
if os.path.exists(local_path):
if all:
return [local_path]
return local_path
return []
|
Fix static files finder errors
|
Fix static files finder errors
|
Python
|
bsd-3-clause
|
jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle
|
from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg
"""
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
+
if not tenant_dir:
- return
+ return []
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
local_path = safe_join(tenant_dir, tenant_path)
if os.path.exists(local_path):
+ if all:
+ return [local_path]
return local_path
- return
+ return []
|
Fix static files finder errors
|
## Code Before:
from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg
"""
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
local_path = safe_join(tenant_dir, tenant_path)
if os.path.exists(local_path):
return local_path
return
## Instruction:
Fix static files finder errors
## Code After:
from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg
"""
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return []
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
local_path = safe_join(tenant_dir, tenant_path)
if os.path.exists(local_path):
if all:
return [local_path]
return local_path
return []
|
// ... existing code ...
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return []
// ... modified code ...
if os.path.exists(local_path):
if all:
return [local_path]
return local_path
return []
// ... rest of the code ...
|
e3a3e729eb60f5a7e134da5b58bb52d672e1d8b2
|
sitenco/config/sphinx.py
|
sitenco/config/sphinx.py
|
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
[sys.executable, 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
|
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
['python3', 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
|
Use python interpreter instead of sys.executable
|
Use python interpreter instead of sys.executable
|
Python
|
bsd-3-clause
|
Kozea/sitenco
|
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
- [sys.executable, 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
+ ['python3', 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
|
Use python interpreter instead of sys.executable
|
## Code Before:
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
[sys.executable, 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
## Instruction:
Use python interpreter instead of sys.executable
## Code After:
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
['python3', 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
|
// ... existing code ...
subprocess.check_call(
['python3', 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
// ... rest of the code ...
|
50dd73443a2bcb0e973162afab6849078e68ac51
|
account_banking_payment_export/migrations/7.0.0.1.165/pre-migration.py
|
account_banking_payment_export/migrations/7.0.0.1.165/pre-migration.py
|
def migrate(cr, version):
cr.execute(
"UPDATE payment_line SET communication = communication2, "
"communication2 = null "
"FROM payment_order "
"WHERE payment_line.order_id = payment_order.id "
"AND payment_order.state in ('draft', 'open') "
"AND payment_line.state = 'normal' "
"AND communication2 is not null")
|
def migrate(cr, version):
cr.execute(
"UPDATE payment_line SET communication = communication2, "
"communication2 = null "
"FROM payment_order "
"WHERE payment_line.order_id = payment_order.id "
"AND payment_order.state in ('draft', 'open') "
"AND payment_line.state = 'normal' "
"AND communication is null"
"AND communication2 is not null")
|
Update SQL query with "and communication is null"
|
Update SQL query with "and communication is null"
|
Python
|
agpl-3.0
|
syci/bank-payment,ndtran/bank-payment,yvaucher/bank-payment,vrenaville/bank-payment,Antiun/bank-payment,rlizana/bank-payment,rschnapka/bank-payment,open-synergy/bank-payment,ndtran/bank-payment,sergio-incaser/bank-payment,hbrunn/bank-payment,rlizana/bank-payment,rschnapka/bank-payment,David-Amaro/bank-payment,yvaucher/bank-payment,sergio-teruel/bank-payment,syci/bank-payment,CompassionCH/bank-payment,diagramsoftware/bank-payment,incaser/bank-payment,vrenaville/bank-payment,CompassionCH/bank-payment,acsone/bank-payment,damdam-s/bank-payment,damdam-s/bank-payment,sergio-teruel/bank-payment,sergiocorato/bank-payment,sergio-incaser/bank-payment,David-Amaro/bank-payment,sergiocorato/bank-payment,Antiun/bank-payment
|
def migrate(cr, version):
cr.execute(
"UPDATE payment_line SET communication = communication2, "
"communication2 = null "
"FROM payment_order "
"WHERE payment_line.order_id = payment_order.id "
"AND payment_order.state in ('draft', 'open') "
"AND payment_line.state = 'normal' "
+ "AND communication is null"
"AND communication2 is not null")
|
Update SQL query with "and communication is null"
|
## Code Before:
def migrate(cr, version):
cr.execute(
"UPDATE payment_line SET communication = communication2, "
"communication2 = null "
"FROM payment_order "
"WHERE payment_line.order_id = payment_order.id "
"AND payment_order.state in ('draft', 'open') "
"AND payment_line.state = 'normal' "
"AND communication2 is not null")
## Instruction:
Update SQL query with "and communication is null"
## Code After:
def migrate(cr, version):
cr.execute(
"UPDATE payment_line SET communication = communication2, "
"communication2 = null "
"FROM payment_order "
"WHERE payment_line.order_id = payment_order.id "
"AND payment_order.state in ('draft', 'open') "
"AND payment_line.state = 'normal' "
"AND communication is null"
"AND communication2 is not null")
|
# ... existing code ...
"AND payment_line.state = 'normal' "
"AND communication is null"
"AND communication2 is not null")
# ... rest of the code ...
|
962f26299a7038879eb1efeb8f16b0801fd9a04a
|
glitter/assets/apps.py
|
glitter/assets/apps.py
|
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
|
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
verbose_name = 'Assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
|
Improve verbose name for assets
|
Improve verbose name for assets
|
Python
|
bsd-3-clause
|
blancltd/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,developersociety/django-glitter
|
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
+ verbose_name = 'Assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
|
Improve verbose name for assets
|
## Code Before:
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
## Instruction:
Improve verbose name for assets
## Code After:
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
verbose_name = 'Assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
|
// ... existing code ...
label = 'glitter_assets'
verbose_name = 'Assets'
// ... rest of the code ...
|
687c0f3c1b8d1b5cd0cee6403a9664bb2b8f63d1
|
cleverbot/utils.py
|
cleverbot/utils.py
|
def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
return property(getter, setter)
|
def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
deleter = lambda self: delattr(self, _name)
return property(getter, setter, deleter)
|
Add deleter to Conversation properties
|
Add deleter to Conversation properties
|
Python
|
mit
|
orlnub123/cleverbot.py
|
def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
+ deleter = lambda self: delattr(self, _name)
- return property(getter, setter)
+ return property(getter, setter, deleter)
|
Add deleter to Conversation properties
|
## Code Before:
def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
return property(getter, setter)
## Instruction:
Add deleter to Conversation properties
## Code After:
def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
deleter = lambda self: delattr(self, _name)
return property(getter, setter, deleter)
|
...
setter = lambda self, value: setattr(self, _name, value)
deleter = lambda self: delattr(self, _name)
return property(getter, setter, deleter)
...
|
45325a43cf4525ef39afec86c03451525f907e92
|
hiro/utils.py
|
hiro/utils.py
|
import datetime
import functools
import time
from .errors import InvalidTypeError
def timedelta_to_seconds(delta):
"""
converts a timedelta object to seconds
"""
seconds = delta.microseconds
seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6
return float(seconds) / 10 ** 6
def time_in_seconds(value):
"""
normalized either a datetime.date, datetime.datetime or float
to a float
"""
if isinstance(value, (float, int)):
return value
elif isinstance(value, (datetime.date, datetime.datetime)):
return time.mktime(value.timetuple())
else:
raise InvalidTypeError(value)
#adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators
def chained(method):
"""
Method decorator to allow chaining.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""
fluent wrapper
"""
result = method(self, *args, **kwargs)
return self if result is None else result
return wrapper
|
import calendar
import datetime
import functools
from .errors import InvalidTypeError
def timedelta_to_seconds(delta):
"""
converts a timedelta object to seconds
"""
seconds = delta.microseconds
seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6
return float(seconds) / 10 ** 6
def time_in_seconds(value):
"""
normalized either a datetime.date, datetime.datetime or float
to a float
"""
if isinstance(value, (float, int)):
return value
elif isinstance(value, (datetime.date, datetime.datetime)):
return calendar.timegm(value.timetuple())
else:
raise InvalidTypeError(value)
#adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators
def chained(method):
"""
Method decorator to allow chaining.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""
fluent wrapper
"""
result = method(self, *args, **kwargs)
return self if result is None else result
return wrapper
|
Fix TZ-dependent return values from time_in_seconds()
|
Fix TZ-dependent return values from time_in_seconds()
time.mktime assumes that the time tuple is in local time, rather than UTC. Use
calendar.timegm instead for consistency.
|
Python
|
mit
|
alisaifee/hiro,alisaifee/hiro
|
+ import calendar
import datetime
import functools
- import time
from .errors import InvalidTypeError
def timedelta_to_seconds(delta):
"""
converts a timedelta object to seconds
"""
seconds = delta.microseconds
seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6
return float(seconds) / 10 ** 6
def time_in_seconds(value):
"""
normalized either a datetime.date, datetime.datetime or float
to a float
"""
if isinstance(value, (float, int)):
return value
elif isinstance(value, (datetime.date, datetime.datetime)):
- return time.mktime(value.timetuple())
+ return calendar.timegm(value.timetuple())
else:
raise InvalidTypeError(value)
#adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators
def chained(method):
"""
Method decorator to allow chaining.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""
fluent wrapper
"""
result = method(self, *args, **kwargs)
return self if result is None else result
return wrapper
|
Fix TZ-dependent return values from time_in_seconds()
|
## Code Before:
import datetime
import functools
import time
from .errors import InvalidTypeError
def timedelta_to_seconds(delta):
"""
converts a timedelta object to seconds
"""
seconds = delta.microseconds
seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6
return float(seconds) / 10 ** 6
def time_in_seconds(value):
"""
normalized either a datetime.date, datetime.datetime or float
to a float
"""
if isinstance(value, (float, int)):
return value
elif isinstance(value, (datetime.date, datetime.datetime)):
return time.mktime(value.timetuple())
else:
raise InvalidTypeError(value)
#adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators
def chained(method):
"""
Method decorator to allow chaining.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""
fluent wrapper
"""
result = method(self, *args, **kwargs)
return self if result is None else result
return wrapper
## Instruction:
Fix TZ-dependent return values from time_in_seconds()
## Code After:
import calendar
import datetime
import functools
from .errors import InvalidTypeError
def timedelta_to_seconds(delta):
"""
converts a timedelta object to seconds
"""
seconds = delta.microseconds
seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6
return float(seconds) / 10 ** 6
def time_in_seconds(value):
"""
normalized either a datetime.date, datetime.datetime or float
to a float
"""
if isinstance(value, (float, int)):
return value
elif isinstance(value, (datetime.date, datetime.datetime)):
return calendar.timegm(value.timetuple())
else:
raise InvalidTypeError(value)
#adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators
def chained(method):
"""
Method decorator to allow chaining.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""
fluent wrapper
"""
result = method(self, *args, **kwargs)
return self if result is None else result
return wrapper
|
# ... existing code ...
import calendar
import datetime
# ... modified code ...
import functools
from .errors import InvalidTypeError
...
elif isinstance(value, (datetime.date, datetime.datetime)):
return calendar.timegm(value.timetuple())
else:
# ... rest of the code ...
|
7e63e514c041ccc12ff5caa01fb4f6684727788b
|
src/PerformerIndexEntry.py
|
src/PerformerIndexEntry.py
|
from BaseIndexEntry import BaseIndexEntry
class PerformerIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(PerformerIndexEntry, self).__init__(name, titles, number)
# Set the performer number on each of the titles
for title in self._titles:
title.performer_number = self._number
# To be set later
self._albums = []
self._albums_initialised = False
self._freeze()
def __str__(self):
return '{}: {} {}, albums: {} {}, titles: {}'.format(
self.__class__.__name__,
self._number,
self._name,
self.number_of_albums, self._albums,
self.number_of_titles)
def init_albums(self):
for title in self._titles:
if title.album_number not in self._albums:
self._albums.append(title.album_number)
self._albums_initialised = True
@property
def albums(self):
if self._albums_initialised:
return self._albums
else:
raise Exception("Albums not initialised.")
@property
def number_of_albums(self):
return len(self._albums)
|
from BaseIndexEntry import BaseIndexEntry
class PerformerIndexEntry(BaseIndexEntry):
'''A class to hold index data for performers.
Performers have titles and albums.
'''
def __init__(self, name, titles, number):
super(PerformerIndexEntry, self).__init__(name, titles, number)
# Set the performer number on each of the titles
for title in self._titles:
title.performer_number = self._number
# To be set later
self._albums = []
self._album_numbers = []
self._albums_initialised = False
self._freeze()
def __str__(self):
return '{}: {} {}, albums: {} {}, titles: {}'.format(
self.__class__.__name__,
self._number,
self._name,
self.number_of_albums, self._album_numbers,
self.number_of_titles)
def init_albums(self, albums):
for title in self._titles:
if title.album_number not in self._album_numbers:
self._album_numbers.append(title.album_number)
self._albums.append(albums[title.album_number])
self._albums_initialised = True
@property
def album_numbers(self):
if self._albums_initialised:
return self._album_numbers
else:
raise Exception("Albums not initialised.")
@property
def number_of_albums(self):
if self._albums_initialised:
return len(self._album_numbers)
else:
raise Exception("Albums not initialised.")
def album(self, album_number):
for a in self._albums:
if a.number == album_number:
return a
return None
def number_of_titles_for_album(self, album_number):
count = set()
for title in self._titles:
if title.album_number == album_number:
count.add(title.index)
return len(count)
|
Store references to albums, add new methods.
|
Store references to albums, add new methods.
|
Python
|
apache-2.0
|
chrrrisw/kmel_db,chrrrisw/kmel_db
|
from BaseIndexEntry import BaseIndexEntry
class PerformerIndexEntry(BaseIndexEntry):
+ '''A class to hold index data for performers.
+
+ Performers have titles and albums.
+ '''
def __init__(self, name, titles, number):
super(PerformerIndexEntry, self).__init__(name, titles, number)
# Set the performer number on each of the titles
for title in self._titles:
title.performer_number = self._number
# To be set later
self._albums = []
+ self._album_numbers = []
self._albums_initialised = False
self._freeze()
def __str__(self):
return '{}: {} {}, albums: {} {}, titles: {}'.format(
self.__class__.__name__,
self._number,
self._name,
- self.number_of_albums, self._albums,
+ self.number_of_albums, self._album_numbers,
self.number_of_titles)
- def init_albums(self):
+ def init_albums(self, albums):
for title in self._titles:
- if title.album_number not in self._albums:
+ if title.album_number not in self._album_numbers:
- self._albums.append(title.album_number)
+ self._album_numbers.append(title.album_number)
+ self._albums.append(albums[title.album_number])
self._albums_initialised = True
@property
- def albums(self):
+ def album_numbers(self):
if self._albums_initialised:
- return self._albums
+ return self._album_numbers
else:
raise Exception("Albums not initialised.")
@property
def number_of_albums(self):
+ if self._albums_initialised:
- return len(self._albums)
+ return len(self._album_numbers)
+ else:
+ raise Exception("Albums not initialised.")
+ def album(self, album_number):
+ for a in self._albums:
+ if a.number == album_number:
+ return a
+ return None
+
+ def number_of_titles_for_album(self, album_number):
+ count = set()
+ for title in self._titles:
+ if title.album_number == album_number:
+ count.add(title.index)
+ return len(count)
+
|
Store references to albums, add new methods.
|
## Code Before:
from BaseIndexEntry import BaseIndexEntry
class PerformerIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(PerformerIndexEntry, self).__init__(name, titles, number)
# Set the performer number on each of the titles
for title in self._titles:
title.performer_number = self._number
# To be set later
self._albums = []
self._albums_initialised = False
self._freeze()
def __str__(self):
return '{}: {} {}, albums: {} {}, titles: {}'.format(
self.__class__.__name__,
self._number,
self._name,
self.number_of_albums, self._albums,
self.number_of_titles)
def init_albums(self):
for title in self._titles:
if title.album_number not in self._albums:
self._albums.append(title.album_number)
self._albums_initialised = True
@property
def albums(self):
if self._albums_initialised:
return self._albums
else:
raise Exception("Albums not initialised.")
@property
def number_of_albums(self):
return len(self._albums)
## Instruction:
Store references to albums, add new methods.
## Code After:
from BaseIndexEntry import BaseIndexEntry
class PerformerIndexEntry(BaseIndexEntry):
'''A class to hold index data for performers.
Performers have titles and albums.
'''
def __init__(self, name, titles, number):
super(PerformerIndexEntry, self).__init__(name, titles, number)
# Set the performer number on each of the titles
for title in self._titles:
title.performer_number = self._number
# To be set later
self._albums = []
self._album_numbers = []
self._albums_initialised = False
self._freeze()
def __str__(self):
return '{}: {} {}, albums: {} {}, titles: {}'.format(
self.__class__.__name__,
self._number,
self._name,
self.number_of_albums, self._album_numbers,
self.number_of_titles)
def init_albums(self, albums):
for title in self._titles:
if title.album_number not in self._album_numbers:
self._album_numbers.append(title.album_number)
self._albums.append(albums[title.album_number])
self._albums_initialised = True
@property
def album_numbers(self):
if self._albums_initialised:
return self._album_numbers
else:
raise Exception("Albums not initialised.")
@property
def number_of_albums(self):
if self._albums_initialised:
return len(self._album_numbers)
else:
raise Exception("Albums not initialised.")
def album(self, album_number):
for a in self._albums:
if a.number == album_number:
return a
return None
def number_of_titles_for_album(self, album_number):
count = set()
for title in self._titles:
if title.album_number == album_number:
count.add(title.index)
return len(count)
|
# ... existing code ...
class PerformerIndexEntry(BaseIndexEntry):
'''A class to hold index data for performers.
Performers have titles and albums.
'''
# ... modified code ...
self._albums = []
self._album_numbers = []
self._albums_initialised = False
...
self._name,
self.number_of_albums, self._album_numbers,
self.number_of_titles)
...
def init_albums(self, albums):
for title in self._titles:
if title.album_number not in self._album_numbers:
self._album_numbers.append(title.album_number)
self._albums.append(albums[title.album_number])
self._albums_initialised = True
...
@property
def album_numbers(self):
if self._albums_initialised:
return self._album_numbers
else:
...
def number_of_albums(self):
if self._albums_initialised:
return len(self._album_numbers)
else:
raise Exception("Albums not initialised.")
def album(self, album_number):
for a in self._albums:
if a.number == album_number:
return a
return None
def number_of_titles_for_album(self, album_number):
count = set()
for title in self._titles:
if title.album_number == album_number:
count.add(title.index)
return len(count)
# ... rest of the code ...
|
8139a3a49e4ee6d1fc8a2a71becbfd6d625b5c5f
|
apps/accounts/serializers.py
|
apps/accounts/serializers.py
|
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
picture = SorlImageField('userprofile.picture', '100x100', crop='center')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
Add picture field member detail api.
|
Add picture field member detail api.
|
Python
|
bsd-3-clause
|
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
|
+ from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
+ picture = SorlImageField('userprofile.picture', '100x100', crop='center')
class Meta:
model = User
- fields = ('id', 'first_name', 'last_name', 'username', 'url')
+ fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
Add picture field member detail api.
|
## Code Before:
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
## Instruction:
Add picture field member detail api.
## Code After:
from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
picture = SorlImageField('userprofile.picture', '100x100', crop='center')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
# ... existing code ...
from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
# ... modified code ...
url = HyperlinkedIdentityField(view_name='member-detail')
picture = SorlImageField('userprofile.picture', '100x100', crop='center')
...
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
# ... rest of the code ...
|
1782b15b244597d56bff18c465237c7e1f3ab482
|
wikked/commands/users.py
|
wikked/commands/users.py
|
import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
|
import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
logger.info("")
logger.info("(copy this into your .wikirc file)")
|
Add some explanation as to what to do with the output.
|
newuser: Add some explanation as to what to do with the output.
|
Python
|
apache-2.0
|
ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked
|
import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
+ logger.info("")
+ logger.info("(copy this into your .wikirc file)")
|
Add some explanation as to what to do with the output.
|
## Code Before:
import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
## Instruction:
Add some explanation as to what to do with the output.
## Code After:
import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
logger.info("")
logger.info("(copy this into your .wikirc file)")
|
// ... existing code ...
logger.info("%s = %s" % (username[0], password))
logger.info("")
logger.info("(copy this into your .wikirc file)")
// ... rest of the code ...
|
6a5c9ccf0bd2582cf42577712309b8fd6e912966
|
blo/__init__.py
|
blo/__init__.py
|
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
Add replace double quotation mark from configuration file parameters.
|
Add replace double quotation mark from configuration file parameters.
|
Python
|
mit
|
10nin/blo,10nin/blo
|
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
- self._db_file_path = config['DB']['DB_PATH']
+ self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
- self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
+ self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
- self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
+ self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
Add replace double quotation mark from configuration file parameters.
|
## Code Before:
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
## Instruction:
Add replace double quotation mark from configuration file parameters.
## Code After:
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
// ... existing code ...
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
// ... rest of the code ...
|
eabc792a4ed87900ae1cb6a9404c3f85874cd053
|
avwx_api/views.py
|
avwx_api/views.py
|
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'})
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
return jsonify({'Error': 'No station given'})
|
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'}), 400
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
return jsonify({'Error': 'No station given'}), 400
|
Return 400 status for incomplete API queries
|
Return 400 status for incomplete API queries
|
Python
|
mit
|
flyinactor91/AVWX-API,flyinactor91/AVWX-API,flyinactor91/AVWX-API
|
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
- return jsonify({'Error': 'No report type given'})
+ return jsonify({'Error': 'No report type given'}), 400
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
- return jsonify({'Error': 'No station given'})
+ return jsonify({'Error': 'No station given'}), 400
|
Return 400 status for incomplete API queries
|
## Code Before:
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'})
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
return jsonify({'Error': 'No station given'})
## Instruction:
Return 400 status for incomplete API queries
## Code After:
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'}), 400
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
return jsonify({'Error': 'No station given'}), 400
|
...
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'}), 400
...
"""Returns no station msg"""
return jsonify({'Error': 'No station given'}), 400
...
|
a90c2eecf95323a6f968e1313c3d7852e4eb25b2
|
speeches/management/commands/populatespeakers.py
|
speeches/management/commands/populatespeakers.py
|
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.POPIT_INSTANCE,
hostname = settings.POPIT_HOSTNAME,
api_version = settings.POPIT_API_VERSION)
results = api.person.get()
for person in results['results']:
speaker, created = Speaker.objects.get_or_create(popit_id=person['_id'])
# we ignore created for now, just always set the name
speaker.name = person['name']
speaker.save();
|
import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.POPIT_INSTANCE,
hostname = settings.POPIT_HOSTNAME,
api_version = settings.POPIT_API_VERSION)
results = api.person.get()
for person in results['results']:
logger.warn('Processing: {0}'.format(person['meta']['api_url']))
speaker, created = Speaker.objects.get_or_create(popit_url=person['meta']['api_url'])
logger.warn('Person was created? {0}'.format(created))
logger.warn('Persons id in the spoke db is: {0}'.format(speaker.id))
# we ignore created for now, just always set the name
speaker.name = person['name']
speaker.save();
|
Update speaker population command to set popit_url instead of popit_id
|
Update speaker population command to set popit_url instead of popit_id
|
Python
|
agpl-3.0
|
opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit
|
+ import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
+ logger = logging.getLogger(__name__)
+
class Command(NoArgsCommand):
+
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.POPIT_INSTANCE,
hostname = settings.POPIT_HOSTNAME,
api_version = settings.POPIT_API_VERSION)
results = api.person.get()
for person in results['results']:
+
+ logger.warn('Processing: {0}'.format(person['meta']['api_url']))
+
- speaker, created = Speaker.objects.get_or_create(popit_id=person['_id'])
+ speaker, created = Speaker.objects.get_or_create(popit_url=person['meta']['api_url'])
+
+ logger.warn('Person was created? {0}'.format(created))
+ logger.warn('Persons id in the spoke db is: {0}'.format(speaker.id))
+
# we ignore created for now, just always set the name
speaker.name = person['name']
speaker.save();
|
Update speaker population command to set popit_url instead of popit_id
|
## Code Before:
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.POPIT_INSTANCE,
hostname = settings.POPIT_HOSTNAME,
api_version = settings.POPIT_API_VERSION)
results = api.person.get()
for person in results['results']:
speaker, created = Speaker.objects.get_or_create(popit_id=person['_id'])
# we ignore created for now, just always set the name
speaker.name = person['name']
speaker.save();
## Instruction:
Update speaker population command to set popit_url instead of popit_id
## Code After:
import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.POPIT_INSTANCE,
hostname = settings.POPIT_HOSTNAME,
api_version = settings.POPIT_API_VERSION)
results = api.person.get()
for person in results['results']:
logger.warn('Processing: {0}'.format(person['meta']['api_url']))
speaker, created = Speaker.objects.get_or_create(popit_url=person['meta']['api_url'])
logger.warn('Person was created? {0}'.format(created))
logger.warn('Persons id in the spoke db is: {0}'.format(speaker.id))
# we ignore created for now, just always set the name
speaker.name = person['name']
speaker.save();
|
// ... existing code ...
import logging
from django.core.management.base import NoArgsCommand
// ... modified code ...
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
...
for person in results['results']:
logger.warn('Processing: {0}'.format(person['meta']['api_url']))
speaker, created = Speaker.objects.get_or_create(popit_url=person['meta']['api_url'])
logger.warn('Person was created? {0}'.format(created))
logger.warn('Persons id in the spoke db is: {0}'.format(speaker.id))
# we ignore created for now, just always set the name
// ... rest of the code ...
|
471828d39ff256961bf48323feb43438901a4762
|
orges/plugins/base.py
|
orges/plugins/base.py
|
"""This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyInvocationPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
|
"""This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
|
Fix broken reference in documentation
|
Fix broken reference in documentation
|
Python
|
bsd-3-clause
|
cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt
|
"""This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
- or from :class:`orges.plugins.dummy.DummyInvocationPlugin` to only override
+ or from :class:`orges.plugins.dummy.DummyPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
|
Fix broken reference in documentation
|
## Code Before:
"""This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyInvocationPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
## Instruction:
Fix broken reference in documentation
## Code After:
"""This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
|
// ... existing code ...
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyPlugin` to only override
methods selectively.
// ... rest of the code ...
|
72f79bb208fb71e40e10e6dd5a2ee8be2e744336
|
pvextractor/tests/test_wcspath.py
|
pvextractor/tests/test_wcspath.py
|
from .. import pvregions
from astropy import wcs
from astropy.io import fits
import numpy as np
import os
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
|
import os
import pytest
import numpy as np
from astropy import wcs
from astropy.io import fits
from .. import pvregions
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
@pytest.mark.xfail
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
|
Mark test as xfail since it requires a fork of pyregion
|
Mark test as xfail since it requires a fork of pyregion
|
Python
|
bsd-3-clause
|
keflavich/pvextractor,radio-astro-tools/pvextractor
|
- from .. import pvregions
+ import os
+
+ import pytest
+ import numpy as np
from astropy import wcs
from astropy.io import fits
- import numpy as np
- import os
+
+ from .. import pvregions
+
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
+
+ @pytest.mark.xfail
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
|
Mark test as xfail since it requires a fork of pyregion
|
## Code Before:
from .. import pvregions
from astropy import wcs
from astropy.io import fits
import numpy as np
import os
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
## Instruction:
Mark test as xfail since it requires a fork of pyregion
## Code After:
import os
import pytest
import numpy as np
from astropy import wcs
from astropy.io import fits
from .. import pvregions
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
@pytest.mark.xfail
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
|
...
import os
import pytest
import numpy as np
from astropy import wcs
...
from astropy.io import fits
from .. import pvregions
...
@pytest.mark.xfail
def test_wcspath():
...
|
d9cb41e12b3f64e71d64dc32fcdc133813897e0b
|
core/data/DataTransformer.py
|
core/data/DataTransformer.py
|
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:type imageData: vtkImageData
:type transform: vtkTransform
"""
reslicer = vtkImageReslice()
reslicer.SetInterpolationModeToCubic()
range = imageData.GetScalarRange()
reslicer.SetBackgroundLevel(range[0])
# reslicer.SetAutoCropOutput(1) # Not sure if this is what we want
reslicer.SetInputData(imageData)
reslicer.SetResliceTransform(transform.GetInverse())
reslicer.Update()
return reslicer.GetOutput()
|
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:type imageData: vtkImageData
:type transform: vtkTransform
"""
range = imageData.GetScalarRange()
reslicer = vtkImageReslice()
reslicer.SetInterpolationModeToCubic()
reslicer.SetBackgroundLevel(range[0])
reslicer.AutoCropOutputOff()
reslicer.SetInputData(imageData)
reslicer.SetResliceTransform(transform.GetInverse())
reslicer.Update()
return reslicer.GetOutput()
|
Make sure that the reslicer does not ommit any image data.
|
Make sure that the reslicer does not ommit any image data.
|
Python
|
mit
|
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
|
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:type imageData: vtkImageData
:type transform: vtkTransform
"""
+ range = imageData.GetScalarRange()
reslicer = vtkImageReslice()
reslicer.SetInterpolationModeToCubic()
- range = imageData.GetScalarRange()
reslicer.SetBackgroundLevel(range[0])
+ reslicer.AutoCropOutputOff()
- # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want
-
reslicer.SetInputData(imageData)
reslicer.SetResliceTransform(transform.GetInverse())
reslicer.Update()
return reslicer.GetOutput()
|
Make sure that the reslicer does not ommit any image data.
|
## Code Before:
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:type imageData: vtkImageData
:type transform: vtkTransform
"""
reslicer = vtkImageReslice()
reslicer.SetInterpolationModeToCubic()
range = imageData.GetScalarRange()
reslicer.SetBackgroundLevel(range[0])
# reslicer.SetAutoCropOutput(1) # Not sure if this is what we want
reslicer.SetInputData(imageData)
reslicer.SetResliceTransform(transform.GetInverse())
reslicer.Update()
return reslicer.GetOutput()
## Instruction:
Make sure that the reslicer does not ommit any image data.
## Code After:
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:type imageData: vtkImageData
:type transform: vtkTransform
"""
range = imageData.GetScalarRange()
reslicer = vtkImageReslice()
reslicer.SetInterpolationModeToCubic()
reslicer.SetBackgroundLevel(range[0])
reslicer.AutoCropOutputOff()
reslicer.SetInputData(imageData)
reslicer.SetResliceTransform(transform.GetInverse())
reslicer.Update()
return reslicer.GetOutput()
|
...
"""
range = imageData.GetScalarRange()
reslicer = vtkImageReslice()
...
reslicer.SetInterpolationModeToCubic()
reslicer.SetBackgroundLevel(range[0])
reslicer.AutoCropOutputOff()
reslicer.SetInputData(imageData)
...
|
23e1efbd24e317e6571d8436fc414dae9a3da767
|
salt/output/__init__.py
|
salt/output/__init__.py
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
print(get_printout(out, opts)(data).rstrip())
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
for outputter in STATIC:
if outputter in opts:
if opts[outputter]:
if outputter == 'text_out':
out = 'txt'
else:
out = outputter
if out is None:
out = 'pprint'
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
print(get_printout(out, opts)(data).rstrip())
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
for outputter in STATIC:
if outputter in opts:
if opts[outputter]:
if outputter == 'text_out':
out = 'txt'
else:
out = outputter
if out is None:
out = 'pprint'
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
def out_format(data, out, opts=None):
'''
Return the formatted outputter string for the passed data
'''
return get_printout(out, opts)(data).rstrip()
|
Add function to outputter that returns the raw string to print
|
Add function to outputter that returns the raw string to print
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
print(get_printout(out, opts)(data).rstrip())
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
for outputter in STATIC:
if outputter in opts:
if opts[outputter]:
if outputter == 'text_out':
out = 'txt'
else:
out = outputter
if out is None:
out = 'pprint'
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
+
+ def out_format(data, out, opts=None):
+ '''
+ Return the formatted outputter string for the passed data
+ '''
+ return get_printout(out, opts)(data).rstrip()
+
+
|
Add function to outputter that returns the raw string to print
|
## Code Before:
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
print(get_printout(out, opts)(data).rstrip())
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
for outputter in STATIC:
if outputter in opts:
if opts[outputter]:
if outputter == 'text_out':
out = 'txt'
else:
out = outputter
if out is None:
out = 'pprint'
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
## Instruction:
Add function to outputter that returns the raw string to print
## Code After:
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
print(get_printout(out, opts)(data).rstrip())
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
for outputter in STATIC:
if outputter in opts:
if opts[outputter]:
if outputter == 'text_out':
out = 'txt'
else:
out = outputter
if out is None:
out = 'pprint'
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
def out_format(data, out, opts=None):
'''
Return the formatted outputter string for the passed data
'''
return get_printout(out, opts)(data).rstrip()
|
# ... existing code ...
return outputters[out]
def out_format(data, out, opts=None):
'''
Return the formatted outputter string for the passed data
'''
return get_printout(out, opts)(data).rstrip()
# ... rest of the code ...
|
30a173da5850a457393cfdf47b7c0db303cdd2e9
|
tests/test_utils.py
|
tests/test_utils.py
|
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}}
assert utils.merge_dict(dict1, dict2) == expected
def test_import_string():
utils.import_string('cihai')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai2')
|
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}}
assert utils.merge_dict(dict1, dict2) == expected
def test_import_string():
utils.import_string('cihai')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai.core.nonexistingimport')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai2')
|
Test importing of module with unexisting target inside
|
Test importing of module with unexisting target inside
There's a coverage case where a module exists, but what's inside it
isn't covered.
|
Python
|
mit
|
cihai/cihai-python,cihai/cihai,cihai/cihai
|
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}}
assert utils.merge_dict(dict1, dict2) == expected
def test_import_string():
utils.import_string('cihai')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
+ utils.import_string('cihai.core.nonexistingimport')
+
+ with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai2')
|
Test importing of module with unexisting target inside
|
## Code Before:
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}}
assert utils.merge_dict(dict1, dict2) == expected
def test_import_string():
utils.import_string('cihai')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai2')
## Instruction:
Test importing of module with unexisting target inside
## Code After:
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from cihai import exc, utils
def test_merge_dict():
dict1 = {'hi world': 1, 'innerdict': {'hey': 1}}
dict2 = {'innerdict': {'welcome': 2}}
expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}}
assert utils.merge_dict(dict1, dict2) == expected
def test_import_string():
utils.import_string('cihai')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai.core.nonexistingimport')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai2')
|
// ... existing code ...
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai.core.nonexistingimport')
with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
utils.import_string('cihai2')
// ... rest of the code ...
|
7a3c4eed8888c8c2befc94020bebbfc18e1d6156
|
src/redis_client.py
|
src/redis_client.py
|
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
@defer.inlineCallbacks
def run_redis_client(on_started):
pony = yield redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = True)
global connection
connection = pony
on_started()
|
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
def run_redis_client(on_started):
df = redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = False)
def done(pony):
global connection
connection = pony
on_started()
df.addCallback(done)
|
Fix the Redis client connection to actually work
|
Fix the Redis client connection to actually work
It previously lied.
|
Python
|
mit
|
prophile/compd,prophile/compd
|
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
- @defer.inlineCallbacks
def run_redis_client(on_started):
- pony = yield redis.makeConnection(config.redis['host'],
+ df = redis.makeConnection(config.redis['host'],
- config.redis['port'],
+ config.redis['port'],
- config.redis['db'],
+ config.redis['db'],
- poolsize = 8,
+ poolsize = 8,
- reconnect = True,
+ reconnect = True,
- isLazy = True)
+ isLazy = False)
+ def done(pony):
- global connection
+ global connection
- connection = pony
+ connection = pony
- on_started()
+ on_started()
+ df.addCallback(done)
|
Fix the Redis client connection to actually work
|
## Code Before:
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
@defer.inlineCallbacks
def run_redis_client(on_started):
pony = yield redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = True)
global connection
connection = pony
on_started()
## Instruction:
Fix the Redis client connection to actually work
## Code After:
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
def run_redis_client(on_started):
df = redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = False)
def done(pony):
global connection
connection = pony
on_started()
df.addCallback(done)
|
// ... existing code ...
def run_redis_client(on_started):
df = redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = False)
def done(pony):
global connection
connection = pony
on_started()
df.addCallback(done)
// ... rest of the code ...
|
bd18f52c2ee41bbc9c33a3b98fdac1ce2ea18ea7
|
rest/urls.py
|
rest/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.CommentView.as_view(), name='comments'),
url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
name='author'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
views.AuthorFriendsView.as_view(), name='friends'),
url(r'^friendrequest/$', views.FriendRequestView.as_view(),
name='friendrequest'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
r'(?P<other>[\w\-\.]+(:\d{2,5})?(/[0-9a-fA-F\-]+)*/)$',
views.AuthorIsFriendsView.as_view(), name='isfriends')
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.CommentView.as_view(), name='comments'),
url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
name='author'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
views.AuthorFriendsView.as_view(), name='friends'),
url(r'^friendrequest/$', views.FriendRequestView.as_view(),
name='friendrequest'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
r'(?P<other>[\w\-\.]+(:\d{2,5})?(/\w+)*/)$',
views.AuthorIsFriendsView.as_view(), name='isfriends')
]
|
Revert "Handle second service UUID better."
|
Revert "Handle second service UUID better."
Realized I actually made the url parsing worse, this isn't what we wanted.
|
Python
|
apache-2.0
|
CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.CommentView.as_view(), name='comments'),
url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
name='author'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
views.AuthorFriendsView.as_view(), name='friends'),
url(r'^friendrequest/$', views.FriendRequestView.as_view(),
name='friendrequest'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
- r'(?P<other>[\w\-\.]+(:\d{2,5})?(/[0-9a-fA-F\-]+)*/)$',
+ r'(?P<other>[\w\-\.]+(:\d{2,5})?(/\w+)*/)$',
views.AuthorIsFriendsView.as_view(), name='isfriends')
]
|
Revert "Handle second service UUID better."
|
## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.CommentView.as_view(), name='comments'),
url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
name='author'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
views.AuthorFriendsView.as_view(), name='friends'),
url(r'^friendrequest/$', views.FriendRequestView.as_view(),
name='friendrequest'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
r'(?P<other>[\w\-\.]+(:\d{2,5})?(/[0-9a-fA-F\-]+)*/)$',
views.AuthorIsFriendsView.as_view(), name='isfriends')
]
## Instruction:
Revert "Handle second service UUID better."
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.CommentView.as_view(), name='comments'),
url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
name='author'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
views.AuthorFriendsView.as_view(), name='friends'),
url(r'^friendrequest/$', views.FriendRequestView.as_view(),
name='friendrequest'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
r'(?P<other>[\w\-\.]+(:\d{2,5})?(/\w+)*/)$',
views.AuthorIsFriendsView.as_view(), name='isfriends')
]
|
# ... existing code ...
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
r'(?P<other>[\w\-\.]+(:\d{2,5})?(/\w+)*/)$',
views.AuthorIsFriendsView.as_view(), name='isfriends')
# ... rest of the code ...
|
8e7feb7bc09feeca8d3fa0ea9ce6b76edec61ff1
|
test/contrib/test_pyopenssl.py
|
test/contrib/test_pyopenssl.py
|
from urllib3.packages import six
if six.PY3:
from nose.plugins.skip import SkipTest
raise SkipTest('Testing of PyOpenSSL disabled')
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
|
from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
|
Disable PyOpenSSL tests by default.
|
Disable PyOpenSSL tests by default.
|
Python
|
mit
|
Lukasa/urllib3,matejcik/urllib3,asmeurer/urllib3,sornars/urllib3,silveringsea/urllib3,denim2x/urllib3,sornars/urllib3,Geoion/urllib3,haikuginger/urllib3,matejcik/urllib3,Geoion/urllib3,boyxuper/urllib3,urllib3/urllib3,haikuginger/urllib3,sileht/urllib3,sigmavirus24/urllib3,gardner/urllib3,silveringsea/urllib3,luca3m/urllib3,msabramo/urllib3,boyxuper/urllib3,sigmavirus24/urllib3,Disassem/urllib3,Disassem/urllib3,mikelambert/urllib3,denim2x/urllib3,tutumcloud/urllib3,msabramo/urllib3,sileht/urllib3,urllib3/urllib3,asmeurer/urllib3,mikelambert/urllib3,gardner/urllib3,Lukasa/urllib3,luca3m/urllib3,tutumcloud/urllib3
|
+ from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
- from nose.plugins.skip import SkipTest
- raise SkipTest('Testing of PyOpenSSL disabled')
+ raise SkipTest('Testing of PyOpenSSL disabled on PY3')
+ try:
- from urllib3.contrib.pyopenssl import (inject_into_urllib3,
+ from urllib3.contrib.pyopenssl import (inject_into_urllib3,
- extract_from_urllib3)
+ extract_from_urllib3)
+ except ImportError as e:
+ raise SkipTest('Could not import PyOpenSSL: %r' % e)
+
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
|
Disable PyOpenSSL tests by default.
|
## Code Before:
from urllib3.packages import six
if six.PY3:
from nose.plugins.skip import SkipTest
raise SkipTest('Testing of PyOpenSSL disabled')
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
## Instruction:
Disable PyOpenSSL tests by default.
## Code After:
from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
|
# ... existing code ...
from nose.plugins.skip import SkipTest
from urllib3.packages import six
# ... modified code ...
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
# ... rest of the code ...
|
75a598e2b9cf237448cd1b1934d3d58d093808ec
|
server/scraper/util.py
|
server/scraper/util.py
|
import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_file(obj, path):
"""
Write an object to JSON at the specified path.
"""
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
with open(path, mode='w') as f:
json.dump(obj, f, sort_keys=True)
def split_price(meal):
price = meal.split('-')[-1].strip()
name = '-'.join(meal.split('-')[:-1]).strip()
return name, price
|
import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_file(obj, path):
"""
Write an object to JSON at the specified path.
"""
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
with open(path, mode='w') as f:
json.dump(obj, f, sort_keys=True)
def split_price(meal):
if "-" in meal:
price = meal.split('-')[-1].strip()
name = '-'.join(meal.split('-')[:-1]).strip()
return name, price
else:
return meal.strip(), ""
|
Fix price in de brug
|
Fix price in de brug
|
Python
|
mit
|
ZeusWPI/hydra,ZeusWPI/hydra,ZeusWPI/hydra
|
import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_file(obj, path):
"""
Write an object to JSON at the specified path.
"""
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
with open(path, mode='w') as f:
json.dump(obj, f, sort_keys=True)
def split_price(meal):
+ if "-" in meal:
- price = meal.split('-')[-1].strip()
+ price = meal.split('-')[-1].strip()
- name = '-'.join(meal.split('-')[:-1]).strip()
+ name = '-'.join(meal.split('-')[:-1]).strip()
- return name, price
+ return name, price
+ else:
+ return meal.strip(), ""
|
Fix price in de brug
|
## Code Before:
import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_file(obj, path):
"""
Write an object to JSON at the specified path.
"""
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
with open(path, mode='w') as f:
json.dump(obj, f, sort_keys=True)
def split_price(meal):
price = meal.split('-')[-1].strip()
name = '-'.join(meal.split('-')[:-1]).strip()
return name, price
## Instruction:
Fix price in de brug
## Code After:
import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_file(obj, path):
"""
Write an object to JSON at the specified path.
"""
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
with open(path, mode='w') as f:
json.dump(obj, f, sort_keys=True)
def split_price(meal):
if "-" in meal:
price = meal.split('-')[-1].strip()
name = '-'.join(meal.split('-')[:-1]).strip()
return name, price
else:
return meal.strip(), ""
|
...
def split_price(meal):
if "-" in meal:
price = meal.split('-')[-1].strip()
name = '-'.join(meal.split('-')[:-1]).strip()
return name, price
else:
return meal.strip(), ""
...
|
294b305aa7e0c78c72d4eac87ded476425873b62
|
src/inbox/server/basicauth.py
|
src/inbox/server/basicauth.py
|
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
class AuthError(Exception):
pass
def password_auth(email_address):
pw = getpass.getpass('Password for %s (hidden): ' % email_address)
if len(pw) <= 0:
raise AuthError('Password required.')
return dict(email=email_address, password=pw)
|
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
message = 'Password for {0}(hidden): '
class AuthError(Exception):
pass
def password_auth(email_address, message=message):
pw = getpass.getpass(message.format(email_address))
if len(pw) <= 0:
raise AuthError('Password required.')
return dict(email=email_address, password=pw)
|
Change for EAS invalid pw case, to allow user to re-enter pw once before raising error.
|
Change for EAS invalid pw case, to allow user to re-enter pw once before raising error.
Summary:
One line change in password_auth to allow password re-rentry.
See D106 too
Test Plan: None
Reviewers: mg
Differential Revision: https://review.inboxapp.com/D107
|
Python
|
agpl-3.0
|
ErinCall/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,rmasters/inbox,closeio/nylas,EthanBlackburn/sync-engine,Eagles2F/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,jobscore/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,EthanBlackburn/sync-engine,rmasters/inbox,gale320/sync-engine,Eagles2F/sync-engine,gale320/sync-engine,PriviPK/privipk-sync-engine,jobscore/sync-engine,nylas/sync-engine,ErinCall/sync-engine,nylas/sync-engine,ErinCall/sync-engine,closeio/nylas,gale320/sync-engine,closeio/nylas,wakermahmud/sync-engine,closeio/nylas,nylas/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,gale320/sync-engine,rmasters/inbox,Eagles2F/sync-engine,rmasters/inbox,nylas/sync-engine,EthanBlackburn/sync-engine
|
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
+ message = 'Password for {0}(hidden): '
class AuthError(Exception):
pass
- def password_auth(email_address):
+ def password_auth(email_address, message=message):
- pw = getpass.getpass('Password for %s (hidden): ' % email_address)
+ pw = getpass.getpass(message.format(email_address))
if len(pw) <= 0:
raise AuthError('Password required.')
return dict(email=email_address, password=pw)
|
Change for EAS invalid pw case, to allow user to re-enter pw once before raising error.
|
## Code Before:
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
class AuthError(Exception):
pass
def password_auth(email_address):
pw = getpass.getpass('Password for %s (hidden): ' % email_address)
if len(pw) <= 0:
raise AuthError('Password required.')
return dict(email=email_address, password=pw)
## Instruction:
Change for EAS invalid pw case, to allow user to re-enter pw once before raising error.
## Code After:
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
message = 'Password for {0}(hidden): '
class AuthError(Exception):
pass
def password_auth(email_address, message=message):
pw = getpass.getpass(message.format(email_address))
if len(pw) <= 0:
raise AuthError('Password required.')
return dict(email=email_address, password=pw)
|
# ... existing code ...
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
message = 'Password for {0}(hidden): '
# ... modified code ...
def password_auth(email_address, message=message):
pw = getpass.getpass(message.format(email_address))
# ... rest of the code ...
|
17ddd05e35f7cff90530cdb2df0c4971b97e7302
|
cmcb/utils.py
|
cmcb/utils.py
|
import sys
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
if log:
print('calling', function.__name__, args, kwargs, file=out)
result = function(*args, **kwargs)
if log:
print('result', function.__name__, result, file=out)
return result
return wrapped_function
return wrapper
def redis_timeout_async_method_cache(timeout, redis_url):
def wrapper(async_method):
cache = redis.from_url(redis_url)
@wraps(async_method)
async def wrapped_method(self, *args, **kwargs):
name_and_args = (async_method.__name__,) + tuple(a for a in args)
key = _make_key(name_and_args, kwargs, False)
cached_result = cache.get(key)
if cached_result is not None:
return cached_result.decode('utf-8')
result = await async_method(self, *args, **kwargs)
cache.setex(key, result, timeout)
return result
return wrapped_method
return wrapper
|
import sys
import inspect
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
result = function(*args, **kwargs)
if log:
print(function.__name__, args, kwargs, result, file=out)
return result
return wrapped_function
def async_wrapper(async_function):
@wraps(async_function)
async def wrapped_async_function(*args, **kwargs):
result = await async_function(*args, **kwargs)
if log:
print(async_function.__name__, args, kwargs, result, file=out)
return result
return wrapped_async_function
def cool_wrapper(function):
is_async_function = inspect.iscoroutinefunction(function)
if is_async_function:
return async_wrapper(function)
else:
return wrapper(function)
return cool_wrapper
def redis_timeout_async_method_cache(timeout, redis_url):
def wrapper(async_method):
cache = redis.from_url(redis_url)
@wraps(async_method)
async def wrapped_method(self, *args, **kwargs):
name_and_args = (async_method.__name__,) + tuple(a for a in args)
key = _make_key(name_and_args, kwargs, False)
cached_result = cache.get(key)
if cached_result is not None:
return cached_result.decode('utf-8')
result = await async_method(self, *args, **kwargs)
cache.setex(key, result, timeout)
return result
return wrapped_method
return wrapper
|
Update logging to log async functions properly
|
Update logging to log async functions properly
|
Python
|
mit
|
festinuz/cmcb,festinuz/cmcb
|
import sys
+ import inspect
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
- if log:
- print('calling', function.__name__, args, kwargs, file=out)
result = function(*args, **kwargs)
if log:
- print('result', function.__name__, result, file=out)
+ print(function.__name__, args, kwargs, result, file=out)
return result
return wrapped_function
+
+ def async_wrapper(async_function):
+ @wraps(async_function)
+ async def wrapped_async_function(*args, **kwargs):
+ result = await async_function(*args, **kwargs)
+ if log:
+ print(async_function.__name__, args, kwargs, result, file=out)
+ return result
+ return wrapped_async_function
+
+ def cool_wrapper(function):
+ is_async_function = inspect.iscoroutinefunction(function)
+ if is_async_function:
+ return async_wrapper(function)
+ else:
+ return wrapper(function)
+
- return wrapper
+ return cool_wrapper
def redis_timeout_async_method_cache(timeout, redis_url):
def wrapper(async_method):
cache = redis.from_url(redis_url)
@wraps(async_method)
async def wrapped_method(self, *args, **kwargs):
name_and_args = (async_method.__name__,) + tuple(a for a in args)
key = _make_key(name_and_args, kwargs, False)
cached_result = cache.get(key)
if cached_result is not None:
return cached_result.decode('utf-8')
result = await async_method(self, *args, **kwargs)
cache.setex(key, result, timeout)
return result
return wrapped_method
return wrapper
|
Update logging to log async functions properly
|
## Code Before:
import sys
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
if log:
print('calling', function.__name__, args, kwargs, file=out)
result = function(*args, **kwargs)
if log:
print('result', function.__name__, result, file=out)
return result
return wrapped_function
return wrapper
def redis_timeout_async_method_cache(timeout, redis_url):
def wrapper(async_method):
cache = redis.from_url(redis_url)
@wraps(async_method)
async def wrapped_method(self, *args, **kwargs):
name_and_args = (async_method.__name__,) + tuple(a for a in args)
key = _make_key(name_and_args, kwargs, False)
cached_result = cache.get(key)
if cached_result is not None:
return cached_result.decode('utf-8')
result = await async_method(self, *args, **kwargs)
cache.setex(key, result, timeout)
return result
return wrapped_method
return wrapper
## Instruction:
Update logging to log async functions properly
## Code After:
import sys
import inspect
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
result = function(*args, **kwargs)
if log:
print(function.__name__, args, kwargs, result, file=out)
return result
return wrapped_function
def async_wrapper(async_function):
@wraps(async_function)
async def wrapped_async_function(*args, **kwargs):
result = await async_function(*args, **kwargs)
if log:
print(async_function.__name__, args, kwargs, result, file=out)
return result
return wrapped_async_function
def cool_wrapper(function):
is_async_function = inspect.iscoroutinefunction(function)
if is_async_function:
return async_wrapper(function)
else:
return wrapper(function)
return cool_wrapper
def redis_timeout_async_method_cache(timeout, redis_url):
def wrapper(async_method):
cache = redis.from_url(redis_url)
@wraps(async_method)
async def wrapped_method(self, *args, **kwargs):
name_and_args = (async_method.__name__,) + tuple(a for a in args)
key = _make_key(name_and_args, kwargs, False)
cached_result = cache.get(key)
if cached_result is not None:
return cached_result.decode('utf-8')
result = await async_method(self, *args, **kwargs)
cache.setex(key, result, timeout)
return result
return wrapped_method
return wrapper
|
# ... existing code ...
import sys
import inspect
from functools import wraps, _make_key
# ... modified code ...
def wrapped_function(*args, **kwargs):
result = function(*args, **kwargs)
...
if log:
print(function.__name__, args, kwargs, result, file=out)
return result
...
return wrapped_function
def async_wrapper(async_function):
@wraps(async_function)
async def wrapped_async_function(*args, **kwargs):
result = await async_function(*args, **kwargs)
if log:
print(async_function.__name__, args, kwargs, result, file=out)
return result
return wrapped_async_function
def cool_wrapper(function):
is_async_function = inspect.iscoroutinefunction(function)
if is_async_function:
return async_wrapper(function)
else:
return wrapper(function)
return cool_wrapper
# ... rest of the code ...
|
bf241d6c7aa96c5fca834eb1063fc009a9320329
|
portfolio/urls.py
|
portfolio/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
|
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
# url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
|
Change URL pattern for contacts
|
Change URL pattern for contacts
|
Python
|
mit
|
bacarlino/portfolio,bacarlino/portfolio,bacarlino/portfolio
|
from django.conf.urls import url
+ from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
+ url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
- url(r'^contact/$', views.contact, name='contact'),
+ # url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
|
Change URL pattern for contacts
|
## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
## Instruction:
Change URL pattern for contacts
## Code After:
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
# url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
|
...
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
...
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
# url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
...
|
3352920f7e92e2732eb2914313bdee6b5ab7f549
|
setup.py
|
setup.py
|
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=Distribution,
name='mujincontrollerclient',
version=version['__version__'],
packages=['mujincontrollerclient'],
package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'},
scripts=['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py'],
locale_dir='locale',
license='Apache License, Version 2.0',
long_description=open('README.rst').read(),
# flake8 compliance configuration
enable_flake8=True, # Enable checks
fail_on_flake=True, # Fail builds when checks fail
install_requires=[],
)
|
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=Distribution,
name='mujincontrollerclient',
version=version['__version__'],
packages=['mujincontrollerclient'],
package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'},
data_files=[
# using scripts= will cause the first line of the script being modified for python2 or python3
# put the scripts in data_files will copy them as-is
('bin', ['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py']),
],
locale_dir='locale',
license='Apache License, Version 2.0',
long_description=open('README.rst').read(),
# flake8 compliance configuration
enable_flake8=True, # Enable checks
fail_on_flake=True, # Fail builds when checks fail
install_requires=[],
)
|
Fix bin scripts having python2 or python3 specific path.
|
Fix bin scripts having python2 or python3 specific path.
|
Python
|
apache-2.0
|
mujin/mujincontrollerclientpy
|
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=Distribution,
name='mujincontrollerclient',
version=version['__version__'],
packages=['mujincontrollerclient'],
package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'},
+ data_files=[
+ # using scripts= will cause the first line of the script being modified for python2 or python3
+ # put the scripts in data_files will copy them as-is
- scripts=['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py'],
+ ('bin', ['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py']),
+ ],
locale_dir='locale',
license='Apache License, Version 2.0',
long_description=open('README.rst').read(),
# flake8 compliance configuration
enable_flake8=True, # Enable checks
fail_on_flake=True, # Fail builds when checks fail
install_requires=[],
)
|
Fix bin scripts having python2 or python3 specific path.
|
## Code Before:
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=Distribution,
name='mujincontrollerclient',
version=version['__version__'],
packages=['mujincontrollerclient'],
package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'},
scripts=['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py'],
locale_dir='locale',
license='Apache License, Version 2.0',
long_description=open('README.rst').read(),
# flake8 compliance configuration
enable_flake8=True, # Enable checks
fail_on_flake=True, # Fail builds when checks fail
install_requires=[],
)
## Instruction:
Fix bin scripts having python2 or python3 specific path.
## Code After:
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=Distribution,
name='mujincontrollerclient',
version=version['__version__'],
packages=['mujincontrollerclient'],
package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'},
data_files=[
# using scripts= will cause the first line of the script being modified for python2 or python3
# put the scripts in data_files will copy them as-is
('bin', ['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py']),
],
locale_dir='locale',
license='Apache License, Version 2.0',
long_description=open('README.rst').read(),
# flake8 compliance configuration
enable_flake8=True, # Enable checks
fail_on_flake=True, # Fail builds when checks fail
install_requires=[],
)
|
...
package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'},
data_files=[
# using scripts= will cause the first line of the script being modified for python2 or python3
# put the scripts in data_files will copy them as-is
('bin', ['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py']),
],
locale_dir='locale',
...
|
60eb4891013dfc5a00fbecd98a79999a365c0839
|
example/article/admin.py
|
example/article/admin.py
|
from django.contrib import admin
from django.forms import ModelForm
from article.models import Article
# The timezone support was introduced in Django 1.4, fallback to standard library for 1.3.
try:
from django.utils.timezone import now
except ImportError:
from datetime import datetime
now = datetime.now
class ArticleAdminForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ArticleAdminForm, self).__init__(*args, **kwargs)
self.fields['publication_date'].required = False # The admin's .save() method fills in a default.
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
form = ArticleAdminForm
fieldsets = (
(None, {
'fields': ('title', 'slug',),
}),
("Contents", {
'fields': ('content',),
}),
("Publication settings", {
'fields': ('publication_date', 'enable_comments',),
}),
)
def save_model(self, request, obj, form, change):
if not obj.publication_date:
# auto_now_add makes the field uneditable.
# a default in the model fills the field before the post is written (too early)
obj.publication_date = now()
obj.save()
admin.site.register(Article, ArticleAdmin)
|
from django.contrib import admin
from django.forms import ModelForm
from django.utils.timezone import now
from article.models import Article
class ArticleAdminForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ArticleAdminForm, self).__init__(*args, **kwargs)
self.fields['publication_date'].required = False # The admin's .save() method fills in a default.
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
form = ArticleAdminForm
fieldsets = (
(None, {
'fields': ('title', 'slug',),
}),
("Contents", {
'fields': ('content',),
}),
("Publication settings", {
'fields': ('publication_date', 'enable_comments',),
}),
)
def save_model(self, request, obj, form, change):
if not obj.publication_date:
# auto_now_add makes the field uneditable.
# a default in the model fills the field before the post is written (too early)
obj.publication_date = now()
obj.save()
admin.site.register(Article, ArticleAdmin)
|
Remove old Django compatibility code
|
Remove old Django compatibility code
|
Python
|
apache-2.0
|
django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments
|
from django.contrib import admin
from django.forms import ModelForm
+ from django.utils.timezone import now
from article.models import Article
-
- # The timezone support was introduced in Django 1.4, fallback to standard library for 1.3.
- try:
- from django.utils.timezone import now
- except ImportError:
- from datetime import datetime
- now = datetime.now
class ArticleAdminForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ArticleAdminForm, self).__init__(*args, **kwargs)
self.fields['publication_date'].required = False # The admin's .save() method fills in a default.
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
form = ArticleAdminForm
fieldsets = (
(None, {
'fields': ('title', 'slug',),
}),
("Contents", {
'fields': ('content',),
}),
("Publication settings", {
'fields': ('publication_date', 'enable_comments',),
}),
)
def save_model(self, request, obj, form, change):
if not obj.publication_date:
# auto_now_add makes the field uneditable.
# a default in the model fills the field before the post is written (too early)
obj.publication_date = now()
obj.save()
admin.site.register(Article, ArticleAdmin)
|
Remove old Django compatibility code
|
## Code Before:
from django.contrib import admin
from django.forms import ModelForm
from article.models import Article
# The timezone support was introduced in Django 1.4, fallback to standard library for 1.3.
try:
from django.utils.timezone import now
except ImportError:
from datetime import datetime
now = datetime.now
class ArticleAdminForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ArticleAdminForm, self).__init__(*args, **kwargs)
self.fields['publication_date'].required = False # The admin's .save() method fills in a default.
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
form = ArticleAdminForm
fieldsets = (
(None, {
'fields': ('title', 'slug',),
}),
("Contents", {
'fields': ('content',),
}),
("Publication settings", {
'fields': ('publication_date', 'enable_comments',),
}),
)
def save_model(self, request, obj, form, change):
if not obj.publication_date:
# auto_now_add makes the field uneditable.
# a default in the model fills the field before the post is written (too early)
obj.publication_date = now()
obj.save()
admin.site.register(Article, ArticleAdmin)
## Instruction:
Remove old Django compatibility code
## Code After:
from django.contrib import admin
from django.forms import ModelForm
from django.utils.timezone import now
from article.models import Article
class ArticleAdminForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ArticleAdminForm, self).__init__(*args, **kwargs)
self.fields['publication_date'].required = False # The admin's .save() method fills in a default.
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
form = ArticleAdminForm
fieldsets = (
(None, {
'fields': ('title', 'slug',),
}),
("Contents", {
'fields': ('content',),
}),
("Publication settings", {
'fields': ('publication_date', 'enable_comments',),
}),
)
def save_model(self, request, obj, form, change):
if not obj.publication_date:
# auto_now_add makes the field uneditable.
# a default in the model fills the field before the post is written (too early)
obj.publication_date = now()
obj.save()
admin.site.register(Article, ArticleAdmin)
|
# ... existing code ...
from django.forms import ModelForm
from django.utils.timezone import now
from article.models import Article
# ... rest of the code ...
|
3875b14e6c94c4a6a7ad47a3eb55cae62096d0e4
|
agateremote/table_remote.py
|
agateremote/table_remote.py
|
import agate
import requests
import six
def from_url(cls, url, callback=agate.Table.from_csv, binary=False, **kwargs):
"""
Download a remote file and pass it to a :class:`.Table` parser.
:param url:
URL to a file to load.
:param callback:
The method to invoke to create the table. Typically either
:meth:`agate.Table.from_csv` or :meth:`agate.Table.from_json`, but
it could also be a method provided by an extension.
:param binary:
If :code:`False` the downloaded data will be processed as a string,
otherwise it will be treated as binary data. (e.g. for Excel files)
"""
r = requests.get(url)
if binary:
content = six.BytesIO(r.content)
else:
if six.PY2:
content = six.StringIO(r.content.decode('utf-8'))
else:
content = six.StringIO(r.text)
return callback(content, **kwargs)
agate.Table.from_url = classmethod(from_url)
|
import agate
import requests
import six
def from_url(cls, url, callback=agate.Table.from_csv, requests_encoding=None, binary=False, **kwargs):
"""
Download a remote file and pass it to a :class:`.Table` parser.
:param url:
URL to a file to load.
:param callback:
The method to invoke to create the table. Typically either
:meth:`agate.Table.from_csv` or :meth:`agate.Table.from_json`, but
it could also be a method provided by an extension.
:param requests_encoding:
An encoding to pass to requests for use when decoding the response
content. (e.g. force use of 'utf-8-sig' when CSV has a BOM).
:param binary:
If :code:`False` the downloaded data will be processed as a string,
otherwise it will be treated as binary data. (e.g. for Excel files)
"""
r = requests.get(url)
if requests_encoding:
r.encoding = requests_encoding
if binary:
content = six.BytesIO(r.content)
else:
if six.PY2:
content = six.StringIO(r.content.decode('utf-8'))
else:
content = six.StringIO(r.text)
return callback(content, **kwargs)
agate.Table.from_url = classmethod(from_url)
|
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
|
Add 'requests_encoding' parameter
Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
|
Python
|
mit
|
wireservice/agate-remote
|
import agate
import requests
import six
- def from_url(cls, url, callback=agate.Table.from_csv, binary=False, **kwargs):
+ def from_url(cls, url, callback=agate.Table.from_csv, requests_encoding=None, binary=False, **kwargs):
"""
Download a remote file and pass it to a :class:`.Table` parser.
:param url:
URL to a file to load.
:param callback:
The method to invoke to create the table. Typically either
:meth:`agate.Table.from_csv` or :meth:`agate.Table.from_json`, but
it could also be a method provided by an extension.
+ :param requests_encoding:
+ An encoding to pass to requests for use when decoding the response
+ content. (e.g. force use of 'utf-8-sig' when CSV has a BOM).
:param binary:
If :code:`False` the downloaded data will be processed as a string,
otherwise it will be treated as binary data. (e.g. for Excel files)
"""
r = requests.get(url)
+
+ if requests_encoding:
+ r.encoding = requests_encoding
if binary:
content = six.BytesIO(r.content)
else:
if six.PY2:
content = six.StringIO(r.content.decode('utf-8'))
else:
content = six.StringIO(r.text)
return callback(content, **kwargs)
agate.Table.from_url = classmethod(from_url)
|
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
|
## Code Before:
import agate
import requests
import six
def from_url(cls, url, callback=agate.Table.from_csv, binary=False, **kwargs):
"""
Download a remote file and pass it to a :class:`.Table` parser.
:param url:
URL to a file to load.
:param callback:
The method to invoke to create the table. Typically either
:meth:`agate.Table.from_csv` or :meth:`agate.Table.from_json`, but
it could also be a method provided by an extension.
:param binary:
If :code:`False` the downloaded data will be processed as a string,
otherwise it will be treated as binary data. (e.g. for Excel files)
"""
r = requests.get(url)
if binary:
content = six.BytesIO(r.content)
else:
if six.PY2:
content = six.StringIO(r.content.decode('utf-8'))
else:
content = six.StringIO(r.text)
return callback(content, **kwargs)
agate.Table.from_url = classmethod(from_url)
## Instruction:
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
## Code After:
import agate
import requests
import six
def from_url(cls, url, callback=agate.Table.from_csv, requests_encoding=None, binary=False, **kwargs):
"""
Download a remote file and pass it to a :class:`.Table` parser.
:param url:
URL to a file to load.
:param callback:
The method to invoke to create the table. Typically either
:meth:`agate.Table.from_csv` or :meth:`agate.Table.from_json`, but
it could also be a method provided by an extension.
:param requests_encoding:
An encoding to pass to requests for use when decoding the response
content. (e.g. force use of 'utf-8-sig' when CSV has a BOM).
:param binary:
If :code:`False` the downloaded data will be processed as a string,
otherwise it will be treated as binary data. (e.g. for Excel files)
"""
r = requests.get(url)
if requests_encoding:
r.encoding = requests_encoding
if binary:
content = six.BytesIO(r.content)
else:
if six.PY2:
content = six.StringIO(r.content.decode('utf-8'))
else:
content = six.StringIO(r.text)
return callback(content, **kwargs)
agate.Table.from_url = classmethod(from_url)
|
...
def from_url(cls, url, callback=agate.Table.from_csv, requests_encoding=None, binary=False, **kwargs):
"""
...
it could also be a method provided by an extension.
:param requests_encoding:
An encoding to pass to requests for use when decoding the response
content. (e.g. force use of 'utf-8-sig' when CSV has a BOM).
:param binary:
...
r = requests.get(url)
if requests_encoding:
r.encoding = requests_encoding
...
|
c7512104dce2e9ca83e8400b399b4f77113f9368
|
packs/travisci/actions/lib/action.py
|
packs/travisci/actions/lib/action.py
|
import requests
from st2actions.runners.pythonrunner import Action
API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'
class TravisCI(Action):
def _get_auth_headers(self):
headers = {}
headers['Authorization'] = self.config['Authorization']
headers['Content-Type'] = self.config['Content-Type']
return headers
def _perform_request(self, path, method, data=None, requires_auth=False):
url = API_URL + path
if method == "GET":
if requires_auth:
headers = self._get_auth_headers()
else:
headers = {}
response = requests.get(url, headers=headers)
elif method == 'POST':
headers = self._get_auth_headers()
response = requests.post(url, headers=headers)
elif method == 'PUT':
headers = self._get_auth_headers()
response = requests.put(url, data=data, headers=headers)
return response
|
import httplib
import requests
from st2actions.runners.pythonrunner import Action
API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'
class TravisCI(Action):
def _get_auth_headers(self):
headers = {}
headers['Authorization'] = self.config['Authorization']
headers['Content-Type'] = self.config['Content-Type']
return headers
def _perform_request(self, path, method, data=None, requires_auth=False):
url = API_URL + path
if method == "GET":
if requires_auth:
headers = self._get_auth_headers()
else:
headers = {}
response = requests.get(url, headers=headers)
elif method == 'POST':
headers = self._get_auth_headers()
response = requests.post(url, headers=headers)
elif method == 'PUT':
headers = self._get_auth_headers()
response = requests.put(url, data=data, headers=headers)
if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
msg = ('Invalid or missing Travis CI auth token. Make sure you have'
'specified valid token in the config file')
raise Exception(msg)
return response
|
Throw on invalid / missing credentials.
|
Throw on invalid / missing credentials.
|
Python
|
apache-2.0
|
pidah/st2contrib,lmEshoo/st2contrib,psychopenguin/st2contrib,psychopenguin/st2contrib,armab/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,armab/st2contrib,armab/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,pearsontechnology/st2contrib,digideskio/st2contrib,digideskio/st2contrib
|
+ import httplib
+
import requests
from st2actions.runners.pythonrunner import Action
API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'
class TravisCI(Action):
def _get_auth_headers(self):
headers = {}
headers['Authorization'] = self.config['Authorization']
headers['Content-Type'] = self.config['Content-Type']
return headers
def _perform_request(self, path, method, data=None, requires_auth=False):
url = API_URL + path
if method == "GET":
if requires_auth:
headers = self._get_auth_headers()
else:
headers = {}
response = requests.get(url, headers=headers)
elif method == 'POST':
headers = self._get_auth_headers()
response = requests.post(url, headers=headers)
elif method == 'PUT':
headers = self._get_auth_headers()
response = requests.put(url, data=data, headers=headers)
+ if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
+ msg = ('Invalid or missing Travis CI auth token. Make sure you have'
+ 'specified valid token in the config file')
+ raise Exception(msg)
+
return response
|
Throw on invalid / missing credentials.
|
## Code Before:
import requests
from st2actions.runners.pythonrunner import Action
API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'
class TravisCI(Action):
def _get_auth_headers(self):
headers = {}
headers['Authorization'] = self.config['Authorization']
headers['Content-Type'] = self.config['Content-Type']
return headers
def _perform_request(self, path, method, data=None, requires_auth=False):
url = API_URL + path
if method == "GET":
if requires_auth:
headers = self._get_auth_headers()
else:
headers = {}
response = requests.get(url, headers=headers)
elif method == 'POST':
headers = self._get_auth_headers()
response = requests.post(url, headers=headers)
elif method == 'PUT':
headers = self._get_auth_headers()
response = requests.put(url, data=data, headers=headers)
return response
## Instruction:
Throw on invalid / missing credentials.
## Code After:
import httplib
import requests
from st2actions.runners.pythonrunner import Action
API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'
class TravisCI(Action):
def _get_auth_headers(self):
headers = {}
headers['Authorization'] = self.config['Authorization']
headers['Content-Type'] = self.config['Content-Type']
return headers
def _perform_request(self, path, method, data=None, requires_auth=False):
url = API_URL + path
if method == "GET":
if requires_auth:
headers = self._get_auth_headers()
else:
headers = {}
response = requests.get(url, headers=headers)
elif method == 'POST':
headers = self._get_auth_headers()
response = requests.post(url, headers=headers)
elif method == 'PUT':
headers = self._get_auth_headers()
response = requests.put(url, data=data, headers=headers)
if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
msg = ('Invalid or missing Travis CI auth token. Make sure you have'
'specified valid token in the config file')
raise Exception(msg)
return response
|
// ... existing code ...
import httplib
import requests
// ... modified code ...
if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
msg = ('Invalid or missing Travis CI auth token. Make sure you have'
'specified valid token in the config file')
raise Exception(msg)
return response
// ... rest of the code ...
|
404d499877c050f706ca0f713d1c8ef0e5a88889
|
ooni/tests/bases.py
|
ooni/tests/bases.py
|
from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
config.initialize_ooni_home("ooni_home")
def tearDown(self):
config.read_config_file()
|
import os
from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
config.global_options['datadir'] = os.path.join(__file__, '..', '..', '..', 'data')
config.global_options['datadir'] = os.path.abspath(config.global_options['datadir'])
config.initialize_ooni_home("ooni_home")
def tearDown(self):
config.read_config_file()
|
Set the datadirectory to be that of the repo.
|
Set the datadirectory to be that of the repo.
|
Python
|
bsd-2-clause
|
kdmurray91/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe
|
+ import os
+
from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
+ config.global_options['datadir'] = os.path.join(__file__, '..', '..', '..', 'data')
+ config.global_options['datadir'] = os.path.abspath(config.global_options['datadir'])
config.initialize_ooni_home("ooni_home")
def tearDown(self):
config.read_config_file()
+
|
Set the datadirectory to be that of the repo.
|
## Code Before:
from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
config.initialize_ooni_home("ooni_home")
def tearDown(self):
config.read_config_file()
## Instruction:
Set the datadirectory to be that of the repo.
## Code After:
import os
from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
config.global_options['datadir'] = os.path.join(__file__, '..', '..', '..', 'data')
config.global_options['datadir'] = os.path.abspath(config.global_options['datadir'])
config.initialize_ooni_home("ooni_home")
def tearDown(self):
config.read_config_file()
|
...
import os
from twisted.trial import unittest
...
def setUp(self):
config.global_options['datadir'] = os.path.join(__file__, '..', '..', '..', 'data')
config.global_options['datadir'] = os.path.abspath(config.global_options['datadir'])
config.initialize_ooni_home("ooni_home")
...
|
38d7092f07884cb2530f95a5dc24ba177bfbe699
|
ncclient/operations/third_party/nexus/rpc.py
|
ncclient/operations/third_party/nexus/rpc.py
|
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmd):
parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
child_node.text = cmd
return self._request(parent_node)
|
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmds):
node = etree.Element(qualify('exec-command', NXOS_1_0))
for cmd in cmds:
etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
return self._request(node)
|
Allow specifying multiple cmd elements
|
Allow specifying multiple cmd elements
|
Python
|
apache-2.0
|
nwautomator/ncclient,joysboy/ncclient,aitorhh/ncclient,ncclient/ncclient,vnitinv/ncclient,cmoberg/ncclient,earies/ncclient,einarnn/ncclient,leopoul/ncclient,kroustou/ncclient,lightlu/ncclient,nnakamot/ncclient,OpenClovis/ncclient,GIC-de/ncclient
|
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
- def request(self, cmd):
+ def request(self, cmds):
- parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
+ node = etree.Element(qualify('exec-command', NXOS_1_0))
- child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
- child_node.text = cmd
- return self._request(parent_node)
+ for cmd in cmds:
+ etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
+
+ return self._request(node)
+
|
Allow specifying multiple cmd elements
|
## Code Before:
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmd):
parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
child_node.text = cmd
return self._request(parent_node)
## Instruction:
Allow specifying multiple cmd elements
## Code After:
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmds):
node = etree.Element(qualify('exec-command', NXOS_1_0))
for cmd in cmds:
etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
return self._request(node)
|
...
class ExecCommand(RPC):
def request(self, cmds):
node = etree.Element(qualify('exec-command', NXOS_1_0))
for cmd in cmds:
etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
return self._request(node)
...
|
da466b391470333492a56395569812653ed6658f
|
compose/cli/__init__.py
|
compose/cli/__init__.py
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
from .colors import red
print(
red('ERROR:'),
"Dependency conflict: an older version of the 'docker-py' package "
"is polluting the namespace. "
"Run the following command to remedy the issue:\n"
"pip uninstall docker docker-py; pip install docker",
file=sys.stderr
)
sys.exit(1)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
from .colors import yellow
print(
yellow('WARNING:'),
"Dependency conflict: an older version of the 'docker-py' package "
"may be polluting the namespace. "
"If you're experiencing crashes, run the following command to remedy the issue:\n"
"pip uninstall docker-py; pip uninstall docker; pip install docker",
file=sys.stderr
)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
|
Change docker-py dependency error to a warning, update fix command
|
Change docker-py dependency error to a warning, update fix command
Signed-off-by: Joffrey F <[email protected]>
|
Python
|
apache-2.0
|
thaJeztah/compose,shin-/compose,vdemeester/compose,sdurrheimer/compose,sdurrheimer/compose,schmunk42/compose,hoogenm/compose,jrabbit/compose,dnephin/compose,dnephin/compose,schmunk42/compose,swoopla/compose,funkyfuture/docker-compose,shin-/compose,thaJeztah/compose,hoogenm/compose,funkyfuture/docker-compose,jrabbit/compose,swoopla/compose,vdemeester/compose
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
- from .colors import red
+ from .colors import yellow
print(
- red('ERROR:'),
+ yellow('WARNING:'),
"Dependency conflict: an older version of the 'docker-py' package "
- "is polluting the namespace. "
+ "may be polluting the namespace. "
- "Run the following command to remedy the issue:\n"
+ "If you're experiencing crashes, run the following command to remedy the issue:\n"
- "pip uninstall docker docker-py; pip install docker",
+ "pip uninstall docker-py; pip uninstall docker; pip install docker",
file=sys.stderr
)
- sys.exit(1)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
|
Change docker-py dependency error to a warning, update fix command
|
## Code Before:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
from .colors import red
print(
red('ERROR:'),
"Dependency conflict: an older version of the 'docker-py' package "
"is polluting the namespace. "
"Run the following command to remedy the issue:\n"
"pip uninstall docker docker-py; pip install docker",
file=sys.stderr
)
sys.exit(1)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
## Instruction:
Change docker-py dependency error to a warning, update fix command
## Code After:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
from .colors import yellow
print(
yellow('WARNING:'),
"Dependency conflict: an older version of the 'docker-py' package "
"may be polluting the namespace. "
"If you're experiencing crashes, run the following command to remedy the issue:\n"
"pip uninstall docker-py; pip uninstall docker; pip install docker",
file=sys.stderr
)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
|
...
if dockerpy_installed:
from .colors import yellow
print(
yellow('WARNING:'),
"Dependency conflict: an older version of the 'docker-py' package "
"may be polluting the namespace. "
"If you're experiencing crashes, run the following command to remedy the issue:\n"
"pip uninstall docker-py; pip uninstall docker; pip install docker",
file=sys.stderr
...
)
...
|
d4033694f7686fe1ad48a185ae740c4d966d40d8
|
classes/dnsresolver.py
|
classes/dnsresolver.py
|
import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call to configure
# the object. Then, depending on the value in configure argument,
# do something with the nameservers argument, which is unique to this
# class object instead.
super(DNSResolver, self).__init__(filename, configure)
if not configure:
if isinstance(nameservers, str):
self.nameservers = [nameservers]
elif isinstance(nameservers, list):
self.nameservers = nameservers
else:
self.nameservers = ['8.8.8.8, 8.8.4.4']
def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list:
addrs = []
for answer in resolver.query(domain, 'A').response.answer:
for item in answer:
addrs.append(item.address)
for answer in resolver.query(domain, 'AAAA').response.answer:
for item in answer:
addrs.append(item.address)
return addrs
|
import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call to configure
# the object. Then, depending on the value in configure argument,
# do something with the nameservers argument, which is unique to this
# class object instead.
super(DNSResolver, self).__init__(filename, configure)
if not configure:
if isinstance(nameservers, str):
self.nameservers = [nameservers]
elif isinstance(nameservers, list):
self.nameservers = nameservers
else:
self.nameservers = ['8.8.8.8, 8.8.4.4']
def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list:
addrs = []
try:
for answer in resolver.query(domain, 'A').response.answer:
for item in answer:
if item.rdtype == dns.rdatatype.A:
addrs.append(item.address)
except dns.resolver.NoAnswer:
pass
try:
for answer in resolver.query(domain, 'AAAA').response.answer:
for item in answer:
if item.rdtype == dns.rdatatype.AAAA:
addrs.append(item.address)
except dns.resolver.NoAnswer:
pass
return addrs
|
Implement rdatatype-aware and NoAnswer-aware DNS handling
|
Implement rdatatype-aware and NoAnswer-aware DNS handling
This will work for CNAME entries because CNAMEs hit by A or AAAA lookups behave like `dig` does - they will trigger a second resultset for the CNAME entry in order to return the IP address.
This also is amended to handle a "NoAnswer" response - i.e. if there are no IPv4 or IPv6 addresses for a given CNAME or records lookup. The list will therefore have all the CNAME-resolved IP addresses as independent strings.
|
Python
|
apache-2.0
|
Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector
|
import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call to configure
# the object. Then, depending on the value in configure argument,
# do something with the nameservers argument, which is unique to this
# class object instead.
super(DNSResolver, self).__init__(filename, configure)
if not configure:
if isinstance(nameservers, str):
self.nameservers = [nameservers]
elif isinstance(nameservers, list):
self.nameservers = nameservers
else:
self.nameservers = ['8.8.8.8, 8.8.4.4']
def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list:
addrs = []
+ try:
- for answer in resolver.query(domain, 'A').response.answer:
+ for answer in resolver.query(domain, 'A').response.answer:
- for item in answer:
+ for item in answer:
+ if item.rdtype == dns.rdatatype.A:
- addrs.append(item.address)
+ addrs.append(item.address)
+ except dns.resolver.NoAnswer:
+ pass
+ try:
- for answer in resolver.query(domain, 'AAAA').response.answer:
+ for answer in resolver.query(domain, 'AAAA').response.answer:
- for item in answer:
+ for item in answer:
+ if item.rdtype == dns.rdatatype.AAAA:
- addrs.append(item.address)
+ addrs.append(item.address)
+ except dns.resolver.NoAnswer:
+ pass
return addrs
|
Implement rdatatype-aware and NoAnswer-aware DNS handling
|
## Code Before:
import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call to configure
# the object. Then, depending on the value in configure argument,
# do something with the nameservers argument, which is unique to this
# class object instead.
super(DNSResolver, self).__init__(filename, configure)
if not configure:
if isinstance(nameservers, str):
self.nameservers = [nameservers]
elif isinstance(nameservers, list):
self.nameservers = nameservers
else:
self.nameservers = ['8.8.8.8, 8.8.4.4']
def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list:
addrs = []
for answer in resolver.query(domain, 'A').response.answer:
for item in answer:
addrs.append(item.address)
for answer in resolver.query(domain, 'AAAA').response.answer:
for item in answer:
addrs.append(item.address)
return addrs
## Instruction:
Implement rdatatype-aware and NoAnswer-aware DNS handling
## Code After:
import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call to configure
# the object. Then, depending on the value in configure argument,
# do something with the nameservers argument, which is unique to this
# class object instead.
super(DNSResolver, self).__init__(filename, configure)
if not configure:
if isinstance(nameservers, str):
self.nameservers = [nameservers]
elif isinstance(nameservers, list):
self.nameservers = nameservers
else:
self.nameservers = ['8.8.8.8, 8.8.4.4']
def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list:
addrs = []
try:
for answer in resolver.query(domain, 'A').response.answer:
for item in answer:
if item.rdtype == dns.rdatatype.A:
addrs.append(item.address)
except dns.resolver.NoAnswer:
pass
try:
for answer in resolver.query(domain, 'AAAA').response.answer:
for item in answer:
if item.rdtype == dns.rdatatype.AAAA:
addrs.append(item.address)
except dns.resolver.NoAnswer:
pass
return addrs
|
// ... existing code ...
try:
for answer in resolver.query(domain, 'A').response.answer:
for item in answer:
if item.rdtype == dns.rdatatype.A:
addrs.append(item.address)
except dns.resolver.NoAnswer:
pass
try:
for answer in resolver.query(domain, 'AAAA').response.answer:
for item in answer:
if item.rdtype == dns.rdatatype.AAAA:
addrs.append(item.address)
except dns.resolver.NoAnswer:
pass
// ... rest of the code ...
|
c3c0bf614e046f4640d123f801739fc7ea0d7cac
|
salt/states/salt_proxy.py
|
salt/states/salt_proxy.py
|
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
This state will configure the salt proxy settings
within /etc/salt/proxy (if /etc/salt/proxy doesn't exists)
and start the salt-proxy process (default true),
if it isn't already running.
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def configure_proxy(name, proxyname='p8000', start=True):
'''
Create the salt proxy file and start the proxy process
if required
Parameters:
name:
The name of this state
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
'''
ret = __salt__['salt_proxy.configure_proxy'](proxyname,
start=start)
ret.update({
'name': name,
'comment': '{0} config messages'.format(name)
})
return ret
|
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
This state will configure the salt proxy settings
within /etc/salt/proxy (if /etc/salt/proxy doesn't exists)
and start the salt-proxy process (default true),
if it isn't already running.
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def configure_proxy(name, proxyname='p8000', start=True):
'''
Create the salt proxy file and start the proxy process
if required
Parameters:
name:
The name of this state
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
Example:
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
'''
ret = __salt__['salt_proxy.configure_proxy'](proxyname,
start=start)
ret.update({
'name': name,
'comment': '{0} config messages'.format(name)
})
return ret
|
Add example to function docstring
|
Add example to function docstring
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
This state will configure the salt proxy settings
within /etc/salt/proxy (if /etc/salt/proxy doesn't exists)
and start the salt-proxy process (default true),
if it isn't already running.
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def configure_proxy(name, proxyname='p8000', start=True):
'''
Create the salt proxy file and start the proxy process
if required
Parameters:
name:
The name of this state
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
+
+ Example:
+
+ ..code-block:: yaml
+
+ salt-proxy-configure:
+ salt_proxy.configure_proxy:
+ - proxyname: p8000
+ - start: True
+
'''
ret = __salt__['salt_proxy.configure_proxy'](proxyname,
start=start)
ret.update({
'name': name,
'comment': '{0} config messages'.format(name)
})
return ret
|
Add example to function docstring
|
## Code Before:
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
This state will configure the salt proxy settings
within /etc/salt/proxy (if /etc/salt/proxy doesn't exists)
and start the salt-proxy process (default true),
if it isn't already running.
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def configure_proxy(name, proxyname='p8000', start=True):
'''
Create the salt proxy file and start the proxy process
if required
Parameters:
name:
The name of this state
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
'''
ret = __salt__['salt_proxy.configure_proxy'](proxyname,
start=start)
ret.update({
'name': name,
'comment': '{0} config messages'.format(name)
})
return ret
## Instruction:
Add example to function docstring
## Code After:
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
This state will configure the salt proxy settings
within /etc/salt/proxy (if /etc/salt/proxy doesn't exists)
and start the salt-proxy process (default true),
if it isn't already running.
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def configure_proxy(name, proxyname='p8000', start=True):
'''
Create the salt proxy file and start the proxy process
if required
Parameters:
name:
The name of this state
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
Example:
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
'''
ret = __salt__['salt_proxy.configure_proxy'](proxyname,
start=start)
ret.update({
'name': name,
'comment': '{0} config messages'.format(name)
})
return ret
|
# ... existing code ...
Boolean indicating if the process should be started
Example:
..code-block:: yaml
salt-proxy-configure:
salt_proxy.configure_proxy:
- proxyname: p8000
- start: True
'''
# ... rest of the code ...
|
aa8117c288fc45743554450448178c47246b088f
|
devicehive/transport.py
|
devicehive/transport.py
|
def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
|
def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
|
Remove Request and Response classes
|
Remove Request and Response classes
|
Python
|
apache-2.0
|
devicehive/devicehive-python
|
def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
-
- class Request(object):
- """Request class."""
-
- def __init__(self, url, action, request, **params):
- self.action = action
- self.request = request
- self.params = params
- self.params['url'] = url
-
-
- class Response(object):
- """Response class."""
-
- def __init__(self, response):
- self.id = response.pop('requestId')
- self.action = response.pop('action')
- self.is_success = response.pop('status') == 'success'
- self.code = response.pop('code', None)
- self.error = response.pop('error', None)
- self.data = response
-
|
Remove Request and Response classes
|
## Code Before:
def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
## Instruction:
Remove Request and Response classes
## Code After:
def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
|
// ... existing code ...
handler_options)
// ... rest of the code ...
|
54bb12bdeec33e98451451837dce90665413bd67
|
mgsv_names.py
|
mgsv_names.py
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
for _ in range(20):
print(generate_name())
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
print(generate_name())
|
Print one name at a time.
|
Print one name at a time.
|
Python
|
unlicense
|
rotated8/mgsv_names
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
- for _ in range(20):
- print(generate_name())
+ print(generate_name())
|
Print one name at a time.
|
## Code Before:
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
for _ in range(20):
print(generate_name())
## Instruction:
Print one name at a time.
## Code After:
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
print(generate_name())
|
// ... existing code ...
if __name__ == '__main__':
print(generate_name())
// ... rest of the code ...
|
bac9b62c40d0c69dcb346adfe82309e10a480276
|
inonemonth/challenges/tests/test_forms.py
|
inonemonth/challenges/tests/test_forms.py
|
import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
# Test takes longer than average test because of requests call
#@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
|
import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
# Test takes about ~0.7 secs because of requests call
@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
|
Write note for test that triggers get request
|
Write note for test that triggers get request
|
Python
|
mit
|
robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth
|
import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
- # Test takes longer than average test because of requests call
+ # Test takes about ~0.7 secs because of requests call
- #@unittest.skip("")
+ @unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
|
Write note for test that triggers get request
|
## Code Before:
import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
# Test takes longer than average test because of requests call
#@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
## Instruction:
Write note for test that triggers get request
## Code After:
import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
# Test takes about ~0.7 secs because of requests call
@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
|
...
# Test takes about ~0.7 secs because of requests call
@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
...
|
77e4fb7ef74bcfd58b548cca8ec9898eb936e7ef
|
conanfile.py
|
conanfile.py
|
from conans import ConanFile, CMake
class EsappConan(ConanFile):
name = 'esapp'
version = '0.4.1'
url = 'https://github.com/jason2506/esapp'
license = 'BSD 3-Clause'
author = 'Chi-En Wu'
requires = 'desa/0.1.0@jason2506/testing'
settings = 'os', 'compiler', 'build_type', 'arch'
generators = 'cmake'
default_options = (
'desa:build_tests=False'
)
exports = (
'CMakeLists.txt',
'cmake/*.cmake',
'include/*.hpp'
)
def build(self):
cmake = CMake(self.settings)
args = []
args.append('-DENABLE_CONAN=%s' % self.options.enable_conan)
args.append('-DBUILD_TESTING=%s' % self.options.build_tests)
args.append('-DCMAKE_INSTALL_PREFIX="%s"' % self.package_folder)
self.run('cmake "%s" %s %s' % (
self.conanfile_directory,
cmake.command_line,
' '.join(args)
))
self.run('cmake --build .')
def package(self):
cmake = CMake(self.settings)
self.run('cmake --build . --target install %s' % cmake.build_config)
|
from conans import ConanFile, CMake
class EsappConan(ConanFile):
name = 'esapp'
version = '0.4.1'
url = 'https://github.com/jason2506/esapp'
license = 'BSD 3-Clause'
author = 'Chi-En Wu'
requires = 'desa/0.1.0@jason2506/testing'
settings = 'os', 'compiler', 'build_type', 'arch'
generators = 'cmake'
exports = (
'CMakeLists.txt',
'cmake/*.cmake',
'include/*.hpp'
)
def build(self):
cmake = CMake(self.settings)
args = []
args.append('-DENABLE_CONAN=%s' % self.options.enable_conan)
args.append('-DBUILD_TESTING=%s' % self.options.build_tests)
args.append('-DCMAKE_INSTALL_PREFIX="%s"' % self.package_folder)
self.run('cmake "%s" %s %s' % (
self.conanfile_directory,
cmake.command_line,
' '.join(args)
))
self.run('cmake --build .')
def package(self):
cmake = CMake(self.settings)
self.run('cmake --build . --target install %s' % cmake.build_config)
|
Remove default option for `desa`
|
Remove default option for `desa`
|
Python
|
bsd-3-clause
|
jason2506/esapp,jason2506/esapp
|
from conans import ConanFile, CMake
class EsappConan(ConanFile):
name = 'esapp'
version = '0.4.1'
url = 'https://github.com/jason2506/esapp'
license = 'BSD 3-Clause'
author = 'Chi-En Wu'
requires = 'desa/0.1.0@jason2506/testing'
settings = 'os', 'compiler', 'build_type', 'arch'
generators = 'cmake'
- default_options = (
- 'desa:build_tests=False'
- )
exports = (
'CMakeLists.txt',
'cmake/*.cmake',
'include/*.hpp'
)
def build(self):
cmake = CMake(self.settings)
args = []
args.append('-DENABLE_CONAN=%s' % self.options.enable_conan)
args.append('-DBUILD_TESTING=%s' % self.options.build_tests)
args.append('-DCMAKE_INSTALL_PREFIX="%s"' % self.package_folder)
self.run('cmake "%s" %s %s' % (
self.conanfile_directory,
cmake.command_line,
' '.join(args)
))
self.run('cmake --build .')
def package(self):
cmake = CMake(self.settings)
self.run('cmake --build . --target install %s' % cmake.build_config)
|
Remove default option for `desa`
|
## Code Before:
from conans import ConanFile, CMake
class EsappConan(ConanFile):
name = 'esapp'
version = '0.4.1'
url = 'https://github.com/jason2506/esapp'
license = 'BSD 3-Clause'
author = 'Chi-En Wu'
requires = 'desa/0.1.0@jason2506/testing'
settings = 'os', 'compiler', 'build_type', 'arch'
generators = 'cmake'
default_options = (
'desa:build_tests=False'
)
exports = (
'CMakeLists.txt',
'cmake/*.cmake',
'include/*.hpp'
)
def build(self):
cmake = CMake(self.settings)
args = []
args.append('-DENABLE_CONAN=%s' % self.options.enable_conan)
args.append('-DBUILD_TESTING=%s' % self.options.build_tests)
args.append('-DCMAKE_INSTALL_PREFIX="%s"' % self.package_folder)
self.run('cmake "%s" %s %s' % (
self.conanfile_directory,
cmake.command_line,
' '.join(args)
))
self.run('cmake --build .')
def package(self):
cmake = CMake(self.settings)
self.run('cmake --build . --target install %s' % cmake.build_config)
## Instruction:
Remove default option for `desa`
## Code After:
from conans import ConanFile, CMake
class EsappConan(ConanFile):
name = 'esapp'
version = '0.4.1'
url = 'https://github.com/jason2506/esapp'
license = 'BSD 3-Clause'
author = 'Chi-En Wu'
requires = 'desa/0.1.0@jason2506/testing'
settings = 'os', 'compiler', 'build_type', 'arch'
generators = 'cmake'
exports = (
'CMakeLists.txt',
'cmake/*.cmake',
'include/*.hpp'
)
def build(self):
cmake = CMake(self.settings)
args = []
args.append('-DENABLE_CONAN=%s' % self.options.enable_conan)
args.append('-DBUILD_TESTING=%s' % self.options.build_tests)
args.append('-DCMAKE_INSTALL_PREFIX="%s"' % self.package_folder)
self.run('cmake "%s" %s %s' % (
self.conanfile_directory,
cmake.command_line,
' '.join(args)
))
self.run('cmake --build .')
def package(self):
cmake = CMake(self.settings)
self.run('cmake --build . --target install %s' % cmake.build_config)
|
# ... existing code ...
generators = 'cmake'
# ... rest of the code ...
|
6323084f97ac80a579d9c8ef7d5fec9cd9a3ec4d
|
src/ipf/ipfblock/connection.py
|
src/ipf/ipfblock/connection.py
|
import ioport
import weakref
class Connection(object):
""" Connection class for IPFBlock
Connection binding OPort and IPort of some IPFBlocks
"""
def __init__(self, oport, iport):
# Check port compatibility and free of input port
if ioport.is_connect_allowed(oport, iport):
self._oport = weakref.ref(oport)
self._iport = weakref.ref(iport)
self._oport().increase_binded_count()
self._iport().set_binded()
else:
raise ValueError("Can not create Connection with given ports")
def __del__(self):
self._oport().decrease_binded_count()
self._iport().set_free()
def contains_port(self, port):
return self._iport() == port or self._oport() == port
def process(self):
""" Send value from output port to input port """
self._iport().pass_value(self._oport().get_value())
|
import ioport
import weakref
class Connection(object):
""" Connection class for IPFBlock
Connection binding OPort and IPort of some IPFBlocks
"""
def __init__(self, oport, iport):
# Check port compatibility and free of input port
if ioport.is_connect_allowed(oport, iport):
self._oport = weakref.ref(oport)
self._iport = weakref.ref(iport)
self._oport().increase_binded_count()
self._iport().set_binded()
else:
raise ValueError("Can not create Connection with given ports")
def __del__(self):
if self._oport() is not None:
self._oport().decrease_binded_count()
if self._iport() is not None:
self._iport().set_free()
def contains_port(self, port):
return self._iport() == port or self._oport() == port
def process(self):
""" Send value from output port to input port """
self._iport().pass_value(self._oport().get_value())
|
Check weakrefs to porst before using in destructor.
|
Check weakrefs to porst before using in destructor.
Prevent raise of exception in case of connect deletion after block.
|
Python
|
lgpl-2.1
|
anton-golubkov/Garland,anton-golubkov/Garland
|
import ioport
import weakref
class Connection(object):
""" Connection class for IPFBlock
Connection binding OPort and IPort of some IPFBlocks
"""
def __init__(self, oport, iport):
# Check port compatibility and free of input port
if ioport.is_connect_allowed(oport, iport):
self._oport = weakref.ref(oport)
self._iport = weakref.ref(iport)
self._oport().increase_binded_count()
self._iport().set_binded()
else:
raise ValueError("Can not create Connection with given ports")
def __del__(self):
+ if self._oport() is not None:
- self._oport().decrease_binded_count()
+ self._oport().decrease_binded_count()
+ if self._iport() is not None:
- self._iport().set_free()
+ self._iport().set_free()
def contains_port(self, port):
return self._iport() == port or self._oport() == port
def process(self):
""" Send value from output port to input port """
self._iport().pass_value(self._oport().get_value())
|
Check weakrefs to porst before using in destructor.
|
## Code Before:
import ioport
import weakref
class Connection(object):
""" Connection class for IPFBlock
Connection binding OPort and IPort of some IPFBlocks
"""
def __init__(self, oport, iport):
# Check port compatibility and free of input port
if ioport.is_connect_allowed(oport, iport):
self._oport = weakref.ref(oport)
self._iport = weakref.ref(iport)
self._oport().increase_binded_count()
self._iport().set_binded()
else:
raise ValueError("Can not create Connection with given ports")
def __del__(self):
self._oport().decrease_binded_count()
self._iport().set_free()
def contains_port(self, port):
return self._iport() == port or self._oport() == port
def process(self):
""" Send value from output port to input port """
self._iport().pass_value(self._oport().get_value())
## Instruction:
Check weakrefs to porst before using in destructor.
## Code After:
import ioport
import weakref
class Connection(object):
""" Connection class for IPFBlock
Connection binding OPort and IPort of some IPFBlocks
"""
def __init__(self, oport, iport):
# Check port compatibility and free of input port
if ioport.is_connect_allowed(oport, iport):
self._oport = weakref.ref(oport)
self._iport = weakref.ref(iport)
self._oport().increase_binded_count()
self._iport().set_binded()
else:
raise ValueError("Can not create Connection with given ports")
def __del__(self):
if self._oport() is not None:
self._oport().decrease_binded_count()
if self._iport() is not None:
self._iport().set_free()
def contains_port(self, port):
return self._iport() == port or self._oport() == port
def process(self):
""" Send value from output port to input port """
self._iport().pass_value(self._oport().get_value())
|
# ... existing code ...
def __del__(self):
if self._oport() is not None:
self._oport().decrease_binded_count()
if self._iport() is not None:
self._iport().set_free()
# ... rest of the code ...
|
de02c92510a6117aad01be7666d737d2ad861fd7
|
send_sms.py
|
send_sms.py
|
import datetime
import json
import sys
import requests
import pytz
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
data = json.loads(request.text)
# Set to epoch begin just in case this is a totally new account
latest_contribution = datetime.datetime(1970, 1, 1, 0, 0)
# Get data for the latest contribution
for i in reversed(data):
if i[1] > 0:
latest_contribution = datetime.datetime.strptime(i[0], '%Y/%m/%d')
break
# Find out today's date in PST (since Github uses PST)
today = datetime.datetime.now(pytz.timezone('US/Pacific'))
# Haven't contributed anything today?
if latest_contribution.date() < today.date():
send(message)
else:
send('There was a problem accessing the Github API :(')
|
import json
import sys
import requests
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
try:
data = json.loads(request.text)
# Get the number of commits made today
commits_today = data[-1][1]
if not commits_today:
send(message)
except:
send('There was an error getting the number of commits today')
else:
send('There was a problem accessing the Github API :(')
|
Improve logic in determining latest contribution
|
Improve logic in determining latest contribution
Looks like the list will always contain data for the last 366 days, and
the last entry in the list will always contain data for the current day
(PST). Much simpler this way.
Added some generic error-handling just in case this isn't true.
|
Python
|
mit
|
dellsystem/github-streak-saver
|
- import datetime
import json
import sys
import requests
- import pytz
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
+ try:
- data = json.loads(request.text)
+ data = json.loads(request.text)
- # Set to epoch begin just in case this is a totally new account
- latest_contribution = datetime.datetime(1970, 1, 1, 0, 0)
+ # Get the number of commits made today
+ commits_today = data[-1][1]
+ if not commits_today:
- # Get data for the latest contribution
- for i in reversed(data):
- if i[1] > 0:
- latest_contribution = datetime.datetime.strptime(i[0], '%Y/%m/%d')
- break
-
- # Find out today's date in PST (since Github uses PST)
- today = datetime.datetime.now(pytz.timezone('US/Pacific'))
-
- # Haven't contributed anything today?
- if latest_contribution.date() < today.date():
- send(message)
+ send(message)
+ except:
+ send('There was an error getting the number of commits today')
else:
send('There was a problem accessing the Github API :(')
|
Improve logic in determining latest contribution
|
## Code Before:
import datetime
import json
import sys
import requests
import pytz
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
data = json.loads(request.text)
# Set to epoch begin just in case this is a totally new account
latest_contribution = datetime.datetime(1970, 1, 1, 0, 0)
# Get data for the latest contribution
for i in reversed(data):
if i[1] > 0:
latest_contribution = datetime.datetime.strptime(i[0], '%Y/%m/%d')
break
# Find out today's date in PST (since Github uses PST)
today = datetime.datetime.now(pytz.timezone('US/Pacific'))
# Haven't contributed anything today?
if latest_contribution.date() < today.date():
send(message)
else:
send('There was a problem accessing the Github API :(')
## Instruction:
Improve logic in determining latest contribution
## Code After:
import json
import sys
import requests
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
try:
data = json.loads(request.text)
# Get the number of commits made today
commits_today = data[-1][1]
if not commits_today:
send(message)
except:
send('There was an error getting the number of commits today')
else:
send('There was a problem accessing the Github API :(')
|
// ... existing code ...
import json
// ... modified code ...
import requests
from twilio.rest import TwilioRestClient
...
if request.ok:
try:
data = json.loads(request.text)
# Get the number of commits made today
commits_today = data[-1][1]
if not commits_today:
send(message)
except:
send('There was an error getting the number of commits today')
else:
// ... rest of the code ...
|
4b43a2f50740bbeab95f64137eb8993ed8ac4617
|
other/password_generator.py
|
other/password_generator.py
|
import string
from random import *
letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation
chars = letters + digits + symbols
min_length = 8
max_length = 16
password = ''.join(choice(chars) for x in range(randint(min_length, max_length)))
print('Password: %s' % password)
print('[ If you are thinking of using this passsword, You better save it. ]')
|
import string
import random
letters = [letter for letter in string.ascii_letters]
digits = [digit for digit in string.digits]
symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
random.shuffle(chars)
min_length = 8
max_length = 16
password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length)))
print('Password: ' + password)
print('[ If you are thinking of using this passsword, You better save it. ]')
|
Add another randomness into the password generator
|
Add another randomness into the password generator
Uses import random for namespace cleanliness
Uses list instead of string for 'chars' variable in order to shuffle, increases randomness
Instead of string formatting, uses string concatenation because (currently) it is simpler
|
Python
|
mit
|
TheAlgorithms/Python
|
import string
- from random import *
+ import random
- letters = string.ascii_letters
- digits = string.digits
- symbols = string.punctuation
+ letters = [letter for letter in string.ascii_letters]
+ digits = [digit for digit in string.digits]
+ symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
+ random.shuffle(chars)
min_length = 8
max_length = 16
- password = ''.join(choice(chars) for x in range(randint(min_length, max_length)))
+ password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length)))
- print('Password: %s' % password)
+ print('Password: ' + password)
print('[ If you are thinking of using this passsword, You better save it. ]')
|
Add another randomness into the password generator
|
## Code Before:
import string
from random import *
letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation
chars = letters + digits + symbols
min_length = 8
max_length = 16
password = ''.join(choice(chars) for x in range(randint(min_length, max_length)))
print('Password: %s' % password)
print('[ If you are thinking of using this passsword, You better save it. ]')
## Instruction:
Add another randomness into the password generator
## Code After:
import string
import random
letters = [letter for letter in string.ascii_letters]
digits = [digit for digit in string.digits]
symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
random.shuffle(chars)
min_length = 8
max_length = 16
password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length)))
print('Password: ' + password)
print('[ If you are thinking of using this passsword, You better save it. ]')
|
# ... existing code ...
import string
import random
letters = [letter for letter in string.ascii_letters]
digits = [digit for digit in string.digits]
symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
random.shuffle(chars)
# ... modified code ...
max_length = 16
password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length)))
print('Password: ' + password)
print('[ If you are thinking of using this passsword, You better save it. ]')
# ... rest of the code ...
|
d0461fa033bdca4fffeff718219f8b71123449d7
|
pskb_website/models/__init__.py
|
pskb_website/models/__init__.py
|
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import save_article_meta_data
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .file import published_articles
from .file import in_review_articles
from .file import draft_articles
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
|
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
|
Remove some functions from exported model API that are not used outside model layer
|
Remove some functions from exported model API that are not used outside model layer
- Just some refactoring to trim down the number of things exported that aren't
necessary at this time.
|
Python
|
agpl-3.0
|
paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms
|
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
- from .article import save_article_meta_data
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
- from .file import published_articles
- from .file import in_review_articles
- from .file import draft_articles
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
|
Remove some functions from exported model API that are not used outside model layer
|
## Code Before:
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import save_article_meta_data
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .file import published_articles
from .file import in_review_articles
from .file import draft_articles
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
## Instruction:
Remove some functions from exported model API that are not used outside model layer
## Code After:
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
|
# ... existing code ...
from .article import get_public_articles_for_author
from .article import find_article_by_title
# ... modified code ...
from .file import update_article_listing
# ... rest of the code ...
|
c544afed5c8d961db0d34b7f73313699ce3bf656
|
test/ocookie_test.py
|
test/ocookie_test.py
|
import unittest, time
import ocookie
class OcookieTest(unittest.TestCase):
def test_foo(self):
pass
class CookieParserTest(unittest.TestCase):
def test_parsing(self):
text = 'foo=bar'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
def test_parsing_with_attributes(self):
text = 'foo=bar; domain=.cc.edu; path=/; expires=Mon Jul 11 10:41:15 EDT 2011'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals('.cc.edu', cookie.domain)
self.assertEquals('/', cookie.path)
self.assertEquals('Mon Jul 11 10:41:15 EDT 2011', cookie.expires)
def test_parsing_with_valueless_attributes(self):
text = 'foo=bar; httponly'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals(True, cookie.httponly)
if __name__ == '__main__':
unittest.main()
|
import unittest, time
import ocookie
class CookieTest(unittest.TestCase):
def test_construction(self):
cookie = ocookie.Cookie('foo', 'bar', httponly=True)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertTrue(cookie.httponly)
self.assertFalse(cookie.secure)
class CookieParserTest(unittest.TestCase):
def test_parsing(self):
text = 'foo=bar'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
def test_parsing_with_attributes(self):
text = 'foo=bar; domain=.cc.edu; path=/; expires=Mon Jul 11 10:41:15 EDT 2011'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals('.cc.edu', cookie.domain)
self.assertEquals('/', cookie.path)
self.assertEquals('Mon Jul 11 10:41:15 EDT 2011', cookie.expires)
def test_parsing_with_valueless_attributes(self):
text = 'foo=bar; httponly'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals(True, cookie.httponly)
if __name__ == '__main__':
unittest.main()
|
Add a cookie class test
|
Add a cookie class test
|
Python
|
bsd-2-clause
|
p/ocookie
|
import unittest, time
import ocookie
- class OcookieTest(unittest.TestCase):
+ class CookieTest(unittest.TestCase):
- def test_foo(self):
+ def test_construction(self):
- pass
+ cookie = ocookie.Cookie('foo', 'bar', httponly=True)
+ self.assertEquals('foo', cookie.name)
+ self.assertEquals('bar', cookie.value)
+ self.assertTrue(cookie.httponly)
+ self.assertFalse(cookie.secure)
class CookieParserTest(unittest.TestCase):
def test_parsing(self):
text = 'foo=bar'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
def test_parsing_with_attributes(self):
text = 'foo=bar; domain=.cc.edu; path=/; expires=Mon Jul 11 10:41:15 EDT 2011'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals('.cc.edu', cookie.domain)
self.assertEquals('/', cookie.path)
self.assertEquals('Mon Jul 11 10:41:15 EDT 2011', cookie.expires)
def test_parsing_with_valueless_attributes(self):
text = 'foo=bar; httponly'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals(True, cookie.httponly)
if __name__ == '__main__':
unittest.main()
|
Add a cookie class test
|
## Code Before:
import unittest, time
import ocookie
class OcookieTest(unittest.TestCase):
def test_foo(self):
pass
class CookieParserTest(unittest.TestCase):
def test_parsing(self):
text = 'foo=bar'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
def test_parsing_with_attributes(self):
text = 'foo=bar; domain=.cc.edu; path=/; expires=Mon Jul 11 10:41:15 EDT 2011'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals('.cc.edu', cookie.domain)
self.assertEquals('/', cookie.path)
self.assertEquals('Mon Jul 11 10:41:15 EDT 2011', cookie.expires)
def test_parsing_with_valueless_attributes(self):
text = 'foo=bar; httponly'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals(True, cookie.httponly)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add a cookie class test
## Code After:
import unittest, time
import ocookie
class CookieTest(unittest.TestCase):
def test_construction(self):
cookie = ocookie.Cookie('foo', 'bar', httponly=True)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertTrue(cookie.httponly)
self.assertFalse(cookie.secure)
class CookieParserTest(unittest.TestCase):
def test_parsing(self):
text = 'foo=bar'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
def test_parsing_with_attributes(self):
text = 'foo=bar; domain=.cc.edu; path=/; expires=Mon Jul 11 10:41:15 EDT 2011'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals('.cc.edu', cookie.domain)
self.assertEquals('/', cookie.path)
self.assertEquals('Mon Jul 11 10:41:15 EDT 2011', cookie.expires)
def test_parsing_with_valueless_attributes(self):
text = 'foo=bar; httponly'
cookie = ocookie.CookieParser.parse_set_cookie_value(text)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertEquals(True, cookie.httponly)
if __name__ == '__main__':
unittest.main()
|
...
class CookieTest(unittest.TestCase):
def test_construction(self):
cookie = ocookie.Cookie('foo', 'bar', httponly=True)
self.assertEquals('foo', cookie.name)
self.assertEquals('bar', cookie.value)
self.assertTrue(cookie.httponly)
self.assertFalse(cookie.secure)
...
|
9beb8378831f33c2256b5a7bf73f24d155122bea
|
nasa_data.py
|
nasa_data.py
|
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
return
image_data = requests.get(image_url, stream=True)
except requests.HTTPError:
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
raise TypeError
image_data = requests.get(image_url, stream=True)
except (requests.HTTPError or TypeError):
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
Update 0.6.4 - Fixed exception error
|
Update 0.6.4
- Fixed exception error
|
Python
|
mit
|
FXelix/space_facts_bot
|
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
- return
+ raise TypeError
image_data = requests.get(image_url, stream=True)
- except requests.HTTPError:
+ except (requests.HTTPError or TypeError):
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
Update 0.6.4 - Fixed exception error
|
## Code Before:
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
return
image_data = requests.get(image_url, stream=True)
except requests.HTTPError:
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
## Instruction:
Update 0.6.4 - Fixed exception error
## Code After:
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
raise TypeError
image_data = requests.get(image_url, stream=True)
except (requests.HTTPError or TypeError):
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
...
if image_url.endswith(".gif"):
raise TypeError
image_data = requests.get(image_url, stream=True)
except (requests.HTTPError or TypeError):
return
...
|
fa518cdae22c1a762a593f3c4c67fadb04beb5e6
|
corehq/apps/reports/standard/cases/case_list_explorer.py
|
corehq/apps/reports/standard/cases/case_list_explorer.py
|
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
class CaseListExplorer(CaseListReport):
name = _('Case List Explorer')
slug = 'case_list_explorer'
search_class = CaseSearchES
|
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
from corehq.apps.reports.standard.cases.filters import (
XpathCaseSearchFilter,
)
class CaseListExplorer(CaseListReport):
name = _('Case List Explorer')
slug = 'case_list_explorer'
search_class = CaseSearchES
fields = [
'corehq.apps.reports.filters.case_list.CaseListFilter',
'corehq.apps.reports.filters.select.CaseTypeFilter',
'corehq.apps.reports.filters.select.SelectOpenCloseFilter',
XpathCaseSearchFilter,
]
def get_data(self):
for row in self.es_results['hits'].get('hits', []):
yield flatten_result(row)
def _build_query(self):
query = super(CaseListExplorer, self)._build_query()
xpath = XpathCaseSearchFilter.get_value(self.request, self.domain)
if xpath:
query = query.xpath_query(self.domain, xpath)
return query
|
Add XPath Query filter to report
|
Add XPath Query filter to report
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
+ from corehq.apps.reports.standard.cases.filters import (
+ XpathCaseSearchFilter,
+ )
class CaseListExplorer(CaseListReport):
name = _('Case List Explorer')
slug = 'case_list_explorer'
search_class = CaseSearchES
+ fields = [
+ 'corehq.apps.reports.filters.case_list.CaseListFilter',
+ 'corehq.apps.reports.filters.select.CaseTypeFilter',
+ 'corehq.apps.reports.filters.select.SelectOpenCloseFilter',
+ XpathCaseSearchFilter,
+ ]
+ def get_data(self):
+ for row in self.es_results['hits'].get('hits', []):
+ yield flatten_result(row)
+
+ def _build_query(self):
+ query = super(CaseListExplorer, self)._build_query()
+ xpath = XpathCaseSearchFilter.get_value(self.request, self.domain)
+ if xpath:
+ query = query.xpath_query(self.domain, xpath)
+ return query
+
+
|
Add XPath Query filter to report
|
## Code Before:
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
class CaseListExplorer(CaseListReport):
name = _('Case List Explorer')
slug = 'case_list_explorer'
search_class = CaseSearchES
## Instruction:
Add XPath Query filter to report
## Code After:
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
from corehq.apps.reports.standard.cases.filters import (
XpathCaseSearchFilter,
)
class CaseListExplorer(CaseListReport):
name = _('Case List Explorer')
slug = 'case_list_explorer'
search_class = CaseSearchES
fields = [
'corehq.apps.reports.filters.case_list.CaseListFilter',
'corehq.apps.reports.filters.select.CaseTypeFilter',
'corehq.apps.reports.filters.select.SelectOpenCloseFilter',
XpathCaseSearchFilter,
]
def get_data(self):
for row in self.es_results['hits'].get('hits', []):
yield flatten_result(row)
def _build_query(self):
query = super(CaseListExplorer, self)._build_query()
xpath = XpathCaseSearchFilter.get_value(self.request, self.domain)
if xpath:
query = query.xpath_query(self.domain, xpath)
return query
|
# ... existing code ...
from corehq.apps.reports.standard.cases.basic import CaseListReport
from corehq.apps.reports.standard.cases.filters import (
XpathCaseSearchFilter,
)
# ... modified code ...
fields = [
'corehq.apps.reports.filters.case_list.CaseListFilter',
'corehq.apps.reports.filters.select.CaseTypeFilter',
'corehq.apps.reports.filters.select.SelectOpenCloseFilter',
XpathCaseSearchFilter,
]
def get_data(self):
for row in self.es_results['hits'].get('hits', []):
yield flatten_result(row)
def _build_query(self):
query = super(CaseListExplorer, self)._build_query()
xpath = XpathCaseSearchFilter.get_value(self.request, self.domain)
if xpath:
query = query.xpath_query(self.domain, xpath)
return query
# ... rest of the code ...
|
7a281be50ba1fc59281a76470776fa9c8efdfd54
|
pijobs/scrolljob.py
|
pijobs/scrolljob.py
|
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
|
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.set_rotate()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
|
Add back rotatation for scroll job.
|
Add back rotatation for scroll job.
|
Python
|
mit
|
ollej/piapi,ollej/piapi
|
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
+ self.set_rotate()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
|
Add back rotatation for scroll job.
|
## Code Before:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
## Instruction:
Add back rotatation for scroll job.
## Code After:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.set_rotate()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
|
// ... existing code ...
self.set_brightness()
self.set_rotate()
self.write_message()
// ... rest of the code ...
|
3045f6ffbd8433d60178fee59550d30064015b46
|
tm/tm.py
|
tm/tm.py
|
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
err = ""
if args.kill:
pass
elif args.list:
pass
elif args.session:
pass
if __name__ == "__main__":
main(sys.argv[1:])
|
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
if len(argv) == 0:
parser.print_help()
if args.kill:
p = subprocess.Popen("tmux kill-session -t {}".format(args.kill),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
elif args.list:
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
elif args.session:
p = subprocess.Popen("tmux new -s {}".format(args.session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if __name__ == "__main__":
main(sys.argv[1:])
|
Add kill, list, and create commands
|
Add kill, list, and create commands
|
Python
|
mit
|
ethanal/tm
|
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
- err = ""
+ if len(argv) == 0:
+ parser.print_help()
+
if args.kill:
- pass
+ p = subprocess.Popen("tmux kill-session -t {}".format(args.kill),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ shell=True)
+ out, err = p.communicate()
elif args.list:
- pass
+ p = subprocess.Popen("tmux ls",
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ shell=True)
+ out, err = p.communicate()
elif args.session:
- pass
+ p = subprocess.Popen("tmux new -s {}".format(args.session),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ shell=True)
+ out, err = p.communicate()
if __name__ == "__main__":
main(sys.argv[1:])
|
Add kill, list, and create commands
|
## Code Before:
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
err = ""
if args.kill:
pass
elif args.list:
pass
elif args.session:
pass
if __name__ == "__main__":
main(sys.argv[1:])
## Instruction:
Add kill, list, and create commands
## Code After:
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
if len(argv) == 0:
parser.print_help()
if args.kill:
p = subprocess.Popen("tmux kill-session -t {}".format(args.kill),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
elif args.list:
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
elif args.session:
p = subprocess.Popen("tmux new -s {}".format(args.session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if __name__ == "__main__":
main(sys.argv[1:])
|
# ... existing code ...
if len(argv) == 0:
parser.print_help()
if args.kill:
p = subprocess.Popen("tmux kill-session -t {}".format(args.kill),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
elif args.list:
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
elif args.session:
p = subprocess.Popen("tmux new -s {}".format(args.session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
# ... rest of the code ...
|
7cdc7d1157f7bd37277115d378d76a1daf717b47
|
source/run.py
|
source/run.py
|
from autoreiv import AutoReiv
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except KeyboardInterrupt:
bot.close()
finally:
print('* Bye!')
|
import asyncio
import time
from autoreiv import AutoReiv
def main():
while True:
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except Exception as e:
print('* Crashed with error: {}'.format(e))
finally:
print('* Disconnected.')
asyncio.set_event_loop(asyncio.new_event_loop())
print('* Waiting 10 seconds before reconnecting (press ^C to stop)...')
try:
time.sleep(10)
except KeyboardInterrupt:
break
if __name__ == '__main__':
main()
|
Fix the main loop & reconnecting
|
Fix the main loop & reconnecting
|
Python
|
mit
|
diath/AutoReiv
|
+ import asyncio
+ import time
+
from autoreiv import AutoReiv
+ def main():
+ while True:
- bot = AutoReiv()
+ bot = AutoReiv()
- bot.load()
+ bot.load()
- try:
+ try:
- bot.run(bot.config.get('login'), bot.config.get('password'))
+ bot.run(bot.config.get('login'), bot.config.get('password'))
- except KeyboardInterrupt:
- bot.close()
+ except Exception as e:
+ print('* Crashed with error: {}'.format(e))
- finally:
+ finally:
- print('* Bye!')
+ print('* Disconnected.')
+ asyncio.set_event_loop(asyncio.new_event_loop())
+
+ print('* Waiting 10 seconds before reconnecting (press ^C to stop)...')
+ try:
+ time.sleep(10)
+ except KeyboardInterrupt:
+ break
+
+ if __name__ == '__main__':
+ main()
+
|
Fix the main loop & reconnecting
|
## Code Before:
from autoreiv import AutoReiv
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except KeyboardInterrupt:
bot.close()
finally:
print('* Bye!')
## Instruction:
Fix the main loop & reconnecting
## Code After:
import asyncio
import time
from autoreiv import AutoReiv
def main():
while True:
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except Exception as e:
print('* Crashed with error: {}'.format(e))
finally:
print('* Disconnected.')
asyncio.set_event_loop(asyncio.new_event_loop())
print('* Waiting 10 seconds before reconnecting (press ^C to stop)...')
try:
time.sleep(10)
except KeyboardInterrupt:
break
if __name__ == '__main__':
main()
|
...
import asyncio
import time
from autoreiv import AutoReiv
...
def main():
while True:
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except Exception as e:
print('* Crashed with error: {}'.format(e))
finally:
print('* Disconnected.')
asyncio.set_event_loop(asyncio.new_event_loop())
print('* Waiting 10 seconds before reconnecting (press ^C to stop)...')
try:
time.sleep(10)
except KeyboardInterrupt:
break
if __name__ == '__main__':
main()
...
|
cdaffa187b41f3a84cb5a6b44f2e781a9b249f2b
|
tests/test_users.py
|
tests/test_users.py
|
from context import slot_users_controller as uc
class TestUsers:
def test_validate_credentials_returns_true_for_valid_credentials(self):
result = uc.return_user_if_valid_credentials('slot', 'test')
assert result is True
def test_validate_credentials_returns_false_for_invalid_credentials(self):
result = uc.return_user_if_valid_credentials('bad_username', 'bad_password')
assert result is False
def test_convert_dict_to_user_instance_returns_valid_user_instance(self):
result = uc.convert_dict_to_user_instance({})
assert result
|
from context import slot_users_controller as uc
class TestUsers:
def test_validate_credentials_returns_true_for_valid_credentials(self):
result = uc.return_user_if_valid_credentials('slot', 'test')
assert result is True
def test_validate_credentials_returns_false_for_invalid_credentials(self):
result = uc.return_user_if_valid_credentials('bad_username', 'bad_password')
assert result is False
def test_convert_dict_to_user_instance_returns_valid_user_instance(self):
result = uc.return_user_instance_or_anonymous({})
assert result
|
Update test to reflect new method name.
|
Update test to reflect new method name.
|
Python
|
mit
|
nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT
|
from context import slot_users_controller as uc
class TestUsers:
def test_validate_credentials_returns_true_for_valid_credentials(self):
result = uc.return_user_if_valid_credentials('slot', 'test')
assert result is True
def test_validate_credentials_returns_false_for_invalid_credentials(self):
result = uc.return_user_if_valid_credentials('bad_username', 'bad_password')
assert result is False
def test_convert_dict_to_user_instance_returns_valid_user_instance(self):
- result = uc.convert_dict_to_user_instance({})
+ result = uc.return_user_instance_or_anonymous({})
assert result
|
Update test to reflect new method name.
|
## Code Before:
from context import slot_users_controller as uc
class TestUsers:
def test_validate_credentials_returns_true_for_valid_credentials(self):
result = uc.return_user_if_valid_credentials('slot', 'test')
assert result is True
def test_validate_credentials_returns_false_for_invalid_credentials(self):
result = uc.return_user_if_valid_credentials('bad_username', 'bad_password')
assert result is False
def test_convert_dict_to_user_instance_returns_valid_user_instance(self):
result = uc.convert_dict_to_user_instance({})
assert result
## Instruction:
Update test to reflect new method name.
## Code After:
from context import slot_users_controller as uc
class TestUsers:
def test_validate_credentials_returns_true_for_valid_credentials(self):
result = uc.return_user_if_valid_credentials('slot', 'test')
assert result is True
def test_validate_credentials_returns_false_for_invalid_credentials(self):
result = uc.return_user_if_valid_credentials('bad_username', 'bad_password')
assert result is False
def test_convert_dict_to_user_instance_returns_valid_user_instance(self):
result = uc.return_user_instance_or_anonymous({})
assert result
|
...
def test_convert_dict_to_user_instance_returns_valid_user_instance(self):
result = uc.return_user_instance_or_anonymous({})
assert result
...
|
c91e42c32d8314d3d156c577f854fa311c5b1b67
|
model_presenter.py
|
model_presenter.py
|
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
png_file = NamedTemporaryFile(delete=False, suffix='.png')
png_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(png_file.name)
plt.close(fig)
return png_file.name
|
import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
png_file = NamedTemporaryFile(delete=False, suffix='.png')
png_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(png_file.name)
plt.close(fig)
return png_file.name
|
Fix the error that X is required for plotting
|
Fix the error that X is required for plotting
This enables money-monkey in server environment
|
Python
|
mit
|
cjluo/money-monkey
|
+ import matplotlib
+ # Do not use X for plotting
+ matplotlib.use('Agg')
+
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
png_file = NamedTemporaryFile(delete=False, suffix='.png')
png_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(png_file.name)
plt.close(fig)
return png_file.name
|
Fix the error that X is required for plotting
|
## Code Before:
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
png_file = NamedTemporaryFile(delete=False, suffix='.png')
png_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(png_file.name)
plt.close(fig)
return png_file.name
## Instruction:
Fix the error that X is required for plotting
## Code After:
import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
png_file = NamedTemporaryFile(delete=False, suffix='.png')
png_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(png_file.name)
plt.close(fig)
return png_file.name
|
...
import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
...
|
efabe61cec636d5104a639b8d5cfef23eb840dd7
|
apps/live/urls.py
|
apps/live/urls.py
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import (AwayView, DiscussionView, EpilogueView, GameView,
NotifierView, PrologueView, StatusView)
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Status (for bots).
url(r'^status/$', name='live-status', view=StatusView.as_view()),
)
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import StatusView
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Status (for bots).
url(r'^status/$', name='live-status', view=StatusView.as_view()),
)
|
Remove the missing view references.
|
Remove the missing view references.
|
Python
|
apache-2.0
|
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
+ from .views import StatusView
- from .views import (AwayView, DiscussionView, EpilogueView, GameView,
- NotifierView, PrologueView, StatusView)
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Status (for bots).
url(r'^status/$', name='live-status', view=StatusView.as_view()),
)
|
Remove the missing view references.
|
## Code Before:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import (AwayView, DiscussionView, EpilogueView, GameView,
NotifierView, PrologueView, StatusView)
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Status (for bots).
url(r'^status/$', name='live-status', view=StatusView.as_view()),
)
## Instruction:
Remove the missing view references.
## Code After:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import StatusView
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Status (for bots).
url(r'^status/$', name='live-status', view=StatusView.as_view()),
)
|
...
from .views import StatusView
...
|
9d15915784a94056283845a4ec0fd08ac8849d13
|
jobs/test_settings.py
|
jobs/test_settings.py
|
from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
'HOST': 'db',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
|
from decouple import config
from jobs.settings import *
try:
host = config('DB_HOST')
except:
host = 'db'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
'HOST': host,
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
|
Add logic for db host during runtime
|
Add logic for db host during runtime
|
Python
|
mit
|
misachi/job_match,misachi/job_match,misachi/job_match
|
from decouple import config
from jobs.settings import *
+
+ try:
+ host = config('DB_HOST')
+ except:
+ host = 'db'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
- 'HOST': 'db',
+ 'HOST': host,
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
|
Add logic for db host during runtime
|
## Code Before:
from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
'HOST': 'db',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
## Instruction:
Add logic for db host during runtime
## Code After:
from decouple import config
from jobs.settings import *
try:
host = config('DB_HOST')
except:
host = 'db'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
'HOST': host,
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
|
// ... existing code ...
from jobs.settings import *
try:
host = config('DB_HOST')
except:
host = 'db'
// ... modified code ...
'PASSWORD': 'pass1234',
'HOST': host,
'PORT': 5432,
// ... rest of the code ...
|
d5b0234cca1bbab1a0bd20091df44380aca71ee8
|
tslearn/tests/test_svm.py
|
tslearn/tests/test_svm.py
|
import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_svm_gak():
n, sz, d = 15, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
gak_km = TimeSeriesSVC(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_km._preprocess_sklearn(time_series, labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
|
import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_gamma_value_svm():
n, sz, d = 5, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]:
gak_model = ModelClass(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_model._preprocess_sklearn(time_series,
labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
|
Change test name and test SVR too
|
Change test name and test SVR too
|
Python
|
bsd-2-clause
|
rtavenar/tslearn
|
import numpy as np
from tslearn.metrics import cdist_gak
- from tslearn.svm import TimeSeriesSVC
+ from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
- def test_svm_gak():
+ def test_gamma_value_svm():
- n, sz, d = 15, 10, 3
+ n, sz, d = 5, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
- gak_km = TimeSeriesSVC(kernel="gak", gamma=gamma)
+ for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]:
+ gak_model = ModelClass(kernel="gak", gamma=gamma)
- sklearn_X, _ = gak_km._preprocess_sklearn(time_series, labels,
+ sklearn_X, _ = gak_model._preprocess_sklearn(time_series,
+ labels,
- fit_time=True)
+ fit_time=True)
- cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
+ cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
- np.testing.assert_allclose(sklearn_X, cdist_mat)
+ np.testing.assert_allclose(sklearn_X, cdist_mat)
|
Change test name and test SVR too
|
## Code Before:
import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_svm_gak():
n, sz, d = 15, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
gak_km = TimeSeriesSVC(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_km._preprocess_sklearn(time_series, labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
## Instruction:
Change test name and test SVR too
## Code After:
import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_gamma_value_svm():
n, sz, d = 5, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]:
gak_model = ModelClass(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_model._preprocess_sklearn(time_series,
labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
|
...
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
...
def test_gamma_value_svm():
n, sz, d = 5, 10, 3
rng = np.random.RandomState(0)
...
gamma = 10.
for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]:
gak_model = ModelClass(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_model._preprocess_sklearn(time_series,
labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
...
|
a95b1b2b5331e4248fe1d80244c763df4d3aca41
|
taiga/urls.py
|
taiga/urls.py
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += mediafiles_urlpatterns()
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
|
Set prefix to static url patterm call
|
Set prefix to static url patterm call
|
Python
|
agpl-3.0
|
jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,WALR/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,EvgeneOskin/taiga-back,CoolCloud/taiga-back,WALR/taiga-back,Rademade/taiga-back,seanchen/taiga-back,taigaio/taiga-back,astronaut1712/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,astagi/taiga-back,coopsource/taiga-back,CMLL/taiga-back,gauravjns/taiga-back,Rademade/taiga-back,EvgeneOskin/taiga-back,dycodedev/taiga-back,CMLL/taiga-back,astagi/taiga-back,dayatz/taiga-back,19kestier/taiga-back,19kestier/taiga-back,coopsource/taiga-back,obimod/taiga-back,rajiteh/taiga-back,crr0004/taiga-back,bdang2012/taiga-back-casting,gauravjns/taiga-back,gam-phon/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,astagi/taiga-back,19kestier/taiga-back,CoolCloud/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,Rademade/taiga-back,forging2012/taiga-back,dycodedev/taiga-back,jeffdwyatt/taiga-back,taigaio/taiga-back,dayatz/taiga-back,crr0004/taiga-back,xdevelsistemas/taiga-back-community,Tigerwhit4/taiga-back,Tigerwhit4/taiga-back,obimod/taiga-back,Zaneh-/bearded-tribble-back,jeffdwyatt/taiga-back,crr0004/taiga-back,rajiteh/taiga-back,Zaneh-/bearded-tribble-back,obimod/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,bdang2012/taiga-back-casting,frt-arch/taiga-back,dycodedev/taiga-back,joshisa/taiga-back,Zaneh-/bearded-tribble-back,astronaut1712/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,Tigerwhit4/taiga-back,gauravjns/taiga-back,CMLL/taiga-back,WALR/taiga-back,joshisa/taiga-back,obimod/taiga-back,jeffdwyatt/taiga-back,forging2012/taiga-back,astagi/taiga-back,xdevelsistemas/taiga-back-community,gauravjns/taiga-back,coopsource/taiga-back,joshisa/taiga-back,crr0004/taiga-back,EvgeneOskin/taiga-back,EvgeneOskin/taiga-back,frt-arch/taiga-back,CMLL/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,gam-phon/taiga-back,Tigerwhit4/taiga-back,Rademade/taiga-back,frt-arch/taiga-back,seanchen/taiga-back,WALR/taiga-back,astronaut1712/taiga-back,joshisa/taiga-back,rajiteh/taiga-back
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
- urlpatterns += staticfiles_urlpatterns()
+ urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
|
Set prefix to static url patterm call
|
## Code Before:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += mediafiles_urlpatterns()
## Instruction:
Set prefix to static url patterm call
## Code After:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
|
// ... existing code ...
urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
// ... rest of the code ...
|
b0bb270f1995271ea84c4ec428ade91b1550b36e
|
domotica/views.py
|
domotica/views.py
|
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
def index(request):
s7conn = s7.S7Comm("10.0.3.9")
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return render(request, "lights.html", context)
@csrf_exempt
def lightswitch(request, action):
s7conn = s7.S7Comm("10.0.3.9")
l = light.Light("", request.REQUEST["id"], s7conn)
if action != "toggle":
raise Http404
if not l.toggle():
raise Http404
return HttpResponse()
|
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
PLC_IP = "10.0.3.9"
def index(request):
s7conn = s7.S7Comm(PLC_IP)
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return render(request, "lights.html", context)
@csrf_exempt
def lightswitch(request, action):
s7conn = s7.S7Comm(PLC_IP)
l = light.Light("", request.REQUEST["id"], s7conn)
if action != "toggle":
raise Http404
if not l.toggle():
raise Http404
return HttpResponse()
|
Move IP address to a constant at least
|
Move IP address to a constant at least
Perhaps we need to move it to the 'configuration' file later.
|
Python
|
bsd-2-clause
|
kprovost/domotica,kprovost/domotica
|
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
+ PLC_IP = "10.0.3.9"
+
def index(request):
- s7conn = s7.S7Comm("10.0.3.9")
+ s7conn = s7.S7Comm(PLC_IP)
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return render(request, "lights.html", context)
@csrf_exempt
def lightswitch(request, action):
- s7conn = s7.S7Comm("10.0.3.9")
+ s7conn = s7.S7Comm(PLC_IP)
l = light.Light("", request.REQUEST["id"], s7conn)
if action != "toggle":
raise Http404
if not l.toggle():
raise Http404
return HttpResponse()
|
Move IP address to a constant at least
|
## Code Before:
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
def index(request):
s7conn = s7.S7Comm("10.0.3.9")
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return render(request, "lights.html", context)
@csrf_exempt
def lightswitch(request, action):
s7conn = s7.S7Comm("10.0.3.9")
l = light.Light("", request.REQUEST["id"], s7conn)
if action != "toggle":
raise Http404
if not l.toggle():
raise Http404
return HttpResponse()
## Instruction:
Move IP address to a constant at least
## Code After:
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
PLC_IP = "10.0.3.9"
def index(request):
s7conn = s7.S7Comm(PLC_IP)
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return render(request, "lights.html", context)
@csrf_exempt
def lightswitch(request, action):
s7conn = s7.S7Comm(PLC_IP)
l = light.Light("", request.REQUEST["id"], s7conn)
if action != "toggle":
raise Http404
if not l.toggle():
raise Http404
return HttpResponse()
|
// ... existing code ...
PLC_IP = "10.0.3.9"
def index(request):
s7conn = s7.S7Comm(PLC_IP)
// ... modified code ...
def lightswitch(request, action):
s7conn = s7.S7Comm(PLC_IP)
l = light.Light("", request.REQUEST["id"], s7conn)
// ... rest of the code ...
|
1bd90d597b23f49bce3ca3402256c9bb1ad22647
|
accounts/management/commands/request_common_profile_update.py
|
accounts/management/commands/request_common_profile_update.py
|
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
is_active=True):
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
|
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
is_active=True).exclude(email=""):
try:
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
except ValidationError:
self.stdout.write(u'Error with {}'.format(user.email))
|
Handle missing and invalid email addresses.
|
Handle missing and invalid email addresses.
|
Python
|
agpl-3.0
|
osamak/student-portal,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal
|
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
+ from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
+
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
- is_active=True):
+ is_active=True).exclude(email=""):
+ try:
- mail.send([user.email],
+ mail.send([user.email],
- template="update_common_profile",
+ template="update_common_profile",
- context={'user': user, 'full_url': full_url})
+ context={'user': user, 'full_url': full_url})
- self.stdout.write(u'Emailed {}.'.format(user.email))
+ self.stdout.write(u'Emailed {}.'.format(user.email))
+ except ValidationError:
+ self.stdout.write(u'Error with {}'.format(user.email))
+
|
Handle missing and invalid email addresses.
|
## Code Before:
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
is_active=True):
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
## Instruction:
Handle missing and invalid email addresses.
## Code After:
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
is_active=True).exclude(email=""):
try:
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
except ValidationError:
self.stdout.write(u'Error with {}'.format(user.email))
|
// ... existing code ...
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
// ... modified code ...
from django.core.urlresolvers import reverse
...
for user in User.objects.filter(common_profile__is_student=True,
is_active=True).exclude(email=""):
try:
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
except ValidationError:
self.stdout.write(u'Error with {}'.format(user.email))
// ... rest of the code ...
|
d76cbdd768964a2583cf28ab9efaf46964c815ae
|
swf/core.py
|
swf/core.py
|
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
'aws_access_key_id': None,
'aws_secret_access_key': None
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
})
class ConnectedSWFObject(object):
"""Authenticated object interface
Once inherited, implements the AWS authentication
into the child, adding a `connection` property.
"""
def __init__(self, *args, **kwargs):
for credkey in ('aws_access_key_id', 'aws_secret_access_key'):
if AWS_CREDENTIALS.get(credkey):
setattr(self, credkey, AWS_CREDENTIALS[credkey])
for kwarg in kwargs:
setattr(self, kwarg, kwargs[kwarg])
self.connection = Layer1(
self.aws_access_key_id,
self.aws_secret_access_key
)
def exists(self):
"""Checks if the connected swf object exists amazon-side"""
raise NotImplemented
def save(self):
"""Creates the connected swf object amazon side"""
raise NotImplemented
def deprecate(self):
"""Deprecates the connected swf object amazon side"""
raise NotImplemented
|
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
#'aws_access_key_id': AWS_ACCESS_KEY_ID,
#'aws_secret_access_key': AWS_SECRET_ACCESS_KEY,
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
})
class ConnectedSWFObject(object):
"""Authenticated object interface
Once inherited, implements the AWS authentication
into the child, adding a `connection` property.
"""
def __init__(self, *args, **kwargs):
for kwarg in kwargs:
setattr(self, kwarg, kwargs[kwarg])
self.connection = Layer1(
AWS_CREDENTIALS['aws_access_key_id'],
AWS_CREDENTIALS['aws_secret_access_key'],
)
def exists(self):
"""Checks if the connected swf object exists amazon-side"""
raise NotImplemented
def save(self):
"""Creates the connected swf object amazon side"""
raise NotImplemented
def deprecate(self):
"""Deprecates the connected swf object amazon side"""
raise NotImplemented
|
Update ConnectedSWFObject: raise KeyError if credentials are not set
|
Update ConnectedSWFObject: raise KeyError if credentials are not set
|
Python
|
mit
|
botify-labs/python-simple-workflow,botify-labs/python-simple-workflow
|
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
- 'aws_access_key_id': None,
- 'aws_secret_access_key': None
+ #'aws_access_key_id': AWS_ACCESS_KEY_ID,
+ #'aws_secret_access_key': AWS_SECRET_ACCESS_KEY,
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
})
class ConnectedSWFObject(object):
"""Authenticated object interface
Once inherited, implements the AWS authentication
into the child, adding a `connection` property.
"""
def __init__(self, *args, **kwargs):
- for credkey in ('aws_access_key_id', 'aws_secret_access_key'):
- if AWS_CREDENTIALS.get(credkey):
- setattr(self, credkey, AWS_CREDENTIALS[credkey])
-
for kwarg in kwargs:
setattr(self, kwarg, kwargs[kwarg])
self.connection = Layer1(
- self.aws_access_key_id,
- self.aws_secret_access_key
+ AWS_CREDENTIALS['aws_access_key_id'],
+ AWS_CREDENTIALS['aws_secret_access_key'],
)
def exists(self):
"""Checks if the connected swf object exists amazon-side"""
raise NotImplemented
def save(self):
"""Creates the connected swf object amazon side"""
raise NotImplemented
def deprecate(self):
"""Deprecates the connected swf object amazon side"""
raise NotImplemented
|
Update ConnectedSWFObject: raise KeyError if credentials are not set
|
## Code Before:
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
'aws_access_key_id': None,
'aws_secret_access_key': None
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
})
class ConnectedSWFObject(object):
"""Authenticated object interface
Once inherited, implements the AWS authentication
into the child, adding a `connection` property.
"""
def __init__(self, *args, **kwargs):
for credkey in ('aws_access_key_id', 'aws_secret_access_key'):
if AWS_CREDENTIALS.get(credkey):
setattr(self, credkey, AWS_CREDENTIALS[credkey])
for kwarg in kwargs:
setattr(self, kwarg, kwargs[kwarg])
self.connection = Layer1(
self.aws_access_key_id,
self.aws_secret_access_key
)
def exists(self):
"""Checks if the connected swf object exists amazon-side"""
raise NotImplemented
def save(self):
"""Creates the connected swf object amazon side"""
raise NotImplemented
def deprecate(self):
"""Deprecates the connected swf object amazon side"""
raise NotImplemented
## Instruction:
Update ConnectedSWFObject: raise KeyError if credentials are not set
## Code After:
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
#'aws_access_key_id': AWS_ACCESS_KEY_ID,
#'aws_secret_access_key': AWS_SECRET_ACCESS_KEY,
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
})
class ConnectedSWFObject(object):
"""Authenticated object interface
Once inherited, implements the AWS authentication
into the child, adding a `connection` property.
"""
def __init__(self, *args, **kwargs):
for kwarg in kwargs:
setattr(self, kwarg, kwargs[kwarg])
self.connection = Layer1(
AWS_CREDENTIALS['aws_access_key_id'],
AWS_CREDENTIALS['aws_secret_access_key'],
)
def exists(self):
"""Checks if the connected swf object exists amazon-side"""
raise NotImplemented
def save(self):
"""Creates the connected swf object amazon side"""
raise NotImplemented
def deprecate(self):
"""Deprecates the connected swf object amazon side"""
raise NotImplemented
|
// ... existing code ...
AWS_CREDENTIALS = {
#'aws_access_key_id': AWS_ACCESS_KEY_ID,
#'aws_secret_access_key': AWS_SECRET_ACCESS_KEY,
}
// ... modified code ...
def __init__(self, *args, **kwargs):
for kwarg in kwargs:
...
self.connection = Layer1(
AWS_CREDENTIALS['aws_access_key_id'],
AWS_CREDENTIALS['aws_secret_access_key'],
)
// ... rest of the code ...
|
520487df7b9612e18dc06764ba8632b0ef28aad2
|
solvent/bring.py
|
solvent/bring.py
|
from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
self._destination = destination
def go(self):
requirementLabel = requirementlabel.RequirementLabel(
basename=self._repositoryBasename, product=self._product, hash=self._hash)
label = requirementLabel.matching()
self.label(label=label, destination=self._destination)
@classmethod
def label(cls, label, destination):
logging.info("Checking out '%(label)s'", dict(label=label))
if not os.path.isdir(destination):
os.makedirs(destination)
run.run([
"osmosis", "checkout", destination, label,
"--MD5", "--removeUnknownFiles", "--putIfMissing",
"--objectStores=" + config.objectStoresOsmosisParameter()])
|
from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
self._destination = destination
def go(self):
requirementLabel = requirementlabel.RequirementLabel(
basename=self._repositoryBasename, product=self._product, hash=self._hash)
label = requirementLabel.matching()
self.label(label=label, destination=self._destination)
@classmethod
def label(cls, label, destination):
logging.info("Checking out '%(label)s'", dict(label=label))
if not os.path.isdir(destination):
os.makedirs(destination)
myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else []
run.run([
"osmosis", "checkout", destination, label,
"--MD5", "--removeUnknownFiles", "--putIfMissing",
"--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
|
Bring now uses --myUIDandGIDCheckout if root is not the invoker
|
Bring now uses --myUIDandGIDCheckout if root is not the invoker
|
Python
|
apache-2.0
|
Stratoscale/solvent,Stratoscale/solvent
|
from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
self._destination = destination
def go(self):
requirementLabel = requirementlabel.RequirementLabel(
basename=self._repositoryBasename, product=self._product, hash=self._hash)
label = requirementLabel.matching()
self.label(label=label, destination=self._destination)
@classmethod
def label(cls, label, destination):
logging.info("Checking out '%(label)s'", dict(label=label))
if not os.path.isdir(destination):
os.makedirs(destination)
+ myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else []
run.run([
"osmosis", "checkout", destination, label,
"--MD5", "--removeUnknownFiles", "--putIfMissing",
- "--objectStores=" + config.objectStoresOsmosisParameter()])
+ "--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
|
Bring now uses --myUIDandGIDCheckout if root is not the invoker
|
## Code Before:
from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
self._destination = destination
def go(self):
requirementLabel = requirementlabel.RequirementLabel(
basename=self._repositoryBasename, product=self._product, hash=self._hash)
label = requirementLabel.matching()
self.label(label=label, destination=self._destination)
@classmethod
def label(cls, label, destination):
logging.info("Checking out '%(label)s'", dict(label=label))
if not os.path.isdir(destination):
os.makedirs(destination)
run.run([
"osmosis", "checkout", destination, label,
"--MD5", "--removeUnknownFiles", "--putIfMissing",
"--objectStores=" + config.objectStoresOsmosisParameter()])
## Instruction:
Bring now uses --myUIDandGIDCheckout if root is not the invoker
## Code After:
from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
self._destination = destination
def go(self):
requirementLabel = requirementlabel.RequirementLabel(
basename=self._repositoryBasename, product=self._product, hash=self._hash)
label = requirementLabel.matching()
self.label(label=label, destination=self._destination)
@classmethod
def label(cls, label, destination):
logging.info("Checking out '%(label)s'", dict(label=label))
if not os.path.isdir(destination):
os.makedirs(destination)
myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else []
run.run([
"osmosis", "checkout", destination, label,
"--MD5", "--removeUnknownFiles", "--putIfMissing",
"--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
|
...
os.makedirs(destination)
myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else []
run.run([
...
"--MD5", "--removeUnknownFiles", "--putIfMissing",
"--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
...
|
0d89712bda6e85901e839dec3e639c16aea42d48
|
tests/test_proxy_pagination.py
|
tests/test_proxy_pagination.py
|
import json
from django.test import TestCase
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
self.assertNotIn('count', resp.content)
content = json.loads(resp.content)
self.assertIn('next', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
|
import json
from django.test import TestCase
from django.utils import six
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertNotIn('count', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
|
Fix tests failing with Python 3
|
Fix tests failing with Python 3
|
Python
|
mit
|
tuffnatty/drf-proxy-pagination
|
import json
from django.test import TestCase
+ from django.utils import six
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
- content = json.loads(resp.content)
+ content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
+ content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
- self.assertNotIn('count', resp.content)
- content = json.loads(resp.content)
self.assertIn('next', content)
+ self.assertNotIn('count', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
|
Fix tests failing with Python 3
|
## Code Before:
import json
from django.test import TestCase
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
self.assertNotIn('count', resp.content)
content = json.loads(resp.content)
self.assertIn('next', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
## Instruction:
Fix tests failing with Python 3
## Code After:
import json
from django.test import TestCase
from django.utils import six
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertNotIn('count', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
|
# ... existing code ...
from django.test import TestCase
from django.utils import six
# ... modified code ...
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
...
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertNotIn('count', content)
self.assertNotIn('page=', content['next'])
# ... rest of the code ...
|
09268200fcc1ae21206659ae261c488eb1567071
|
app/__init__.py
|
app/__init__.py
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
Add '/admin' url_prefix to main blueprint
|
Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated.
|
Python
|
mit
|
alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
- application.register_blueprint(main_blueprint)
- main_blueprint.config = application.config.copy()
-
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
- application.before_request(requires_auth)
+ main_blueprint.before_request(requires_auth)
+
+ application.register_blueprint(main_blueprint, url_prefix='/admin')
+ main_blueprint.config = application.config.copy()
return application
|
Add '/admin' url_prefix to main blueprint
|
## Code Before:
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
## Instruction:
Add '/admin' url_prefix to main blueprint
## Code After:
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
// ... existing code ...
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
// ... modified code ...
return application
// ... rest of the code ...
|
53cb3adb97bb434a896938c2c7f78109e5b5566f
|
tests/test_identify_repo.py
|
tests/test_identify_repo.py
|
import pytest
from cookiecutter import exceptions, vcs
def test_identify_git_github():
repo_url = "https://github.com/audreyr/cookiecutter-pypackage.git"
assert vcs.identify_repo(repo_url) == "git"
def test_identify_git_github_no_extension():
repo_url = "https://github.com/audreyr/cookiecutter-pypackage"
assert vcs.identify_repo(repo_url) == "git"
def test_identify_git_gitorious():
repo_url = (
"[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git"
)
assert vcs.identify_repo(repo_url) == "git"
def test_identify_hg_mercurial():
repo_url = "https://[email protected]/audreyr/cookiecutter-bitbucket"
assert vcs.identify_repo(repo_url) == "hg"
def test_unknown_repo_type():
repo_url = "http://norepotypespecified.com"
with pytest.raises(exceptions.UnknownRepoType):
vcs.identify_repo(repo_url)
|
import pytest
from cookiecutter import exceptions, vcs
def test_identify_git_github():
repo_url = 'https://github.com/audreyr/cookiecutter-pypackage.git'
assert vcs.identify_repo(repo_url) == 'git'
def test_identify_git_github_no_extension():
repo_url = 'https://github.com/audreyr/cookiecutter-pypackage'
assert vcs.identify_repo(repo_url) == 'git'
def test_identify_git_gitorious():
repo_url = (
'[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git'
)
assert vcs.identify_repo(repo_url) == 'git'
def test_identify_hg_mercurial():
repo_url = 'https://[email protected]/audreyr/cookiecutter-bitbucket'
assert vcs.identify_repo(repo_url) == 'hg'
def test_unknown_repo_type():
repo_url = 'http://norepotypespecified.com'
with pytest.raises(exceptions.UnknownRepoType):
vcs.identify_repo(repo_url)
|
Use single quotes instead of double quotes
|
Use single quotes instead of double quotes
|
Python
|
bsd-3-clause
|
audreyr/cookiecutter,audreyr/cookiecutter,sp1rs/cookiecutter,lucius-feng/cookiecutter,luzfcb/cookiecutter,christabor/cookiecutter,jhermann/cookiecutter,terryjbates/cookiecutter,cichm/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,venumech/cookiecutter,moi65/cookiecutter,0k/cookiecutter,ramiroluz/cookiecutter,agconti/cookiecutter,nhomar/cookiecutter,benthomasson/cookiecutter,Vauxoo/cookiecutter,kkujawinski/cookiecutter,vincentbernat/cookiecutter,atlassian/cookiecutter,michaeljoseph/cookiecutter,vintasoftware/cookiecutter,takeflight/cookiecutter,stevepiercy/cookiecutter,nhomar/cookiecutter,christabor/cookiecutter,jhermann/cookiecutter,drgarcia1986/cookiecutter,venumech/cookiecutter,benthomasson/cookiecutter,janusnic/cookiecutter,janusnic/cookiecutter,willingc/cookiecutter,tylerdave/cookiecutter,foodszhang/cookiecutter,dajose/cookiecutter,vintasoftware/cookiecutter,stevepiercy/cookiecutter,sp1rs/cookiecutter,takeflight/cookiecutter,pjbull/cookiecutter,0k/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,kkujawinski/cookiecutter,hackebrot/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,cguardia/cookiecutter,tylerdave/cookiecutter,lgp171188/cookiecutter,ionelmc/cookiecutter,foodszhang/cookiecutter,vincentbernat/cookiecutter,cichm/cookiecutter,dajose/cookiecutter,lgp171188/cookiecutter,Springerle/cookiecutter,michaeljoseph/cookiecutter,ionelmc/cookiecutter,agconti/cookiecutter,cguardia/cookiecutter,lucius-feng/cookiecutter,luzfcb/cookiecutter,atlassian/cookiecutter,Vauxoo/cookiecutter,drgarcia1986/cookiecutter,willingc/cookiecutter
|
import pytest
from cookiecutter import exceptions, vcs
def test_identify_git_github():
- repo_url = "https://github.com/audreyr/cookiecutter-pypackage.git"
+ repo_url = 'https://github.com/audreyr/cookiecutter-pypackage.git'
- assert vcs.identify_repo(repo_url) == "git"
+ assert vcs.identify_repo(repo_url) == 'git'
def test_identify_git_github_no_extension():
- repo_url = "https://github.com/audreyr/cookiecutter-pypackage"
+ repo_url = 'https://github.com/audreyr/cookiecutter-pypackage'
- assert vcs.identify_repo(repo_url) == "git"
+ assert vcs.identify_repo(repo_url) == 'git'
def test_identify_git_gitorious():
repo_url = (
- "[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git"
+ '[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git'
)
- assert vcs.identify_repo(repo_url) == "git"
+ assert vcs.identify_repo(repo_url) == 'git'
def test_identify_hg_mercurial():
- repo_url = "https://[email protected]/audreyr/cookiecutter-bitbucket"
+ repo_url = 'https://[email protected]/audreyr/cookiecutter-bitbucket'
- assert vcs.identify_repo(repo_url) == "hg"
+ assert vcs.identify_repo(repo_url) == 'hg'
def test_unknown_repo_type():
- repo_url = "http://norepotypespecified.com"
+ repo_url = 'http://norepotypespecified.com'
with pytest.raises(exceptions.UnknownRepoType):
vcs.identify_repo(repo_url)
|
Use single quotes instead of double quotes
|
## Code Before:
import pytest
from cookiecutter import exceptions, vcs
def test_identify_git_github():
repo_url = "https://github.com/audreyr/cookiecutter-pypackage.git"
assert vcs.identify_repo(repo_url) == "git"
def test_identify_git_github_no_extension():
repo_url = "https://github.com/audreyr/cookiecutter-pypackage"
assert vcs.identify_repo(repo_url) == "git"
def test_identify_git_gitorious():
repo_url = (
"[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git"
)
assert vcs.identify_repo(repo_url) == "git"
def test_identify_hg_mercurial():
repo_url = "https://[email protected]/audreyr/cookiecutter-bitbucket"
assert vcs.identify_repo(repo_url) == "hg"
def test_unknown_repo_type():
repo_url = "http://norepotypespecified.com"
with pytest.raises(exceptions.UnknownRepoType):
vcs.identify_repo(repo_url)
## Instruction:
Use single quotes instead of double quotes
## Code After:
import pytest
from cookiecutter import exceptions, vcs
def test_identify_git_github():
repo_url = 'https://github.com/audreyr/cookiecutter-pypackage.git'
assert vcs.identify_repo(repo_url) == 'git'
def test_identify_git_github_no_extension():
repo_url = 'https://github.com/audreyr/cookiecutter-pypackage'
assert vcs.identify_repo(repo_url) == 'git'
def test_identify_git_gitorious():
repo_url = (
'[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git'
)
assert vcs.identify_repo(repo_url) == 'git'
def test_identify_hg_mercurial():
repo_url = 'https://[email protected]/audreyr/cookiecutter-bitbucket'
assert vcs.identify_repo(repo_url) == 'hg'
def test_unknown_repo_type():
repo_url = 'http://norepotypespecified.com'
with pytest.raises(exceptions.UnknownRepoType):
vcs.identify_repo(repo_url)
|
...
def test_identify_git_github():
repo_url = 'https://github.com/audreyr/cookiecutter-pypackage.git'
assert vcs.identify_repo(repo_url) == 'git'
...
def test_identify_git_github_no_extension():
repo_url = 'https://github.com/audreyr/cookiecutter-pypackage'
assert vcs.identify_repo(repo_url) == 'git'
...
repo_url = (
'[email protected]:cookiecutter-gitorious/cookiecutter-gitorious.git'
)
assert vcs.identify_repo(repo_url) == 'git'
...
def test_identify_hg_mercurial():
repo_url = 'https://[email protected]/audreyr/cookiecutter-bitbucket'
assert vcs.identify_repo(repo_url) == 'hg'
...
def test_unknown_repo_type():
repo_url = 'http://norepotypespecified.com'
with pytest.raises(exceptions.UnknownRepoType):
...
|
c8cc1f8e0e9b6d7dfb29ff9aef04bf2b5867cceb
|
genomediff/records.py
|
genomediff/records.py
|
class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Metadata({}, {})".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **extra):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
self._extra = extra
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
return self._extra[item]
def __repr__(self):
return "Record('{}', {}, {}, {})".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Metadata({}, {})".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **attributes):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
self.attributes = attributes
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
try:
return self.attributes[item]
except KeyError:
raise AttributeError
def __repr__(self):
return "Record('{}', {}, {}, {})".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
Raise AttributeError if key does not exist when trying to get it from a Record
|
Raise AttributeError if key does not exist when trying to get it from a Record
|
Python
|
mit
|
biosustain/genomediff-python
|
class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Metadata({}, {})".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
- def __init__(self, type, id, document=None, parent_ids=None, **extra):
+ def __init__(self, type, id, document=None, parent_ids=None, **attributes):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
- self._extra = extra
+ self.attributes = attributes
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
+ try:
- return self._extra[item]
+ return self.attributes[item]
+ except KeyError:
+ raise AttributeError
- def __repr__(self):
- return "Record('{}', {}, {}, {})".format(self.type,
- self.id,
- self.parent_ids,
- ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
- def __eq__(self, other):
- return self.__dict__ == other.__dict__
+ def __repr__(self):
+ return "Record('{}', {}, {}, {})".format(self.type,
+ self.id,
+ self.parent_ids,
+ ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
+
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
+
|
Raise AttributeError if key does not exist when trying to get it from a Record
|
## Code Before:
class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Metadata({}, {})".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **extra):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
self._extra = extra
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
return self._extra[item]
def __repr__(self):
return "Record('{}', {}, {}, {})".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
## Instruction:
Raise AttributeError if key does not exist when trying to get it from a Record
## Code After:
class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Metadata({}, {})".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **attributes):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
self.attributes = attributes
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
try:
return self.attributes[item]
except KeyError:
raise AttributeError
def __repr__(self):
return "Record('{}', {}, {}, {})".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
// ... existing code ...
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **attributes):
self.document = document
// ... modified code ...
self.parent_ids = parent_ids
self.attributes = attributes
...
def __getattr__(self, item):
try:
return self.attributes[item]
except KeyError:
raise AttributeError
def __repr__(self):
return "Record('{}', {}, {}, {})".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
// ... rest of the code ...
|
128a9a98879fdd52f1f3fb04355fc3094f3769ba
|
scipy/signal/setup.py
|
scipy/signal/setup.py
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Add newsig.c as a dependency to sigtools module.
|
Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf
|
Python
|
bsd-3-clause
|
lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
- depends = ['sigtools.h']
+ depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Add newsig.c as a dependency to sigtools module.
|
## Code Before:
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
## Instruction:
Add newsig.c as a dependency to sigtools module.
## Code After:
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
...
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
...
|
70cfff61c8b3841e71674da0b13c6fc8eee3e924
|
api/institutions/serializers.py
|
api/institutions/serializers.py
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField
class InstitutionSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'id',
'name'
])
name = ser.CharField(read_only=True)
id = ser.CharField(read_only=True, source='_id')
logo_path = ser.CharField(read_only=True)
auth_url = ser.CharField(read_only=True)
links = LinksField({'self': 'get_api_url', })
nodes = RelationshipField(
related_view='institutions:institution-nodes',
related_view_kwargs={'institution_id': '<pk>'},
)
registrations = RelationshipField(
related_view='institutions:institution-registrations',
related_view_kwargs={'institution_id': '<pk>'}
)
users = RelationshipField(
related_view='institutions:institution-users',
related_view_kwargs={'institution_id': '<pk>'}
)
def get_api_url(self, obj):
return obj.absolute_api_v2_url
class Meta:
type_ = 'institutions'
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField
class InstitutionSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'id',
'name'
])
name = ser.CharField(read_only=True)
id = ser.CharField(read_only=True, source='_id')
logo_path = ser.CharField(read_only=True)
auth_url = ser.CharField(read_only=True)
links = LinksField({'self': 'get_api_url', })
nodes = RelationshipField(
related_view='institutions:institution-nodes',
related_view_kwargs={'institution_id': '<pk>'},
)
registrations = RelationshipField(
related_view='institutions:institution-registrations',
related_view_kwargs={'institution_id': '<pk>'}
)
users = RelationshipField(
related_view='institutions:institution-users',
related_view_kwargs={'institution_id': '<pk>'}
)
def get_api_url(self, obj):
return obj.absolute_api_v2_url
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
class Meta:
type_ = 'institutions'
|
Add get_absolute_url method to institutions
|
Add get_absolute_url method to institutions
|
Python
|
apache-2.0
|
zamattiac/osf.io,doublebits/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,chennan47/osf.io,mluo613/osf.io,jnayak1/osf.io,Nesiehr/osf.io,leb2dg/osf.io,caneruguz/osf.io,SSJohns/osf.io,mluke93/osf.io,sloria/osf.io,hmoco/osf.io,binoculars/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,binoculars/osf.io,chrisseto/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,acshi/osf.io,brandonPurvis/osf.io,icereval/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,chrisseto/osf.io,doublebits/osf.io,TomBaxter/osf.io,mluke93/osf.io,pattisdr/osf.io,kwierman/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,doublebits/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,acshi/osf.io,asanfilippo7/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,rdhyee/osf.io,leb2dg/osf.io,cslzchen/osf.io,sloria/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,adlius/osf.io,TomBaxter/osf.io,felliott/osf.io,SSJohns/osf.io,icereval/osf.io,RomanZWang/osf.io,amyshi188/osf.io,billyhunt/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,emetsger/osf.io,zamattiac/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,TomHeatwole/osf.io,abought/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,wearpants/osf.io,zachjanicki/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,doublebits/osf.io,felliott/osf.io,GageGaskins/osf.io,Johnetordoff/osf.io,mluke93/osf.io,asanfilippo7/osf.io,brianjgeiger/osf.io,KAsante95/osf.io,adlius/osf.io,zachjanicki/osf.io,wearpants/osf.io,wearpants/osf.io,laurenrevere/osf.io,billyhunt/osf.io,amyshi188/osf.io,hmoco/osf.io,cwisecarver/osf.io,SSJohns/osf.io,jnayak1/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,GageGaskins/osf.io,adlius/osf.io,brianjgeiger/osf.io,wearpants/osf.io,billyhunt/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,erinspace/osf.io,mluo613/osf.io,alexschiller/osf.io,pattisdr/osf.io,chennan47/osf.io,asanfilippo7/osf.io,crcresearch/osf.io,jnayak1/osf.io,abought/osf.io,mfraezz/osf.io,mfraezz/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,icereval/osf.io,mattclark/osf.io,alexschiller/osf.io,acshi/osf.io,billyhunt/osf.io,emetsger/osf.io,Nesiehr/osf.io,abought/osf.io,erinspace/osf.io,caseyrollins/osf.io,erinspace/osf.io,cslzchen/osf.io,felliott/osf.io,laurenrevere/osf.io,felliott/osf.io,hmoco/osf.io,zachjanicki/osf.io,kwierman/osf.io,caneruguz/osf.io,GageGaskins/osf.io,TomBaxter/osf.io,aaxelb/osf.io,alexschiller/osf.io,emetsger/osf.io,mluo613/osf.io,Nesiehr/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,acshi/osf.io,mluo613/osf.io,kch8qx/osf.io,cwisecarver/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,KAsante95/osf.io,RomanZWang/osf.io,kwierman/osf.io,GageGaskins/osf.io,alexschiller/osf.io,kch8qx/osf.io,cwisecarver/osf.io,zachjanicki/osf.io,kch8qx/osf.io,CenterForOpenScience/osf.io,kch8qx/osf.io,emetsger/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,caneruguz/osf.io,caseyrollins/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,adlius/osf.io,crcresearch/osf.io,mluo613/osf.io,pattisdr/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,baylee-d/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,binoculars/osf.io,mattclark/osf.io,mattclark/osf.io,kwierman/osf.io,amyshi188/osf.io,chennan47/osf.io,mfraezz/osf.io,sloria/osf.io,KAsante95/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,brandonPurvis/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,caneruguz/osf.io,acshi/osf.io,mluke93/osf.io,abought/osf.io,leb2dg/osf.io,zamattiac/osf.io,samchrisinger/osf.io,doublebits/osf.io,chrisseto/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,saradbowman/osf.io,baylee-d/osf.io,chrisseto/osf.io
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField
class InstitutionSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'id',
'name'
])
name = ser.CharField(read_only=True)
id = ser.CharField(read_only=True, source='_id')
logo_path = ser.CharField(read_only=True)
auth_url = ser.CharField(read_only=True)
links = LinksField({'self': 'get_api_url', })
nodes = RelationshipField(
related_view='institutions:institution-nodes',
related_view_kwargs={'institution_id': '<pk>'},
)
registrations = RelationshipField(
related_view='institutions:institution-registrations',
related_view_kwargs={'institution_id': '<pk>'}
)
users = RelationshipField(
related_view='institutions:institution-users',
related_view_kwargs={'institution_id': '<pk>'}
)
def get_api_url(self, obj):
return obj.absolute_api_v2_url
+ def get_absolute_url(self, obj):
+ return obj.absolute_api_v2_url
+
class Meta:
type_ = 'institutions'
|
Add get_absolute_url method to institutions
|
## Code Before:
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField
class InstitutionSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'id',
'name'
])
name = ser.CharField(read_only=True)
id = ser.CharField(read_only=True, source='_id')
logo_path = ser.CharField(read_only=True)
auth_url = ser.CharField(read_only=True)
links = LinksField({'self': 'get_api_url', })
nodes = RelationshipField(
related_view='institutions:institution-nodes',
related_view_kwargs={'institution_id': '<pk>'},
)
registrations = RelationshipField(
related_view='institutions:institution-registrations',
related_view_kwargs={'institution_id': '<pk>'}
)
users = RelationshipField(
related_view='institutions:institution-users',
related_view_kwargs={'institution_id': '<pk>'}
)
def get_api_url(self, obj):
return obj.absolute_api_v2_url
class Meta:
type_ = 'institutions'
## Instruction:
Add get_absolute_url method to institutions
## Code After:
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField
class InstitutionSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'id',
'name'
])
name = ser.CharField(read_only=True)
id = ser.CharField(read_only=True, source='_id')
logo_path = ser.CharField(read_only=True)
auth_url = ser.CharField(read_only=True)
links = LinksField({'self': 'get_api_url', })
nodes = RelationshipField(
related_view='institutions:institution-nodes',
related_view_kwargs={'institution_id': '<pk>'},
)
registrations = RelationshipField(
related_view='institutions:institution-registrations',
related_view_kwargs={'institution_id': '<pk>'}
)
users = RelationshipField(
related_view='institutions:institution-users',
related_view_kwargs={'institution_id': '<pk>'}
)
def get_api_url(self, obj):
return obj.absolute_api_v2_url
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
class Meta:
type_ = 'institutions'
|
# ... existing code ...
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
class Meta:
# ... rest of the code ...
|
709017ea46cd3784983ef0ee64cfe608aa44cf0c
|
tests/integration/aiohttp_utils.py
|
tests/integration/aiohttp_utils.py
|
import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == 'text':
content = yield from response.text() # NOQA: E999
elif output == 'json':
content = yield from response.json() # NOQA: E999
elif output == 'raw':
content = yield from response.read() # NOQA: E999
response_ctx._resp.close()
yield from session.close()
return response, content
|
import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == 'text':
content = yield from response.text() # NOQA: E999
elif output == 'json':
content = yield from response.json(encoding=encoding) # NOQA: E999
elif output == 'raw':
content = yield from response.read() # NOQA: E999
response_ctx._resp.close()
yield from session.close()
return response, content
|
Fix aiohttp utils to pass encondig to response.json
|
Fix aiohttp utils to pass encondig to response.json
|
Python
|
mit
|
graingert/vcrpy,graingert/vcrpy,kevin1024/vcrpy,kevin1024/vcrpy
|
import asyncio
import aiohttp
@asyncio.coroutine
- def aiohttp_request(loop, method, url, output='text', **kwargs):
+ def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == 'text':
content = yield from response.text() # NOQA: E999
elif output == 'json':
- content = yield from response.json() # NOQA: E999
+ content = yield from response.json(encoding=encoding) # NOQA: E999
elif output == 'raw':
content = yield from response.read() # NOQA: E999
response_ctx._resp.close()
yield from session.close()
return response, content
|
Fix aiohttp utils to pass encondig to response.json
|
## Code Before:
import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == 'text':
content = yield from response.text() # NOQA: E999
elif output == 'json':
content = yield from response.json() # NOQA: E999
elif output == 'raw':
content = yield from response.read() # NOQA: E999
response_ctx._resp.close()
yield from session.close()
return response, content
## Instruction:
Fix aiohttp utils to pass encondig to response.json
## Code After:
import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == 'text':
content = yield from response.text() # NOQA: E999
elif output == 'json':
content = yield from response.json(encoding=encoding) # NOQA: E999
elif output == 'raw':
content = yield from response.read() # NOQA: E999
response_ctx._resp.close()
yield from session.close()
return response, content
|
# ... existing code ...
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
# ... modified code ...
elif output == 'json':
content = yield from response.json(encoding=encoding) # NOQA: E999
elif output == 'raw':
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.