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
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
1f98e497136ce3d9da7e63a6dc7c3f67fedf50b5
observations/views.py
observations/views.py
from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') def form_valid(self, form): observation = form.save(commit=False) observation.observer = self.request.observer observation.save() return super(AddObservationView, self).form_valid(form) class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
Save the observation if the form was valid.
Save the observation if the form was valid.
Python
mit
zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net
from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') + def form_valid(self, form): + observation = form.save(commit=False) + observation.observer = self.request.observer + observation.save() + return super(AddObservationView, self).form_valid(form) + class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
Save the observation if the form was valid.
## Code Before: from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form) ## Instruction: Save the observation if the form was valid. ## Code After: from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') def form_valid(self, form): observation = form.save(commit=False) observation.observer = self.request.observer observation.save() return super(AddObservationView, self).form_valid(form) class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
3a27568211c07cf614aa9865a2f08d2a9b9bfb71
dinosaurs/views.py
dinosaurs/views.py
import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) ret, passwd = api.create_email(connection, email) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED)
import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): def write_error(self, status_code, **kwargs): self.finish({ "code": status_code, "message": self._reason, }) def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) try: ret, passwd = api.create_email(connection, email) except api.YandexException as e: if e.message != 'occupied': raise self.write({}) raise tornado.web.HTTPError(http.FORBIDDEN) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED)
Return errors in json only
Return errors in json only
Python
mit
chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy
import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): + def write_error(self, status_code, **kwargs): + self.finish({ + "code": status_code, + "message": self._reason, + }) + def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) + try: - ret, passwd = api.create_email(connection, email) + ret, passwd = api.create_email(connection, email) + except api.YandexException as e: + if e.message != 'occupied': + raise + self.write({}) + raise tornado.web.HTTPError(http.FORBIDDEN) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED)
Return errors in json only
## Code Before: import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) ret, passwd = api.create_email(connection, email) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED) ## Instruction: Return errors in json only ## Code After: import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): def write_error(self, status_code, **kwargs): self.finish({ "code": status_code, "message": self._reason, }) def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) try: ret, passwd = api.create_email(connection, email) except api.YandexException as e: if e.message != 'occupied': raise self.write({}) raise tornado.web.HTTPError(http.FORBIDDEN) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED)
f574e19b14ff861c45f6c66c64a2570bdb0e3a3c
crawl_comments.py
crawl_comments.py
__doc__ = ''' Crawl comment from nicovideo.jp Usage: main_crawl.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
__doc__ = ''' Crawl comment from nicovideo.jp Usage: crawl_comments.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
Apply change of file name
Apply change of file name
Python
mit
tosh1ki/NicoCrawler
__doc__ = ''' Crawl comment from nicovideo.jp Usage: - main_crawl.py [--sqlite <sqlite>] [--csv <csv>] + crawl_comments.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
Apply change of file name
## Code Before: __doc__ = ''' Crawl comment from nicovideo.jp Usage: main_crawl.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1) ## Instruction: Apply change of file name ## Code After: __doc__ = ''' Crawl comment from nicovideo.jp Usage: crawl_comments.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
317926c18ac2e139d2018acd767d10b4f53428f3
installer/installer_config/views.py
installer/installer_config/views.py
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
Remove unneeded post method from CreateEnvProfile view
Remove unneeded post method from CreateEnvProfile view
Python
mit
ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse - from django.http import HttpResponseRedirect + class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) - - def post(self, request, *args, **kwargs): - form_class = self.get_form_class() - form = form_class(request.POST) - if form.is_valid(): - config_profile = form.save(commit=False) - config_profile.user = request.user - config_profile.save() - return HttpResponseRedirect(reverse('profile:profile')) - return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() - # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, - content_type='application') + content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
Remove unneeded post method from CreateEnvProfile view
## Code Before: from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response ## Instruction: Remove unneeded post method from CreateEnvProfile view ## Code After: from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
c24dbc2d4d8b59a62a68f326edb350b3c633ea25
interleaving/interleaving_method.py
interleaving/interleaving_method.py
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return a list of pairs of ranker indices in which element (i, j) indicates i won j. e.g. a result [(1, 0), (2, 1), (2, 0)] indicates ranker 1 won ranker 0, and ranker 2 won ranker 0 as well as ranker 1. ''' raise NotImplementedError()
Change the comment of InterleavingMethod.evaluate
Change the comment of InterleavingMethod.evaluate
Python
mit
mpkato/interleaving
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user - Return one of the following tuples: - - (1, 0): Ranking 'a' won - - (0, 1): Ranking 'b' won - - (0, 0): Tie + Return a list of pairs of ranker indices + in which element (i, j) indicates i won j. + + e.g. a result [(1, 0), (2, 1), (2, 0)] indicates + ranker 1 won ranker 0, and ranker 2 won ranker 0 as well as ranker 1. ''' raise NotImplementedError()
Change the comment of InterleavingMethod.evaluate
## Code Before: class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError() ## Instruction: Change the comment of InterleavingMethod.evaluate ## Code After: class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return a list of pairs of ranker indices in which element (i, j) indicates i won j. e.g. a result [(1, 0), (2, 1), (2, 0)] indicates ranker 1 won ranker 0, and ranker 2 won ranker 0 as well as ranker 1. ''' raise NotImplementedError()
85769162560d83a58ccc92f818559ddd3dce2a09
pages/index.py
pages/index.py
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: courses = Course.GetAllCoursesIds() return renderer.main(courses) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main() else: return renderer.index(True)
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(True)
Fix another bug in the authentication
Fix another bug in the authentication
Python
agpl-3.0
layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: - courses = Course.GetAllCoursesIds() - return renderer.main(courses) + return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): - return renderer.main() + return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(True)
Fix another bug in the authentication
## Code Before: import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: courses = Course.GetAllCoursesIds() return renderer.main(courses) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main() else: return renderer.index(True) ## Instruction: Fix another bug in the authentication ## Code After: import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(True)
cf07c34fe3a3d7b8767e50e77e609253dd177cff
moulinette/utils/serialize.py
moulinette/utils/serialize.py
import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): return str(o) # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o)
import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): return o.isoformat() # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o)
Use isoformat date RFC 3339
[enh] Use isoformat date RFC 3339
Python
agpl-3.0
YunoHost/moulinette
import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): - return str(o) + return o.isoformat() # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o)
Use isoformat date RFC 3339
## Code Before: import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): return str(o) # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o) ## Instruction: Use isoformat date RFC 3339 ## Code After: import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): return o.isoformat() # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o)
15ae458f7cf1a8257967b2b3b0ceb812547c4766
IPython/utils/tests/test_pycolorize.py
IPython/utils/tests/test_pycolorize.py
#----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- def test_unicode_colorize(): p = Parser() f1 = p.format('1/0', 'str') f2 = p.format(u'1/0', 'str') nt.assert_equal(f1, f2)
#----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser import io #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- sample = u""" def function(arg, *args, kwarg=True, **kwargs): ''' this is docs ''' pass is True False == None with io.open(ru'unicode'): raise ValueError("\n escape \r sequence") print("wěird ünicoðe") class Bar(Super): def __init__(self): super(Bar, self).__init__(1**2, 3^4, 5 or 6) """ def test_loop_colors(): for scheme in ('Linux', 'NoColor','LightBG'): def test_unicode_colorize(): p = Parser() f1 = p.format('1/0', 'str', scheme=scheme) f2 = p.format(u'1/0', 'str', scheme=scheme) nt.assert_equal(f1, f2) def test_parse_sample(): """and test writing to a buffer""" buf = io.StringIO() p = Parser() p.format(sample, buf, scheme=scheme) buf.seek(0) f1 = buf.read() nt.assert_not_in('ERROR', f1) def test_parse_error(): p = Parser() f1 = p.format(')', 'str', scheme=scheme) if scheme != 'NoColor': nt.assert_in('ERROR', f1) yield test_unicode_colorize yield test_parse_sample yield test_parse_error
Test more edge cases of the highlighting parser
Test more edge cases of the highlighting parser
Python
bsd-3-clause
ipython/ipython,ipython/ipython
#----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser + import io #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- - def test_unicode_colorize(): - p = Parser() - f1 = p.format('1/0', 'str') - f2 = p.format(u'1/0', 'str') - nt.assert_equal(f1, f2) + sample = u""" + def function(arg, *args, kwarg=True, **kwargs): + ''' + this is docs + ''' + pass is True + False == None + with io.open(ru'unicode'): + raise ValueError("\n escape \r sequence") + print("wěird ünicoðe") + + class Bar(Super): + + def __init__(self): + super(Bar, self).__init__(1**2, 3^4, 5 or 6) + """ + + def test_loop_colors(): + + for scheme in ('Linux', 'NoColor','LightBG'): + + def test_unicode_colorize(): + p = Parser() + f1 = p.format('1/0', 'str', scheme=scheme) + f2 = p.format(u'1/0', 'str', scheme=scheme) + nt.assert_equal(f1, f2) + + def test_parse_sample(): + """and test writing to a buffer""" + buf = io.StringIO() + p = Parser() + p.format(sample, buf, scheme=scheme) + buf.seek(0) + f1 = buf.read() + + nt.assert_not_in('ERROR', f1) + + def test_parse_error(): + p = Parser() + f1 = p.format(')', 'str', scheme=scheme) + if scheme != 'NoColor': + nt.assert_in('ERROR', f1) + + yield test_unicode_colorize + yield test_parse_sample + yield test_parse_error +
Test more edge cases of the highlighting parser
## Code Before: #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- def test_unicode_colorize(): p = Parser() f1 = p.format('1/0', 'str') f2 = p.format(u'1/0', 'str') nt.assert_equal(f1, f2) ## Instruction: Test more edge cases of the highlighting parser ## Code After: #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser import io #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- sample = u""" def function(arg, *args, kwarg=True, **kwargs): ''' this is docs ''' pass is True False == None with io.open(ru'unicode'): raise ValueError("\n escape \r sequence") print("wěird ünicoðe") class Bar(Super): def __init__(self): super(Bar, self).__init__(1**2, 3^4, 5 or 6) """ def test_loop_colors(): for scheme in ('Linux', 'NoColor','LightBG'): def test_unicode_colorize(): p = Parser() f1 = p.format('1/0', 'str', scheme=scheme) f2 = p.format(u'1/0', 'str', scheme=scheme) nt.assert_equal(f1, f2) def test_parse_sample(): """and test writing to a buffer""" buf = io.StringIO() p = Parser() p.format(sample, buf, scheme=scheme) buf.seek(0) f1 = buf.read() nt.assert_not_in('ERROR', f1) def test_parse_error(): p = Parser() f1 = p.format(')', 'str', scheme=scheme) if scheme != 'NoColor': nt.assert_in('ERROR', f1) yield test_unicode_colorize yield test_parse_sample yield test_parse_error
6cb0822aade07999d54e5fcd19eb2c7322abc80a
measurement/admin.py
measurement/admin.py
from django.contrib import admin from .models import Measurement admin.site.register(Measurement)
from django.contrib import admin from .models import Measurement class MeasurementAdmin(admin.ModelAdmin): model = Measurement def get_queryset(self, request): return super(MeasurementAdmin, self).get_queryset(request).select_related('patient__user') admin.site.register(Measurement, MeasurementAdmin)
Improve performance @ Measurement Admin
Improve performance @ Measurement Admin
Python
mit
sigurdsa/angelika-api
from django.contrib import admin from .models import Measurement - admin.site.register(Measurement) + class MeasurementAdmin(admin.ModelAdmin): + model = Measurement + + def get_queryset(self, request): + return super(MeasurementAdmin, self).get_queryset(request).select_related('patient__user') + + admin.site.register(Measurement, MeasurementAdmin) +
Improve performance @ Measurement Admin
## Code Before: from django.contrib import admin from .models import Measurement admin.site.register(Measurement) ## Instruction: Improve performance @ Measurement Admin ## Code After: from django.contrib import admin from .models import Measurement class MeasurementAdmin(admin.ModelAdmin): model = Measurement def get_queryset(self, request): return super(MeasurementAdmin, self).get_queryset(request).select_related('patient__user') admin.site.register(Measurement, MeasurementAdmin)
b9b3837937341e6b1b052bbfdd979e3bb57d87c4
tests/integration/test_with_ssl.py
tests/integration/test_with_ssl.py
from . import base class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
import os from pymco.test import ctxt from . import base FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures') class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', 'plugin.ssl_server_private': os.path.join(FIXTURES_PATH, 'server-private.pem'), 'securityprovider': 'ssl', 'plugin.ssl_client_cert_dir': FIXTURES_PATH, } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
Fix SSL security provider integration tests
Fix SSL security provider integration tests They were running with none provider instead.
Python
bsd-3-clause
rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective
+ import os + + from pymco.test import ctxt from . import base + + FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures') class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', + 'plugin.ssl_server_private': os.path.join(FIXTURES_PATH, + 'server-private.pem'), + 'securityprovider': 'ssl', + 'plugin.ssl_client_cert_dir': FIXTURES_PATH, } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
Fix SSL security provider integration tests
## Code Before: from . import base class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.''' ## Instruction: Fix SSL security provider integration tests ## Code After: import os from pymco.test import ctxt from . import base FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures') class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', 'plugin.ssl_server_private': os.path.join(FIXTURES_PATH, 'server-private.pem'), 'securityprovider': 'ssl', 'plugin.ssl_client_cert_dir': FIXTURES_PATH, } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
f127f0e9bb0b8778feafbdbc1fa68e79a923d639
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()]))
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] product_dict = {} for product in items: product_id = product['link'].split('/')[-1] product_dict[str(product_id)] = product for product in Product.objects.all(): self.assertEqual( product_dict[str(product.id)]['description'], product.description) self.assertEqual( product_dict[str(product.id)]['name'], product.name) self.assertEqual( product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()]))
Update product listing test to use product ids rather than index
Update product listing test to use product ids rather than index
Python
apache-2.0
osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ - Tests to see if the list of products contains the proper productss and + Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] + product_dict = {} + + for product in items: + product_id = product['link'].split('/')[-1] + product_dict[str(product_id)] = product + for product in Product.objects.all(): self.assertEqual( - items[product.id-1]['description'], product.description) + product_dict[str(product.id)]['description'], + product.description) self.assertEqual( - items[product.id-1]['name'], product.name) + product_dict[str(product.id)]['name'], product.name) self.assertEqual( - items[product.id-1]['link'], + product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( - items[product.id-1]['modified'], + product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( - sort(items[product.id-1]['preparations']), + sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()]))
Update product listing test to use product ids rather than index
## Code Before: from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()])) ## Instruction: Update product listing test to use product ids rather than index ## Code After: from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] product_dict = {} for product in items: product_id = product['link'].split('/')[-1] product_dict[str(product_id)] = product for product in Product.objects.all(): self.assertEqual( product_dict[str(product.id)]['description'], product.description) self.assertEqual( product_dict[str(product.id)]['name'], product.name) self.assertEqual( product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()]))
fc75f5843af70c09e0d63284277bf88689cbb06d
invocations/docs.py
invocations/docs.py
import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task def docs(clean=False, browse=False): if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body()
import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task def api_docs(target, output="api", exclude=""): """ Runs ``sphinx-apidoc`` to autogenerate your API docs. Must give target directory/package as ``target``. Results are written out to ``docs/<output>`` (``docs/api`` by default). To exclude certain output files from the final build give ``exclude`` as a comma separated list of file paths. """ output = os.path.join('docs', output) # Have to make these absolute or apidoc is dumb :( exclude = map( lambda x: os.path.abspath(os.path.join(os.getcwd(), x)), exclude.split(',') ) run("sphinx-apidoc -o %s %s %s" % (output, target, ' '.join(exclude))) @task def docs(clean=False, browse=False, api_target=None, api_output=None, api_exclude=None): """ Build Sphinx docs, optionally ``clean``ing and/or ``browse``ing. Can also build API docs by giving ``api_target`` and optionally ``api_output`` and/or ``api_exclude``. """ if api_target: kwargs = {'target': api_target} if api_output: kwargs['output'] = api_output if api_exclude: kwargs['exclude'] = api_exclude api_docs.body(**kwargs) if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body()
Add apidoc to doc building
Add apidoc to doc building
Python
bsd-2-clause
mrjmad/invocations,pyinvoke/invocations,alex/invocations,singingwolfboy/invocations
import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task - def docs(clean=False, browse=False): + def api_docs(target, output="api", exclude=""): + """ + Runs ``sphinx-apidoc`` to autogenerate your API docs. + + Must give target directory/package as ``target``. Results are written out + to ``docs/<output>`` (``docs/api`` by default). + + To exclude certain output files from the final build give ``exclude`` as a + comma separated list of file paths. + """ + output = os.path.join('docs', output) + # Have to make these absolute or apidoc is dumb :( + exclude = map( + lambda x: os.path.abspath(os.path.join(os.getcwd(), x)), + exclude.split(',') + ) + run("sphinx-apidoc -o %s %s %s" % (output, target, ' '.join(exclude))) + + + @task + def docs(clean=False, browse=False, api_target=None, api_output=None, + api_exclude=None): + """ + Build Sphinx docs, optionally ``clean``ing and/or ``browse``ing. + + Can also build API docs by giving ``api_target`` and optionally + ``api_output`` and/or ``api_exclude``. + """ + if api_target: + kwargs = {'target': api_target} + if api_output: + kwargs['output'] = api_output + if api_exclude: + kwargs['exclude'] = api_exclude + api_docs.body(**kwargs) if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body()
Add apidoc to doc building
## Code Before: import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task def docs(clean=False, browse=False): if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body() ## Instruction: Add apidoc to doc building ## Code After: import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task def api_docs(target, output="api", exclude=""): """ Runs ``sphinx-apidoc`` to autogenerate your API docs. Must give target directory/package as ``target``. Results are written out to ``docs/<output>`` (``docs/api`` by default). To exclude certain output files from the final build give ``exclude`` as a comma separated list of file paths. """ output = os.path.join('docs', output) # Have to make these absolute or apidoc is dumb :( exclude = map( lambda x: os.path.abspath(os.path.join(os.getcwd(), x)), exclude.split(',') ) run("sphinx-apidoc -o %s %s %s" % (output, target, ' '.join(exclude))) @task def docs(clean=False, browse=False, api_target=None, api_output=None, api_exclude=None): """ Build Sphinx docs, optionally ``clean``ing and/or ``browse``ing. Can also build API docs by giving ``api_target`` and optionally ``api_output`` and/or ``api_exclude``. """ if api_target: kwargs = {'target': api_target} if api_output: kwargs['output'] = api_output if api_exclude: kwargs['exclude'] = api_exclude api_docs.body(**kwargs) if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body()
a9ac098ec492739f37005c9bd6278105df0261c5
parliamentsearch/items.py
parliamentsearch/items.py
import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field()
import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() q_url = scrapy.Field() q_annex = scrapy.Field()
Add fields to save question url and annexure links
Add fields to save question url and annexure links Details of each question is in another link and some questions have annexures (in English/Hindi), add fields to save all these items Signed-off-by: Arun Siluvery <66692e34e783869a1e5829b4c5eee5e1a471c4f7@gmail.com>
Python
mit
mthipparthi/parliament-search
import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() + q_url = scrapy.Field() + q_annex = scrapy.Field()
Add fields to save question url and annexure links
## Code Before: import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() ## Instruction: Add fields to save question url and annexure links ## Code After: import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() q_url = scrapy.Field() q_annex = scrapy.Field()
376b8aa5b77066e06c17f41d65fe32a3c2bdef1f
geo.py
geo.py
import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader()
import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None self.header_limit = -1 def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader()
Add a default value to the header limit
Add a default value to the header limit
Python
mit
a2ohm/geo
import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None + self.header_limit = -1 def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader()
Add a default value to the header limit
## Code Before: import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader() ## Instruction: Add a default value to the header limit ## Code After: import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None self.header_limit = -1 def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader()
fdae17a50223c2f9b8ba4a665fc24726e2c2ce14
tests/lib/es_tools.py
tests/lib/es_tools.py
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200").json()["tagline"] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post(url, headers=headers, data=body)
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200", auth=("elastic", "changeme")).json()[ "tagline" ] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post( url, headers=headers, data=body, auth=("elastic", "changeme") )
Add auth header to the fixture loader
Add auth header to the fixture loader It seems to work fine with the unauthenticated es instance
Python
mit
matthewfranglen/postgres-elasticsearch-fdw
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( - requests.get("http://localhost:9200").json()["tagline"] + requests.get("http://localhost:9200", auth=("elastic", "changeme")).json()[ + "tagline" + ] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") - return requests.post(url, headers=headers, data=body) + return requests.post( + url, headers=headers, data=body, auth=("elastic", "changeme") + )
Add auth header to the fixture loader
## Code Before: """ Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200").json()["tagline"] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post(url, headers=headers, data=body) ## Instruction: Add auth header to the fixture loader ## Code After: """ Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200", auth=("elastic", "changeme")).json()[ "tagline" ] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post( url, headers=headers, data=body, auth=("elastic", "changeme") )
bafdbd28e35d80d28bfb82c23532533cb2915066
fuel/exceptions.py
fuel/exceptions.py
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- message : str The error message to be associated with this exception. filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
Add docs for MissingInputFiles 'message' arg.
Add docs for MissingInputFiles 'message' arg.
Python
mit
hantek/fuel,rodrigob/fuel,dmitriy-serdyuk/fuel,codeaudit/fuel,udibr/fuel,mjwillson/fuel,dribnet/fuel,capybaralet/fuel,aalmah/fuel,glewis17/fuel,glewis17/fuel,vdumoulin/fuel,dmitriy-serdyuk/fuel,dwf/fuel,bouthilx/fuel,mila-udem/fuel,chrishokamp/fuel,udibr/fuel,janchorowski/fuel,dwf/fuel,dribnet/fuel,markusnagel/fuel,aalmah/fuel,markusnagel/fuel,orhanf/fuel,capybaralet/fuel,rodrigob/fuel,dhruvparamhans/fuel,dhruvparamhans/fuel,janchorowski/fuel,mila-udem/fuel,bouthilx/fuel,harmdevries89/fuel,hantek/fuel,harmdevries89/fuel,chrishokamp/fuel,codeaudit/fuel,orhanf/fuel,vdumoulin/fuel,mjwillson/fuel
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- + message : str + The error message to be associated with this exception. filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
Add docs for MissingInputFiles 'message' arg.
## Code Before: class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file.""" ## Instruction: Add docs for MissingInputFiles 'message' arg. ## Code After: class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- message : str The error message to be associated with this exception. filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
c99e0ac2e463302d41838f11ea28ea8a62990671
wafer/kv/serializers.py
wafer/kv/serializers.py
from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs)
from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue fields = ('group', 'key', 'value') # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs)
Add catchall fields property to KeyValueSerializer
Add catchall fields property to KeyValueSerializer With the latest django-restframework, not explicitly setting the fields for a serializer causes errors. This explicitly sets the fields to those of the model.
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue + fields = ('group', 'key', 'value') # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs)
Add catchall fields property to KeyValueSerializer
## Code Before: from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs) ## Instruction: Add catchall fields property to KeyValueSerializer ## Code After: from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue fields = ('group', 'key', 'value') # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs)
baacda228682a50acc5a4528d43f5d3a88c7c6ec
salt/client/netapi.py
salt/client/netapi.py
''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) multiprocessing.Process(target=netapi[fun]).start()
''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing import signal # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts self.processes = [] def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) p = multiprocessing.Process(target=netapi[fun]) p.start() self.processes.append(p) # make sure to kill the subprocesses if the parent is killed signal.signal(signal.SIGTERM, self.kill_children) def kill_children(self, *args): ''' Kill all of the children ''' for p in self.processes: p.terminate() p.join()
Make sure to not leave hanging children processes if the parent is killed
Make sure to not leave hanging children processes if the parent is killed
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing + import signal # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts + self.processes = [] def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) - multiprocessing.Process(target=netapi[fun]).start() + p = multiprocessing.Process(target=netapi[fun]) + p.start() + self.processes.append(p) + # make sure to kill the subprocesses if the parent is killed + signal.signal(signal.SIGTERM, self.kill_children) + + def kill_children(self, *args): + ''' + Kill all of the children + ''' + for p in self.processes: + p.terminate() + p.join() +
Make sure to not leave hanging children processes if the parent is killed
## Code Before: ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) multiprocessing.Process(target=netapi[fun]).start() ## Instruction: Make sure to not leave hanging children processes if the parent is killed ## Code After: ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing import signal # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts self.processes = [] def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) p = multiprocessing.Process(target=netapi[fun]) p.start() self.processes.append(p) # make sure to kill the subprocesses if the parent is killed signal.signal(signal.SIGTERM, self.kill_children) def kill_children(self, *args): ''' Kill all of the children ''' for p in self.processes: p.terminate() p.join()
a3b119e14df4aff213231492470587f88457a241
setuptools/command/upload.py
setuptools/command/upload.py
import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( self.password or self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password
import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( self.password or self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password
Add carriage return for symmetry
Add carriage return for symmetry
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( + self.password or - self.password or self._load_password_from_keyring() or + self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password
Add carriage return for symmetry
## Code Before: import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( self.password or self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password ## Instruction: Add carriage return for symmetry ## Code After: import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( self.password or self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password
0b8cc130f00b51b18e55805f82ba661fdf66fba6
saml2idp/saml2idp_metadata.py
saml2idp/saml2idp_metadata.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): available_keys = set(keys).intersection(set(config.keys())) if not available_keys: raise ImproperlyConfigured( 'one of the followin keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME]) check_configuration_contains(config=config, keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME]) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): available_keys = frozenset(keys).intersection(frozenset(config.keys())) if not available_keys: raise ImproperlyConfigured( 'one of the following keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME)) check_configuration_contains(config=config, keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME)) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
Implement suggested changes in PR review
Implement suggested changes in PR review
Python
mit
mobify/dj-saml-idp,mobify/dj-saml-idp,mobify/dj-saml-idp
from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): - available_keys = set(keys).intersection(set(config.keys())) + available_keys = frozenset(keys).intersection(frozenset(config.keys())) if not available_keys: raise ImproperlyConfigured( - 'one of the followin keys is required but none was ' + 'one of the following keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, - keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME]) + keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME)) check_configuration_contains(config=config, - keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME]) + keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME)) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
Implement suggested changes in PR review
## Code Before: from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): available_keys = set(keys).intersection(set(config.keys())) if not available_keys: raise ImproperlyConfigured( 'one of the followin keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME]) check_configuration_contains(config=config, keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME]) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.') ## Instruction: Implement suggested changes in PR review ## Code After: from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): available_keys = frozenset(keys).intersection(frozenset(config.keys())) if not available_keys: raise ImproperlyConfigured( 'one of the following keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME)) check_configuration_contains(config=config, keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME)) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
70ba84dc485ed3db4ccf5008db87b2c9f003634b
tests/fixtures/__init__.py
tests/fixtures/__init__.py
"""Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). FILE_CONTENT = FILE_PATH.read_text().strip() JSON_FILE_CONTENT = JSON_FILE_PATH.read_text() BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT
"""Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). FILE_CONTENT = FILE_PATH.read_text('utf8').strip() JSON_FILE_CONTENT = JSON_FILE_PATH.read_text('utf8') BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT
Fix fixture encoding on Windows
Fix fixture encoding on Windows
Python
bsd-3-clause
PKRoma/httpie,jakubroztocil/httpie,jkbrzt/httpie,jakubroztocil/httpie,jkbrzt/httpie,jakubroztocil/httpie,jkbrzt/httpie,PKRoma/httpie
"""Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). - FILE_CONTENT = FILE_PATH.read_text().strip() + FILE_CONTENT = FILE_PATH.read_text('utf8').strip() - JSON_FILE_CONTENT = JSON_FILE_PATH.read_text() + JSON_FILE_CONTENT = JSON_FILE_PATH.read_text('utf8') BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT
Fix fixture encoding on Windows
## Code Before: """Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). FILE_CONTENT = FILE_PATH.read_text().strip() JSON_FILE_CONTENT = JSON_FILE_PATH.read_text() BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT ## Instruction: Fix fixture encoding on Windows ## Code After: """Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). FILE_CONTENT = FILE_PATH.read_text('utf8').strip() JSON_FILE_CONTENT = JSON_FILE_PATH.read_text('utf8') BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT
4be668a7d8cdb692c20be2eabf65c20e294e16a8
scopus/utils/get_encoded_text.py
scopus/utils/get_encoded_text.py
ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: return container.find(xpath, ns).text except AttributeError: return None
ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: return "".join(container.find(xpath, ns).itertext()) except AttributeError: return None
Use itertext() to skip children in elements with text
Use itertext() to skip children in elements with text
Python
mit
scopus-api/scopus,jkitchin/scopus
ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: - return container.find(xpath, ns).text + return "".join(container.find(xpath, ns).itertext()) except AttributeError: return None
Use itertext() to skip children in elements with text
## Code Before: ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: return container.find(xpath, ns).text except AttributeError: return None ## Instruction: Use itertext() to skip children in elements with text ## Code After: ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: return "".join(container.find(xpath, ns).itertext()) except AttributeError: return None
e924f67b37c1a7612e520cca9715152029ddf338
test/integration/ggrc/services/test_query_snapshots.py
test/integration/ggrc/services/test_query_snapshots.py
"""Tests for /query api endpoint.""" from datetime import datetime from operator import itemgetter from flask import json from nose.plugins.skip import SkipTest from ggrc import db from ggrc import views from ggrc.models import CustomAttributeDefinition as CAD from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" # we don't call super as TestCase.setUp clears the DB # super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): audit = factories.AuditFactory() factories.MarketFactory() factories.MarketFactory() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects()
"""Tests for /query api endpoint.""" from ggrc import views from ggrc import models from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): text_cad = factories.CustomAttributeDefinitionFactory( definition_type="market", ) date_cad = factories.CustomAttributeDefinitionFactory( definition_type="market", attribute_type="Text", ) audit = factories.AuditFactory() for i in range(5): market = factories.MarketFactory() factories.CustomAttributeValueFactory( custom_attribute=date_cad, attributable=market, attribute_value="2016-11-0{}".format(i + 1), ) factories.CustomAttributeValueFactory( custom_attribute=text_cad, attributable=market, attribute_value="2016-11-0{}".format(i + 1), ) revisions = models.Revision.query.filter( models.Revision.resource_type == "Market") self.snapshots = [ factories.SnapshotFactory( child_id=revision.resource_id, child_type=revision.resource_type, revision=revision, parent=audit, ) for revision in revisions ] views.do_reindex() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects()
Update snapshot query test generation
Update snapshot query test generation
Python
apache-2.0
selahssea/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core
"""Tests for /query api endpoint.""" - from datetime import datetime - from operator import itemgetter - from flask import json - from nose.plugins.skip import SkipTest - from ggrc import db from ggrc import views - from ggrc.models import CustomAttributeDefinition as CAD + from ggrc import models from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" - # we don't call super as TestCase.setUp clears the DB - # super(BaseQueryAPITestCase, self).setUp() + super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): + text_cad = factories.CustomAttributeDefinitionFactory( + definition_type="market", + ) + date_cad = factories.CustomAttributeDefinitionFactory( + definition_type="market", + attribute_type="Text", + ) audit = factories.AuditFactory() + for i in range(5): - factories.MarketFactory() + market = factories.MarketFactory() - factories.MarketFactory() + factories.CustomAttributeValueFactory( + custom_attribute=date_cad, + attributable=market, + attribute_value="2016-11-0{}".format(i + 1), + ) + factories.CustomAttributeValueFactory( + custom_attribute=text_cad, + attributable=market, + attribute_value="2016-11-0{}".format(i + 1), + ) + revisions = models.Revision.query.filter( + models.Revision.resource_type == "Market") + + self.snapshots = [ + factories.SnapshotFactory( + child_id=revision.resource_id, + child_type=revision.resource_type, + revision=revision, + parent=audit, + ) + for revision in revisions + ] + views.do_reindex() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects()
Update snapshot query test generation
## Code Before: """Tests for /query api endpoint.""" from datetime import datetime from operator import itemgetter from flask import json from nose.plugins.skip import SkipTest from ggrc import db from ggrc import views from ggrc.models import CustomAttributeDefinition as CAD from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" # we don't call super as TestCase.setUp clears the DB # super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): audit = factories.AuditFactory() factories.MarketFactory() factories.MarketFactory() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects() ## Instruction: Update snapshot query test generation ## Code After: """Tests for /query api endpoint.""" from ggrc import views from ggrc import models from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): text_cad = factories.CustomAttributeDefinitionFactory( definition_type="market", ) date_cad = factories.CustomAttributeDefinitionFactory( definition_type="market", attribute_type="Text", ) audit = factories.AuditFactory() for i in range(5): market = factories.MarketFactory() factories.CustomAttributeValueFactory( custom_attribute=date_cad, attributable=market, attribute_value="2016-11-0{}".format(i + 1), ) factories.CustomAttributeValueFactory( custom_attribute=text_cad, attributable=market, attribute_value="2016-11-0{}".format(i + 1), ) revisions = models.Revision.query.filter( models.Revision.resource_type == "Market") self.snapshots = [ factories.SnapshotFactory( child_id=revision.resource_id, child_type=revision.resource_type, revision=revision, parent=audit, ) for revision in revisions ] views.do_reindex() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects()
aaa3f6b8154f03eab16528c05d889c6160e63f22
server/siege/views/devices.py
server/siege/views/devices.py
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): new_device = Device(comment=request.access_route) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): comment = '%s, %s' % (request.remote_addr, request.user_agent) new_device = Device(comment=comment) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
Put the user agent in the device object
Put the user agent in the device object
Python
bsd-2-clause
WalterCReel3/siege,WalterCReel3/siege,WalterCReel3/siege,WalterCReel3/siege
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): + comment = '%s, %s' % (request.remote_addr, request.user_agent) + - new_device = Device(comment=request.access_route) + new_device = Device(comment=comment) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
Put the user agent in the device object
## Code Before: from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): new_device = Device(comment=request.access_route) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response ## Instruction: Put the user agent in the device object ## Code After: from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): comment = '%s, %s' % (request.remote_addr, request.user_agent) new_device = Device(comment=comment) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
95d0461cf2f06534f81a954b1f95658cbb019ec6
tests/startsymbol_tests/NonterminalNotInGrammarTest.py
tests/startsymbol_tests/NonterminalNotInGrammarTest.py
from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException class NonterminalNotInGrammarTest(TestCase): pass if __name__ == '__main__': main()
from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException class A(Nonterminal): pass class B(Nonterminal): pass class NonterminalNotInGrammarTest(TestCase): def test_shouldNotSetStartSymbol(self): g = Grammar(nonterminals=[A]) self.assertFalse(g.start_isSet()) with self.assertRaises(NonterminalDoesNotExistsException): g.start_set(B) self.assertFalse(g.start_isSet()) self.assertFalse(g.start_is(B)) def test_shouldNotSetStartSymbolWhenCreate(self): with self.assertRaises(NonterminalDoesNotExistsException): g = Grammar(nonterminals=[B], start_symbol=A) def test_oldStartSymbolShouldStaySame(self): g = Grammar(nonterminals=[A], start_symbol=A) self.assertTrue(g.start_isSet()) with self.assertRaises(NonterminalDoesNotExistsException): g.start_set(B) self.assertTrue(g.start_isSet()) self.assertTrue(g.start_is(A)) self.assertEqual(g.start_get(), A) if __name__ == '__main__': main()
Add tests of setting nonterminal, which is not in grammar, as start symbol
Add tests of setting nonterminal, which is not in grammar, as start symbol
Python
mit
PatrikValkovic/grammpy
from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException + class A(Nonterminal): + pass + + + class B(Nonterminal): + pass + + class NonterminalNotInGrammarTest(TestCase): - pass + def test_shouldNotSetStartSymbol(self): + g = Grammar(nonterminals=[A]) + self.assertFalse(g.start_isSet()) + with self.assertRaises(NonterminalDoesNotExistsException): + g.start_set(B) + self.assertFalse(g.start_isSet()) + self.assertFalse(g.start_is(B)) + + def test_shouldNotSetStartSymbolWhenCreate(self): + with self.assertRaises(NonterminalDoesNotExistsException): + g = Grammar(nonterminals=[B], + start_symbol=A) + + def test_oldStartSymbolShouldStaySame(self): + g = Grammar(nonterminals=[A], start_symbol=A) + self.assertTrue(g.start_isSet()) + with self.assertRaises(NonterminalDoesNotExistsException): + g.start_set(B) + self.assertTrue(g.start_isSet()) + self.assertTrue(g.start_is(A)) + self.assertEqual(g.start_get(), A) if __name__ == '__main__': main()
Add tests of setting nonterminal, which is not in grammar, as start symbol
## Code Before: from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException class NonterminalNotInGrammarTest(TestCase): pass if __name__ == '__main__': main() ## Instruction: Add tests of setting nonterminal, which is not in grammar, as start symbol ## Code After: from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException class A(Nonterminal): pass class B(Nonterminal): pass class NonterminalNotInGrammarTest(TestCase): def test_shouldNotSetStartSymbol(self): g = Grammar(nonterminals=[A]) self.assertFalse(g.start_isSet()) with self.assertRaises(NonterminalDoesNotExistsException): g.start_set(B) self.assertFalse(g.start_isSet()) self.assertFalse(g.start_is(B)) def test_shouldNotSetStartSymbolWhenCreate(self): with self.assertRaises(NonterminalDoesNotExistsException): g = Grammar(nonterminals=[B], start_symbol=A) def test_oldStartSymbolShouldStaySame(self): g = Grammar(nonterminals=[A], start_symbol=A) self.assertTrue(g.start_isSet()) with self.assertRaises(NonterminalDoesNotExistsException): g.start_set(B) self.assertTrue(g.start_isSet()) self.assertTrue(g.start_is(A)) self.assertEqual(g.start_get(), A) if __name__ == '__main__': main()
9dad4033e4a66208ca00bcb0340f6a2271f1090f
montage_wrapper/mpi.py
montage_wrapper/mpi.py
MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ global MPI_COMMAND MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
Fix setting of custom MPI command
Fix setting of custom MPI command
Python
bsd-3-clause
vterron/montage-wrapper,astrofrog/montage-wrapper,astropy/montage-wrapper,astrofrog/montage-wrapper,jat255/montage-wrapper
MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ + global MPI_COMMAND MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
Fix setting of custom MPI command
## Code Before: MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc) ## Instruction: Fix setting of custom MPI command ## Code After: MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ global MPI_COMMAND MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
a09689c570e70c80ad7cadd9702133b3851c63b9
providers/provider.py
providers/provider.py
import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector): html = self._http_get(url) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data def parse_json(self, url, path=None): data = self._http_get(url) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60 * 60): response = requests.get(url, timeout=10) return get_unicode_from_response(response)
import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector, timeout=60): html = self._http_get(url, timeout=timeout) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data def parse_json(self, url, path=None, timeout=60): data = self._http_get(url, timeout=timeout) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60): response = requests.get(url, timeout=timeout) return get_unicode_from_response(response)
Increase timeout to 60 sec and make available to external callers.
Increase timeout to 60 sec and make available to external callers.
Python
mit
EmilStenstrom/nephele
import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== - def parse_html(self, url, css_selector): + def parse_html(self, url, css_selector, timeout=60): - html = self._http_get(url) + html = self._http_get(url, timeout=timeout) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data - def parse_json(self, url, path=None): + def parse_json(self, url, path=None, timeout=60): - data = self._http_get(url) + data = self._http_get(url, timeout=timeout) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== - def _http_get(self, url, timeout=60 * 60): + def _http_get(self, url, timeout=60): - response = requests.get(url, timeout=10) + response = requests.get(url, timeout=timeout) return get_unicode_from_response(response)
Increase timeout to 60 sec and make available to external callers.
## Code Before: import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector): html = self._http_get(url) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data def parse_json(self, url, path=None): data = self._http_get(url) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60 * 60): response = requests.get(url, timeout=10) return get_unicode_from_response(response) ## Instruction: Increase timeout to 60 sec and make available to external callers. ## Code After: import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector, timeout=60): html = self._http_get(url, timeout=timeout) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data def parse_json(self, url, path=None, timeout=60): data = self._http_get(url, timeout=timeout) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60): response = requests.get(url, timeout=timeout) return get_unicode_from_response(response)
a229e1737542a5011e70c3fa63c360638e96e754
lettuce_webdriver/css_selector_steps.py
lettuce_webdriver/css_selector_steps.py
from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) def wait_for_elem(browser, xpath, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: elems = browser.find_elements_by_css_selector(xpath) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) #elems = wait_for_elem(world.browser, selector, seconds) #assert_true(step, elems) __all__ = ['wait_for_element_by_selector']
import time from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) def wait_for_elem(browser, sel, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: elems = browser.find_elements_by_css_selector(sel) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) elems = wait_for_elem(world.browser, selector, seconds) assert_true(step, elems) __all__ = ['wait_for_element_by_selector']
Make the step actually do something.
Make the step actually do something.
Python
mit
koterpillar/aloe_webdriver,aloetesting/aloe_webdriver,macndesign/lettuce_webdriver,ponsfrilus/lettuce_webdriver,aloetesting/aloe_webdriver,macndesign/lettuce_webdriver,infoxchange/aloe_webdriver,bbangert/lettuce_webdriver,aloetesting/aloe_webdriver,koterpillar/aloe_webdriver,infoxchange/lettuce_webdriver,infoxchange/aloe_webdriver,infoxchange/lettuce_webdriver,ponsfrilus/lettuce_webdriver,bbangert/lettuce_webdriver
+ import time + from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) - def wait_for_elem(browser, xpath, timeout=15): + def wait_for_elem(browser, sel, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: - elems = browser.find_elements_by_css_selector(xpath) + elems = browser.find_elements_by_css_selector(sel) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) - #elems = wait_for_elem(world.browser, selector, seconds) + elems = wait_for_elem(world.browser, selector, seconds) - #assert_true(step, elems) + assert_true(step, elems) __all__ = ['wait_for_element_by_selector']
Make the step actually do something.
## Code Before: from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) def wait_for_elem(browser, xpath, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: elems = browser.find_elements_by_css_selector(xpath) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) #elems = wait_for_elem(world.browser, selector, seconds) #assert_true(step, elems) __all__ = ['wait_for_element_by_selector'] ## Instruction: Make the step actually do something. ## Code After: import time from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) def wait_for_elem(browser, sel, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: elems = browser.find_elements_by_css_selector(sel) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) elems = wait_for_elem(world.browser, selector, seconds) assert_true(step, elems) __all__ = ['wait_for_element_by_selector']
6926ddbb9cdbf05808339412cee5106e581f66cb
tests/import_wordpress_and_build_workflow.py
tests/import_wordpress_and_build_workflow.py
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
Use the more or less new options for importing
Use the more or less new options for importing
Python
mit
damianavila/nikola,xuhdev/nikola,getnikola/nikola,berezovskyi/nikola,TyberiusPrime/nikola,kotnik/nikola,atiro/nikola,servalproject/nikola,gwax/nikola,schettino72/nikola,kotnik/nikola,lucacerone/nikola,okin/nikola,s2hc-johan/nikola,andredias/nikola,masayuko/nikola,x1101/nikola,s2hc-johan/nikola,Proteus-tech/nikola,techdragon/nikola,jjconti/nikola,berezovskyi/nikola,techdragon/nikola,servalproject/nikola,masayuko/nikola,getnikola/nikola,immanetize/nikola,damianavila/nikola,jjconti/nikola,knowsuchagency/nikola,wcmckee/nikola,JohnTroony/nikola,xuhdev/nikola,getnikola/nikola,masayuko/nikola,andredias/nikola,gwax/nikola,knowsuchagency/nikola,damianavila/nikola,berezovskyi/nikola,TyberiusPrime/nikola,wcmckee/nikola,pluser/nikola,okin/nikola,schettino72/nikola,xuhdev/nikola,okin/nikola,x1101/nikola,TyberiusPrime/nikola,JohnTroony/nikola,wcmckee/nikola,atiro/nikola,lucacerone/nikola,yamila-moreno/nikola,Proteus-tech/nikola,x1101/nikola,lucacerone/nikola,kotnik/nikola,jjconti/nikola,JohnTroony/nikola,xuhdev/nikola,atiro/nikola,knowsuchagency/nikola,immanetize/nikola,Proteus-tech/nikola,gwax/nikola,techdragon/nikola,getnikola/nikola,pluser/nikola,s2hc-johan/nikola,immanetize/nikola,schettino72/nikola,servalproject/nikola,Proteus-tech/nikola,yamila-moreno/nikola,okin/nikola,andredias/nikola,pluser/nikola,yamila-moreno/nikola
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( - 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) + 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, + folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
Use the more or less new options for importing
## Code Before: from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main() ## Instruction: Use the more or less new options for importing ## Code After: from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
48394c55599968c456f1f58c0fcdf58e1750f293
amplpy/tests/TestBase.py
amplpy/tests/TestBase.py
from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def str2file(self, filename, content): fullpath = self.tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return fullpath def tmpfile(self, filename): return os.path.join(self.dirpath, filename) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os # For MSYS2, MINGW, etc., run with: # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests REAL_ROOT = os.environ.get('REAL_ROOT', None) class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def _tmpfile(self, filename): return os.path.join(self.dirpath, filename) def _real_filename(self, filename): # Workaround for MSYS2, MINGW paths if REAL_ROOT is not None and filename.startswith('/'): filename = filename.replace('/', REAL_ROOT, 1) return filename def str2file(self, filename, content): fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return self._real_filename(fullpath) def tmpfile(self, filename): return self._real_filename(self._tmpfile(filename)) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
Add workaround for tests on MSYS2 and MINGW
Add workaround for tests on MSYS2 and MINGW
Python
bsd-3-clause
ampl/amplpy,ampl/amplpy,ampl/amplpy
from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os + # For MSYS2, MINGW, etc., run with: + # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests + REAL_ROOT = os.environ.get('REAL_ROOT', None) + + class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() + def _tmpfile(self, filename): + return os.path.join(self.dirpath, filename) + + def _real_filename(self, filename): + # Workaround for MSYS2, MINGW paths + if REAL_ROOT is not None and filename.startswith('/'): + filename = filename.replace('/', REAL_ROOT, 1) + return filename + def str2file(self, filename, content): - fullpath = self.tmpfile(filename) + fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) - return fullpath + return self._real_filename(fullpath) def tmpfile(self, filename): - return os.path.join(self.dirpath, filename) + return self._real_filename(self._tmpfile(filename)) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
Add workaround for tests on MSYS2 and MINGW
## Code Before: from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def str2file(self, filename, content): fullpath = self.tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return fullpath def tmpfile(self, filename): return os.path.join(self.dirpath, filename) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main() ## Instruction: Add workaround for tests on MSYS2 and MINGW ## Code After: from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os # For MSYS2, MINGW, etc., run with: # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests REAL_ROOT = os.environ.get('REAL_ROOT', None) class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def _tmpfile(self, filename): return os.path.join(self.dirpath, filename) def _real_filename(self, filename): # Workaround for MSYS2, MINGW paths if REAL_ROOT is not None and filename.startswith('/'): filename = filename.replace('/', REAL_ROOT, 1) return filename def str2file(self, filename, content): fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return self._real_filename(fullpath) def tmpfile(self, filename): return self._real_filename(self._tmpfile(filename)) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
43afda1fa0ae2d0011d6b87b5c05e3eb1fe13a21
viewer_examples/viewers/collection_viewer.py
viewer_examples/viewers/collection_viewer.py
import numpy as np from skimage import data from skimage.viewer import CollectionViewer img = data.lena() img_collection = [np.uint8(img * 0.9**i) for i in range(20)] view = CollectionViewer(img_collection) view.show()
import numpy as np from skimage import data from skimage.viewer import CollectionViewer from skimage.transform import build_gaussian_pyramid img = data.lena() img_collection = tuple(build_gaussian_pyramid(img)) view = CollectionViewer(img_collection) view.show()
Use gaussian pyramid function for collection viewer example
Use gaussian pyramid function for collection viewer example
Python
bsd-3-clause
rjeli/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,newville/scikit-image,SamHames/scikit-image,bennlich/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,blink1073/scikit-image,GaZ3ll3/scikit-image,keflavich/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,emon10005/scikit-image,youprofit/scikit-image,ofgulban/scikit-image,newville/scikit-image,bsipocz/scikit-image,Midafi/scikit-image,almarklein/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,chintak/scikit-image,SamHames/scikit-image,michaelaye/scikit-image,chintak/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,dpshelio/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,bennlich/scikit-image,almarklein/scikit-image,oew1v07/scikit-image,Britefury/scikit-image,keflavich/scikit-image,chriscrosscutler/scikit-image,blink1073/scikit-image,rjeli/scikit-image,jwiggins/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,warmspringwinds/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,ClinicalGraphics/scikit-image,chriscrosscutler/scikit-image,Hiyorimi/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,bsipocz/scikit-image,ajaybhat/scikit-image,oew1v07/scikit-image,warmspringwinds/scikit-image,ClinicalGraphics/scikit-image,Britefury/scikit-image,robintw/scikit-image,SamHames/scikit-image,paalge/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,emon10005/scikit-image,youprofit/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,dpshelio/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,WarrenWeckesser/scikits-image
import numpy as np from skimage import data from skimage.viewer import CollectionViewer + from skimage.transform import build_gaussian_pyramid + img = data.lena() - img_collection = [np.uint8(img * 0.9**i) for i in range(20)] + img_collection = tuple(build_gaussian_pyramid(img)) view = CollectionViewer(img_collection) view.show()
Use gaussian pyramid function for collection viewer example
## Code Before: import numpy as np from skimage import data from skimage.viewer import CollectionViewer img = data.lena() img_collection = [np.uint8(img * 0.9**i) for i in range(20)] view = CollectionViewer(img_collection) view.show() ## Instruction: Use gaussian pyramid function for collection viewer example ## Code After: import numpy as np from skimage import data from skimage.viewer import CollectionViewer from skimage.transform import build_gaussian_pyramid img = data.lena() img_collection = tuple(build_gaussian_pyramid(img)) view = CollectionViewer(img_collection) view.show()
710c77b2805058364e326d26c9e0c7cfcfed6453
repugeng/Compat3k.py
repugeng/Compat3k.py
from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) return sys.stdin.readline().rstrip("\r\n")
from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) (file or sys.stderr).flush() return sys.stdin.readline().rstrip("\r\n")
Fix yet another 3k issue (stderr not flushing automatically).
Fix yet another 3k issue (stderr not flushing automatically). Signed-off-by: Thomas Hori <7133b3a0da8e60bd3295f2c8559ef184054a68ed@liddicott.com>
Python
mpl-2.0
thomas-hori/Repuge-NG
from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) + (file or sys.stderr).flush() return sys.stdin.readline().rstrip("\r\n")
Fix yet another 3k issue (stderr not flushing automatically).
## Code Before: from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) return sys.stdin.readline().rstrip("\r\n") ## Instruction: Fix yet another 3k issue (stderr not flushing automatically). ## Code After: from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) (file or sys.stderr).flush() return sys.stdin.readline().rstrip("\r\n")
c0ff6cbf293bca3f0757a62e05a14c56dbdf12a4
installscripts/jazz-terraform-unix-noinstances/scripts/health_check.py
installscripts/jazz-terraform-unix-noinstances/scripts/health_check.py
import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): if max_tries == 1: return False else: max_tries -= 1 try: response = client.describe_target_health(TargetGroupArn=str(tg_arn)) if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': time.sleep(30) return True else: time.sleep(30) health_check_tg(client, tg_arn, max_tries) except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50)
import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): if max_tries == 1: return False else: max_tries -= 1 try: response = client.describe_target_health(TargetGroupArn=str(tg_arn)) if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': time.sleep(30) return True else: time.sleep(30) health_check_tg(client, tg_arn, max_tries) except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50)
Fix travis issue for v1.13.1 release
Fix travis issue for v1.13.1 release
Python
apache-2.0
tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer
import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): - if max_tries == 1: + if max_tries == 1: - return False + return False + else: + max_tries -= 1 + try: + response = client.describe_target_health(TargetGroupArn=str(tg_arn)) + if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': + time.sleep(30) + return True else: - max_tries -= 1 - try: - response = client.describe_target_health(TargetGroupArn=str(tg_arn)) - if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': - time.sleep(30) - return True - else: - time.sleep(30) - health_check_tg(client, tg_arn, max_tries) - except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) + except Exception: + time.sleep(30) + health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50)
Fix travis issue for v1.13.1 release
## Code Before: import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): if max_tries == 1: return False else: max_tries -= 1 try: response = client.describe_target_health(TargetGroupArn=str(tg_arn)) if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': time.sleep(30) return True else: time.sleep(30) health_check_tg(client, tg_arn, max_tries) except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50) ## Instruction: Fix travis issue for v1.13.1 release ## Code After: import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): if max_tries == 1: return False else: max_tries -= 1 try: response = client.describe_target_health(TargetGroupArn=str(tg_arn)) if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': time.sleep(30) return True else: time.sleep(30) health_check_tg(client, tg_arn, max_tries) except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50)
cd38101f097edc60312f0c083385968ed40fd54a
src/control.py
src/control.py
import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose current_pose = message.pose[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose, current_twist current_pose = message.pose[2] current_twist = message.twist[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None current_twist = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None or current_twist is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
Store current twist in a global variable
Store current twist in a global variable
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): - global current_pose + global current_pose, current_twist current_pose = message.pose[2] + current_twist = message.twist[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None + current_twist = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) - while current_pose is None: + while current_pose is None or current_twist is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
Store current twist in a global variable
## Code Before: import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose current_pose = message.pose[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin() ## Instruction: Store current twist in a global variable ## Code After: import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose, current_twist current_pose = message.pose[2] current_twist = message.twist[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None current_twist = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None or current_twist is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
7d03a6bfa32d2bf20a95769b2937e098972285af
src/scs_mfr/test/opc_test.py
src/scs_mfr/test/opc_test.py
import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... opc = OPCN2(Host.OPC_SPI_BUS, Host.OPC_SPI_DEVICE) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close()
import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... opc = OPCN2(Host.opc_spi_bus(), Host.opc_spi_device()) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close()
Put SPI slave configurations on Host.
Put SPI slave configurations on Host.
Python
mit
south-coast-science/scs_mfr,south-coast-science/scs_mfr
import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... - opc = OPCN2(Host.OPC_SPI_BUS, Host.OPC_SPI_DEVICE) + opc = OPCN2(Host.opc_spi_bus(), Host.opc_spi_device()) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close()
Put SPI slave configurations on Host.
## Code Before: import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... opc = OPCN2(Host.OPC_SPI_BUS, Host.OPC_SPI_DEVICE) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close() ## Instruction: Put SPI slave configurations on Host. ## Code After: import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... opc = OPCN2(Host.opc_spi_bus(), Host.opc_spi_device()) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close()
6b819174557a1dffbcb397dc1d6e2a3f7e01a12b
milestones/migrations/0002_data__seed_relationship_types.py
milestones/migrations/0002_data__seed_relationship_types.py
from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.using(db_alias).get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.using(db_alias).filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ]
from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ]
Remove uses of using() from migrations
Remove uses of using() from migrations This hardcoded the db_alias fetched from schema_editor and forces django to try and migrate any second database you use, rather than routing to the default database. In testing a build from scratch, these do not appear needed. Using using() prevents us from using multiple databases behind edxapp
Python
agpl-3.0
edx/edx-milestones
from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") - db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): - MilestoneRelationshipType.objects.using(db_alias).get_or_create( + MilestoneRelationshipType.objects.get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") - db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): - MilestoneRelationshipType.objects.using(db_alias).filter(name=name).delete() + MilestoneRelationshipType.objects.filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ]
Remove uses of using() from migrations
## Code Before: from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.using(db_alias).get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.using(db_alias).filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ] ## Instruction: Remove uses of using() from migrations ## Code After: from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ]
6bdb91aefc6acb9b0065c7edae19887778dedb22
.ci/package-version.py
.ci/package-version.py
import os.path import sys def main(): setup_py = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setup.py') with open(setup_py, 'r') as f: for line in f: if line.startswith('VERSION ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 print('could not find package version in setup.py', file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())
import os.path import sys def main(): version_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'uvloop', '__init__.py') with open(version_file, 'r') as f: for line in f: if line.startswith('__version__ ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 print('could not find package version in uvloop/__init__.py', file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())
Fix ci / package_version.py script to support __version__
Fix ci / package_version.py script to support __version__
Python
apache-2.0
1st1/uvloop,MagicStack/uvloop,MagicStack/uvloop
import os.path import sys def main(): - setup_py = os.path.join(os.path.dirname(os.path.dirname(__file__)), - 'setup.py') + version_file = os.path.join( + os.path.dirname(os.path.dirname(__file__)), 'uvloop', '__init__.py') - with open(setup_py, 'r') as f: + with open(version_file, 'r') as f: for line in f: - if line.startswith('VERSION ='): + if line.startswith('__version__ ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 - print('could not find package version in setup.py', file=sys.stderr) + print('could not find package version in uvloop/__init__.py', + file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())
Fix ci / package_version.py script to support __version__
## Code Before: import os.path import sys def main(): setup_py = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setup.py') with open(setup_py, 'r') as f: for line in f: if line.startswith('VERSION ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 print('could not find package version in setup.py', file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main()) ## Instruction: Fix ci / package_version.py script to support __version__ ## Code After: import os.path import sys def main(): version_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'uvloop', '__init__.py') with open(version_file, 'r') as f: for line in f: if line.startswith('__version__ ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 print('could not find package version in uvloop/__init__.py', file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())
261cb5aecc52d07b10d826e8b22d17817d1c3529
web/backend/backend_django/apps/capacity/management/commands/importpath.py
web/backend/backend_django/apps/capacity/management/commands/importpath.py
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) for k, path in trips.items(): trip_id = k[0] stop_id = k[1] try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) self.stdout.write("Done")
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) i = i+1 self.stdout.write("Done")
Update import path method to reflect behaviour
Update import path method to reflect behaviour
Python
apache-2.0
tOverney/ADA-Project,tOverney/ADA-Project,tOverney/ADA-Project
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) - + i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] + + if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) + i = i+1 + self.stdout.write("Done")
Update import path method to reflect behaviour
## Code Before: from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) for k, path in trips.items(): trip_id = k[0] stop_id = k[1] try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) self.stdout.write("Done") ## Instruction: Update import path method to reflect behaviour ## Code After: from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) i = i+1 self.stdout.write("Done")
e4079d7cdeb59a3cac129813b7bb14a6639ea9db
plugins/Webcam_plugin.py
plugins/Webcam_plugin.py
info = { 'id': 'webcam', 'name': 'Webcam', 'description': 'Generic webcam driver', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', }
info = { 'id': 'webcam', 'name': 'OpenCV', 'description': 'Video camera interfacing through OpenCV', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', }
Rename 'webcam' plugin to OpenCV
Rename 'webcam' plugin to OpenCV
Python
mit
ptomato/Beams
info = { 'id': 'webcam', - 'name': 'Webcam', + 'name': 'OpenCV', - 'description': 'Generic webcam driver', + 'description': 'Video camera interfacing through OpenCV', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', }
Rename 'webcam' plugin to OpenCV
## Code Before: info = { 'id': 'webcam', 'name': 'Webcam', 'description': 'Generic webcam driver', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', } ## Instruction: Rename 'webcam' plugin to OpenCV ## Code After: info = { 'id': 'webcam', 'name': 'OpenCV', 'description': 'Video camera interfacing through OpenCV', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', }
df6642256806e0a501e83c06e64b35f187efaf60
rally/benchmark/scenarios/authenticate/authenticate.py
rally/benchmark/scenarios/authenticate/authenticate.py
from rally.benchmark.scenarios import base from rally import osclients class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): keystone_endpoint = self.clients("endpoint") cl = osclients.Clients(keystone_endpoint) cl.get_keystone_client()
from rally.benchmark.scenarios import base class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): self.clients("keystone")
Fix for Authentication scenario to correctly use self.clients
Fix for Authentication scenario to correctly use self.clients Scenario has recently been refactored, self.clients in Scenario now takes the name of the CLI client. During the refactoring, the Authenticate scenario was not correctly updated, which causes the authentication scenario to fail. This patch fixes that. Change-Id: I546c0846e00a5285f0d47bc80b6304a53cc566ff Closes-Bug: #1291386
Python
apache-2.0
pandeyop/rally,go-bears/rally,vefimova/rally,aplanas/rally,group-policy/rally,amit0701/rally,shdowofdeath/rally,ytsarev/rally,go-bears/rally,vefimova/rally,group-policy/rally,shdowofdeath/rally,openstack/rally,gluke77/rally,ytsarev/rally,redhat-openstack/rally,varunarya10/rally,amit0701/rally,gluke77/rally,vganapath/rally,gluke77/rally,aforalee/RRally,amit0701/rally,gluke77/rally,afaheem88/rally,eayunstack/rally,vponomaryov/rally,cernops/rally,vganapath/rally,aforalee/RRally,openstack/rally,aplanas/rally,vponomaryov/rally,paboldin/rally,redhat-openstack/rally,cernops/rally,vganapath/rally,eonpatapon/rally,paboldin/rally,yeming233/rally,pyKun/rally,eayunstack/rally,openstack/rally,eonpatapon/rally,vganapath/rally,paboldin/rally,eayunstack/rally,group-policy/rally,yeming233/rally,varunarya10/rally,openstack/rally,pyKun/rally,pandeyop/rally,afaheem88/rally
from rally.benchmark.scenarios import base - from rally import osclients class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): + self.clients("keystone") - keystone_endpoint = self.clients("endpoint") - cl = osclients.Clients(keystone_endpoint) - cl.get_keystone_client()
Fix for Authentication scenario to correctly use self.clients
## Code Before: from rally.benchmark.scenarios import base from rally import osclients class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): keystone_endpoint = self.clients("endpoint") cl = osclients.Clients(keystone_endpoint) cl.get_keystone_client() ## Instruction: Fix for Authentication scenario to correctly use self.clients ## Code After: from rally.benchmark.scenarios import base class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): self.clients("keystone")
022f2cc6d067769a6c8e56601c0238aac69ec9ab
jfr_playoff/settings.py
jfr_playoff/settings.py
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.settings = None self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') if self.settings is None: self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
Load config file only once
Load config file only once
Python
bsd-2-clause
emkael/jfrteamy-playoff,emkael/jfrteamy-playoff
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): + self.settings = None self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') + if self.settings is None: - self.settings = json.load(open(self.settings_file)) + self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
Load config file only once
## Code Before: import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section ## Instruction: Load config file only once ## Code After: import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.settings = None self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') if self.settings is None: self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
19faa280c924254b960a8b9fcb716017e51db09f
pymks/tests/test_mksRegressionModel.py
pymks/tests/test_mksRegressionModel.py
from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) model.coeff = np.fft.ifft(model.Fcoeff, axis=0) assert np.allclose(coeff, model.coeff) if __name__ == '__main__': test()
from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff) if __name__ == '__main__': test()
Fix test due to addition of coeff property
Fix test due to addition of coeff property Address #49 Add fftshift to test coefficients as model.coeff now returns the shifted real versions.
Python
mit
davidbrough1/pymks,XinyiGong/pymks,awhite40/pymks,davidbrough1/pymks,fredhohman/pymks
from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) - model.coeff = np.fft.ifft(model.Fcoeff, axis=0) - assert np.allclose(coeff, model.coeff) + assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff) if __name__ == '__main__': test()
Fix test due to addition of coeff property
## Code Before: from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) model.coeff = np.fft.ifft(model.Fcoeff, axis=0) assert np.allclose(coeff, model.coeff) if __name__ == '__main__': test() ## Instruction: Fix test due to addition of coeff property ## Code After: from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff) if __name__ == '__main__': test()
0336651c6538d756eb40babe086975a0f7fcabd6
qual/tests/test_historical_calendar.py
qual/tests/test_historical_calendar.py
from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar gregorian_triplets = [(1752, 9, 13)] julian_triplets = [(1752, 9, 1)] transition_triplets = [(1752, 9, 6)]
from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar gregorian_triplets = [(1752, 9, 14)] julian_triplets = [(1752, 9, 1), (1752, 9, 2)] transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
Correct test for the right missing days and present days.
Correct test for the right missing days and present days. 1st and 2nd of September 1752 happened, so did 14th. 3rd to 13th did not.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar - gregorian_triplets = [(1752, 9, 13)] + gregorian_triplets = [(1752, 9, 14)] - julian_triplets = [(1752, 9, 1)] + julian_triplets = [(1752, 9, 1), (1752, 9, 2)] - transition_triplets = [(1752, 9, 6)] + transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
Correct test for the right missing days and present days.
## Code Before: from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar gregorian_triplets = [(1752, 9, 13)] julian_triplets = [(1752, 9, 1)] transition_triplets = [(1752, 9, 6)] ## Instruction: Correct test for the right missing days and present days. ## Code After: from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar gregorian_triplets = [(1752, 9, 14)] julian_triplets = [(1752, 9, 1), (1752, 9, 2)] transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
1c32b17bd4c85165f91fbb188b22471a296c6176
kajiki/i18n.py
kajiki/i18n.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand doc = _Parser(filename='<string>', source=fileobj.read()).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand source = fileobj.read() if isinstance(source, bytes): source = source.decode('utf-8') doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
Fix issue with message extractor on Py2
Fix issue with message extractor on Py2
Python
mit
ollyc/kajiki,ollyc/kajiki,ollyc/kajiki
from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand + source = fileobj.read() + if isinstance(source, bytes): + source = source.decode('utf-8') - doc = _Parser(filename='<string>', source=fileobj.read()).parse() + doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
Fix issue with message extractor on Py2
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand doc = _Parser(filename='<string>', source=fileobj.read()).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, []) ## Instruction: Fix issue with message extractor on Py2 ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand source = fileobj.read() if isinstance(source, bytes): source = source.decode('utf-8') doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
c1785e0713a5af6b849baaa1b314a13ac777f3f5
tests/test_str_py3.py
tests/test_str_py3.py
from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits import fastavro from fastavro.compat import BytesIO letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
"""Python3 string tests for fastavro""" from __future__ import absolute_import from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import fastavro letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually.
Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually.
Python
mit
e-heller/fastavro,e-heller/fastavro
+ """Python3 string tests for fastavro""" + + from __future__ import absolute_import + from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits + try: + from cStringIO import StringIO as BytesIO + except ImportError: + from io import BytesIO + import fastavro - from fastavro.compat import BytesIO + letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' + if __name__ == '__main__': test_str_py3()
Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually.
## Code Before: from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits import fastavro from fastavro.compat import BytesIO letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3() ## Instruction: Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually. ## Code After: """Python3 string tests for fastavro""" from __future__ import absolute_import from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import fastavro letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
df1397dcf6fe849b87db139e8ea3087a5f73649a
tests/graphics/toolbuttons.py
tests/graphics/toolbuttons.py
from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() radial_button = RadioToolButton(named_icon='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() list_button = RadioToolButton(named_icon='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test)
from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() radial_button = RadioToolButton(icon_name='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() list_button = RadioToolButton(icon_name='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test)
Update toolbar buttons testcase with API change for the icon name
Update toolbar buttons testcase with API change for the icon name Follow up of fe11a3aa23c0e7fbc3c0c498e147b0a20348cc12 . Signed-off-by: Manuel Quiñones <6f5069c5b6be23302a13accec56587944be09079@laptop.org>
Python
lgpl-2.1
i5o/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,sugarlabs/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,samdroid-apps/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,samdroid-apps/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3
from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() - radial_button = RadioToolButton(named_icon='view-radial') + radial_button = RadioToolButton(icon_name='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() - list_button = RadioToolButton(named_icon='view-list') + list_button = RadioToolButton(icon_name='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test)
Update toolbar buttons testcase with API change for the icon name
## Code Before: from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() radial_button = RadioToolButton(named_icon='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() list_button = RadioToolButton(named_icon='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test) ## Instruction: Update toolbar buttons testcase with API change for the icon name ## Code After: from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() radial_button = RadioToolButton(icon_name='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() list_button = RadioToolButton(icon_name='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test)
e5fa10e27d9c5911b0238d23fc13acc081accc79
utils/dates.py
utils/dates.py
from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(datetime): return datetime.strftime(datetime, DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(date): return date.strftime(DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
Fix error on date save
Fix error on date save
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") - def datetime_to_string(datetime): + def datetime_to_string(date): - return datetime.strftime(datetime, DT_FORMAT) + return date.strftime(DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
Fix error on date save
## Code Before: from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(datetime): return datetime.strftime(datetime, DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1)) ## Instruction: Fix error on date save ## Code After: from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(date): return date.strftime(DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
ca430300c08f78b7c2de4153e08c1645996f85b7
tests/test_parsers.py
tests/test_parsers.py
import unittest from brew.parsers import JSONDataLoader class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
import unittest from brew.parsers import DataLoader from brew.parsers import JSONDataLoader class TestDataLoader(unittest.TestCase): def setUp(self): self.parser = DataLoader('./') def test_read_data_raises(self): with self.assertRaises(NotImplementedError): self.parser.read_data('filename') class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
Add test to DataLoader base class
Add test to DataLoader base class
Python
mit
chrisgilmerproj/brewday,chrisgilmerproj/brewday
import unittest + from brew.parsers import DataLoader from brew.parsers import JSONDataLoader + + + class TestDataLoader(unittest.TestCase): + + def setUp(self): + self.parser = DataLoader('./') + + def test_read_data_raises(self): + with self.assertRaises(NotImplementedError): + self.parser.read_data('filename') class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
Add test to DataLoader base class
## Code Before: import unittest from brew.parsers import JSONDataLoader class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected) ## Instruction: Add test to DataLoader base class ## Code After: import unittest from brew.parsers import DataLoader from brew.parsers import JSONDataLoader class TestDataLoader(unittest.TestCase): def setUp(self): self.parser = DataLoader('./') def test_read_data_raises(self): with self.assertRaises(NotImplementedError): self.parser.read_data('filename') class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
17d2d4eaf58011ceb33a4d5944253578c2b5edd1
pmdarima/preprocessing/endog/tests/test_log.py
pmdarima/preprocessing/endog/tests/test_log.py
import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer() log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t)
import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer(lmbda=0) log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t) def test_invertible(): y = [1, 2, 3] trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) y_prime, _ = trans.inverse_transform(y_t) assert_array_almost_equal(y, y_prime)
Add test_invertible to log transformer test
Add test_invertible to log transformer test
Python
mit
alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima,tgsmith61591/pyramid
import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer + def test_same(): y = [1, 2, 3] - trans = BoxCoxEndogTransformer() + trans = BoxCoxEndogTransformer(lmbda=0) log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t) + + def test_invertible(): + y = [1, 2, 3] + trans = LogEndogTransformer() + y_t, _ = trans.fit_transform(y) + y_prime, _ = trans.inverse_transform(y_t) + assert_array_almost_equal(y, y_prime) +
Add test_invertible to log transformer test
## Code Before: import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer() log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t) ## Instruction: Add test_invertible to log transformer test ## Code After: import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer(lmbda=0) log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t) def test_invertible(): y = [1, 2, 3] trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) y_prime, _ = trans.inverse_transform(y_t) assert_array_almost_equal(y, y_prime)
61bbd4e8fc0712fe56614481173eb86d409eb8d7
tests/test_linked_list.py
tests/test_linked_list.py
from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in xrange(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
Fix range issue with travis
Fix range issue with travis
Python
mit
apranav19/pystructures
+ from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() - results = [l.insert(val) for val in xrange(10, 100, 10)] + results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
Fix range issue with travis
## Code Before: from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in xrange(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...") ## Instruction: Fix range issue with travis ## Code After: from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
01c0dd4d34e61df589b3dd9ee3c5f8b96cf5486b
tests/test_transformer.py
tests/test_transformer.py
from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] class TestTransformer(object): def setup_method(self, method): self.harvester = TestHarvester("TEST", TEST_SCHEMA, TEST_NAMESPACES) def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial
from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] @property def name(self): return 'TEST' @property def namespaces(self): return TEST_NAMESPACES @property def schema(self): return TEST_SCHEMA class TestTransformer(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial
Update tests with required properties
Update tests with required properties
Python
apache-2.0
CenterForOpenScience/scrapi,jeffreyliu3230/scrapi,fabianvf/scrapi,felliott/scrapi,erinspace/scrapi,icereval/scrapi,mehanig/scrapi,ostwald/scrapi,erinspace/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi
from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] + @property + def name(self): + return 'TEST' + + @property + def namespaces(self): + return TEST_NAMESPACES + + @property + def schema(self): + return TEST_SCHEMA + + class TestTransformer(object): def setup_method(self, method): - self.harvester = TestHarvester("TEST", TEST_SCHEMA, TEST_NAMESPACES) + self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial
Update tests with required properties
## Code Before: from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] class TestTransformer(object): def setup_method(self, method): self.harvester = TestHarvester("TEST", TEST_SCHEMA, TEST_NAMESPACES) def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial ## Instruction: Update tests with required properties ## Code After: from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] @property def name(self): return 'TEST' @property def namespaces(self): return TEST_NAMESPACES @property def schema(self): return TEST_SCHEMA class TestTransformer(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial
46d274401080d47f3a9974c6ee80f2f3b9c0c8b0
metakernel/magics/tests/test_download_magic.py
metakernel/magics/tests/test_download_magic.py
from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" def teardown(): try: os.remove("TEST.txt") except: pass
from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" clear_log_text(kernel) kernel.do_execute("%download https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'LICENSE.txt'" in text, text assert os.path.isfile("LICENSE.txt"), "File does not exist: LICENSE.txt" def teardown(): for fname in ['TEST.txt', 'LICENSE.txt']: try: os.remove(fname) except: pass
Add download test without filename
Add download test without filename
Python
bsd-3-clause
Calysto/metakernel
from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" + clear_log_text(kernel) + + kernel.do_execute("%download https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") + text = get_log_text(kernel) + assert "Downloaded 'LICENSE.txt'" in text, text + assert os.path.isfile("LICENSE.txt"), "File does not exist: LICENSE.txt" + + def teardown(): + for fname in ['TEST.txt', 'LICENSE.txt']: - try: + try: - os.remove("TEST.txt") + os.remove(fname) - except: + except: - pass + pass
Add download test without filename
## Code Before: from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" def teardown(): try: os.remove("TEST.txt") except: pass ## Instruction: Add download test without filename ## Code After: from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" clear_log_text(kernel) kernel.do_execute("%download https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'LICENSE.txt'" in text, text assert os.path.isfile("LICENSE.txt"), "File does not exist: LICENSE.txt" def teardown(): for fname in ['TEST.txt', 'LICENSE.txt']: try: os.remove(fname) except: pass
975a5010e97b11b9b6f00923c87268dd883b1cfa
2017-code/opt/test1.py
2017-code/opt/test1.py
import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints noise_level = 0.0000005 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] print(scipy.optimize.minimize(g, (11, 5), constraints=constraints))
import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints noise_level = 0.05 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] print(scipy.optimize.minimize(g, (11, 5), method = "COBYLA", tol = 0.01, constraints=constraints))
Switch to COBYLA optimization method. Works much better.
Switch to COBYLA optimization method. Works much better.
Python
mit
ron-rivest/2017-bayes-audit,ron-rivest/2017-bayes-audit
import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints - noise_level = 0.0000005 + noise_level = 0.05 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] - print(scipy.optimize.minimize(g, (11, 5), constraints=constraints)) + print(scipy.optimize.minimize(g, + (11, 5), + method = "COBYLA", + tol = 0.01, + constraints=constraints))
Switch to COBYLA optimization method. Works much better.
## Code Before: import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints noise_level = 0.0000005 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] print(scipy.optimize.minimize(g, (11, 5), constraints=constraints)) ## Instruction: Switch to COBYLA optimization method. Works much better. ## Code After: import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints noise_level = 0.05 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] print(scipy.optimize.minimize(g, (11, 5), method = "COBYLA", tol = 0.01, constraints=constraints))
6941d9048a8c630244bb48100864872b35a1a307
tests/functional/test_layout_and_styling.py
tests/functional/test_layout_and_styling.py
import os from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) self.assertIn( "//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", self.browser.page_source.strip()) self.assertIn( "//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js", self.browser.page_source.strip()) self.assertIn( '//code.jquery.com/jquery.min.js', self.browser.page_source.strip())
from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) links = [link.get_attribute("href") for link in self.browser.find_elements_by_tag_name('link')] scripts = [script.get_attribute("src") for script in self.browser.find_elements_by_tag_name('script')] self.assertTrue( ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" in link for link in links]) self.assertTrue( ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" in link for link in links]) self.assertTrue( ["//code.jquery.com/jquery.min.js" in link for link in scripts])
Fix bootstrap and jQuery link checking in homepage
Fix bootstrap and jQuery link checking in homepage
Python
bsd-3-clause
andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop
- import os - from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) - self.assertIn( - "//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", - self.browser.page_source.strip()) + links = [link.get_attribute("href") + for link in self.browser.find_elements_by_tag_name('link')] + scripts = [script.get_attribute("src") + for script in self.browser.find_elements_by_tag_name('script')] - self.assertIn( + self.assertTrue( - "//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js", + ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" - self.browser.page_source.strip()) + in link for link in links]) - self.assertIn( + self.assertTrue( - '//code.jquery.com/jquery.min.js', - self.browser.page_source.strip()) + ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" + in link for link in links]) + self.assertTrue( + ["//code.jquery.com/jquery.min.js" + in link for link in scripts]) +
Fix bootstrap and jQuery link checking in homepage
## Code Before: import os from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) self.assertIn( "//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", self.browser.page_source.strip()) self.assertIn( "//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js", self.browser.page_source.strip()) self.assertIn( '//code.jquery.com/jquery.min.js', self.browser.page_source.strip()) ## Instruction: Fix bootstrap and jQuery link checking in homepage ## Code After: from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) links = [link.get_attribute("href") for link in self.browser.find_elements_by_tag_name('link')] scripts = [script.get_attribute("src") for script in self.browser.find_elements_by_tag_name('script')] self.assertTrue( ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" in link for link in links]) self.assertTrue( ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" in link for link in links]) self.assertTrue( ["//code.jquery.com/jquery.min.js" in link for link in scripts])
6d624d693a05749879f4184231e727590542db03
backend/globaleaks/tests/utils/test_zipstream.py
backend/globaleaks/tests/utils/test_zipstream.py
import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) self.files = [] for k in self.internationalized_text: self.files.append({'name': self.internationalized_text[k].encode('utf8'), 'buf': self.internationalized_text[k].encode('utf-8')}) def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip())
import os import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) self.unicode_seq = ''.join(unichr(x) for x in range(0x400, 0x40A)) self.files = [ {'name': self.unicode_seq, 'buf': self.unicode_seq}, {'name': __file__, 'path': os.path.abspath(__file__)} ] def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip()) with ZipFile(output, 'r') as f: infolist = f.infolist() self.assertTrue(len(infolist), 2) for ff in infolist: if ff.filename == self.unicode_seq: self.assertTrue(ff.file_size == len(self.unicode_seq)) else: self.assertTrue(ff.file_size == os.stat(os.path.abspath(__file__)).st_size)
Improve unit testing of zipstream utilities
Improve unit testing of zipstream utilities
Python
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
+ + import os import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream - class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) + self.unicode_seq = ''.join(unichr(x) for x in range(0x400, 0x40A)) + - self.files = [] + self.files = [ - for k in self.internationalized_text: - self.files.append({'name': self.internationalized_text[k].encode('utf8'), - 'buf': self.internationalized_text[k].encode('utf-8')}) + {'name': self.unicode_seq, 'buf': self.unicode_seq}, + {'name': __file__, 'path': os.path.abspath(__file__)} + ] def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip()) + with ZipFile(output, 'r') as f: + infolist = f.infolist() + self.assertTrue(len(infolist), 2) + for ff in infolist: + if ff.filename == self.unicode_seq: + self.assertTrue(ff.file_size == len(self.unicode_seq)) + else: + self.assertTrue(ff.file_size == os.stat(os.path.abspath(__file__)).st_size) +
Improve unit testing of zipstream utilities
## Code Before: import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) self.files = [] for k in self.internationalized_text: self.files.append({'name': self.internationalized_text[k].encode('utf8'), 'buf': self.internationalized_text[k].encode('utf-8')}) def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip()) ## Instruction: Improve unit testing of zipstream utilities ## Code After: import os import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) self.unicode_seq = ''.join(unichr(x) for x in range(0x400, 0x40A)) self.files = [ {'name': self.unicode_seq, 'buf': self.unicode_seq}, {'name': __file__, 'path': os.path.abspath(__file__)} ] def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip()) with ZipFile(output, 'r') as f: infolist = f.infolist() self.assertTrue(len(infolist), 2) for ff in infolist: if ff.filename == self.unicode_seq: self.assertTrue(ff.file_size == len(self.unicode_seq)) else: self.assertTrue(ff.file_size == os.stat(os.path.abspath(__file__)).st_size)
92138f23dfc5dbbcb81aeb1f429e68a63a9d5005
apps/organizations/admin.py
apps/organizations/admin.py
from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') admin.site.register(Organization, OrganizationAdmin) admin.site.register(OrganizationMember)
from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') admin.site.register(Organization, OrganizationAdmin) class OrganizationMemberAdmin(admin.ModelAdmin): list_display = ('user', 'function', 'organization') list_filter = ('function',) search_fields = ('user__first_name', 'user__last_name', 'user__username', 'organization__name') admin.site.register(OrganizationMember, OrganizationMemberAdmin)
Add a custom Admin page for organization members.
Add a custom Admin page for organization members. This is a partial fix for BB-66.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') - admin.site.register(Organization, OrganizationAdmin) - admin.site.register(OrganizationMember) + class OrganizationMemberAdmin(admin.ModelAdmin): + list_display = ('user', 'function', 'organization') + list_filter = ('function',) + search_fields = ('user__first_name', 'user__last_name', + 'user__username', 'organization__name') + + admin.site.register(OrganizationMember, OrganizationMemberAdmin)
Add a custom Admin page for organization members.
## Code Before: from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') admin.site.register(Organization, OrganizationAdmin) admin.site.register(OrganizationMember) ## Instruction: Add a custom Admin page for organization members. ## Code After: from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') admin.site.register(Organization, OrganizationAdmin) class OrganizationMemberAdmin(admin.ModelAdmin): list_display = ('user', 'function', 'organization') list_filter = ('function',) search_fields = ('user__first_name', 'user__last_name', 'user__username', 'organization__name') admin.site.register(OrganizationMember, OrganizationMemberAdmin)
539608a9ca9a21707184496e744fc40a8cb72cc1
announce/management/commands/migrate_mailchimp_users.py
announce/management/commands/migrate_mailchimp_users.py
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub) # update profile.communication_opt_in = True for users subscribed to the mailchimp newsletter unsubscribed_users = User.objects.filter(profile__communication_opt_in=False, is_active=True, profile__email_confirmed_at__isnull=False) to_update = list(filter(lambda u: u.email.lower() in emails, unsubscribed_users)) for user in to_update: user.profile.communication_opt_in = True user.profile.save()
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub)
Remove once of code for mailchimp list migration
Remove once of code for mailchimp list migration
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub) - # update profile.communication_opt_in = True for users subscribed to the mailchimp newsletter - unsubscribed_users = User.objects.filter(profile__communication_opt_in=False, is_active=True, profile__email_confirmed_at__isnull=False) - to_update = list(filter(lambda u: u.email.lower() in emails, unsubscribed_users)) - for user in to_update: - user.profile.communication_opt_in = True - user.profile.save() - - - -
Remove once of code for mailchimp list migration
## Code Before: from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub) # update profile.communication_opt_in = True for users subscribed to the mailchimp newsletter unsubscribed_users = User.objects.filter(profile__communication_opt_in=False, is_active=True, profile__email_confirmed_at__isnull=False) to_update = list(filter(lambda u: u.email.lower() in emails, unsubscribed_users)) for user in to_update: user.profile.communication_opt_in = True user.profile.save() ## Instruction: Remove once of code for mailchimp list migration ## Code After: from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub)
3d7bbd37485dca4782ad7e7fdb088b22db586b66
pyscores/config.py
pyscores/config.py
BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { "PL": "426", "ELC": "427", "EL1": "428", "FAC": "429", "BL1": "430", "BL2": "431", "DFB": "432", "DED": "433", "FL1": "434", "FL2": "435", "PD": "436", "SD": "437", "SA": "438", "PPL": "439", "CL": "440", "SB": "441", "ENL": "442", "EL2": "443" }
BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { "BSA": "444", "PL": "445", "ELC": "446", "EL1": "447", "EL2": "448", "DED": "449", "FL1": "450", "FL2": "451", "BL1": "452", "BL2": "453", "PD": "455", "SA": "456", "PPL": "457", "DFB": "458", "SB": "459", "CL": "464", "AAL": "466" }
Update league codes for new season
Update league codes for new season
Python
mit
conormag94/pyscores
BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { + "BSA": "444", - "PL": "426", + "PL": "445", - "ELC": "427", + "ELC": "446", - "EL1": "428", + "EL1": "447", - "FAC": "429", - "BL1": "430", - "BL2": "431", + "EL2": "448", - "DFB": "432", - "DED": "433", + "DED": "449", - "FL1": "434", + "FL1": "450", - "FL2": "435", + "FL2": "451", + "BL1": "452", + "BL2": "453", - "PD": "436", + "PD": "455", - "SD": "437", - "SA": "438", + "SA": "456", - "PPL": "439", + "PPL": "457", + "DFB": "458", + "SB": "459", - "CL": "440", + "CL": "464", - "SB": "441", - "ENL": "442", - "EL2": "443" + "AAL": "466" }
Update league codes for new season
## Code Before: BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { "PL": "426", "ELC": "427", "EL1": "428", "FAC": "429", "BL1": "430", "BL2": "431", "DFB": "432", "DED": "433", "FL1": "434", "FL2": "435", "PD": "436", "SD": "437", "SA": "438", "PPL": "439", "CL": "440", "SB": "441", "ENL": "442", "EL2": "443" } ## Instruction: Update league codes for new season ## Code After: BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { "BSA": "444", "PL": "445", "ELC": "446", "EL1": "447", "EL2": "448", "DED": "449", "FL1": "450", "FL2": "451", "BL1": "452", "BL2": "453", "PD": "455", "SA": "456", "PPL": "457", "DFB": "458", "SB": "459", "CL": "464", "AAL": "466" }
a476c42216af99488c2e02bacd29f7e3a869a3e7
tests/retrieval_metrics/test_precision_at_k.py
tests/retrieval_metrics/test_precision_at_k.py
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected)
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected, atol=1e-05)
Update atol on precision at k test.
Update atol on precision at k test.
Python
apache-2.0
tensorflow/similarity
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) - np.testing.assert_allclose(precision, expected) + np.testing.assert_allclose(precision, expected, atol=1e-05)
Update atol on precision at k test.
## Code Before: import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected) ## Instruction: Update atol on precision at k test. ## Code After: import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected, atol=1e-05)
d0367aacfea7c238c476772a2c83f7826b1e9de5
corehq/apps/export/tasks.py
corehq/apps/export/tasks.py
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) def rebuild_export_task(export_instance): rebuild_export(export_instance)
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True) def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): rebuild_export(export_instance, last_access_cutoff, filter)
Fix botched keyword args in rebuild_export_task()
Fix botched keyword args in rebuild_export_task()
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() - @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) - def rebuild_export_task(export_instance): - rebuild_export(export_instance) + @task(queue='background_queue', ignore_result=True) + def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): + rebuild_export(export_instance, last_access_cutoff, filter)
Fix botched keyword args in rebuild_export_task()
## Code Before: from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) def rebuild_export_task(export_instance): rebuild_export(export_instance) ## Instruction: Fix botched keyword args in rebuild_export_task() ## Code After: from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True) def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): rebuild_export(export_instance, last_access_cutoff, filter)
86a325777742e1fa79bc632fca9460f3b1b8eb16
to_do/urls.py
to_do/urls.py
from django.conf.urls import patterns, include, url from task.views import TaskList, TaskView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """
from django.conf.urls import patterns, include, url from task.views import TaskList, TaskView, get_task_list # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), url(r'^tasks/', get_task_list, name='get_task_list'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """
Enable url to get all list of tasks by ajax
Enable url to get all list of tasks by ajax
Python
mit
rosadurante/to_do,rosadurante/to_do
from django.conf.urls import patterns, include, url - from task.views import TaskList, TaskView + from task.views import TaskList, TaskView, get_task_list # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), + url(r'^tasks/', get_task_list, name='get_task_list'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """
Enable url to get all list of tasks by ajax
## Code Before: from django.conf.urls import patterns, include, url from task.views import TaskList, TaskView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """ ## Instruction: Enable url to get all list of tasks by ajax ## Code After: from django.conf.urls import patterns, include, url from task.views import TaskList, TaskView, get_task_list # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), url(r'^tasks/', get_task_list, name='get_task_list'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """
49975504a590a1ae53e2e8cc81aadea277cc5600
cvrminer/app/__init__.py
cvrminer/app/__init__.py
"""cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app
"""cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap, StaticCDN def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) # Serve assets from wmflabs for privacy reasons app.extensions['bootstrap']['cdns']['jquery'] = StaticCDN() app.extensions['bootstrap']['cdns']['bootstrap'] = StaticCDN() if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app
Change to use local Javascript and CSS files
Change to use local Javascript and CSS files
Python
apache-2.0
fnielsen/cvrminer,fnielsen/cvrminer,fnielsen/cvrminer
"""cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask - from flask_bootstrap import Bootstrap + from flask_bootstrap import Bootstrap, StaticCDN def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) + # Serve assets from wmflabs for privacy reasons + app.extensions['bootstrap']['cdns']['jquery'] = StaticCDN() + app.extensions['bootstrap']['cdns']['bootstrap'] = StaticCDN() + if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app
Change to use local Javascript and CSS files
## Code Before: """cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app ## Instruction: Change to use local Javascript and CSS files ## Code After: """cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap, StaticCDN def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) # Serve assets from wmflabs for privacy reasons app.extensions['bootstrap']['cdns']['jquery'] = StaticCDN() app.extensions['bootstrap']['cdns']['bootstrap'] = StaticCDN() if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app
f7bfcd7fee64ae9220710835974125f41dae1c50
frappe/core/doctype/role/test_role.py
frappe/core/doctype/role/test_role.py
from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
Test Case for disabled role
fix: Test Case for disabled role
Python
mit
mhbu50/frappe,mhbu50/frappe,saurabh6790/frappe,frappe/frappe,saurabh6790/frappe,vjFaLk/frappe,StrellaGroup/frappe,vjFaLk/frappe,yashodhank/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,adityahase/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,yashodhank/frappe,frappe/frappe,vjFaLk/frappe,vjFaLk/frappe,yashodhank/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,yashodhank/frappe,mhbu50/frappe,almeidapaulopt/frappe,frappe/frappe,saurabh6790/frappe,saurabh6790/frappe
from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") - + role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() - + self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) + - - frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") - self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) - role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() - + frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com")) - +
Test Case for disabled role
## Code Before: from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com")) ## Instruction: Test Case for disabled role ## Code After: from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
82121f05032f83de538c4a16596b24b5b012a3be
chaco/shell/tests/test_tutorial_example.py
chaco/shell/tests/test_tutorial_example.py
import unittest from numpy import linspace, pi, sin from enthought.chaco.shell import plot, show, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main()
import unittest from numpy import linspace, pi, sin from chaco.shell import plot, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main()
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
Python
bsd-3-clause
tommy-u/chaco,burnpanck/chaco,burnpanck/chaco,tommy-u/chaco,tommy-u/chaco,burnpanck/chaco
import unittest from numpy import linspace, pi, sin - from enthought.chaco.shell import plot, show, title, ytitle + from chaco.shell import plot, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main()
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
## Code Before: import unittest from numpy import linspace, pi, sin from enthought.chaco.shell import plot, show, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main() ## Instruction: Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later. ## Code After: import unittest from numpy import linspace, pi, sin from chaco.shell import plot, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main()
e029998f73a77ebd8f4a6e32a8b03edcc93ec0d7
dataproperty/__init__.py
dataproperty/__init__.py
from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len, strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
Delete import that no longer used
Delete import that no longer used
Python
mit
thombashi/DataProperty
from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, - get_text_len, + get_text_len - strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
Delete import that no longer used
## Code Before: from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len, strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode ## Instruction: Delete import that no longer used ## Code After: from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
69abcf66d36079e100815f629487d121ae016ee9
future/tests/test_standard_library_renames.py
future/tests/test_standard_library_renames.py
from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue heap = ['thing', 'another thing'] queue.heapq.heapify(heap) self.assertEqual(heap, ['another thing', 'thing']) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main()
from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue q = queue.Queue() q.put('thing') self.assertFalse(q.empty()) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main()
Fix test for queue module
Fix test for queue module I was testing heapq before ;) ...
Python
mit
QuLogic/python-future,QuLogic/python-future,krischer/python-future,michaelpacer/python-future,michaelpacer/python-future,krischer/python-future,PythonCharmers/python-future,PythonCharmers/python-future
from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue - heap = ['thing', 'another thing'] - queue.heapq.heapify(heap) - self.assertEqual(heap, ['another thing', 'thing']) + q = queue.Queue() + q.put('thing') + self.assertFalse(q.empty()) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main()
Fix test for queue module
## Code Before: from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue heap = ['thing', 'another thing'] queue.heapq.heapify(heap) self.assertEqual(heap, ['another thing', 'thing']) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main() ## Instruction: Fix test for queue module ## Code After: from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue q = queue.Queue() q.put('thing') self.assertFalse(q.empty()) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main()
f266132c05c37469290027e7aa8000d1f9a19a6c
tst/colors.py
tst/colors.py
YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' GREEN="\033[9;32m" WHITE="\033[1;37m" LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m'
YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' GREEN = '\033[9;32m' WHITE = '\033[0;37m' LWHITE = '\033[1;37m' LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m' CRITICAL = '\033[41;37m'
Add some new color codes
Add some new color codes
Python
agpl-3.0
daltonserey/tst,daltonserey/tst
YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' - GREEN="\033[9;32m" + GREEN = '\033[9;32m' + WHITE = '\033[0;37m' - WHITE="\033[1;37m" + LWHITE = '\033[1;37m' LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m' + CRITICAL = '\033[41;37m'
Add some new color codes
## Code Before: YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' GREEN="\033[9;32m" WHITE="\033[1;37m" LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m' ## Instruction: Add some new color codes ## Code After: YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' GREEN = '\033[9;32m' WHITE = '\033[0;37m' LWHITE = '\033[1;37m' LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m' CRITICAL = '\033[41;37m'
038978f87883247a14e9bec08708452c98c91285
test/test_chimera.py
test/test_chimera.py
import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main()
import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') with open('out.chimerax') as fh: lines = fh.readlines() self.assertEqual(lines[-4], 'open_files("url1", "url2")\n') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main()
Check generated file for sanity.
Check generated file for sanity.
Python
lgpl-2.1
salilab/cryptosite,salilab/cryptosite,salilab/cryptosite
import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') + with open('out.chimerax') as fh: + lines = fh.readlines() + self.assertEqual(lines[-4], 'open_files("url1", "url2")\n') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main()
Check generated file for sanity.
## Code Before: import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main() ## Instruction: Check generated file for sanity. ## Code After: import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') with open('out.chimerax') as fh: lines = fh.readlines() self.assertEqual(lines[-4], 'open_files("url1", "url2")\n') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main()
ca777965c26b8dfd43b472adeb032f048e2537ed
acceptancetests/tests/acc_test_login_page.py
acceptancetests/tests/acc_test_login_page.py
import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(self.browser.title, title) self.assertIn('Login with ID.', self.browser.html)
import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
Check that expected title exists in the actual title, not the other way round
Check that expected title exists in the actual title, not the other way round
Python
mit
dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse
import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) - self.assertIn(self.browser.title, title) + self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
Check that expected title exists in the actual title, not the other way round
## Code Before: import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(self.browser.title, title) self.assertIn('Login with ID.', self.browser.html) ## Instruction: Check that expected title exists in the actual title, not the other way round ## Code After: import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
154b64b2ee56fa4391251268ba4a85d178bedd60
djangoautoconf/urls.py
djangoautoconf/urls.py
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
Fix the issue of override url by mistake.
Fix the issue of override url by mistake.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) - urlpatterns = [ - # ... the rest of your URLconf goes here ... - ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
Fix the issue of override url by mistake.
## Code Before: from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns ## Instruction: Fix the issue of override url by mistake. ## Code After: from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
96f9819ab67b48135a61c8a1e15bc808cf82d194
bokeh/models/widget.py
bokeh/models/widget.py
from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool class Widget(PlotObject): disabled = Bool(False)
from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool from ..embed import notebook_div class Widget(PlotObject): disabled = Bool(False) def _repr_html_(self): return notebook_div(self) @property def html(self): from IPython.core.display import HTML return HTML(self._repr_html_())
Implement display protocol for Widget (_repr_html_)
Implement display protocol for Widget (_repr_html_) This effectively allows us to automatically display plots and widgets.
Python
bsd-3-clause
evidation-health/bokeh,abele/bokeh,mutirri/bokeh,percyfal/bokeh,htygithub/bokeh,jakirkham/bokeh,rhiever/bokeh,DuCorey/bokeh,srinathv/bokeh,DuCorey/bokeh,awanke/bokeh,clairetang6/bokeh,ericdill/bokeh,ahmadia/bokeh,saifrahmed/bokeh,mutirri/bokeh,bokeh/bokeh,gpfreitas/bokeh,philippjfr/bokeh,xguse/bokeh,srinathv/bokeh,draperjames/bokeh,schoolie/bokeh,laurent-george/bokeh,paultcochrane/bokeh,akloster/bokeh,caseyclements/bokeh,justacec/bokeh,maxalbert/bokeh,philippjfr/bokeh,birdsarah/bokeh,evidation-health/bokeh,rs2/bokeh,phobson/bokeh,PythonCharmers/bokeh,draperjames/bokeh,satishgoda/bokeh,mindriot101/bokeh,PythonCharmers/bokeh,CrazyGuo/bokeh,mindriot101/bokeh,birdsarah/bokeh,jplourenco/bokeh,matbra/bokeh,htygithub/bokeh,deeplook/bokeh,abele/bokeh,bsipocz/bokeh,rhiever/bokeh,laurent-george/bokeh,ericmjl/bokeh,htygithub/bokeh,DuCorey/bokeh,justacec/bokeh,PythonCharmers/bokeh,msarahan/bokeh,mutirri/bokeh,percyfal/bokeh,timsnyder/bokeh,timsnyder/bokeh,muku42/bokeh,deeplook/bokeh,xguse/bokeh,daodaoliang/bokeh,ChristosChristofidis/bokeh,ericmjl/bokeh,timothydmorton/bokeh,percyfal/bokeh,schoolie/bokeh,alan-unravel/bokeh,jplourenco/bokeh,canavandl/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,evidation-health/bokeh,Karel-van-de-Plassche/bokeh,tacaswell/bokeh,bsipocz/bokeh,mutirri/bokeh,deeplook/bokeh,dennisobrien/bokeh,msarahan/bokeh,quasiben/bokeh,roxyboy/bokeh,josherick/bokeh,mindriot101/bokeh,saifrahmed/bokeh,rothnic/bokeh,CrazyGuo/bokeh,canavandl/bokeh,aiguofer/bokeh,akloster/bokeh,clairetang6/bokeh,almarklein/bokeh,josherick/bokeh,aiguofer/bokeh,timothydmorton/bokeh,ptitjano/bokeh,KasperPRasmussen/bokeh,mindriot101/bokeh,aavanian/bokeh,josherick/bokeh,quasiben/bokeh,xguse/bokeh,saifrahmed/bokeh,KasperPRasmussen/bokeh,akloster/bokeh,awanke/bokeh,ptitjano/bokeh,aavanian/bokeh,azjps/bokeh,tacaswell/bokeh,draperjames/bokeh,alan-unravel/bokeh,ericmjl/bokeh,rs2/bokeh,bokeh/bokeh,stonebig/bokeh,tacaswell/bokeh,ChinaQuants/bokeh,stonebig/bokeh,stuart-knock/bokeh,paultcochrane/bokeh,xguse/bokeh,jakirkham/bokeh,abele/bokeh,alan-unravel/bokeh,KasperPRasmussen/bokeh,birdsarah/bokeh,stuart-knock/bokeh,Karel-van-de-Plassche/bokeh,carlvlewis/bokeh,gpfreitas/bokeh,dennisobrien/bokeh,deeplook/bokeh,alan-unravel/bokeh,lukebarnard1/bokeh,jakirkham/bokeh,ahmadia/bokeh,aavanian/bokeh,phobson/bokeh,clairetang6/bokeh,timsnyder/bokeh,ptitjano/bokeh,ahmadia/bokeh,lukebarnard1/bokeh,rs2/bokeh,tacaswell/bokeh,ericdill/bokeh,matbra/bokeh,satishgoda/bokeh,awanke/bokeh,rothnic/bokeh,evidation-health/bokeh,jplourenco/bokeh,muku42/bokeh,CrazyGuo/bokeh,roxyboy/bokeh,bokeh/bokeh,caseyclements/bokeh,jplourenco/bokeh,matbra/bokeh,gpfreitas/bokeh,ChinaQuants/bokeh,ChinaQuants/bokeh,KasperPRasmussen/bokeh,dennisobrien/bokeh,saifrahmed/bokeh,timothydmorton/bokeh,rhiever/bokeh,timsnyder/bokeh,maxalbert/bokeh,DuCorey/bokeh,azjps/bokeh,birdsarah/bokeh,satishgoda/bokeh,stonebig/bokeh,srinathv/bokeh,rs2/bokeh,aiguofer/bokeh,schoolie/bokeh,rothnic/bokeh,philippjfr/bokeh,laurent-george/bokeh,stonebig/bokeh,matbra/bokeh,justacec/bokeh,maxalbert/bokeh,percyfal/bokeh,jakirkham/bokeh,eteq/bokeh,eteq/bokeh,rs2/bokeh,philippjfr/bokeh,daodaoliang/bokeh,ericdill/bokeh,azjps/bokeh,khkaminska/bokeh,draperjames/bokeh,philippjfr/bokeh,almarklein/bokeh,canavandl/bokeh,ericmjl/bokeh,clairetang6/bokeh,ptitjano/bokeh,srinathv/bokeh,KasperPRasmussen/bokeh,ericmjl/bokeh,htygithub/bokeh,carlvlewis/bokeh,ptitjano/bokeh,aiguofer/bokeh,laurent-george/bokeh,lukebarnard1/bokeh,ChristosChristofidis/bokeh,abele/bokeh,ChristosChristofidis/bokeh,azjps/bokeh,draperjames/bokeh,jakirkham/bokeh,roxyboy/bokeh,Karel-van-de-Plassche/bokeh,roxyboy/bokeh,khkaminska/bokeh,phobson/bokeh,caseyclements/bokeh,paultcochrane/bokeh,percyfal/bokeh,caseyclements/bokeh,muku42/bokeh,eteq/bokeh,msarahan/bokeh,aiguofer/bokeh,almarklein/bokeh,ChinaQuants/bokeh,ericdill/bokeh,PythonCharmers/bokeh,khkaminska/bokeh,carlvlewis/bokeh,canavandl/bokeh,bokeh/bokeh,timsnyder/bokeh,eteq/bokeh,muku42/bokeh,rothnic/bokeh,ahmadia/bokeh,timothydmorton/bokeh,DuCorey/bokeh,stuart-knock/bokeh,bsipocz/bokeh,phobson/bokeh,dennisobrien/bokeh,stuart-knock/bokeh,CrazyGuo/bokeh,aavanian/bokeh,schoolie/bokeh,phobson/bokeh,dennisobrien/bokeh,akloster/bokeh,bsipocz/bokeh,paultcochrane/bokeh,josherick/bokeh,daodaoliang/bokeh,schoolie/bokeh,rhiever/bokeh,maxalbert/bokeh,satishgoda/bokeh,ChristosChristofidis/bokeh,msarahan/bokeh,carlvlewis/bokeh,justacec/bokeh,Karel-van-de-Plassche/bokeh,lukebarnard1/bokeh,daodaoliang/bokeh,azjps/bokeh,awanke/bokeh,khkaminska/bokeh,gpfreitas/bokeh,aavanian/bokeh,quasiben/bokeh
from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool + from ..embed import notebook_div class Widget(PlotObject): disabled = Bool(False) + def _repr_html_(self): + return notebook_div(self) + + @property + def html(self): + from IPython.core.display import HTML + return HTML(self._repr_html_()) +
Implement display protocol for Widget (_repr_html_)
## Code Before: from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool class Widget(PlotObject): disabled = Bool(False) ## Instruction: Implement display protocol for Widget (_repr_html_) ## Code After: from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool from ..embed import notebook_div class Widget(PlotObject): disabled = Bool(False) def _repr_html_(self): return notebook_div(self) @property def html(self): from IPython.core.display import HTML return HTML(self._repr_html_())
16d0f3f0ca4ce59f08e598b6f9f25bb6dc8e1713
benchmark/benchmark.py
benchmark/benchmark.py
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return " ".join(s)
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s
Fix bad console output formatting
Fix bad console output formatting
Python
mit
jameshy/libtree,conceptsandtraining/libtree
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) - return " ".join(s) + return s
Fix bad console output formatting
## Code Before: import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return " ".join(s) ## Instruction: Fix bad console output formatting ## Code After: import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s
2cf8d03324af2fadf905da811cfab4a29a6bc93a
pony_barn/settings/django_settings.py
pony_barn/settings/django_settings.py
DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': 'other_db' } }
import os pid = os.getpid() DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': 'other_db_%s' % pid, } }
Append PID to Django database to avoid conflicts.
Append PID to Django database to avoid conflicts.
Python
mit
ericholscher/pony_barn,ericholscher/pony_barn
+ import os + pid = os.getpid() + DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', - 'TEST_NAME': 'other_db' + 'TEST_NAME': 'other_db_%s' % pid, } }
Append PID to Django database to avoid conflicts.
## Code Before: DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': 'other_db' } } ## Instruction: Append PID to Django database to avoid conflicts. ## Code After: import os pid = os.getpid() DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': 'other_db_%s' % pid, } }
8f1fd73d6a88436d24f936adec997f88ad7f1413
neutron/tests/unit/objects/test_l3agent.py
neutron/tests/unit/objects/test_l3agent.py
from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] self.update_obj_fields( {'router_id': self._router.id, 'l3_agent_id': getter})
from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] index = iter(range(1, len(self.objs) + 1)) self.update_obj_fields( {'router_id': self._router.id, 'binding_index': lambda: next(index), 'l3_agent_id': getter})
Use unique binding_index for RouterL3AgentBinding
Use unique binding_index for RouterL3AgentBinding This is because (router_id, binding_index) tuple is expected to be unique, as per db model. Closes-Bug: #1674434 Change-Id: I64fcee88f2ac942e6fa173644fbfb7655ea6041b
Python
apache-2.0
openstack/neutron,mahak/neutron,noironetworks/neutron,huntxu/neutron,eayunstack/neutron,openstack/neutron,huntxu/neutron,eayunstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron,noironetworks/neutron
from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] + index = iter(range(1, len(self.objs) + 1)) self.update_obj_fields( {'router_id': self._router.id, + 'binding_index': lambda: next(index), 'l3_agent_id': getter})
Use unique binding_index for RouterL3AgentBinding
## Code Before: from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] self.update_obj_fields( {'router_id': self._router.id, 'l3_agent_id': getter}) ## Instruction: Use unique binding_index for RouterL3AgentBinding ## Code After: from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] index = iter(range(1, len(self.objs) + 1)) self.update_obj_fields( {'router_id': self._router.id, 'binding_index': lambda: next(index), 'l3_agent_id': getter})
867a8081646eb061555eda2471c5174a842dd6fd
tests/test_floodplain.py
tests/test_floodplain.py
from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7)
from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): import matplotlib as mpl mpl.use('agg') import matplotlib.pyplot as plt plt.show = lambda: None fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7)
Fix tests for running floodplain model in ci
Fix tests for running floodplain model in ci
Python
mit
johanvdw/niche_vlaanderen
from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): + import matplotlib as mpl + mpl.use('agg') + + import matplotlib.pyplot as plt + plt.show = lambda: None + fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7)
Fix tests for running floodplain model in ci
## Code Before: from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7) ## Instruction: Fix tests for running floodplain model in ci ## Code After: from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): import matplotlib as mpl mpl.use('agg') import matplotlib.pyplot as plt plt.show = lambda: None fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7)
fc8ac6ba5081e7847847d31588a65db8ea13416c
openprescribing/matrixstore/build/dates.py
openprescribing/matrixstore/build/dates.py
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months((year, month), months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
Fix another py27-ism which Black can't handle
Fix another py27-ism which Black can't handle Not sure how I missed this one last time.
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) - def increment_months((year, month), months): + def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ + year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
Fix another py27-ism which Black can't handle
## Code Before: DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months((year, month), months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1 ## Instruction: Fix another py27-ism which Black can't handle ## Code After: DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
73b61983de6ff655b4f11205c0acd2b2f92915f4
eva/util/nutil.py
eva/util/nutil.py
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): """ Stochastically binarize values in [0, 1] by treating them as p-values of a Bernoulli distribution. """ return (generate(size=arr.shape) < arr).astype('float32')
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): return (generate(size=arr.shape) < arr).astype('i')
Remove comment; change to int
Remove comment; change to int
Python
apache-2.0
israelg99/eva
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): - """ - Stochastically binarize values in [0, 1] by treating them as p-values of - a Bernoulli distribution. - """ - return (generate(size=arr.shape) < arr).astype('float32') + return (generate(size=arr.shape) < arr).astype('i')
Remove comment; change to int
## Code Before: import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): """ Stochastically binarize values in [0, 1] by treating them as p-values of a Bernoulli distribution. """ return (generate(size=arr.shape) < arr).astype('float32') ## Instruction: Remove comment; change to int ## Code After: import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): return (generate(size=arr.shape) < arr).astype('i')
d70ccd856bb4ddb061ff608716ef15f778380d62
gnsq/stream/defalte.py
gnsq/stream/defalte.py
from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): self._decompressor = zlib.decompressobj(level) self._compressor = zlib.compressobj(level) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data)
from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): wbits = -zlib.MAX_WBITS self._decompressor = zlib.decompressobj(wbits) self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data)
Set correct waits for deflate.
Set correct waits for deflate.
Python
bsd-3-clause
wtolson/gnsq,hiringsolved/gnsq,wtolson/gnsq
from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): + wbits = -zlib.MAX_WBITS - self._decompressor = zlib.decompressobj(level) + self._decompressor = zlib.decompressobj(wbits) - self._compressor = zlib.compressobj(level) + self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data)
Set correct waits for deflate.
## Code Before: from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): self._decompressor = zlib.decompressobj(level) self._compressor = zlib.compressobj(level) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data) ## Instruction: Set correct waits for deflate. ## Code After: from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): wbits = -zlib.MAX_WBITS self._decompressor = zlib.decompressobj(wbits) self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data)
02ca8bc5908b0ff15cd97846e1fd1488eddb4087
backend/schedule/models.py
backend/schedule/models.py
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') square_footage = models.IntegerField capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
Add square feet to Location data model.
Add square feet to Location data model.
Python
mit
bable5/schdlr,bable5/schdlr,bable5/schdlr,bable5/schdlr
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') + square_footage = models.IntegerField capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
Add square feet to Location data model.
## Code Before: from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True) ## Instruction: Add square feet to Location data model. ## Code After: from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') square_footage = models.IntegerField capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
8e75605e0511b85dfd500b644613739f29705da6
cfnf.py
cfnf.py
import sublime, sublime_plugin import time class cfnewfile(sublime_plugin.TextCommand): def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) self.view.insert(edit,0,"<!---\r\n Name:\r\n Description:\r\n Written By:\r\n Date Created: "+localtime+"\r\n History:\r\n--->\r\n")
import sublime, sublime_plugin import time class cfnfCommand(sublime_plugin.WindowCommand): def run(self): a = self.window.new_file() a.run_command("addheader") class addheaderCommand(sublime_plugin.TextCommand): def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) self.view.insert(edit,0,"<!---\n Name:\n Description:\n Written By:\n Date Created: "+localtime+"\n History:\n--->\n")
Send text to new file
Send text to new file
Python
bsd-2-clause
dwkd/SublimeCFNewFile
+ import sublime, sublime_plugin import time - class cfnewfile(sublime_plugin.TextCommand): + class cfnfCommand(sublime_plugin.WindowCommand): + def run(self): + a = self.window.new_file() + a.run_command("addheader") + + class addheaderCommand(sublime_plugin.TextCommand): - def run(self, edit): + def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) - self.view.insert(edit,0,"<!---\r\n Name:\r\n Description:\r\n Written By:\r\n Date Created: "+localtime+"\r\n History:\r\n--->\r\n") + self.view.insert(edit,0,"<!---\n Name:\n Description:\n Written By:\n Date Created: "+localtime+"\n History:\n--->\n")
Send text to new file
## Code Before: import sublime, sublime_plugin import time class cfnewfile(sublime_plugin.TextCommand): def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) self.view.insert(edit,0,"<!---\r\n Name:\r\n Description:\r\n Written By:\r\n Date Created: "+localtime+"\r\n History:\r\n--->\r\n") ## Instruction: Send text to new file ## Code After: import sublime, sublime_plugin import time class cfnfCommand(sublime_plugin.WindowCommand): def run(self): a = self.window.new_file() a.run_command("addheader") class addheaderCommand(sublime_plugin.TextCommand): def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) self.view.insert(edit,0,"<!---\n Name:\n Description:\n Written By:\n Date Created: "+localtime+"\n History:\n--->\n")
6589df70baad1b57c604736d75e424465cf8775e
djangoautoconf/auto_conf_admin_tools/reversion_feature.py
djangoautoconf/auto_conf_admin_tools/reversion_feature.py
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: from reversion import VersionAdmin parent_list.append(VersionAdmin)
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: try: from reversion import VersionAdmin # for Django 1.5 except: from reversion.admin import VersionAdmin # for Django 1.8 parent_list.append(VersionAdmin)
Fix import issue for Django 1.5 above
Fix import issue for Django 1.5 above
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: + try: - from reversion import VersionAdmin + from reversion import VersionAdmin # for Django 1.5 + except: + from reversion.admin import VersionAdmin # for Django 1.8 parent_list.append(VersionAdmin)
Fix import issue for Django 1.5 above
## Code Before: from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: from reversion import VersionAdmin parent_list.append(VersionAdmin) ## Instruction: Fix import issue for Django 1.5 above ## Code After: from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: try: from reversion import VersionAdmin # for Django 1.5 except: from reversion.admin import VersionAdmin # for Django 1.8 parent_list.append(VersionAdmin)
6df7ee955c7dfaee9a597b331dbc4c448fe3738a
fpr/migrations/0017_ocr_unique_names.py
fpr/migrations/0017_ocr_unique_names.py
from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ IDCommand = apps.get_model('fpr', 'IDCommand') ocr_command = IDCommand.objects.get( uuid='5d501dbf-76bb-4569-a9db-9e367800995e') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ]
from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ FPCommand = apps.get_model('fpr', 'FPCommand') ocr_command = FPCommand.objects.get( uuid='4ea06c2b-ee42-4f80-ad10-4e044ba0676a') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ]
Fix OCR command UUID typo
Fix OCR command UUID typo
Python
agpl-3.0
artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin
from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ - IDCommand = apps.get_model('fpr', 'IDCommand') + FPCommand = apps.get_model('fpr', 'FPCommand') - ocr_command = IDCommand.objects.get( + ocr_command = FPCommand.objects.get( - uuid='5d501dbf-76bb-4569-a9db-9e367800995e') + uuid='4ea06c2b-ee42-4f80-ad10-4e044ba0676a') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ]
Fix OCR command UUID typo
## Code Before: from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ IDCommand = apps.get_model('fpr', 'IDCommand') ocr_command = IDCommand.objects.get( uuid='5d501dbf-76bb-4569-a9db-9e367800995e') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ] ## Instruction: Fix OCR command UUID typo ## Code After: from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ FPCommand = apps.get_model('fpr', 'FPCommand') ocr_command = FPCommand.objects.get( uuid='4ea06c2b-ee42-4f80-ad10-4e044ba0676a') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ]
8c49359a79d815cc21acbd58adc36c52d75e20b7
dash2012/auth/views.py
dash2012/auth/views.py
from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) return render(r, 'auth.html') def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html')
from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): c = {} if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) c['errors'] = "Login failed, please try again" return render(r, 'auth.html', c) def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html')
Add login failed flash message
Add login failed flash message
Python
bsd-3-clause
losmiserables/djangodash2012,losmiserables/djangodash2012
from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): + c = {} if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) + c['errors'] = "Login failed, please try again" - return render(r, 'auth.html') + return render(r, 'auth.html', c) def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html')
Add login failed flash message
## Code Before: from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) return render(r, 'auth.html') def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html') ## Instruction: Add login failed flash message ## Code After: from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): c = {} if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) c['errors'] = "Login failed, please try again" return render(r, 'auth.html', c) def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html')
e170a96859232d1436930be7a0cbfc7f2295c8a7
main.py
main.py
from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): self.numberRequests += 1 request.setHeader("content-type", "text/plain") return "I am request #" + str(self.numberRequests) + "\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run()
from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): request.setHeader("content-type", "text/plain") return "Welcome to teiler\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run()
Set root resource to welcome
Set root resource to welcome
Python
mit
derwolfe/teiler,derwolfe/teiler
from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): - self.numberRequests += 1 request.setHeader("content-type", "text/plain") - return "I am request #" + str(self.numberRequests) + "\n" + return "Welcome to teiler\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run()
Set root resource to welcome
## Code Before: from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): self.numberRequests += 1 request.setHeader("content-type", "text/plain") return "I am request #" + str(self.numberRequests) + "\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run() ## Instruction: Set root resource to welcome ## Code After: from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): request.setHeader("content-type", "text/plain") return "Welcome to teiler\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run()
73b6a84cfc0ccc20d04c3dd80c3e505cd118be4d
nsfw.py
nsfw.py
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel']) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel'], hidden=True) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
Make command invisible by default
Make command invisible by default
Python
mit
BeatButton/beattie-bot,BeatButton/beattie
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot - @commands.command(aliases=['gel']) + @commands.command(aliases=['gel'], hidden=True) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
Make command invisible by default
## Code Before: import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel']) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot)) ## Instruction: Make command invisible by default ## Code After: import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel'], hidden=True) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
22e6cce28da8a700bd4cd45aa47913aaff559a9d
functional_tests/management/commands/create_testrecipe.py
functional_tests/management/commands/create_testrecipe.py
from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save()
import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save() r.add_date = datetime.date.today() - datetime.timedelta(days=2) r.save()
Make sure that recipes created by the command show up
Make sure that recipes created by the command show up
Python
agpl-3.0
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
+ import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save() + r.add_date = datetime.date.today() - datetime.timedelta(days=2) + r.save()
Make sure that recipes created by the command show up
## Code Before: from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save() ## Instruction: Make sure that recipes created by the command show up ## Code After: import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save() r.add_date = datetime.date.today() - datetime.timedelta(days=2) r.save()
f96990118d51b56ad438a8efbf2a7f83ec0f3c63
conference_scheduler/tests/test_parameters.py
conference_scheduler/tests/test_parameters.py
from conference_scheduler import parameters def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10
from conference_scheduler import parameters import numpy as np def test_tags(events): tags = parameters.tags(events) assert np.array_equal(tags, np.array([[1, 0], [1, 1], [0, 1]])) def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10
Add failing test to function to build tags matrix.
Add failing test to function to build tags matrix.
Python
mit
PyconUK/ConferenceScheduler
from conference_scheduler import parameters + import numpy as np + def test_tags(events): + tags = parameters.tags(events) + assert np.array_equal(tags, np.array([[1, 0], [1, 1], [0, 1]])) def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10
Add failing test to function to build tags matrix.
## Code Before: from conference_scheduler import parameters def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10 ## Instruction: Add failing test to function to build tags matrix. ## Code After: from conference_scheduler import parameters import numpy as np def test_tags(events): tags = parameters.tags(events) assert np.array_equal(tags, np.array([[1, 0], [1, 1], [0, 1]])) def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10
24e65db624221d559f46ce74d88ad28ec970d754
profile_collection/startup/00-startup.py
profile_collection/startup/00-startup.py
import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd'
import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd' import bluesky.qt_kicker bluesky.qt_kicker.install_qt_kicker()
Update bluesky's API to the qt_kicker.
Update bluesky's API to the qt_kicker.
Python
bsd-2-clause
NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd,pavoljuhas/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd' + + import bluesky.qt_kicker + bluesky.qt_kicker.install_qt_kicker() + +
Update bluesky's API to the qt_kicker.
## Code Before: import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd' ## Instruction: Update bluesky's API to the qt_kicker. ## Code After: import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd' import bluesky.qt_kicker bluesky.qt_kicker.install_qt_kicker()
54b2a6953a4da2b217052d166ad1f069f683b9ee
scripts/nomenclature/nomenclature_map.py
scripts/nomenclature/nomenclature_map.py
import pandas as pd itis_results = pd.read_csv("search_result.csv", encoding = "ISO-8859-1")
import pandas as pd from PyFloraBook.in_out.data_coordinator import locate_nomenclature_folder # Globals INPUT_FILE_NAME = "search_results.csv" # Input nomenclature_folder = locate_nomenclature_folder() itis_results = pd.read_csv( str(nomenclature_folder / INPUT_FILE_NAME), encoding="ISO-8859-1")
Implement locator in nomenclature map
Implement locator in nomenclature map
Python
mit
jnfrye/local_plants_book
import pandas as pd - itis_results = pd.read_csv("search_result.csv", encoding = "ISO-8859-1") + from PyFloraBook.in_out.data_coordinator import locate_nomenclature_folder + + # Globals + INPUT_FILE_NAME = "search_results.csv" + + # Input + nomenclature_folder = locate_nomenclature_folder() + itis_results = pd.read_csv( + str(nomenclature_folder / INPUT_FILE_NAME), encoding="ISO-8859-1") +
Implement locator in nomenclature map
## Code Before: import pandas as pd itis_results = pd.read_csv("search_result.csv", encoding = "ISO-8859-1") ## Instruction: Implement locator in nomenclature map ## Code After: import pandas as pd from PyFloraBook.in_out.data_coordinator import locate_nomenclature_folder # Globals INPUT_FILE_NAME = "search_results.csv" # Input nomenclature_folder = locate_nomenclature_folder() itis_results = pd.read_csv( str(nomenclature_folder / INPUT_FILE_NAME), encoding="ISO-8859-1")
b77e39b21a326655a04dbd15fcacfd2cc57a6008
core/emails.py
core/emails.py
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(user, content, subject): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(content, subject, user): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
Fix broken order of arguments in send_email
Fix broken order of arguments in send_email Ticket #342
Python
bsd-3-clause
patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) - def send_email(user, content, subject): + def send_email(content, subject, user): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
Fix broken order of arguments in send_email
## Code Before: from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(user, content, subject): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send() ## Instruction: Fix broken order of arguments in send_email ## Code After: from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(content, subject, user): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
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)
a6300723150d7d1ff9a58f4f3f1297e0fe2c6f78
css_updater/git/manager.py
css_updater/git/manager.py
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
Check for errors in config
Python
mit
neoliberal/css-updater
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json + try: - self.config: Dict[str, Any] = json.loads(config.read()) + self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] + except KeyError as invalid_json: + print(invalid_json) + except IOError as io_error: + print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
## Code Before: """manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup() ## Instruction: Check for errors in config ## Code After: """manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
3d64eb4a7438b6b4f46f1fdf7f47d530cb11b09c
spacy/tests/regression/test_issue2396.py
spacy/tests/regression/test_issue2396.py
from __future__ import unicode_literals from ..util import get_doc import pytest import numpy @pytest.mark.parametrize('sentence,matrix', [ ( 'She created a test for spacy', numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(EN, sentence, matrix): doc = EN(sentence) span = doc[:] assert (doc.get_lca_matrix() == matrix).all() assert (span.get_lca_matrix() == matrix).all()
from __future__ import unicode_literals from ..util import get_doc import pytest import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix)
Update get_lca_matrix test for develop
Update get_lca_matrix test for develop
Python
mit
explosion/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
from __future__ import unicode_literals from ..util import get_doc import pytest import numpy + from numpy.testing import assert_array_equal + - @pytest.mark.parametrize('sentence,matrix', [ + @pytest.mark.parametrize('words,heads,matrix', [ ( - 'She created a test for spacy', + 'She created a test for spacy'.split(), + [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) - def test_issue2396(EN, sentence, matrix): - doc = EN(sentence) + def test_issue2396(en_vocab, words, heads, matrix): + doc = get_doc(en_vocab, words=words, heads=heads) + span = doc[:] - assert (doc.get_lca_matrix() == matrix).all() + assert_array_equal(doc.get_lca_matrix(), matrix) - assert (span.get_lca_matrix() == matrix).all() + assert_array_equal(span.get_lca_matrix(), matrix)
Update get_lca_matrix test for develop
## Code Before: from __future__ import unicode_literals from ..util import get_doc import pytest import numpy @pytest.mark.parametrize('sentence,matrix', [ ( 'She created a test for spacy', numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(EN, sentence, matrix): doc = EN(sentence) span = doc[:] assert (doc.get_lca_matrix() == matrix).all() assert (span.get_lca_matrix() == matrix).all() ## Instruction: Update get_lca_matrix test for develop ## Code After: from __future__ import unicode_literals from ..util import get_doc import pytest import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix)
8dc822cf3577663cf817cd5d1ab537df3605752c
art_archive_api/models.py
art_archive_api/models.py
from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255))
from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) def serialize(self): return { 'id': self.id, 'name': self.name, 'birth_year': self.birth_year, 'death_year': self.death_year, 'country': self.country, 'genre': self.genre, } def serialize_with_images(self): return { 'id': self.id, 'name': self.name, 'birth_year': self.birth_year, 'death_year': self.death_year, 'country': self.country, 'genre': self.genre, "images" : [image.serialize() for image in self.images] } class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255)) def serialize(self): return { 'id': self.id, 'image_url': self.image_url, 'title': self.title, 'year': self.year, 'description': self.description, }
UPDATE serialize method for json data
UPDATE serialize method for json data
Python
mit
EunJung-Seo/art_archive
from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) + def serialize(self): + return { + 'id': self.id, + 'name': self.name, + 'birth_year': self.birth_year, + 'death_year': self.death_year, + 'country': self.country, + 'genre': self.genre, + } + + def serialize_with_images(self): + return { + 'id': self.id, + 'name': self.name, + 'birth_year': self.birth_year, + 'death_year': self.death_year, + 'country': self.country, + 'genre': self.genre, + "images" : [image.serialize() for image in self.images] + } + class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255)) + def serialize(self): + return { + 'id': self.id, + 'image_url': self.image_url, + 'title': self.title, + 'year': self.year, + 'description': self.description, + }
UPDATE serialize method for json data
## Code Before: from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255)) ## Instruction: UPDATE serialize method for json data ## Code After: from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) def serialize(self): return { 'id': self.id, 'name': self.name, 'birth_year': self.birth_year, 'death_year': self.death_year, 'country': self.country, 'genre': self.genre, } def serialize_with_images(self): return { 'id': self.id, 'name': self.name, 'birth_year': self.birth_year, 'death_year': self.death_year, 'country': self.country, 'genre': self.genre, "images" : [image.serialize() for image in self.images] } class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255)) def serialize(self): return { 'id': self.id, 'image_url': self.image_url, 'title': self.title, 'year': self.year, 'description': self.description, }
26672e83ab1bd1a932d275dfd244fe20749e3b1e
tripleo_common/utils/safe_import.py
tripleo_common/utils/safe_import.py
import eventlet from eventlet.green import subprocess # Due to an eventlet issue subprocess is not being correctly patched # on git module so it has to be done manually git = eventlet.import_patched('git', ('subprocess', subprocess)) Repo = git.Repo # git.refs is lazy loaded when there's a new commit, this needs to be # patched as well. eventlet.import_patched('git.refs')
from eventlet.green import subprocess import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched # on git.refs patcher.inject('git.refs', None, ('subprocess', subprocess), ) # this has to be loaded after the inject. import git # noqa: E402 Repo = git.Repo
Make gitpython and eventlet work with eventlet 0.25.1
Make gitpython and eventlet work with eventlet 0.25.1 Version 0.25 is having a bad interaction with python git. that is due to the way that eventlet unloads some modules now. Changed to use the inject method that supports what we need intead of the imported_patched that was having the problem Change-Id: I79894d4f711c64f536593fffcb6959df97c38838 Closes-bug: #1845181
Python
apache-2.0
openstack/tripleo-common,openstack/tripleo-common
- import eventlet from eventlet.green import subprocess + import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched - # on git module so it has to be done manually + # on git.refs + patcher.inject('git.refs', None, ('subprocess', subprocess), ) - git = eventlet.import_patched('git', ('subprocess', subprocess)) + # this has to be loaded after the inject. + + import git # noqa: E402 + Repo = git.Repo - # git.refs is lazy loaded when there's a new commit, this needs to be - # patched as well. - eventlet.import_patched('git.refs') -
Make gitpython and eventlet work with eventlet 0.25.1
## Code Before: import eventlet from eventlet.green import subprocess # Due to an eventlet issue subprocess is not being correctly patched # on git module so it has to be done manually git = eventlet.import_patched('git', ('subprocess', subprocess)) Repo = git.Repo # git.refs is lazy loaded when there's a new commit, this needs to be # patched as well. eventlet.import_patched('git.refs') ## Instruction: Make gitpython and eventlet work with eventlet 0.25.1 ## Code After: from eventlet.green import subprocess import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched # on git.refs patcher.inject('git.refs', None, ('subprocess', subprocess), ) # this has to be loaded after the inject. import git # noqa: E402 Repo = git.Repo
4ae3b77847eeefd07d83f863c6ec71d7fdf750cb
turbustat/tests/test_rfft_to_fft.py
turbustat/tests/test_rfft_to_fft.py
from turbustat.statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt from unittest import TestCase class testRFFT(TestCase): """docstring for testRFFT""" def __init__(self): self.dataset1 = dataset1 self.comp_rfft = rfft_to_fft(self.dataset1) def rfft_to_rfft(self): test_rfft = np.abs(np.fft.rfftn(self.dataset1)) shape2 = test_rfft.shape[-1] npt.assert_allclose(test_rfft, self.comp_rfft[:, :, :shape2+1]) def fft_to_rfft(self): test_fft = np.abs(np.fft.fftn(self.dataset1)) npt.assert_allclose(test_fft, self.comp_rfft)
import pytest from ..statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt def test_rfft_to_rfft(): comp_rfft = rfft_to_fft(dataset1['moment0'][0]) test_rfft = np.abs(np.fft.rfftn(dataset1['moment0'][0])) shape2 = test_rfft.shape[-1] npt.assert_allclose(test_rfft, comp_rfft[:, :shape2]) def test_fft_to_rfft(): comp_rfft = rfft_to_fft(dataset1['moment0'][0]) test_fft = np.abs(np.fft.fftn(dataset1['moment0'][0])) npt.assert_allclose(test_fft, comp_rfft)
Fix and update the rfft tests
Fix and update the rfft tests
Python
mit
e-koch/TurbuStat,Astroua/TurbuStat
+ import pytest + - from turbustat.statistics.rfft_to_fft import rfft_to_fft + from ..statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt - from unittest import TestCase + def test_rfft_to_rfft(): - class testRFFT(TestCase): - """docstring for testRFFT""" - def __init__(self): - self.dataset1 = dataset1 - self.comp_rfft = rfft_to_fft(self.dataset1) + comp_rfft = rfft_to_fft(dataset1['moment0'][0]) - def rfft_to_rfft(self): - test_rfft = np.abs(np.fft.rfftn(self.dataset1)) + test_rfft = np.abs(np.fft.rfftn(dataset1['moment0'][0])) - shape2 = test_rfft.shape[-1] + shape2 = test_rfft.shape[-1] - npt.assert_allclose(test_rfft, self.comp_rfft[:, :, :shape2+1]) + npt.assert_allclose(test_rfft, comp_rfft[:, :shape2]) - def fft_to_rfft(self): - test_fft = np.abs(np.fft.fftn(self.dataset1)) - npt.assert_allclose(test_fft, self.comp_rfft) + def test_fft_to_rfft(): + comp_rfft = rfft_to_fft(dataset1['moment0'][0]) + test_fft = np.abs(np.fft.fftn(dataset1['moment0'][0])) + + npt.assert_allclose(test_fft, comp_rfft) +
Fix and update the rfft tests
## Code Before: from turbustat.statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt from unittest import TestCase class testRFFT(TestCase): """docstring for testRFFT""" def __init__(self): self.dataset1 = dataset1 self.comp_rfft = rfft_to_fft(self.dataset1) def rfft_to_rfft(self): test_rfft = np.abs(np.fft.rfftn(self.dataset1)) shape2 = test_rfft.shape[-1] npt.assert_allclose(test_rfft, self.comp_rfft[:, :, :shape2+1]) def fft_to_rfft(self): test_fft = np.abs(np.fft.fftn(self.dataset1)) npt.assert_allclose(test_fft, self.comp_rfft) ## Instruction: Fix and update the rfft tests ## Code After: import pytest from ..statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt def test_rfft_to_rfft(): comp_rfft = rfft_to_fft(dataset1['moment0'][0]) test_rfft = np.abs(np.fft.rfftn(dataset1['moment0'][0])) shape2 = test_rfft.shape[-1] npt.assert_allclose(test_rfft, comp_rfft[:, :shape2]) def test_fft_to_rfft(): comp_rfft = rfft_to_fft(dataset1['moment0'][0]) test_fft = np.abs(np.fft.fftn(dataset1['moment0'][0])) npt.assert_allclose(test_fft, comp_rfft)
2d36b6fee7905e32aded8da7ffba68a5ec3c5d34
dwitter/user/forms.py
dwitter/user/forms.py
from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() fields = ('first_name', 'last_name', 'email',)
from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() fields = ('email',)
Remove first_name and last_name from user settings
Remove first_name and last_name from user settings
Python
apache-2.0
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() - fields = ('first_name', + fields = ('email',) - 'last_name', - 'email',)
Remove first_name and last_name from user settings
## Code Before: from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() fields = ('first_name', 'last_name', 'email',) ## Instruction: Remove first_name and last_name from user settings ## Code After: from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() fields = ('email',)
7d9265cd3cb29606e37b296dde5af07099098228
axes/tests/test_checks.py
axes/tests/test_checks.py
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors)
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) @override_settings( AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_does_not_produce_check_errors_with_database_handler(self): errors = run_checks() self.assertEqual([], errors)
Add check test for missing case branch
Add check test for missing case branch Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi>
Python
mit
jazzband/django-axes,django-pci/django-axes
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase - @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): + @override_settings( + AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', - @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) + CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, + ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) + @override_settings( + AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', - @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) + CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, + ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) + @override_settings( + AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', + CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, + ) + def test_cache_check_does_not_produce_check_errors_with_database_handler(self): + errors = run_checks() + self.assertEqual([], errors) +
Add check test for missing case branch
## Code Before: from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) ## Instruction: Add check test for missing case branch ## Code After: from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) @override_settings( AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_does_not_produce_check_errors_with_database_handler(self): errors = run_checks() self.assertEqual([], errors)
41368a5d45aa9568d8495a98399cb92398eeaa32
eva/models/pixelcnn.py
eva/models/pixelcnn.py
from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', optimizer=Nadam(), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model
from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', optimizer=Nadam(clipnorm=1., clipvalue=1.), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model
Add gradient clipping value and norm
Add gradient clipping value and norm
Python
apache-2.0
israelg99/eva
from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', - optimizer=Nadam(), + optimizer=Nadam(clipnorm=1., clipvalue=1.), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model
Add gradient clipping value and norm
## Code Before: from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', optimizer=Nadam(), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model ## Instruction: Add gradient clipping value and norm ## Code After: from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', optimizer=Nadam(clipnorm=1., clipvalue=1.), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model
85d1fa8a390e715f38ddf9f680acb4337a469a66
cura/Settings/QualityAndUserProfilesModel.py
cura/Settings/QualityAndUserProfilesModel.py
from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() application = Application.getInstance() machine_definition = quality_manager.getParentMachineDefinition(application.getGlobalContainerStack().getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list
from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): global_container_stack = Application.getInstance().getGlobalContainerStack() if not global_container_stack: return [] # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list
Fix error on profiles page when there is no active machine
Fix error on profiles page when there is no active machine
Python
agpl-3.0
hmflash/Cura,Curahelper/Cura,Curahelper/Cura,fieldOfView/Cura,ynotstartups/Wanhao,hmflash/Cura,ynotstartups/Wanhao,fieldOfView/Cura
from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): + global_container_stack = Application.getInstance().getGlobalContainerStack() + if not global_container_stack: + return [] + # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() - application = Application.getInstance() - machine_definition = quality_manager.getParentMachineDefinition(application.getGlobalContainerStack().getBottom()) + machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list
Fix error on profiles page when there is no active machine
## Code Before: from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() application = Application.getInstance() machine_definition = quality_manager.getParentMachineDefinition(application.getGlobalContainerStack().getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list ## Instruction: Fix error on profiles page when there is no active machine ## Code After: from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): global_container_stack = Application.getInstance().getGlobalContainerStack() if not global_container_stack: return [] # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list