commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
75ee8c74af18c2ac9b3f4975d79a5d799ccc46da
pylatex/graphics.py
pylatex/graphics.py
# -*- coding: utf-8 -*- """ pylatex.graphics ~~~~~~~~~~~~~~~~ This module implements the class that deals with graphics. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from .utils import fix_filename from .base_classes import BaseLaTeXNamedContainer from ....
# -*- coding: utf-8 -*- """ pylatex.graphics ~~~~~~~~~~~~~~~~ This module implements the class that deals with graphics. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from .utils import fix_filename from .base_classes import BaseLaTeXNamedContainer from ....
Make figure a bit better
Make figure a bit better
Python
mit
jendas1/PyLaTeX,bjodah/PyLaTeX,bjodah/PyLaTeX,ovaskevich/PyLaTeX,votti/PyLaTeX,JelteF/PyLaTeX,votti/PyLaTeX,jendas1/PyLaTeX,sebastianhaas/PyLaTeX,JelteF/PyLaTeX,ovaskevich/PyLaTeX,sebastianhaas/PyLaTeX
3ceba413c57eec2034fb02e8a5557e69cf54a415
litslist/commands.py
litslist/commands.py
""" Includes execution logic for the commands """ import os import csv import random def run_create(count): file_list = [filename for filename in os.listdir('.') if os.path.isfile(filename)] sets = {} for filename in file_list: content = open(os.path.join(os.curdir, filename)).read().split('\n') random.shuffle...
""" Includes execution logic for the commands """ import os import csv import random def run_create(count): file_list = [filename for filename in os.listdir('.') if os.path.isfile(filename)] sets = {} for filename in file_list: content = open(os.path.join(os.curdir, filename)).read().split('\n') random.shuffle...
Set up creating files for unused items
Set up creating files for unused items
Python
mit
AlexMathew/litslist
4468827795606ae57c5a7d62f5b2f08d93387f39
virustotal/server.py
virustotal/server.py
#!/usr/bin/env python from contextlib import closing from sqlite3 import connect from bottle import template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) ...
#!/usr/bin/env python from contextlib import closing from sqlite3 import connect from bottle import request, template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, ...
Use refresh only if required in parameters (?refresh=something)
Use refresh only if required in parameters (?refresh=something)
Python
mit
enricobacis/playscraper
0c04f8cac3e1cbe24a5e4ed699e7c743b962e945
pygotham/filters.py
pygotham/filters.py
"""Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' _ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = core.publish_parts(source=value, wri...
"""Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' _ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'dl', 'dt', 'dd', 'cite', ] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = cor...
Add additional HTML tags to reST filter
Add additional HTML tags to reST filter
Python
bsd-3-clause
djds23/pygotham-1,djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,djds23/pygotham-1,pathunstrom/pygotham,pathunstrom/pygotham,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham
6a36f0cef03af2c61dbc0c5dfd4fc47496ae1f05
moss/plots.py
moss/plots.py
import os.path as op import numpy as np import nibabel as nib import matplotlib.pyplot as plt import seaborn as sns def plot_mask_distribution(fname, ax=None, hist=False): """Plot the distribution of voxel coordinates in a mask file. Parameters ---------- fname : string path to binary mask fil...
import numpy as np import nibabel as nib import matplotlib.pyplot as plt import seaborn as sns def plot_mask_distribution(mask_img, hist=False): """Plot the distribution of voxel coordinates in a mask image or file. Parameters ---------- fname : string or nibabel image path to binary mask file...
Allow plot_mask to take nibabel image
Allow plot_mask to take nibabel image
Python
bsd-3-clause
mwaskom/moss,mwaskom/moss
7ffea5f365c7b21b43eee00646f560b04c8e17e0
molly/conf/urls.py
molly/conf/urls.py
from django.conf.urls.defaults import RegexURLPattern def url(pattern, name=None, extra={}): def url_annotator(view): view.pattern = RegexURLPattern(pattern, view, extra, name) return view return url_annotator
from django.core.urlresolvers import RegexURLPattern def url(pattern, name=None, extra={}): def url_annotator(view): view.pattern = RegexURLPattern(pattern, view, extra, name) return view return url_annotator
Make new URL tag forward compatible
Make new URL tag forward compatible
Python
apache-2.0
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
ec52fee0fbefaa8fe2df1f38aab000456fb44c45
website/admin.py
website/admin.py
from django.contrib import admin from .models import Card, FaqQuestion, Banner, Rule admin.site.register(Card) admin.site.register(FaqQuestion) admin.site.register(Rule) admin.site.register(Banner)
from django.contrib import admin from django.contrib.admin import EmptyFieldListFilter from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Card, FaqQuestion, Banner, Rule class WatchlistFilter(EmptyFieldListFilter): def __init__(self, field, request, pa...
Add filter for users on watchlist
Add filter for users on watchlist
Python
mit
hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website
9293a72faf8cd41dc68bb1f2220e10459bbe09ff
pycom/oslo_i18n.py
pycom/oslo_i18n.py
# coding: utf-8 import oslo_i18n def reset_i18n(domain="app", localedir=None): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function u...
# coding: utf-8 import oslo_i18n def reset_i18n(domain="app", localedir=None, lazy=True): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation if lazy: oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The pr...
Add a argument and fix a error.
Add a argument and fix a error.
Python
mit
xgfone/pycom,xgfone/xutils
82b65fee35960a1f47f92aac1d8031bb0b57b2e7
jsonapiquery/drivers/__init__.py
jsonapiquery/drivers/__init__.py
from abc import ABCMeta, abstractmethod class DriverBase(metaclass=ABCMeta): def __init__(self, obj): self.obj = obj def __repr__(self): return '{}(type={})'.format(self.__class__.__name__, self.obj) def parse(self, item): """Return a new, typed item instance.""" obj = s...
from abc import ABCMeta, abstractmethod class DriverBase(metaclass=ABCMeta): def __init__(self, obj): self.obj = obj def __repr__(self): return '{}(type={})'.format(self.__class__.__name__, self.obj) def init_type(self, type, **init_kwargs): """Initialize a new type. :p...
Move type initialization to its own method
Move type initialization to its own method
Python
apache-2.0
caxiam/sqlalchemy-jsonapi-collections
45c4f2455b453ee361cbb38ed1add996012b1c5e
datahelper.py
datahelper.py
""" Just some useful Flask stuff for ndb. """ from google.appengine.ext import ndb from flask import g from app import app def put_later(*objs): """ Any ndb model instances passed to this method will be put after the flask request has been processed. """ for obj in objs: if obj not in g.dirty...
""" Just some useful Flask stuff for ndb. """ from google.appengine.ext import ndb from flask import g from app import app def put_later(*objs): """ Any ndb model instances passed to this method will be put after the flask request has been processed. """ for obj in objs: if obj not in g.dirty...
Fix bug where dirty_ndb was silently failing.
Fix bug where dirty_ndb was silently failing.
Python
apache-2.0
kkinder/GAEStarterKit,kkinder/GAEStarterKit,kkinder/GAEStarterKit
545fef9216559d08f58f7e20082b36352203a8cf
python/decorators.py
python/decorators.py
def passive(cls): passive_note = ''' .. note:: This object is a "passive" object. Any changes you make to it will not be reflected in the core and vice-versa. If you wish to update a core version of this object you should use the appropriate API. ''' if hasattr(cls, "__doc__") and cls.__doc__: cls.__doc__ += pas...
def passive(cls): passive_note = ''' .. note:: This object is a "passive" object. Any changes you make to it will not be reflected in the core and vice-versa. If you wish to update a core version of this object you should use the appropriate API. ''' if hasattr(cls, "__doc__") and cls.__doc__: cls.__doc__ += pas...
Add documentaiton decorator for Enterprise.
Add documentaiton decorator for Enterprise.
Python
mit
Vector35/binaryninja-api,Vector35/binaryninja-api,Vector35/binaryninja-api,Vector35/binaryninja-api,Vector35/binaryninja-api,Vector35/binaryninja-api,Vector35/binaryninja-api
73e15928a8427eb5a6e4a886660b9493e50cd699
currencies/models.py
currencies/models.py
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1, blank=True) factor = models.DecimalF...
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1, blank=True) factor = models.DecimalF...
Add a Currency.is_base field (currently unused)
Add a Currency.is_base field (currently unused)
Python
bsd-3-clause
pathakamit88/django-currencies,panosl/django-currencies,ydaniv/django-currencies,mysociety/django-currencies,panosl/django-currencies,barseghyanartur/django-currencies,bashu/django-simple-currencies,pathakamit88/django-currencies,ydaniv/django-currencies,marcosalcazar/django-currencies,jmp0xf/django-currencies,racitup/...
d6a020778343567e671a671ca9fd5b40eed1ee9c
rename-pdf.py
rename-pdf.py
#!/usr/bin/env python __author__ = 'Jacob Bieker' import os DATA_DIRECTORY = os.path.join("test_file") DATA = os.listdir(DATA_DIRECTORY) file_name_dict = {} for file_name in DATA: split_name = file_name.split("_") print split_name file_name_dict.setdefault(split_name[0], []) # Name has the extra _NUM e...
#!/usr/bin/env python __author__ = 'Jacob Bieker' import os DATA_DIRECTORY = os.path.join("test_file") DATA = os.listdir(DATA_DIRECTORY) file_name_dict = {} for file_name in DATA: split_name = file_name.split("_") print split_name file_name_dict.setdefault(split_name[0], []) # Name has the extra _NUM e...
Add renaming file to correct file name
Add renaming file to correct file name
Python
apache-2.0
UO-SPUR/misc
512e6aac47e1fc73837a16b24024081e1407220b
kolla/common/task.py
kolla/common/task.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
Replace abc.abstractproperty with property and abc.abstractmethod
Replace abc.abstractproperty with property and abc.abstractmethod Replace abc.abstractproperty with property and abc.abstractmethod, as abc.abstractproperty has been deprecated since python3.3[1] [1]https://docs.python.org/3.8/whatsnew/3.3.html?highlight=deprecated#abc Change-Id: Ibb048b879fa58b5e144ae228628b3ffaeae...
Python
apache-2.0
openstack/kolla,openstack/kolla
f1a2991ed8ff463255ad6a254fe049ffd1cbc46e
workshopvenues/venues/models.py
workshopvenues/venues/models.py
from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10...
from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10...
Add migration for new fields in Venue
Add migration for new fields in Venue
Python
bsd-3-clause
andreagrandi/workshopvenues
fae33cf7d42559384deb7a9949f47b0881b0a29b
Cython/Tests/TestCythonUtils.py
Cython/Tests/TestCythonUtils.py
import unittest from ..Utils import build_hex_version class TestCythonUtils(unittest.TestCase): def test_build_hex_version(self): self.assertEqual('0x001D00A1', build_hex_version('0.29a1')) self.assertEqual('0x001D00A1', build_hex_version('0.29a1')) self.assertEqual('0x001D03C4', build_hex...
import unittest from ..Utils import build_hex_version class TestCythonUtils(unittest.TestCase): def test_build_hex_version(self): self.assertEqual('0x001D00A1', build_hex_version('0.29a1')) self.assertEqual('0x001D03C4', build_hex_version('0.29.3rc4')) self.assertEqual('0x001D00F0', build_...
Remove accidentally duplicated test code.
Remove accidentally duplicated test code.
Python
apache-2.0
da-woods/cython,scoder/cython,da-woods/cython,cython/cython,scoder/cython,scoder/cython,da-woods/cython,cython/cython,scoder/cython,cython/cython,da-woods/cython,cython/cython
c1de1a5406de7e36b3a36f5591aa16f315b1e368
opps/images/models.py
opps/images/models.py
# -*- coding: utf-8 -*- import uuid import os from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from taggit.managers import TaggableManager from opps.core.models import Publishable def get_file_path(instance, filenam...
# -*- coding: utf-8 -*- import uuid import os from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from taggit.models import TaggedItemBase from taggit.managers import TaggableManager from opps.core.models import Publisha...
Create TaggedImage, unique marker for image
Create TaggedImage, unique marker for image
Python
mit
YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps
d91d6951c146ba4611d1b3869cbc08d396facd54
collections/set.py
collections/set.py
# Set #Removes the duplicates from the given group of values to create the set. flight_set = {500,520,600,345,520,634,600,500,200,200} print("Flight Set : ", flight_set) # Converting List into Set passengers_list=["George", "Annie", "Jack", "Annie", "Henry", "Helen", "Maria", "George", "Jack", "Remo"] unique_passenger...
# Set #Removes the duplicates from the given group of values to create the set. flight_set = {500,520,600,345,520,634,600,500,200,200} print("Flight Set : ", flight_set) # Converting List into Set passengers_list=["George", "Annie", "Jack", "Annie", "Henry", "Helen", "Maria", "George", "Jack", "Remo"] unique_passenger...
Set with add, update, discard, remove, union, intersection, difference
Set with add, update, discard, remove, union, intersection, difference
Python
mit
pk-python/basics
51caae36a10cf5616982c78506c5dcec593259a3
test_suite.py
test_suite.py
import os os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.core import management apps = [ 'test', 'core', 'exporting', 'formatters', 'lexicon', 'events', 'history', 'models', 'query', 'sets', 'stats', 'search', 'subcommands', 'validation', ]...
import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.core import management apps = sys.argv[1:] if not apps: apps = [ 'core', 'exporting', 'formatters', 'lexicon', 'events', 'history', 'models', 'query', ...
Allow apps to be specified from the command line
Allow apps to be specified from the command line
Python
bsd-2-clause
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
74af1019c7a21b69586ee55af2fa4ded6fe2eb03
refmanage/__init__.py
refmanage/__init__.py
# -*- coding: utf-8 -*- """ =============================== Base Library (:mod:`refmanage`) =============================== .. currentmodule:: refmanage """ from version import __version__ from fs_utils import *
# -*- coding: utf-8 -*- """ =============================== Base Library (:mod:`refmanage`) =============================== .. currentmodule:: refmanage """ from version import __version__ import fs_utils
Fix import into refmanage namespace
Fix import into refmanage namespace
Python
mit
jrsmith3/refmanage
9b8d18d52ef6ddd5009a448bcaf003435b387e72
wake/views.py
wake/views.py
from been.couch import CouchStore from flask import render_template from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events())
from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) ...
Add by_slug view for single events.
Add by_slug view for single events.
Python
bsd-3-clause
chromakode/wake
76c9b7e8e8e6836ad73c81610a82ee2098cea026
tests/main/views/test_status.py
tests/main/views/test_status.py
from tests.bases import BaseApplicationTest class TestStatus(BaseApplicationTest): def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code == 200
from tests.bases import BaseApplicationTest from sqlalchemy.exc import SQLAlchemyError import mock class TestStatus(BaseApplicationTest): def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code ==...
Test coverage for SQLAlchemyError handling in status view
Test coverage for SQLAlchemyError handling in status view
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
5514450bbc72ad9ed181a79ffc546ba8015b5fd0
vcs/models.py
vcs/models.py
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_...
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_...
Use a OneToMany field for the activity joiner.
Use a OneToMany field for the activity joiner.
Python
bsd-3-clause
AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker
8c68e23dc95bd77b1ccf9e8c989caa4673620fab
wallace/db.py
wallace/db.py
"""Create a connection to the database.""" from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base import os db_url = os.environ.get("DATABASE_URL", "postgresql://postgres@localhost/wallace") engine = create_engine(db_url) Se...
"""Create a connection to the database.""" from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base import os db_url = os.environ.get("DATABASE_URL", "postgresql://postgres@localhost/wallace") engine = create_engine(db_url, po...
Allow a pool size of 100
Allow a pool size of 100
Python
mit
berkeley-cocosci/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,suchow/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,suchow/Wallace,suchow/Wal...
515e3b4da9d8c793c57e8cb8deeda93e42aa3871
nereid/ctx.py
nereid/ctx.py
#This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. from flask.ctx import RequestContext as RequestContextBase from flask.ctx import has_request_context # noqa class RequestContext(RequestContextBase): """ The r...
#This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. from flask.ctx import RequestContext as RequestContextBase from flask.ctx import has_request_context # noqa class RequestContext(RequestContextBase): """ The r...
Add request argument for RequestContext
Add request argument for RequestContext See: cb2055bbcb345e367b6bdfe177a407546286695c@097353695e3178a38403b204ae4889c8a32bf997
Python
bsd-3-clause
riteshshrv/nereid,fulfilio/nereid,riteshshrv/nereid,fulfilio/nereid,usudaysingh/nereid,prakashpp/nereid,usudaysingh/nereid,prakashpp/nereid
d5bca737d19f7bfd34fd37d00f1210f8bc777c76
crmapp/accounts/views.py
crmapp/accounts/views.py
from django.shortcuts import render # Create your views here.
from django.views.generic import ListView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .models import Account class AccountList(ListView): model = Account template_name = 'accounts/account_list.html' context_object_name = 'accounts' ...
Create the Account List > List Accounts - Create View
Create the Account List > List Accounts - Create View
Python
mit
tabdon/crmeasyapp,tabdon/crmeasyapp,deenaariff/Django
6b15bf92f8995542361ce1fe57f7b101f9ceba5e
flask_jsonapi/filters_schema.py
flask_jsonapi/filters_schema.py
import contextlib import flask class FilterSchema: def __init__(self, fields: dict): self.fields = fields def parse(self): result = {} for name, field in self.fields.items(): with contextlib.suppress(KeyError): result[name] = field.parse(name) retu...
import contextlib import flask from flask_jsonapi import exceptions class FilterSchema: def __init__(self, fields: dict): self.fields = fields def parse(self): result = {} for name, field in self.fields.items(): with contextlib.suppress(KeyError): result[...
Return jsonapi error when parsing filters failed.
Return jsonapi error when parsing filters failed. Change-Id: I4bd26823d9e29b31ab8fdc47b8ef2bb65071d27b Reviewed-on: https://review.socialwifi.com/14069 Reviewed-by: Piotr Maliński <5f24252672783b9dd319151f284628d8f524ff27@socialwifi.com> Tested-by: Jakub Skiepko <27b910087fee73ba587f81728e9a4e87eb24c8cc@socialwifi.com...
Python
bsd-3-clause
maruqu/flask-jsonapi
3c901a198f6396a0c48a0766618b9971e795530f
board/views.py
board/views.py
from django.core.urlresolvers import reverse from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView from board.forms import PostCreateForm from board.mixins import BoardMixin, UserLoggingMixin from board.models import Board, Po...
from django.core.urlresolvers import reverse from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView from board.forms import PostCreateForm from board.mixins import BoardMixin, UserLoggingMixin from board.models import Board, Po...
Add filtering and ordering to PostListView
Add filtering and ordering to PostListView
Python
mit
devunt/hydrocarbon,devunt/hydrocarbon,devunt/hydrocarbon
d0feed675897570d92eeb7b801b8ba094171bee0
send_email.py
send_email.py
import smtplib from email.mime.text import MIMEText def process_email(data): table_template = open('table_template.html', 'r').read() same_guild_html = [] for game in data['same_guild']: tt = table_template same_guild_html.append(tt.format(**game)) games_html = [] for game in dat...
import datetime import smtplib from email.mime.text import MIMEText def process_email(data): table_template = open('table_template.html', 'r').read() same_guild_html = [] for game in data['same_guild']: tt = table_template same_guild_html.append(tt.format(**game)) games_html = [] ...
Update email subject with datetime so as to not have it end up in a thread in email client.
Update email subject with datetime so as to not have it end up in a thread in email client.
Python
agpl-3.0
v01d-cypher/kgs_league_scorer,v01d-cypher/kgs_league_scorer
198d1d8827ffc04bf7f33e99bc929a33c8a7ba8c
src/sana/core/models/__init__.py
src/sana/core/models/__init__.py
""" Data models for the core Sana data engine. These should be extended as required. :Authors: Sana dev team :Version: 2.0 """ from sana.core.models.concept import Concept, Relationship, RelationshipCategory from sana.core.models.device import Device from sana.core.models.encounter import Encounter from sana.core.m...
""" Data models for the core Sana data engine. These should be extended as required. :Authors: Sana dev team :Version: 2.0 """ from .concept import Concept, Relationship, RelationshipCategory from .device import Device from .encounter import Encounter from .events import Event from .notification import Notification...
Update to use relative imports.
Update to use relative imports.
Python
bsd-3-clause
SanaMobile/sana.mds,rryan/sana.mds,SanaMobile/sana.mds,SanaMobile/sana.mds,rryan/sana.mds,SanaMobile/sana.mds
5531cac216918d4482858b5eb487003c67c96406
bluebottle/auth/tests/test_api.py
bluebottle/auth/tests/test_api.py
import json import mock from rest_framework import status from bluebottle.test.utils import BluebottleTestCase from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from django.core.urlresolvers import reverse class UserTokenTestCase(BluebottleTestCase): def setUp(self): super(UserTo...
import json import mock from rest_framework import status from bluebottle.test.utils import BluebottleTestCase from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from django.core.urlresolvers import reverse class UserTokenTestCase(BluebottleTestCase): def setUp(self): super(UserTo...
Add tests for API login
Add tests for API login
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
622e1e780b84a8e04c5af2d6758fb457ff92ea93
polymorphic/formsets/utils.py
polymorphic/formsets/utils.py
""" Internal utils """ import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. Only required for Django < 2.0 """ if django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._j...
""" Internal utils """ import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, ...
Fix media-combining in formsets on Django 2.2
Fix media-combining in formsets on Django 2.2
Python
bsd-3-clause
chrisglass/django_polymorphic,chrisglass/django_polymorphic
3cbe02f1a5410148269113f7b8f41949086c9ac1
instance/tasks.py
instance/tasks.py
# -*- encoding: utf-8 -*- # # Copyright (c) 2015, OpenCraft # # Imports ##################################################################### from pprint import pprint from django.conf import settings from huey.djhuey import task from .ansible import run_ansible_playbook, get_inventory_str, get_vars_str from .gandi...
# -*- encoding: utf-8 -*- # # Copyright (c) 2015, OpenCraft # # Imports ##################################################################### from pprint import pprint from django.conf import settings from huey.djhuey import task from .ansible import run_ansible_playbook, get_inventory_str, get_vars_str from .gandi...
Return command output log in `create_sandbox_instance()`
Return command output log in `create_sandbox_instance()`
Python
agpl-3.0
brousch/opencraft,omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,brousch/opencraft,open-craft/opencraft,omarkhan/opencraft,open-craft/opencraft,omarkhan/opencraft,brousch/opencraft,open-craft/opencraft,open-craft/opencraft
20115684ea5ab52e0c51f43fd85aa9945560d103
interleave-pdf.py
interleave-pdf.py
import PyPDF2 from formlayout import fedit def main(): paths = [('Input', ''), ('Output', '')] pathsRead = fedit(paths, title="Interleave pdf", comment="Enter the full path to the source pdf and a path to output the result." ) # Full path to files should be...
import PyPDF2 from tkinter import * from tkinter.filedialog import askopenfilename from tkinter.filedialog import asksaveasfilename class Application(Frame): def __init__(self): self.input_path = None; self.output_path = None; Frame.__init__(self) self.master.resizable(False, False) self.master.title('Int...
Replace formlayout GUI with tkinter
Replace formlayout GUI with tkinter Separate buttons for selecting input and output, and for running the interleave procedure.
Python
mit
sproberts92/interleave-pdf
89af0ed8bf7f62f6a48d7dd5b09a3fa46a2cf9c7
spyder_terminal/__init__.py
spyder_terminal/__init__.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Spyder Te...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Spyder Te...
Set release version to v0.2.3
Set release version to v0.2.3
Python
mit
andfoy/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal
232f2961d8ff26f7263df5ab59c8b36ac8bd9b43
stars/serializers.py
stars/serializers.py
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer)...
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer)...
Replace subcategory__ prefix to endpoint response field names.
Replace subcategory__ prefix to endpoint response field names.
Python
apache-2.0
belatrix/BackendAllStars
aa4a032016944f581ad7485ebdf8c39108511098
commandbased/commandbasedrobot.py
commandbased/commandbasedrobot.py
import hal from wpilib.timedrobot import TimedRobot from wpilib.command.scheduler import Scheduler from wpilib.livewindow import LiveWindow class CommandBasedRobot(TimedRobot): ''' The base class for a Command-Based Robot. To use, instantiate commands and trigger them. ''' def startCompetition(s...
from wpilib import TimedRobot from wpilib.command import Scheduler class CommandBasedRobot(TimedRobot): ''' The base class for a Command-Based Robot. To use, instantiate commands and trigger them. ''' def startCompetition(self): """Initalizes the scheduler before starting robotInit()""" ...
Remove LiveWindow call from CommandBasedRobot
Remove LiveWindow call from CommandBasedRobot LiveWindow is automatically updated regardless of mode as part of 2018 WPILib IterativeRobot changes, so calling LiveWindow.run() manually is unnecessary.
Python
bsd-3-clause
robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities
a8fcd8c56db0ce862c6c0ac79fc58a9e65992f6e
onlineweb4/context_processors.py
onlineweb4/context_processors.py
from django.conf import settings from apps.feedback.models import FeedbackRelation def context_settings(request): context_extras = {} if hasattr(settings, 'GOOGLE_ANALYTICS_KEY'): context_extras['GOOGLE_ANALYTICS_KEY'] = settings.GOOGLE_ANALYTICS_KEY if hasattr(settings, 'HOT_RELOAD'): con...
# -*- coding: utf-8 -*- from django.conf import settings from django.utils import timezone from apps.feedback.models import FeedbackRelation def context_settings(request): context_extras = {} if hasattr(settings, 'GOOGLE_ANALYTICS_KEY'): context_extras['GOOGLE_ANALYTICS_KEY'] = settings.GOOGLE_ANALYT...
Add more constraints to active feedback schemas
Add more constraints to active feedback schemas
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
175c1775aa7f5cd0ba2022e95389507d8a4c87dc
syncplay/__init__.py
syncplay/__init__.py
version = '1.6.6' revision = ' development' milestone = 'Yoitsu' release_number = '87' projectURL = 'https://syncplay.pl/'
version = '1.6.6' revision = ' beta 1' milestone = 'Yoitsu' release_number = '88' projectURL = 'https://syncplay.pl/'
Mark as 1.6.6 beta 1
Mark as 1.6.6 beta 1
Python
apache-2.0
alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,alby128/syncplay
1c7928a5aeff55518bfda2b9a9ef1ec2a2ef76e4
corehq/celery_monitoring/tests.py
corehq/celery_monitoring/tests.py
from __future__ import absolute_import from __future__ import print_function import datetime from freezegun import freeze_time from corehq.celery_monitoring.heartbeat import Heartbeat, HeartbeatNeverRecorded, \ HEARTBEAT_FREQUENCY from testil import assert_raises, eq def test_heartbeat(): hb = Heartbeat('c...
from __future__ import absolute_import from __future__ import print_function import datetime from freezegun import freeze_time from corehq.celery_monitoring.heartbeat import Heartbeat, HeartbeatNeverRecorded, \ HEARTBEAT_FREQUENCY from testil import assert_raises, eq from corehq.celery_monitoring.signals import...
Add simple test for celery time to start timer
Add simple test for celery time to start timer
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
fa4e6e849eaff2611a5d978c7f7727a16a8c301e
daedalus/attacks/sample_attack.py
daedalus/attacks/sample_attack.py
# This file should serve as a template # We will be importing all such files into daedalus from which any attack can be then called with required input ########################################################################### # attack(input={}) # This function will be called from with daedalus.py # along with the r...
# This file should serve as a template # We will be importing all such files into daedalus from which any attack can be then called with required input ########################################################################### # attack(input={}) # This function will be called from with daedalus.py # along with the r...
Remove extra parameters to "attack()"
Remove extra parameters to "attack()" The `results` and `errors` structures aren't needed as input parameters. All we need to ensure is that these are returned by `attack()`.
Python
mit
IEEE-NITK/Daedalus,IEEE-NITK/Daedalus,chinmaydd/NITK_IEEE_SaS,IEEE-NITK/Daedalus
66cc9d8c6f91378fadbbc3e40fe4397e43b7b757
mopidy/frontends/mpd/__init__.py
mopidy/frontends/mpd/__init__.py
import logging from mopidy.frontends.base import BaseFrontend from mopidy.frontends.mpd.dispatcher import MpdDispatcher from mopidy.frontends.mpd.thread import MpdThread from mopidy.utils.process import unpickle_connection logger = logging.getLogger('mopidy.frontends.mpd') class MpdFrontend(BaseFrontend): """ ...
import logging from mopidy.frontends.base import BaseFrontend from mopidy.frontends.mpd.dispatcher import MpdDispatcher from mopidy.frontends.mpd.thread import MpdThread from mopidy.utils.process import unpickle_connection logger = logging.getLogger('mopidy.frontends.mpd') class MpdFrontend(BaseFrontend): """ ...
Allow reply_to to not be set in messages to the MPD frontend
Allow reply_to to not be set in messages to the MPD frontend
Python
apache-2.0
vrs01/mopidy,dbrgn/mopidy,bencevans/mopidy,swak/mopidy,diandiankan/mopidy,tkem/mopidy,glogiotatidis/mopidy,priestd09/mopidy,dbrgn/mopidy,abarisain/mopidy,vrs01/mopidy,swak/mopidy,jmarsik/mopidy,ali/mopidy,vrs01/mopidy,priestd09/mopidy,SuperStarPL/mopidy,mopidy/mopidy,liamw9534/mopidy,pacificIT/mopidy,bencevans/mopidy,w...
98bd24100097473ac771dd08b19640f30970a62d
chainerrl/explorers/additive_gaussian.py
chainerrl/explorers/additive_gaussian.py
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import numpy as np from chainerrl import explorer class A...
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import numpy as np from chainerrl import explorer class A...
Add low and high to docstring and __repr__
Add low and high to docstring and __repr__
Python
mit
toslunar/chainerrl,toslunar/chainerrl
39a534d380afea37231cc0c2ca4c8a742354d6e1
app.py
app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template from sh import git app = Flask(__name__) version = git("rev-parse", "--short", "HEAD").strip() @app.route("/", methods=["GET"]) def status(): """ Status check. Display the current version of heatlamp, some basic diag...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from flask import Flask, render_template from sh import git app = Flask(__name__) version = git("rev-parse", "--short", "HEAD").strip() command = os.getenv("HEATLAMP_COMMAND") def validate(): """ Validate the application configuration befor...
Configure the command that's executed.
Configure the command that's executed.
Python
mit
heatlamp/heatlamp-core,heatlamp/heatlamp-core
603fccbbdda5fa45dcc84421901fec085fffcb81
test/test_general.py
test/test_general.py
import hive import threading import time import sys import worker # import pash from another directory import pash class ErrWorker(worker.Worker): def work(self, command): proc = pash.ShellProc() proc.run(command) return "Exit code: %s" % proc.get_val('exit_code') def test(): apiary = hive.Hive() apiary.crea...
import threading import time import sys from busybees import worker from busybees import hive import pash class ErrWorker(worker.Worker): def work(self, command): proc = pash.ShellProc() proc.run(command) return "Exit code: %s" % proc.get_val('exit_code') def test(): apiary = hive.Hive() apiary.create_quee...
Change imports to work with new scheme
Change imports to work with new scheme
Python
bsd-3-clause
iansmcf/busybees
abb23c47f503197e005637ce220a07975dc01094
recipes/spyder-line-profiler/run_test.py
recipes/spyder-line-profiler/run_test.py
from xvfbwrapper import Xvfb vdisplay = Xvfb() vdisplay.start() import spyder_line_profiler vdisplay.stop()
""" Test whether spyder_line_profiler is installed The test is only whether the module can be found. It does not attempt to import the module because this needs an X server. """ import imp imp.find_module('spyder_line_profiler')
Use imp.find_module in test for spyder-line-profiler
Use imp.find_module in test for spyder-line-profiler
Python
bsd-3-clause
jjhelmus/staged-recipes,igortg/staged-recipes,petrushy/staged-recipes,Cashalow/staged-recipes,patricksnape/staged-recipes,conda-forge/staged-recipes,NOAA-ORR-ERD/staged-recipes,petrushy/staged-recipes,synapticarbors/staged-recipes,grlee77/staged-recipes,larray-project/staged-recipes,shadowwalkersb/staged-recipes,patric...
4ff1eb00f8e212d280ac858feb4efcc795d97d80
tests/test_models.py
tests/test_models.py
import pytest from suddendev.models import GameController def test_create_game(session): pass
import pytest from suddendev.models import GameSetup def test_create_game(session): game_setup = GameSetup('ASDF') assert game_setup.player_count == 1
Fix broken import in model tests.
[NG] Fix broken import in model tests.
Python
mit
SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev
9e413449f6f85e0cf9465762e31e8f251e14c23e
spacy/tests/regression/test_issue1537.py
spacy/tests/regression/test_issue1537.py
'''Test Span.as_doc() doesn't segfault''' from ...tokens import Doc from ...vocab import Vocab from ... import load as load_spacy def test_issue1537(): string = 'The sky is blue . The man is pink . The dog is purple .' doc = Doc(Vocab(), words=string.split()) doc[0].sent_start = True for word in doc[...
'''Test Span.as_doc() doesn't segfault''' from __future__ import unicode_literals from ...tokens import Doc from ...vocab import Vocab from ... import load as load_spacy def test_issue1537(): string = 'The sky is blue . The man is pink . The dog is purple .' doc = Doc(Vocab(), words=string.split()) doc[0...
Fix unicode error in new test
Fix unicode error in new test
Python
mit
spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/sp...
df9dc6f613916cd96f626e2b337f8d9fe15bb864
tests/test_cayley_client.py
tests/test_cayley_client.py
from unittest import TestCase from pyley import CayleyClient, GraphObject class CayleyClientTests(TestCase): def test_send(self): client = CayleyClient() g = GraphObject() query = g.V().Has("name", "Casablanca") \ .Out("/film/film/starring") \ .Out("/film/performanc...
from unittest import TestCase import unittest from pyley import CayleyClient, GraphObject class CayleyClientTests(TestCase): @unittest.skip('Disabled for now!') def test_send(self): client = CayleyClient() g = GraphObject() query = g.V().Has("name", "Casablanca") \ .Out("/f...
Add skip attribute for CayleyClient send test.
Add skip attribute for CayleyClient send test.
Python
unlicense
ziyasal/pyley,ziyasal/pyley,joshainglis/pyley,joshainglis/pyley
0a9f2d46325ce6856a3979127390f2e48357abd9
schedule2stimuli.py
schedule2stimuli.py
#!/usr/bin/python import csv import pprint p = 0 # read schedule (from SCRT) schedule_f = 'schedule_' + str(p) inf = open(schedule_f,'r') for line in inf.readlines(): line = line.rstrip() schedule = line.split(' ') inf.close() # allocate stimuli a = 0 b = [] phase = '' for session in range(1,36): print ...
#!/usr/bin/python import csv import pprint p = 0 # read schedule (from SCRT) schedule_f = 'schedule_' + str(p) inf = open(schedule_f,'r') for line in inf.readlines(): line = line.rstrip() schedule = line.split(' ') inf.close() # allocate stimuli and write csv a = 0 b = [] phase = '' csvfile = ...
Write stimuli schedule to csv file.
Write stimuli schedule to csv file.
Python
cc0-1.0
earcanal/dotprobe,earcanal/dotprobe,earcanal/dotprobe
0dfc3ab0537757bb5e4b5cc6918024c4ea75ed94
fs/archive/opener.py
fs/archive/opener.py
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import contextlib from pkg_resources import iter_entry_points from ..opener import open_fs from ..opener._errors import Unsupported from ..path import basename @contextlib.contextmanager def open_archive(fs_url, archive): ...
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import contextlib from pkg_resources import iter_entry_points from ..opener import open_fs from ..opener._errors import Unsupported from ..path import basename @contextlib.contextmanager def open_archive(fs_url, archive): ...
Patch binfile name only when needed in open_archive
Patch binfile name only when needed in open_archive
Python
mit
althonos/fs.archive
f061499b9d415b7471edf072c81b93ce5453494d
githubtrending/utils.py
githubtrending/utils.py
import os def get_console_size(): ''' returns no of rows, no of cols ''' return map(int, os.popen('stty size', 'r').read().split()) def get_print_size_for_repo(data): name, lang, star = [0]*3 for each in data: repo_name, desc, [stars, language] = each name = max(len(repo_name...
import os def get_console_size(): ''' returns no of rows, no of cols ''' with os.popen('stty size', 'r') as f: size = map(int, f.read().split()) return size def get_print_size_for_repo(data): name, lang, star = [0]*3 for each in data: repo_name, desc, [stars, language] = e...
Refactor get_console_size to close file after reading
Utils: Refactor get_console_size to close file after reading
Python
mit
staranjeet/github-trending-cli
237b66c8b9cef714b64a75b1f20a79a4357c71b5
apps/continiousauth/serializers.py
apps/continiousauth/serializers.py
from rest_framework import serializers from .models import AuthenticationSession class AuthenticationSessionSerializer(serializers.ModelSerializer): class Meta: model = AuthenticationSession fields = ('application', 'external_session_id', 'session_photo_bytes', 'flag', 'start_time', 'end_time')
from rest_framework import serializers from .models import AuthenticationSession class AuthenticationSessionSerializer(serializers.ModelSerializer): class Meta: model = AuthenticationSession fields = ('application', 'external_session_id', 'session_photo_bytes', 'flag')
Change serializer to omit dates
Change serializer to omit dates
Python
mit
larserikgk/mobiauth-server,larserikgk/mobiauth-server,larserikgk/mobiauth-server
dbb668c3f72ab6d20abe08f9f23b7d66cfa0d8c3
ideascube/blog/forms.py
ideascube/blog/forms.py
from django import forms from ideascube.widgets import LangSelect from .models import Content class ContentForm(forms.ModelForm): class Meta: model = Content widgets = { # We need a normalized date string for JS datepicker, so we take # control over the format to bypass ...
from django import forms from ideascube.widgets import LangSelect from .models import Content class ContentForm(forms.ModelForm): use_required_attribute = False class Meta: model = Content widgets = { # We need a normalized date string for JS datepicker, so we take #...
Fix the blog content form
Fix the blog content form The form plays a trick on the 'text' field: it hides it, and creates a nicer-looking 'content' field. When submitting the form, the content of the 'content' field is injected into the 'text' field. This works great, until Django 1.10. With Django 1.10, the browser refuses to submit the form...
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
2d0901eb60302750cd42007241d4e0f6010bea7c
pypeerassets/provider/rpcnode.py
pypeerassets/provider/rpcnode.py
'''Communicate with local or remote peercoin-daemon via JSON-RPC''' from operator import itemgetter try: from peercoin_rpc import Client except: raise EnvironmentError("peercoin_rpc library is required for this to work,\ use pip to install it.") def select_inputs(cls, total_amoun...
'''Communicate with local or remote peercoin-daemon via JSON-RPC''' from operator import itemgetter try: from peercoin_rpc import Client except: raise EnvironmentError("peercoin_rpc library is required for this to work,\ use pip to install it.") def select_inputs(cls, total_amoun...
Return dict with selected utxo list and total
Return dict with selected utxo list and total
Python
bsd-3-clause
backpacker69/pypeerassets,PeerAssets/pypeerassets
c3792ccdde5a44979f34d84cebad722c7a64ab64
juliet_importer.py
juliet_importer.py
import os import imp modules = {} def load_modules(path="./modules/"): # Consider adding recursive sorting at some point in the future names = os.listdir(path) for name in names: if not name.endswith(".py"): continue print("Importing module {0}".format(name)) name = name.split('.')[0] ...
import os import imp modules = {} def load_modules(path="./modules/"): # Consider adding recursive searching at some point in the future modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py") names = os.listdir(path) for name in names: if not name.endswith(".py"): c...
Change juliet_module to load before other modules for dependency reasons
Change juliet_module to load before other modules for dependency reasons
Python
bsd-2-clause
halfbro/juliet
33ceea40e41d9f568b11e30779b8b7c16ba8f5b8
bench/split-file.py
bench/split-file.py
""" Split out a monolithic file with many different runs of indexed_search.py. The resulting files are meant for use in get-figures.py. Usage: python split-file.py prefix filename """ import sys prefix = sys.argv[1] filename = sys.argv[2] f = open(filename) sf = None for line in f: if line.startswith('Processing...
""" Split out a monolithic file with many different runs of indexed_search.py. The resulting files are meant for use in get-figures.py. Usage: python split-file.py prefix filename """ import sys prefix = sys.argv[1] filename = sys.argv[2] f = open(filename) sf = None for line in f: if line.startswith('Processing...
Support for splitting outputs for PyTables and Postgres indexing benchmarks all in one.
Support for splitting outputs for PyTables and Postgres indexing benchmarks all in one. git-svn-id: 92c705c98a17f0f7623a131b3c42ed50fcde59b4@2885 1b98710c-d8ec-0310-ae81-f5f2bcd8cb94
Python
bsd-3-clause
jennolsen84/PyTables,rabernat/PyTables,avalentino/PyTables,jack-pappas/PyTables,rdhyee/PyTables,gdementen/PyTables,joonro/PyTables,PyTables/PyTables,mohamed-ali/PyTables,andreabedini/PyTables,tp199911/PyTables,jennolsen84/PyTables,tp199911/PyTables,dotsdl/PyTables,cpcloud/PyTables,tp199911/PyTables,FrancescAlted/PyTabl...
ba026f431ca7196a489dd1157af0c58972fe2356
localore/people/wagtail_hooks.py
localore/people/wagtail_hooks.py
from django.utils.html import format_html from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('profile_photo', 'full_name', '...
from django.utils.html import format_html from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('profile_photo', 'full_name', '...
Fix people list breaking due to deleted photo.
Fix people list breaking due to deleted photo.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
a8b4409dd2261edea536f3e8080b90a770eccf70
mediacloud/mediawords/tm/mine.py
mediacloud/mediawords/tm/mine.py
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def po...
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def po...
Add LIMIT 1 to speed up query
Add LIMIT 1 to speed up query
Python
agpl-3.0
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
5d0df4c15bc28cba8b7c766f3e5bd63a27f8d5b7
tflitehub/lit.cfg.py
tflitehub/lit.cfg.py
import os import sys import lit.formats import lit.util import lit.llvm # Configuration file for the 'lit' test runner. lit.llvm.initialize(lit_config, config) # name: The name of this test suite. config.name = 'TFLITEHUB' config.test_format = lit.formats.ShTest() # suffixes: A list of file extensions to treat as...
import os import sys import lit.formats import lit.util import lit.llvm # Configuration file for the 'lit' test runner. lit.llvm.initialize(lit_config, config) # name: The name of this test suite. config.name = 'TFLITEHUB' config.test_format = lit.formats.ShTest() # suffixes: A list of file extensions to treat as...
Add coco_test_data.py to lit ignore list
Add coco_test_data.py to lit ignore list
Python
apache-2.0
iree-org/iree-samples,iree-org/iree-samples,iree-org/iree-samples,iree-org/iree-samples
6bc11ea44c07cddd567a5039b9442a95e9ce04fe
comics/crawler/utils/lxmlparser.py
comics/crawler/utils/lxmlparser.py
#encoding: utf-8 from lxml.html import parse, fromstring class LxmlParser(object): def __init__(self, url=None, string=None): if url: self.root = parse(url).getroot() self.root.make_links_absolute(url) elif string: self.root = fromstring(string) def text(se...
#encoding: utf-8 from lxml.html import parse, fromstring class LxmlParser(object): def __init__(self, url=None, string=None): if url is not None: self.root = parse(url).getroot() self.root.make_links_absolute(url) elif string is not None: self.root = fromstring(...
Update exception handling in LxmlParser
Update exception handling in LxmlParser
Python
agpl-3.0
datagutten/comics,klette/comics,klette/comics,jodal/comics,jodal/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics
32789be8f1f98f7538f4452a8118c261037f2d75
tempwatcher/watch.py
tempwatcher/watch.py
import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check...
import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check...
Refactor the initialization a bit to make configuration easier.
Refactor the initialization a bit to make configuration easier.
Python
bsd-3-clause
adamfast/tempwatcher
89804f4d2caeab07b56a90912afc058145620375
jal_stats/stats/views.py
jal_stats/stats/views.py
# from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from rest_framework import viewsets, permissions # , serializers from .models import Stat, Activity from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Crea...
# from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from rest_framework import viewsets, mixins, permissions # , serializers from .models import Stat, Activity # from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializ...
Update StatViewSet to generic, add necessary mixins
Update StatViewSet to generic, add necessary mixins
Python
mit
jal-stats/django
9887b962ddc27f7bebe212e169d1a2c442a35239
ironic_ui/content/ironic/panel.py
ironic_ui/content/ironic/panel.py
# Copyright 2016 Cisco Systems, Inc. # Copyright (c) 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apa...
# Copyright 2016 Cisco Systems, Inc. # Copyright (c) 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apa...
Use permissions attribute to detect ironic service
Use permissions attribute to detect ironic service Horizon implements a logic to enable/disable panel by permissions defined in each panel class. This change replaces the current redundant logic by that built-in feature to simplify how we define requirements of the Ironic panels. Change-Id: I4a9dabfea79c23155fb8986fe...
Python
apache-2.0
openstack/ironic-ui,openstack/ironic-ui,openstack/ironic-ui,openstack/ironic-ui
058882a1d0e4ac458fe8cab972010e17c248ee81
wate/views.py
wate/views.py
from wate import app import db_ops @app.route('/') def index(): users = db_ops.users_everything_get() header = db_ops.COMPLETE_USER_SCHEMA retval = "" # First, print the header for item in header: retval += ( item + ", " ) retval += ( "<br>"*2 ) # Now print each user for use...
from wate import app import db_ops @app.route('/') def index(): users = db_ops.users_everything_get() header = db_ops.COMPLETE_USER_SCHEMA retval = '<table border="1">' # First, print the header retval += '<tr>' for item in header: retval += "<th>{}</th>".format(item) retval += ...
Make a table for the front page
Make a table for the front page
Python
mit
jamesmunns/wate,jamesmunns/wate,jamesmunns/wate
935043dda123a030130571a2a4bb45b2b13f145c
addons/website_quote/__manifest__.py
addons/website_quote/__manifest__.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", 'depends': ['website', 'sale_...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", 'depends': ['website', 'sale_...
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale"
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale" No dependency change in stable version This reverts commit 65a589eb54a1421baa71074701bea2873a83c75f.
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
8b8c7f851b96456e80201295af645066ab8f6fbb
contrib/internal/build-media.py
contrib/internal/build-media.py
#!/usr/bin/env python from __future__ import unicode_literals import os import sys scripts_dir = os.path.abspath(os.path.dirname(__file__)) # Source root directory sys.path.insert(0, os.path.abspath(os.path.join(scripts_dir, '..', '..'))) # Script config directory sys.path.insert(0, os.path.join(scripts_dir, 'conf...
#!/usr/bin/env python from __future__ import unicode_literals import os import sys scripts_dir = os.path.abspath(os.path.dirname(__file__)) # Source root directory sys.path.insert(0, os.path.abspath(os.path.join(scripts_dir, '..', '..'))) # Script config directory sys.path.insert(0, os.path.join(scripts_dir, 'conf...
Fix building static media on Django 1.11.
Fix building static media on Django 1.11. Our wrapper script for building static media attempted to honor the exit code of the `collectstatic` management command, passing it along to `sys.exit()` so that we wouldn't have a failure show up as a successful result. However, exit codes are never returned. Instead, we wer...
Python
mit
reviewboard/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard
a6eaf7d4b43e1bb3177e4eb0e3e288db2d419020
halo/_utils.py
halo/_utils.py
# -*- coding: utf-8 -*- """Utilities for Halo library. """ import platform import six import codecs from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean ...
# -*- coding: utf-8 -*- """Utilities for Halo library. """ import platform import six import codecs import shutil from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- ...
Add shutil dependency to get the terminal size
Add shutil dependency to get the terminal size
Python
mit
manrajgrover/halo,ManrajGrover/halo
9fa562a413900252acd27d6f1b90055df2e95fe2
tests/test_apply.py
tests/test_apply.py
import unittest import cbs class AttrSettings(): PROJECT_NAME = 'fancy_project' class MethodSettings(): def PROJECT_NAME(self): return 'fancy_project' class TestApply(unittest.TestCase): def test_apply_settings_attr(self): g = {} cbs.apply(AttrSettings, g) self.assert...
import unittest import cbs class AttrSettings(): PROJECT_NAME = 'fancy_project' class MethodSettings(): def PROJECT_NAME(self): return 'fancy_project' class TestApply(unittest.TestCase): def test_apply_settings_attr(self): g = {} cbs.apply(AttrSettings, g) self.assert...
Test all the code paths
Test all the code paths
Python
bsd-2-clause
ar45/django-classy-settings,pombredanne/django-classy-settings,tysonclugg/django-classy-settings,funkybob/django-classy-settings
6cc1e7ca79b8730cfd5e0db71dd19aae9848e3d2
mownfish/db/api.py
mownfish/db/api.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lice...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lice...
Modify db client to __new__
Modify db client to __new__ change db singlton from instance() staticmethod to __new__()
Python
apache-2.0
Ethan-Zhang/mownfish
158b37b1bd45eb1f554386e4866820296f8ea537
metal/label_model/lm_defaults.py
metal/label_model/lm_defaults.py
lm_default_config = { ### GENERAL 'seed': None, 'verbose': True, 'show_plots': True, ### TRAIN 'train_config': { # Classifier # Class balance (if learn_class_balance=False, fix to class_balance) 'learn_class_balance': False, # Class balance initialization / p...
lm_default_config = { ### GENERAL 'seed': None, 'verbose': True, 'show_plots': True, ### TRAIN 'train_config': { # Classifier # Class balance (if learn_class_balance=False, fix to class_balance) 'learn_class_balance': False, # Class balance initialization / p...
Remove l2 from lm_default_config since it is currently unused
Remove l2 from lm_default_config since it is currently unused
Python
apache-2.0
HazyResearch/metal,HazyResearch/metal
d33d059821e391fcf34630cfb3ea8d67a0c6ec59
tests/test_views.py
tests/test_views.py
import unittest from mongows import views from tests import MongoWSTestCase class ViewsTestCase(MongoWSTestCase): def test_hello(self): rv = self.app.get('/') self.assertTrue('Hello World!' in rv.data)
import unittest from mongows import views from tests import MongoWSTestCase class ViewsTestCase(MongoWSTestCase): def test_hello(self): rv = self.app.get('/') self.assertTrue('Hello World!' in rv.data) def test_create_mws_resource(self): url = '/mws' rv = self.app.post(url) ...
Add stub unit tests for stub views funcs.
Views: Add stub unit tests for stub views funcs.
Python
apache-2.0
ecbtln/mongo-web-shell,xl76/mongo-web-shell,ecbtln/mongo-web-shell,FuegoFro/mongo-web-shell,mongodb-labs/mongo-web-shell,10gen-labs/mongo-web-shell,pilliq/mongo-web-shell,xl76/mongo-web-shell,pilliq/mongo-web-shell,rcchan/mongo-web-shell,mongodb-labs/mongo-web-shell,rcchan/mongo-web-shell,mongodb-labs/mongo-web-shell,m...
925fefdcdaf32123a9ed4ed2b038bcb11269d77d
main/appengine_config.py
main/appengine_config.py
# coding: utf-8 import os import sys sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', ''...
# coding: utf-8 import os import sys if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) ...
Remove duplicate libx path insertion
Remove duplicate libx path insertion
Python
mit
gae-init/gae-init-babel,lipis/life-line,lipis/life-line,mdxs/gae-init-babel,gae-init/gae-init-babel,gae-init/gae-init-babel,mdxs/gae-init-babel,gae-init/gae-init-babel,mdxs/gae-init-babel,lipis/life-line
62451e8c5b3d93409fa4bcc7ec29827be6253e88
website/registries/utils.py
website/registries/utils.py
REG_CAMPAIGNS = { 'prereg': 'Prereg Challenge', 'registered_report': 'Registered Report Protocol Preregistration', } def get_campaign_schema(campaign): from osf.models import RegistrationSchema if campaign not in REG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(REG...
REG_CAMPAIGNS = { 'prereg': 'Prereg Challenge', 'registered_report': 'Registered Report Protocol Preregistration', } def get_campaign_schema(campaign): from osf.models import RegistrationSchema if campaign not in REG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(REG...
Speed up draft registrations query.
Speed up draft registrations query.
Python
apache-2.0
baylee-d/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,adlius/osf.io,mattclark/osf.io,felliott/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,baylee-d/osf.io,mattclark/osf.io,brianjgeiger/osf.io,mattclark/osf...
8afbd0fe7f4732d8484a2a41b91451ec220fc2f8
tools/perf/benchmarks/memory.py
tools/perf/benchmarks/memory.py
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import test from measurements import memory class Memory(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' class...
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import test from measurements import memory class MemoryTop25(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' ...
Rename Memory benchmark to avoid conflict with Memory measurement.
[telemetry] Rename Memory benchmark to avoid conflict with Memory measurement. Quick fix for now, but I may need to reconsider how run_measurement resolved name conflicts. BUG=263511 TEST=None. R=tonyg@chromium.org Review URL: https://chromiumcodereview.appspot.com/19915008 git-svn-id: de016e52bd170d2d4f2344f9bf92...
Python
bsd-3-clause
PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/ch...
39671789613e1811f2282d45a7c8970b0262e5ea
mopidy_jukebox/models.py
mopidy_jukebox/models.py
""" Models for the Jukebox application User - All users Vote - Votes on songs """ import logging from peewee import SqliteDatabase, Model, CharField, DateTimeField, ForeignKeyField db = SqliteDatabase(None) logger = logging.getLogger(__name__) class User(Model): name = CharField() @staticmethod def c...
""" Models for the Jukebox application User - All users Vote - Votes on songs """ import datetime import logging from peewee import SqliteDatabase, Model, CharField, DateTimeField, ForeignKeyField, UUIDField db = SqliteDatabase(None) logger = logging.getLogger(__name__) class User(Model): id = CharField(prima...
Create model for session, add properties for user
Create model for session, add properties for user
Python
mit
qurben/mopidy-jukebox,qurben/mopidy-jukebox,qurben/mopidy-jukebox
c7650f69e1a1d7ff16e72a741b329b32636a5a3d
lizard_apps/views.py
lizard_apps/views.py
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans, see LICENSE.rst. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView from lizard_apps.models import Screen class AppScreen...
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans, see LICENSE.rst. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView from django.shortcuts import get_object_or_404 from liz...
Return 404 instead of incorrect JS file when screen does not exist.
Return 404 instead of incorrect JS file when screen does not exist.
Python
mit
lizardsystem/lizard-apps,lizardsystem/lizard-apps
360bdaa2df7673bc2090476df077c86c6f7c5633
utils/exceptions.py
utils/exceptions.py
class ResponseError(Exception): """For throwing in case of a non-200 response status.""" def __init__(self, *args, code=None, **kwargs): self.code = code super().__init__(*args, **kwargs)
class ResponseError(Exception): """For throwing in case of a non-200 response status.""" def __init__(self, code=None, *args): self.code = code super().__init__(code, *args)
Change constructor to be more appropriate
Change constructor to be more appropriate
Python
mit
BeatButton/beattie-bot,BeatButton/beattie
7740ff36679b13be9d63b333cff35f913e0066dc
python/tests/py3/test_asyncio.py
python/tests/py3/test_asyncio.py
import asyncio import pytest def test_hello_world(workspace): workspace.src('main.py', r""" import asyncio async def main(): print('Hello, ', end='') await asyncio.sleep(1) print('World!') # Python 3.7+ asyncio.run(main()) """) r = workspace.run('python main.py') ...
import asyncio import pytest def test_hello_world(workspace): workspace.src('main.py', r""" import asyncio async def do_something_else(): print('...', end='') await asyncio.sleep(1) print('!', end='') async def say_hello_async(who): print('Hello, ', end='') awa...
Make hello world (asyncio) more involved
[python] Make hello world (asyncio) more involved
Python
mit
imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning
144280ff8c656fb589e92a3f0fe5cba7ce63d85d
tailor/listeners/mainlistener.py
tailor/listeners/mainlistener.py
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): pass d...
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__veri...
Implement UpperCamelCase name check for enums
Implement UpperCamelCase name check for enums
Python
mit
sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor
ef0d59781fbc9dcd89334843e5b6fc1461aed246
rollbar/contrib/asgi/__init__.py
rollbar/contrib/asgi/__init__.py
__all__ = ["ASGIMiddleware"] import rollbar try: from starlette.types import ASGIApp, Receive, Scope, Send except ImportError: STARLETTE_INSTALLED = False else: STARLETTE_INSTALLED = True # Optional class annotations must be statically declared because # IDEs cannot infer type hinting for arbitrary dyna...
__all__ = ["ASGIMiddleware"] import rollbar try: from starlette.types import ASGIApp as ASGIAppType, Receive, Scope, Send except ImportError: STARLETTE_INSTALLED = False else: STARLETTE_INSTALLED = True # Optional class annotations must be statically declared because # IDEs cannot infer type hinting for...
Use unique identifier name for ASGIApp type
Use unique identifier name for ASGIApp type Due to collision with ASGIApp class decorator
Python
mit
rollbar/pyrollbar
2b83d2dd0c3e0230968a5ab2bd55a647eee2eb3a
packs/aws/actions/run.py
packs/aws/actions/run.py
from lib import action class ActionManager(action.BaseAction): def run(self, **kwargs): action = kwargs['action'] del kwargs['action'] module_path = kwargs['module_path'] del kwargs['module_path'] if action == 'run_instances': kwargs['user_data'] = self.st2_use...
from lib import action class ActionManager(action.BaseAction): def run(self, **kwargs): action = kwargs['action'] del kwargs['action'] module_path = kwargs['module_path'] del kwargs['module_path'] if action == 'run_instances': kwargs['user_data'] = self.st2_use...
Support DNS round-robin balancing through Route53
Support DNS round-robin balancing through Route53 Our codegen actions for adding/updating A records in Route53 only support a single IP as a value. Changing to accept a comma-separated list, which will add an unweighted round-robin A record. Should also add WRR at some point probably, but I just don't care enough.
Python
apache-2.0
StackStorm/st2contrib,StackStorm/st2contrib,StackStorm/st2contrib
ee3634fbee7e0bd311337007743b30934aca73ba
pyfibot/modules/module_thetvdb.py
pyfibot/modules/module_thetvdb.py
#!/usr/bin/python from datetime import datetime, timedelta import tvdb_api import tvdb_exceptions def command_ep(bot, user, channel, args): t = tvdb_api.Tvdb() now = datetime.now() try: series = t[args] except tvdb_exceptions.tvdb_shownotfound: bot.say(channel, "Series '%s' not found"...
#!/usr/bin/python from datetime import datetime, timedelta import tvdb_api import tvdb_exceptions def command_ep(bot, user, channel, args): t = tvdb_api.Tvdb() now = datetime.now() try: series = t[args] except tvdb_exceptions.tvdb_shownotfound: bot.say(channel, "Series '%s' not found"...
Fix episode finding logic to handle specials and cases where episodes are out of order in tvdb api result
Fix episode finding logic to handle specials and cases where episodes are out of order in tvdb api result git-svn-id: 056f9092885898c4775d98c479d2d33d00273e45@374 dda364a1-ef19-0410-af65-756c83048fb2
Python
bsd-3-clause
rnyberg/pyfibot,rnyberg/pyfibot,aapa/pyfibot,huqa/pyfibot,lepinkainen/pyfibot,lepinkainen/pyfibot,EArmour/pyfibot,aapa/pyfibot,EArmour/pyfibot,huqa/pyfibot
4aa6714284cb45a2747cea8e0f38e8fbcd8ec0bc
pymatgen/core/design_patterns.py
pymatgen/core/design_patterns.py
# coding: utf-8 from __future__ import division, unicode_literals """ This module defines some useful design patterns. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Producti...
# coding: utf-8 from __future__ import division, unicode_literals """ This module defines some useful design patterns. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Producti...
Move NullFile and NullStream to monty
Move NullFile and NullStream to monty
Python
mit
Bismarrck/pymatgen,Bismarrck/pymatgen,sonium0/pymatgen,rousseab/pymatgen,Dioptas/pymatgen,migueldiascosta/pymatgen,yanikou19/pymatgen,ctoher/pymatgen,migueldiascosta/pymatgen,yanikou19/pymatgen,rousseab/pymatgen,sonium0/pymatgen,ctoher/pymatgen,ctoher/pymatgen,rousseab/pymatgen,sonium0/pymatgen,Bismarrck/pymatgen,migue...
b2fd89928f2462c4c8de8a6028c65996d69bfd31
motion_test.py
motion_test.py
from gpiozero import MotionSensor ##Quick script to check communication between motion sensor and Pi on GPIO 4. pir = MotionSensor(4) i = 0 while(i < 5): if pir.motion_detected: print i , 'motion detected' i+=1;
from gpiozero import MotionSensor ##Send an email upon motion detecion pir = MotionSensor(4) i = 0 while(i < 1): if pir.motion_detected: print i , 'motion detected' execfile("send_email.py") i+=1;
Send email when motion is detected
Send email when motion is detected
Python
mit
efagerberg/PiCam
4c96f2dc52810c10ef6d73732be0ecd8745c4567
moviePlayer.py
moviePlayer.py
import tkinter as tk from time import sleep from movie01 import reel window = tk.Tk() def main(): window.title("Tkinter Movie Player") button = tk.Button(window, text = "Play", command = processPlay) button.pack() window.mainloop() def processPlay(): TIME_STEP = 0.3 label =...
import tkinter as tk from time import sleep from movie01 import reel window = tk.Tk() def main(): window.title("Tkinter Movie Player") button = tk.Button(window, text = "Play", command = processPlay) button.pack() window.mainloop() def processPlay(): TIME_STEP = 0.3 label =...
Change font of ASCII to Courier
Change font of ASCII to Courier
Python
apache-2.0
awhittle3/ASCII-Movie
2bd5887a62d0f6bfd6f9290604effad322e8ab1e
myElsClient.py
myElsClient.py
import requests class myElsClient: """A class that implements a Python interface to api.elsevier.com""" # local variables __base_url = "https://api.elsevier.com/" # constructors def __init__(self, apiKey): """Instantiates a client with a given API Key.""" self.apiKey = apiKey ...
import requests class myElsClient: """A class that implements a Python interface to api.elsevier.com""" # local variables __base_url = "https://api.elsevier.com/" # constructors def __init__(self, apiKey): """Instantiates a client with a given API Key.""" self.apiKey = apiKey ...
Add basic HTTP error handling.
Add basic HTTP error handling.
Python
bsd-3-clause
ElsevierDev/elsapy
e7eb0697f9362cc5ec5b8a21b064873eda6ed329
apps/basaltApp/scripts/photoDataExport.py
apps/basaltApp/scripts/photoDataExport.py
#! /usr/bin/env python import django from datetime import datetime import pytz django.setup() from basaltApp.models import BasaltImageSet, BasaltSingleImage from geocamTrack.utils import getClosestPosition hawaiiStandardTime = pytz.timezone('US/Hawaii') startTime = datetime(2016, 11, 8, 0, 0, 0, tzinfo=hawaiiStandard...
#! /usr/bin/env python import django from datetime import datetime import pytz django.setup() from basaltApp.models import BasaltImageSet, BasaltSingleImage, BasaltResource from geocamTrack.utils import getClosestPosition hawaiiStandardTime = pytz.timezone('US/Hawaii') startTime = datetime(2016, 11, 8, 0, 0, 0, tzinf...
Add postion lookup stuff to script. Use acquistion_time for timestamp
Add postion lookup stuff to script. Use acquistion_time for timestamp
Python
apache-2.0
xgds/xgds_basalt,xgds/xgds_basalt,xgds/xgds_basalt,xgds/xgds_basalt
d3a9657b7318327a59c3eee08a25f1e5c4ba4edf
django_casscache.py
django_casscache.py
""" django_casscache ~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Matt Robenolt. :license: BSD, see LICENSE for more details. """ from django.core.cache.backends.memcached import BaseMemcachedCache class CasscacheCache(BaseMemcachedCache): "An implementation of a cache binding using casscache" def __init__(self...
""" django_casscache ~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Matt Robenolt. :license: BSD, see LICENSE for more details. """ from django.core.cache.backends.memcached import BaseMemcachedCache class CasscacheCache(BaseMemcachedCache): "An implementation of a cache binding using casscache" def __init__(self...
Add a method to noop the make_key in Django
Add a method to noop the make_key in Django
Python
bsd-3-clause
mattrobenolt/django-casscache
8a25b5f76ffe5b32f6c1a8d691c3d78ce3fb07c8
fluent_contents/utils/search.py
fluent_contents/utils/search.py
""" Internal utils for search. """ from django.utils.encoding import force_unicode from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.se...
""" Internal utils for search. """ from django.utils.encoding import force_text from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.searc...
Fix force_unicode for Python 3, use force_text()
Fix force_unicode for Python 3, use force_text()
Python
apache-2.0
django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents
2685b94838c8ec7ce31da60bc6f28953152c788a
pixelmap/pixelmap.py
pixelmap/pixelmap.py
"""Pixelmap Cool pixelmap of Pixels. Last updated: March 7, 2017 """ from pixel import Pixel class Pixelmap: def __init__(self, width, height): """Pixelmap constructor :param width: Width of map in pixels. :param height: Height of map in pixels. """ self.width = width ...
"""Pixelmap Cool pixelmap of Pixels. Last updated: March 11, 2017 """ from .pixel import Pixel class Pixelmap: def __init__(self, cols, rows, default_val=None): """Pixelmap constructor :param cols: Width of map in pixels. :param rows: Height of map in pixels. :param default_val...
Add default value for matrix and methods to get columns and rows.
Add default value for matrix and methods to get columns and rows.
Python
mit
yebra06/pixelmap
96733510eeee4b06c3b509097e7c26fd143d687f
plugins/clue/clue.py
plugins/clue/clue.py
from __future__ import unicode_literals import re crontable = [] outputs = [] state = {} class ClueState: def __init__(self): self.count = 0 self.clue = '' def process_message(data): channel = data['channel'] if channel not in state.keys(): state[channel] = ClueState() st...
from __future__ import unicode_literals import re crontable = [] outputs = [] state = {} class ClueState: def __init__(self): self.count = 0 self.clue = '' def process_message(data): channel = data['channel'] if channel not in state.keys(): state[channel] = ClueState() st...
Fix to only match '>' at the beginning of a line
Fix to only match '>' at the beginning of a line Which was the intention with the '\n' in the pattern before, but I had made it optional for the common case of the '>' being at the beginning of the message, which of course had the side effect of allowing the '>' to be matched anywhere (bleh). Now, with a MULTLINE-mod...
Python
mit
cworth-gh/stony
4a32bd6bdc91564276a4e46210fc9019dd1b8a89
statement_format.py
statement_format.py
import pandas as pd def fn(row): if row['Type'] == 'DIRECT DEBIT': return 'DD' if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME': return 'BP' if row['Amount (GBP)'] < 0: return 'SO' raise Exception('Unintended state') df = pd.read_csv('statement.csv') ...
import json import pandas as pd def fn(row): if row['Type'] == 'DIRECT DEBIT': return 'DD' if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME': return 'BP' if row['Amount (GBP)'] < 0: return 'SO' raise Exception('Unintended state') df = pd.read_csv('stat...
Correct operation. Now to fix panda warnings
Correct operation. Now to fix panda warnings
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
896f7b82eb1c84538a94e65d8ff55282e36c6818
squadron/exthandlers/__init__.py
squadron/exthandlers/__init__.py
from .dir import ext_dir from .makegit import ext_git from .download import ext_download from .template import ext_template extension_handles = { 'dir':ext_dir, 'git':ext_git, 'download':ext_download, 'virtualenv',ext_virtualenv, 'tpl':ext_template }
from .dir import ext_dir from .makegit import ext_git from .download import ext_download from .template import ext_template from .virtualenv import ext_virtualenv extension_handles = { 'dir':ext_dir, 'git':ext_git, 'download':ext_download, 'virtualenv':ext_virtualenv, 'tpl':ext_template }
Fix broken tests because of virtualenv handler
Fix broken tests because of virtualenv handler
Python
mit
gosquadron/squadron,gosquadron/squadron
9afa8829f0ded4c19f0467f1a5e2c8539f33ac31
profile_bs_xf03id/startup/52-suspenders.py
profile_bs_xf03id/startup/52-suspenders.py
from bluesky.suspenders import (SuspendFloor, SuspendBoolHigh, SuspendBoolLow) from bluesky.global_state import get_gs gs = get_gs() RE = gs.RE # Here are some conditions that will cause scans to pause automatically: # - when the beam current goes below a certain threshold susp_current = SuspendFloor(beamline_status...
from bluesky.suspenders import (SuspendFloor, SuspendBoolHigh, SuspendBoolLow) from bluesky.global_state import get_gs gs = get_gs() RE = gs.RE # Here are some conditions that will cause scans to pause automatically: # - when the beam current goes below a certain threshold susp_current = SuspendFloor(beamline_status...
Add a tripped message to the suspenders, but disable for now
Add a tripped message to the suspenders, but disable for now
Python
bsd-2-clause
NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd
48fd99751ddd000bb179214c69ee65ac7f70d2a2
scripts/remove-all-annotations.py
scripts/remove-all-annotations.py
#!/usr/bin/python # This is a small helper script to remove all annotations from a # project. # You may need to install psycopg2, e.g. with: # sudo apt-get install python-psycopg2 import sys import psycopg2 import os from common import db_connection, conf if len(sys.argv) != 1: print >> sys.stderr, "Usage:", ...
#!/usr/bin/python # This is a small helper script to remove all annotations from a # project. # You may need to install psycopg2, e.g. with: # sudo apt-get install python-psycopg2 import sys import psycopg2 import os from common import db_connection, conf if len(sys.argv) != 1: print >> sys.stderr, "Usage:", ...
Make remove all annotation also remove classes and relations
Make remove all annotation also remove classes and relations
Python
agpl-3.0
fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID
426d3fd0572d0b648ceb7d5394b555f4a7c65a1e
source/cytoplasm/configuration.py
source/cytoplasm/configuration.py
# This module contains the user's configurations, to be accessed like: # `print cytoplasm.configuration.build_dir` import os, imp # If the user has a file called _config.py, import that. # The user's _config.py should "from cytoplasm.defaults import *" if they want to use # some of the defaults. if os.path.exists("_co...
# This module contains the user's configurations, to be accessed like: # `print cytoplasm.configuration.build_dir` import os, imp from .errors import CytoplasmError # If the user has a file called _config.py, import that. # The user's _config.py should "from cytoplasm.defaults import *" if they want to use # some of t...
Raise an error if the user doesn't have a _config.py
Raise an error if the user doesn't have a _config.py This raises a less cryptic error.
Python
mit
startling/cytoplasm
c5bc66351870ce369b0d06161f07a1943dfeed93
plugin_handler.py
plugin_handler.py
# -*- coding: utf-8 -*- # Execute this file to see what plugins will be loaded. # Implementation leans to Lex Toumbourou's example: # https://lextoumbourou.com/blog/posts/dynamically-loading-modules-and-classes-in-python/ import os import pkgutil import sys def load_venue_plugins(): """ Read plugin directo...
# -*- coding: utf-8 -*- # Execute this file to see what plugins will be loaded. # Implementation leans to Lex Toumbourou's example: # https://lextoumbourou.com/blog/posts/dynamically-loading-modules-and-classes-in-python/ import os import pkgutil import sys def load_venue_plugins(): """ Read plugin directo...
Enable On the rocks plugin
Enable On the rocks plugin
Python
isc
weezel/BandEventNotifier
90e8f58c24608c503697e9d491ff77b5b46972ba
pi_director/controllers/controllers.py
pi_director/controllers/controllers.py
from pi_director.models.models import ( DBSession, MyModel, ) def get_pis(): PiList=DBSession.query(MyModel).filter(MyModel.uuid!="default").all() return PiList
from pi_director.models.models import ( DBSession, MyModel, ) def get_pis(): PiList=DBSession.query(MyModel).filter(MyModel.uuid!="default").order_by(MyModel.lastseen).all() return PiList
Order Pis in list by lastseen, showing non-communicating pis at the top
Order Pis in list by lastseen, showing non-communicating pis at the top
Python
mit
PeterGrace/pi_director,PeterGrace/pi_director,PeterGrace/pi_director,selfcommit/pi_director,selfcommit/pi_director,selfcommit/pi_director
1046157fa2e062f12123e110c82851c2484216be
gallery_plugins/plugin_gfycat.py
gallery_plugins/plugin_gfycat.py
import re try: import urllib.request as urllib except: import urllib # Python 2 def title(source): gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1] link = 'https://gfycat.com/cajax/get/' + gfyId respond = urllib.urlopen(link).read() username = re.findall(r'\"userName\":\"(.+?)\...
import re try: import urllib.request as urllib except: import urllib # Python 2 def title(source): gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1] link = 'https://gfycat.com/cajax/get/' + gfyId respond = urllib.urlopen(link).read().decode("utf8") username = re.findall(r'\"user...
Update gfycat plugin for python3 support
Update gfycat plugin for python3 support
Python
mit
regosen/gallery_get