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
8af1f7a0525f69a6e2ee6c5cfd7d6a923873a7ec
froide/helper/auth.py
froide/helper/auth.py
from django.contrib.auth.backends import ModelBackend from django.core.validators import email_re from django.contrib.auth import models, load_backend, login from django.conf import settings class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): if email_re.search(username...
from django.contrib.auth.backends import ModelBackend from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.contrib.auth import models, load_backend, login from django.conf import settings class EmailBackend(ModelBackend): def authenticate(self, username=...
Validate email the correct way
Validate email the correct way
Python
mit
catcosmo/froide,ryankanno/froide,okfse/froide,fin/froide,LilithWittmann/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,LilithWittmann/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,...
3e6798113d3f1ddc08f4db7d65f3130ea2211dd7
nursereg/admin.py
nursereg/admin.py
from django.contrib import admin from .models import NurseSource, NurseReg admin.site.register(NurseSource) admin.site.register(NurseReg)
from django.contrib import admin from control.utils import CsvExportAdminMixin from .models import NurseSource, NurseReg class NurseRegAdmin(CsvExportAdminMixin, admin.ModelAdmin): csv_header = [ 'cmsisdn', 'dmsisdn', 'rmsisdn', 'faccode', 'id_type', 'id_no', 'passport_origin', 'dob', 'nu...
Add export inline for Nurse Registrations
Add export inline for Nurse Registrations
Python
bsd-3-clause
praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control
8bd3b1eb25d2207e33cd8970ac2cf739c983e191
properties/__init__.py
properties/__init__.py
"""Properties Giving structure (and documentation!) to the properties you use in your code avoids confusion and allows users to interact flexibly and provide multiple styles of input, have those inputs validated, and allow you as a developer to set expectations for what you want to work with. import properties class ...
"""Properties Giving structure (and documentation!) to the properties you use in your code avoids confusion and allows users to interact flexibly and provide multiple styles of input, have those inputs validated, and allow you as a developer to set expectations for what you want to work with. import properties class ...
Modify init to only import available modules
Modify init to only import available modules
Python
mit
aranzgeo/properties,3ptscience/properties
6cac0b8531297dab6bdaff2959646d5a8a90dd01
parse_vcfFile.py
parse_vcfFile.py
import pandas def read_vcf(filename): """ Reads an input VCF file containing lines for each SNP and columns with genotype info for each sample. :param filename: Path to VCF file :return: Pandas DataFrame representing VCF file with rows as SNPs and columns with info and samples """ vcf = open(...
import pandas def read_vcf(filename): """ Reads an input VCF file containing lines for each SNP and columns with genotype info for each sample. :param filename: Path to VCF file :return: Pandas DataFrame representing VCF file with columns as SNPs and rows with samples """ vcf = open(filename)...
Update VCF parsing to output SNP-column sample-row DataFrame
Update VCF parsing to output SNP-column sample-row DataFrame
Python
mit
NCBI-Hackathons/Network_Stats_Acc_Interop,NCBI-Hackathons/Network_Stats_Acc_Interop,NCBI-Hackathons/Network_Stats_Acc_Interop,NCBI-Hackathons/Network_Stats_Acc_Interop
38b4af0b3c1c6105d68ff453d86107758ef9d751
preconditions.py
preconditions.py
class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
import inspect class PreconditionError (TypeError): pass def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'.format...
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Python
mit
nejucomo/preconditions
fc74e6a4bc9992647abbb9f92a7e5880e5c29506
models.py
models.py
from django.db import models # Create your models here. class User(models.Model): display_name = models.CharField(max_length=64) auth_key = models.CharField(max_length=64) class Post(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=4000) class Comment(models.Model): user = model...
from django.db import models # Create your models here. class User(models.Model): display_name = models.CharField(max_length=64) auth_key = models.CharField(max_length=64) class Post(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=4000) last_modified = models.DateTimeField() cl...
Add 'last modified' field to Post model
Add 'last modified' field to Post model
Python
mit
SyntaxBlitz/bridie,SyntaxBlitz/bridie
6989e6b2308cbe496857b5f911c136fcf3043444
zeus/api/resources/user_token.py
zeus/api/resources/user_token.py
from flask import Response from sqlalchemy.exc import IntegrityError from zeus import auth from zeus.config import db from zeus.models import UserApiToken from .base import Resource from ..schemas import TokenSchema token_schema = TokenSchema(strict=True) class UserTokenResource(Resource): def dispatch_request...
from sqlalchemy.exc import IntegrityError from zeus import auth from zeus.config import db from zeus.models import UserApiToken from .base import Resource from ..schemas import TokenSchema token_schema = TokenSchema(strict=True) class UserTokenResource(Resource): def get(self): """ Return the A...
Fix user token endpoint authorization
fix(token): Fix user token endpoint authorization
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
a8e2f3e00145f56429eb3d01aa08efe329191b18
src/proposals/admin.py
src/proposals/admin.py
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): m...
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): m...
Make submitter a raw_id_field to prevent long select tag
Make submitter a raw_id_field to prevent long select tag
Python
mit
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
43696b102bada7408c5c8151e4ae87e5a2855337
ds_binary_tree_ft.py
ds_binary_tree_ft.py
def binary_tree(r): pass def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function def binary_tree(r): """Binary tree using list of list.""" return [r, [], []] def insert_left(root, new_branch): left_tree = root.pop(1) if len(left_tree) > 1: root.insert(1, [new_bran...
Complete ds: binary_tree using ls of ls
Complete ds: binary_tree using ls of ls
Python
bsd-2-clause
bowen0701/algorithms_data_structures
6c78f66cda7842894ba11109bee602633edd87b5
symposion/reviews/forms.py
symposion/reviews/forms.py
from django import forms from markedit.widgets import MarkEdit from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ["vote", "comment"] widgets = {"comment": MarkEdit()} def __init__(self,...
from django import forms from django.forms import Textarea from markedit.widgets import MarkEdit from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ["vote", "comment"] widgets = {"comment": M...
Make review feedback not a Markdown widget
Make review feedback not a Markdown widget Review feedback wasn't supposed to be in markdown. Change the widget to a regular text area.
Python
bsd-3-clause
pyconjp/pyconjp-website,Diwahars/pycon,PyCon/pycon,njl/pycon,njl/pycon,PyCon/pycon,Diwahars/pycon,osmfj/sotmjp-website,smellman/sotmjp-website,smellman/sotmjp-website,PyCon/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,Diwahars/pycon,njl/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,pyconjp/pyconjp-website,sm...
82eb7a69ccb88d27141aeb483e4482041108723f
app/Display/display.py
app/Display/display.py
import sys ESC = chr(27) CLEAR = ESC + "[2J" MOVE_HOME = ESC + "[H" ERASE = CLEAR + MOVE_HOME LINES = 24 COLS = 80 class Display: def __init__(self, title): self.title = title def clear(self): sys.stdout.write(ERASE) def show_properties(self, properties, names=None): ...
import sys ESC = chr(27) CSI = ESC + "[" CLEAR = CSI + "2J" MOVE_HOME = CSI + "H" ERASE = CLEAR + MOVE_HOME MOVE_TO = CSI + "{0};{1}H" LINES = 24 COLS = 80 class Display: def __init__(self, title, info=None): self.title = title self.info = info def clear(self): ...
Add support for cursor position, centered title, and an info bar
Add support for cursor position, centered title, and an info bar
Python
mit
gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x
fe4f2697afdc280e0158aad1acf9613d1decb32d
project_template.py
project_template.py
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): def run(self): # Check whether the folder is open only one in the current window. folders = self.window.folders() msg = None if len(folders) == 0: msg = "No floder opened i...
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. folders = self.window.fol...
Implement checking the format of settings
Implement checking the format of settings
Python
mit
autopp/SublimeProjectTemplate,autopp/SublimeProjectTemplate
a08bd02fcd255d19991398444a5d1ec0d11409d2
test/test_featurecounts.py
test/test_featurecounts.py
import sequana.featurecounts as fc from sequana import sequana_data def test_featurecounts(): RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0" RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1" RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2" RNASEQ_DIR_undef = sequana_data...
import sequana.featurecounts as fc from sequana import sequana_data def test_featurecounts(): RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0" RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1" RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2" RNASEQ_DIR_undef = sequana_data...
Fix syntax in featureCounts test
Fix syntax in featureCounts test
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
c38b9f378f7dbf968ee6bcb7b3f0625a1993d61d
tests/core/test_history.py
tests/core/test_history.py
from __future__ import unicode_literals import unittest from mopidy.core import History from mopidy.models import Artist, Track class PlaybackHistoryTest(unittest.TestCase): def setUp(self): self.tracks = [ Track(uri='dummy1:a', name='foo', artists=[Artist(name='foober'), A...
from __future__ import unicode_literals import unittest from mopidy.core import History from mopidy.models import Artist, Track class PlaybackHistoryTest(unittest.TestCase): def setUp(self): self.tracks = [ Track(uri='dummy1:a', name='foo', artists=[Artist(name='foober'), A...
Use assertIn instead of assertTrue to test membership.
Use assertIn instead of assertTrue to test membership.
Python
apache-2.0
swak/mopidy,ali/mopidy,mokieyue/mopidy,tkem/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,tkem/mopidy,bacontext/mopidy,adamcik/mopidy,glogiotatidis/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,mopidy/mopidy,bencevans/mopidy,bacontext/mopidy,jcass77/mopidy,jodal/mopidy,diandiankan/mopidy,vrs01/mopidy,bencevans/mopidy,p...
92da4abbcf1551d87192b627b3c5f44f2fe82e91
quickplots/textsize.py
quickplots/textsize.py
"""Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return 10
"""Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return int(height)
Make very basic font size calculator
Make very basic font size calculator
Python
mit
samirelanduk/quickplots
e3287b9669e07dc4265efe768ba2b4c3351839d3
base_geoengine/geo_db.py
base_geoengine/geo_db.py
# Copyright 2011-2012 Nicolas Bessi (Camptocamp SA) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). """Helper to setup Postgis""" import logging from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS suppo...
# Copyright 2011-2012 Nicolas Bessi (Camptocamp SA) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). """Helper to setup Postgis""" import logging from odoo import _ from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis ...
Make MissingError translatable for auto install of postgis extension, plus fix some typos
Make MissingError translatable for auto install of postgis extension, plus fix some typos
Python
agpl-3.0
OCA/geospatial,OCA/geospatial,OCA/geospatial
aa436864f53a4c77b4869baabfb1478d7fea36f0
tests/products/__init__.py
tests/products/__init__.py
""" Test utilities for ensuring the correctness of products """ import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': str, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': str, 'instrument': str, 'bounds': BoundingBox, 'bands': [Ba...
""" Test utilities for ensuring the correctness of products """ import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': six.string_types, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': six.string_types, 'instrument': six.string_types, ...
Allow str type comparison in py2/3
Allow str type comparison in py2/3
Python
bsd-3-clause
ceholden/landsat_tile,ceholden/landsat_tiles,ceholden/landsat_tiles,ceholden/tilezilla,ceholden/landsat_tile
f2bf7807754d13c92bd2901072dd804dda61805f
cla_public/apps/contact/constants.py
cla_public/apps/contact/constants.py
# -*- coding: utf-8 -*- "Contact constants" from flask.ext.babel import lazy_gettext as _ DAY_TODAY = 'today' DAY_SPECIFIC = 'specific_day' DAY_CHOICES = ( (DAY_TODAY, _('Call me today at')), (DAY_SPECIFIC, _('Call me in the next week on')) )
# -*- coding: utf-8 -*- "Contact constants" from flask.ext.babel import lazy_gettext as _ DAY_TODAY = 'today' DAY_SPECIFIC = 'specific_day' DAY_CHOICES = ( (DAY_TODAY, _('Call me today at')), (DAY_SPECIFIC, _('Call me in on')) )
Update button label (call back time picker)
FE: Update button label (call back time picker)
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
74d6b8bf119eca7e3f8f1d49f3c8d82b726f3062
faq/search_indexes.py
faq/search_indexes.py
# -*- coding: utf-8 -*- from haystack import indexes from haystack.sites import site from faq.settings import SEARCH_INDEX from faq.models import Topic, Question class FAQIndexBase(SEARCH_INDEX): text = indexes.CharField(document=True, use_template=True) url = indexes.CharField(model_attr='get_absolute_url...
# -*- coding: utf-8 -*- """ Haystack SearchIndexes for FAQ objects. Note that these are compatible with both Haystack 1.0 and Haystack 2.0-beta. The super class for these indexes can be customized by using the ``FAQ_SEARCH_INDEX`` setting. """ from haystack import indexes from faq.settings import SEARCH_INDEX fro...
Add compatibility for Haystack 2.0.
Add compatibility for Haystack 2.0.
Python
bsd-3-clause
benspaulding/django-faq
6e77aff69adba0ded366a704bdafb601514faf5d
salt/thorium/runner.py
salt/thorium/runner.py
# -*- coding: utf-8 -*- ''' React by calling async runners ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # import salt libs import salt.runner def cmd( name, func=None, arg=(), **kwargs): ''' Execute a runner asynchronous: ...
# -*- coding: utf-8 -*- ''' React by calling async runners ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # import salt libs import salt.runner def cmd( name, func=None, arg=(), **kwargs): ''' Execute a runner asynchronous: ...
Fix local opts from CLI
Fix local opts from CLI
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
2cb406cac1a6faf1f2f79c1376ceac39871fb96e
pony_barn/build-django.py
pony_barn/build-django.py
import os import sys from base import BaseBuild from pony_build import client as pony class DjangoBuild(BaseBuild): def __init__(self): super(DjangoBuild, self).__init__() self.directory = os.path.dirname(os.path.abspath(__file__)) self.repo_url = 'git://github.com/django/django.git' ...
import os import sys from base import BaseBuild from pony_build import client as pony class DjangoBuild(BaseBuild): def __init__(self): super(DjangoBuild, self).__init__() self.directory = os.path.dirname(os.path.abspath(__file__)) self.repo_url = 'git://github.com/django/django.git' ...
Make it so that django build actually uses it's own code.
Make it so that django build actually uses it's own code.
Python
mit
ericholscher/pony_barn,ericholscher/pony_barn
0dc217bd0cec8a0321dfc38b88696514179bf833
editorconfig/__init__.py
editorconfig/__init__.py
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "development") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename"...
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" ...
Upgrade version to 0.11.3 final
Upgrade version to 0.11.3 final
Python
bsd-2-clause
VictorBjelkholm/editorconfig-vim,johnfraney/editorconfig-vim,pocke/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,VictorBjelkholm/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,benjifishe...
574dd4ef0aa0d6381938a0638e497374434cb75e
lilkv/columnfamily.py
lilkv/columnfamily.py
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily...
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily...
Store rows as dictionaries of lists.
Store rows as dictionaries of lists.
Python
mit
pgorla/lil-kv
8915729158c9b5c22d16a4c2deee66f79a8276b9
apps/local_apps/account/middleware.py
apps/local_apps/account/middleware.py
from django.utils.cache import patch_vary_headers from django.utils import translation from account.models import Account class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context depending on ...
from django.utils.cache import patch_vary_headers from django.utils import translation from account.models import Account class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context depending on ...
Throw 500 error on multiple account in LocaleMiddleware so we can fix them.
Throw 500 error on multiple account in LocaleMiddleware so we can fix them.
Python
mit
ingenieroariel/pinax,ingenieroariel/pinax
f4d703fb38c8d4efbff709a6e3c7478b7cf96db2
code/conditional_switch_as_else_if.py
code/conditional_switch_as_else_if.py
score = 76 if score < 60: grade = 'F' elif score < 70: grade = 'D' elif score < 80: grade = 'C' elif score < 90: grade = 'B' else: grade = 'A' print(grade)
score = 76 grades = [ (60, 'F'), (70, 'D'), (80, 'C'), (90, 'B'), ] print(next((g for x, g in grades if score < x), 'A'))
Replace swith statement with a mapping
Replace swith statement with a mapping Official Python documentation explains [1], that switch statement can be replaced by `if .. elif .. else` or by a mapping. In first example with varying condtitions `if .. elif .. else` was used, and in this example a mapping is much better fitted way of doing a switch statement...
Python
mit
evmorov/lang-compare,evmorov/lang-compare,evmorov/lang-compare,Evmorov/ruby-coffeescript,Evmorov/ruby-coffeescript,Evmorov/ruby-coffeescript,evmorov/lang-compare,evmorov/lang-compare,evmorov/lang-compare
4583c9949143e58bf400fc86e27d634aa382f605
tests/test_expanded.py
tests/test_expanded.py
from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """-[ RECORD 0 ] name | hello age | 123 -[ RECORD 1 ] name | world age | 456 """ assert expected == expanded_table(input, ["name", "age"])
from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """***************************[ 1. row ]*************************** name | hello age | 123 ***************************[ 2. row ]*************************** name | world ag...
Update expanded tests to match mysql style.
Update expanded tests to match mysql style.
Python
bsd-3-clause
oguzy/mycli,chenpingzhao/mycli,ZuoGuocai/mycli,evook/mycli,jinstrive/mycli,j-bennet/mycli,danieljwest/mycli,suzukaze/mycli,thanatoskira/mycli,chenpingzhao/mycli,j-bennet/mycli,brewneaux/mycli,webwlsong/mycli,MnO2/rediscli,brewneaux/mycli,shoma/mycli,mdsrosa/mycli,oguzy/mycli,danieljwest/mycli,jinstrive/mycli,thanatoski...
56b23bc44655e4a965939ceb5908cd84cfd9de88
src/room.py
src/room.py
class Room(object): """ This class is responsible for managing the people in a room """
class Room(object): """ This class is responsible for managing the people in a room """ def __init__(self, room_type, room_name): self.residents = [] self.room_name = room_name self.room_type =room_type if room_type == "office": self.maximum_no_of_people = 6 ...
Add init method to class Room
Add init method to class Room
Python
mit
EdwinKato/Space-Allocator,EdwinKato/Space-Allocator
a72a13aa89c11c4d9a2bad48b67abdf352989981
parsley/decorators.py
parsley/decorators.py
from django import forms def parsleyfy(klass): class ParsleyClass(klass): def __init__(self, *args, **kwargs): super(ParsleyClass, self).__init__(*args, **kwargs) for key, val in self.fields.items(): if val.required: val.widget.attrs.update({"data...
from django import forms def parsleyfy(klass): class ParsleyClass(klass): def __init__(self, *args, **kwargs): super(ParsleyClass, self).__init__(*args, **kwargs) for key, val in self.fields.items(): if val.required: val.widget.attrs.update({"dat...
Change type comparisions with isinstance
Change type comparisions with isinstance
Python
bsd-3-clause
agiliq/Django-parsley,jproffitt/Django-parsley,jproffitt/Django-parsley,agiliq/Django-parsley,Tivix/Django-parsley,Tivix/Django-parsley,agiliq/Django-parsley,jproffitt/Django-parsley
316d9557002c54c5dd03f2a740367946b997d06a
src/foremast/utils/generate_encoded_user_data.py
src/foremast/utils/generate_encoded_user_data.py
"""Generate base64 encoded User Data.""" import base64 from ..utils import get_template def generate_encoded_user_data(env='dev', region='us-east-1', app_name='', group_name=''): r"""Generate base64 encoded User Data. ...
"""Generate base64 encoded User Data.""" import base64 from .get_template import get_template def generate_encoded_user_data(env='dev', region='us-east-1', app_name='', group_name=''): r"""Generate base64 encoded User Da...
Use new relative import within directory
fix: Use new relative import within directory See also: PSOBAT-1197
Python
apache-2.0
gogoair/foremast,gogoair/foremast
76551f7a05506a872ec6535eb3263710650ea8ce
glue/core/data_factories/__init__.py
glue/core/data_factories/__init__.py
from .helpers import * from .gridded import * from .pandas import * from .excel import * from .image import * from .dendrogram import * from .tables import *
from .helpers import * from .gridded import * from .pandas import * from .excel import * from .image import * from .tables import * from .dendrogram import *
Order of import matters for disambiguation, but this should be fixed later to avoid this.
Order of import matters for disambiguation, but this should be fixed later to avoid this.
Python
bsd-3-clause
saimn/glue,stscieisenhamer/glue,stscieisenhamer/glue,JudoWill/glue,saimn/glue,JudoWill/glue
21a7e7557b8e02ef448bcc46a63e983f48cafe38
tests/test_endpoint.py
tests/test_endpoint.py
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'...
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'...
Test Endpoint.endpoints has all endpoints
Test Endpoint.endpoints has all endpoints
Python
mit
acuros/noopy
b203f5ebbec108da7abffc3c5ef3a8a2d0334837
planet_alignment/app/app_factory.py
planet_alignment/app/app_factory.py
""" .. module:: app_factory :platform: linux :synopsis: .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunc...
""" .. module:: app_factory :platform: linux :synopsis: The class factory to create the application App. .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface impo...
Add doc synopsis for the app factory.
Add doc synopsis for the app factory.
Python
mit
paulfanelli/planet_alignment
1e001eb11938bd5c613e655f86943167cd945d50
local_sync_client.py
local_sync_client.py
# -*- coding: utf-8 -*- import os class LocalSyncClient(object): def __init__(self, local_dir): self.local_dir = local_dir def get_object_timestamp(self, key): object_path = os.path.join(self.local_dir, key) if os.path.exists(object_path): return os.stat(object_path).st_m...
# -*- coding: utf-8 -*- import os class LocalSyncClient(object): def __init__(self, local_dir): self.local_dir = local_dir def get_object_timestamp(self, key): object_path = os.path.join(self.local_dir, key) if os.path.exists(object_path): return os.stat(object_path).st_m...
Fix bug which caused put_object in LocalSyncClient to fail on create
Fix bug which caused put_object in LocalSyncClient to fail on create
Python
mit
MichaelAquilina/s3backup,MichaelAquilina/s3backup
8c2ebccac0f633b3d2198a6a9d477ac4b8a620df
koztumize/application.py
koztumize/application.py
"""Declare the Koztumize application using Pynuts.""" import ldap from pynuts import Pynuts class Koztumize(Pynuts): """The class which open the ldap.""" @property def ldap(self): """Open the ldap.""" if 'LDAP' not in self.config: # pragma: no cover self.config['LDAP'] = ldap...
"""Declare the Koztumize application using Pynuts.""" import os import ldap from pynuts import Pynuts class Koztumize(Pynuts): """The class which open the ldap.""" @property def ldap(self): """Open the ldap.""" if 'LDAP' not in self.config: # pragma: no cover self.config['LDA...
Use an environment variable as config file
Use an environment variable as config file
Python
agpl-3.0
Kozea/Koztumize,Kozea/Koztumize,Kozea/Koztumize
e08be68c9a998678edbb24620518fad7d02582b6
lib/datasets/__init__.py
lib/datasets/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from .imdb import imdb from .pascal_voc import pascal_voc from . import...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from .imdb import imdb from .pascal_voc import pascal_voc from . import...
Use matlab.exe instead of matlab in Windows
Use matlab.exe instead of matlab in Windows
Python
mit
only4hj/fast-rcnn,only4hj/fast-rcnn,only4hj/fast-rcnn
f8ccb67ad9775fa1babe79640d4db46027531046
examples/async_step/features/steps/async_dispatch_steps.py
examples/async_step/features/steps/async_dispatch_steps.py
from behave import given, then, step from behave.api.async_step import use_or_create_async_context, AsyncContext from hamcrest import assert_that, equal_to, empty import asyncio @asyncio.coroutine def async_func(param): yield from asyncio.sleep(0.2) return str(param).upper() @given('I dispatch an async-call w...
# -*- coding: UTF-8 -*- # REQUIRES: Python >= 3.5 from behave import given, then, step from behave.api.async_step import use_or_create_async_context, AsyncContext from hamcrest import assert_that, equal_to, empty import asyncio @asyncio.coroutine def async_func(param): yield from asyncio.sleep(0.2) return str(...
Add encoding hint (and which python version is required).
Add encoding hint (and which python version is required).
Python
bsd-2-clause
jenisys/behave,jenisys/behave
1c516e64518597404e3928d445fb3239748a4861
performanceplatform/collector/logging_setup.py
performanceplatform/collector/logging_setup.py
from logstash_formatter import LogstashFormatter import logging import os import pdb import sys import traceback def get_log_file_handler(path): handler = logging.FileHandler(path) handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)s] -> %(message)s")) return handler def get_json_...
from logstash_formatter import LogstashFormatter import logging import os import pdb import sys import traceback def get_log_file_handler(path): handler = logging.FileHandler(path) handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)s] -> %(message)s")) return handler def get_json_...
Add `json_fields` parameter to set_up_logging
Add `json_fields` parameter to set_up_logging This will allow the main function to add extra fields to JSON log messages, for example to pass through command-line arguments. See https://www.pivotaltracker.com/story/show/70748012
Python
mit
alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector
a102731c88f496b557dedd4024fb9b82801d134a
oauthlib/__init__.py
oauthlib/__init__.py
""" oauthlib ~~~~~~~~ A generic, spec-compliant, thorough implementation of the OAuth request-signing logic. :copyright: (c) 2011 by Idan Gazit. :license: BSD, see LICENSE for details. """ __author__ = 'The OAuthlib Community' __version__ = '2.1.0' import logging try: # Python 2.7+ fro...
""" oauthlib ~~~~~~~~ A generic, spec-compliant, thorough implementation of the OAuth request-signing logic. :copyright: (c) 2011 by Idan Gazit. :license: BSD, see LICENSE for details. """ import logging from logging import NullHandler __author__ = 'The OAuthlib Community' __version__ = '2.1....
Remove Python 2.6 compatibility code.
Remove Python 2.6 compatibility code.
Python
bsd-3-clause
idan/oauthlib,oauthlib/oauthlib
8a7fd251454026baf3cf7a0a1aa0300a0f3772bc
pycanvas/assignment.py
pycanvas/assignment.py
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): # pragma: no cover return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/...
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ ...
Remove no-cover from __str__ method
Remove no-cover from __str__ method
Python
mit
ucfopen/canvasapi,ucfopen/canvasapi,ucfopen/canvasapi
75fd199b239c23d7396bd3b5803d3c6007361b5a
test/repsitory_test.py
test/repsitory_test.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2017, Fabian Greif # All Rights Reserved. # # The file is part of the lbuild project and is released under the # 2-clause BSD license. See the file `LICENSE.txt` for the full license # governing this code. import os import io import sys import unittest ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2017, Fabian Greif # All Rights Reserved. # # The file is part of the lbuild project and is released under the # 2-clause BSD license. See the file `LICENSE.txt` for the full license # governing this code. import os import sys import unittest # Hack to ...
Fix repository import test for Python < 3.6
Fix repository import test for Python < 3.6 Check for broader range of exceptions.
Python
bsd-2-clause
dergraaf/library-builder,dergraaf/library-builder
021c21207cab0cf3f7cca3cb31ffa4c62d49e58c
python/chigger/base/KeyPressInteractorStyle.py
python/chigger/base/KeyPressInteractorStyle.py
#pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/...
#pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/...
Make camera interaction more sensitive
Make camera interaction more sensitive (refs #12095)
Python
lgpl-2.1
lindsayad/moose,dschwen/moose,andrsd/moose,milljm/moose,milljm/moose,sapitts/moose,SudiptaBiswas/moose,bwspenc/moose,sapitts/moose,jessecarterMOOSE/moose,dschwen/moose,harterj/moose,sapitts/moose,permcody/moose,andrsd/moose,idaholab/moose,YaqiWang/moose,jessecarterMOOSE/moose,laagesen/moose,SudiptaBiswas/moose,permcody...
2fba1c04c8083211df8664d87080480a1f63ed2a
csunplugged/utils/group_lessons_by_age.py
csunplugged/utils/group_lessons_by_age.py
"""Return ordered groups of lessons.""" from collections import OrderedDict from topics.models import ( AgeGroup, LessonNumber, ) def group_lessons_by_age(lessons): """Return ordered groups of lessons. Lessons are grouped by the lesson minimum age and maximum ages, and then order by number. ...
"""Return ordered groups of lessons.""" from collections import OrderedDict from topics.models import ( AgeGroup, LessonNumber, ) def group_lessons_by_age(lessons): """Return ordered groups of lessons. Lessons are grouped by the lesson minimum age and maximum ages, and then order by number. ...
Fix bug where lessons are duplicated across age groups.
Fix bug where lessons are duplicated across age groups.
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
5d663ae690f0c488f7a38f4556c30b169389c441
flaskiwsapp/projects/models/target.py
flaskiwsapp/projects/models/target.py
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM from sqlalchemy_utils.types.url import URLType from flask_validator.constraints.internet import ValidateURL AREAS = ('Poli...
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" ...
Remove import from testing packages
Remove import from testing packages
Python
mit
rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel
6e0654386c7a5d7e0a399ac363af4f2d59770d16
coffeestats/caffeine_oauth2/tests/test_models.py
coffeestats/caffeine_oauth2/tests/test_models.py
from __future__ import unicode_literals from django.test import TestCase from caffeine_oauth2.models import CoffeestatsApplication class CoffeestatsApplicationTest(TestCase): def test___str__(self): application = CoffeestatsApplication(name='test', client_id='client') self.assertEquals(str(appli...
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.test import TestCase from caffeine_oauth2.models import CoffeestatsApplication User = get_user_model() class CoffeestatsApplicationTest(TestCase): def test___str__(sel...
Add tests for new caffeine_oauth2.models code
Add tests for new caffeine_oauth2.models code
Python
mit
coffeestats/coffeestats-django,coffeestats/coffeestats-django,coffeestats/coffeestats-django,coffeestats/coffeestats-django
249293336d2bfcc018c44d9279b89b31522c37da
u2fserver/jsobjects.py
u2fserver/jsobjects.py
from u2flib_server.jsapi import (JSONDict, RegisterRequest, RegisterResponse, SignRequest, SignResponse) __all__ = [ 'RegisterRequestData', 'RegisterResponseData', 'AuthenticateRequestData', 'AuthenticateResponseData' ] class RegisterRequestData(JSONDict): @prope...
# Copyright (C) 2014 Yubico AB # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is ...
Use a mixin for get-/setProps
Use a mixin for get-/setProps
Python
bsd-2-clause
moreati/u2fval,Yubico/u2fval
b48bc4c1fff91173327f10a29e140fc781619edb
src/adhocracy/lib/helpers/staticpage_helper.py
src/adhocracy/lib/helpers/staticpage_helper.py
import babel.core from adhocracy.lib import cache from adhocracy.lib.helpers import url as _url @cache.memoize('staticpage_url') def url(staticpage, **kwargs): pid = staticpage.key + '_' + staticpage.lang return _url.build(None, 'static', pid, **kwargs) def get_lang_info(lang): locale = babel.core.Local...
import babel.core from adhocracy.lib import cache, staticpage from adhocracy.lib.helpers import url as _url @cache.memoize('staticpage_url') def url(staticpage, **kwargs): pid = staticpage.key + '_' + staticpage.lang return _url.build(None, 'static', pid, **kwargs) def get_lang_info(lang): locale = babe...
Make can_edit available in the helper
Make can_edit available in the helper
Python
agpl-3.0
alkadis/vcv,liqd/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,phihag/adhocracy,alkadis/vcv,SysTheron/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeuge...
bbfc0357c9a37599776584c40f6a3b4f462ad110
run_notebooks.py
run_notebooks.py
#!/usr/bin/env python import subprocess NOTEBOOKS_DIR = 'notebooks' SKIP_NOTEBOOKS = ['Bonus/What to do when things go wrong.ipynb'] def run_notebook(notebook): args = ['jupyter', 'nbconvert', '--execute', '--ExecutePreprocessor.timeout=900', '--ExecutePreprocessor.kernel_name=workshop',...
#!/usr/bin/env python import subprocess import os.path NOTEBOOKS_DIR = 'notebooks' SKIP_NOTEBOOKS = [os.path.join('Bonus','What to do when things go wrong.ipynb')] def run_notebook(notebook): args = ['jupyter', 'nbconvert', '--execute', '--ExecutePreprocessor.timeout=900', '--ExecutePrep...
Use os.join for testing on multiple platforms.
Use os.join for testing on multiple platforms.
Python
mit
Unidata/unidata-python-workshop,julienchastang/unidata-python-workshop,julienchastang/unidata-python-workshop
af52a3967568a3d5af838e695d5fcdd825f585cf
numba2/runtime/tests/test_ffi.py
numba2/runtime/tests/test_ffi.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def ...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): ...
Insert explicit cast to malloc implementation
Insert explicit cast to malloc implementation
Python
bsd-2-clause
flypy/flypy,flypy/flypy
c7461cfe456b0aaf2f6ab4c9625cf7afc8a02eff
scripts/lib/logger.py
scripts/lib/logger.py
# logger module from datetime import datetime import os logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) use_log_dir = False if use_log_dir: logdir = os.path.join(analysis_path,...
# logger module from datetime import datetime import os import socket # gethostname() logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) logfile = os.path.join(analysis_path...
Append hostname to messages file. This supports a use-case where portions of the processing could happen on various hosts.
Append hostname to messages file. This supports a use-case where portions of the processing could happen on various hosts.
Python
mit
UASLab/ImageAnalysis
484233e1c3140e7cca9cd1874c1cf984280e2c92
zeus/tasks/send_build_notifications.py
zeus/tasks/send_build_notifications.py
from uuid import UUID from zeus import auth from zeus.config import celery from zeus.constants import Result, Status from zeus.models import Build from zeus.notifications import email @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): build = ...
from uuid import UUID from zeus import auth from zeus.config import celery from zeus.constants import Result, Status from zeus.models import Build from zeus.notifications import email @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): build = ...
Remove tenant req from task query
Remove tenant req from task query
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
97bcf652a18808d89c8de2235e2b32ae933036b6
tests/options_tests.py
tests/options_tests.py
from nose.tools import istest, assert_equal from mammoth import style_reader from mammoth.options import read_options, _default_style_map @istest def default_style_map_is_used_if_style_map_is_not_set(): assert_equal(_default_style_map, read_options({})["style_map"]) @istest def custom_style_mappings_are_prepen...
from nose.tools import istest, assert_equal from mammoth import style_reader from mammoth.options import read_options, _default_style_map @istest def default_style_map_is_used_if_style_map_is_not_set(): assert_equal(_default_style_map, read_options({})["style_map"]) @istest def custom_style_mappings_are_prepen...
Add test to ensure that style map lines beginning with hash are ignored
Add test to ensure that style map lines beginning with hash are ignored
Python
bsd-2-clause
mwilliamson/python-mammoth
398a3f8856b1390c2ad8a0fda2dd14eda4efbd2d
test_input/test70.py
test_input/test70.py
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1...
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1...
Fix a problem reported by Greg Ward and pointed out by John Machin when doing:
Fix a problem reported by Greg Ward and pointed out by John Machin when doing: return (need_quotes) and ('"%s"' % text) or (text) The following warning was generated: Using a conditional statement with a constant value ("%s") This was because even the stack wasn't modified after a BINARY_MODULO to s...
Python
bsd-3-clause
thomasvs/pychecker,thomasvs/pychecker,akaihola/PyChecker,akaihola/PyChecker
e229c797a507932d7992f44d3ab93517096c2e94
tests/test_autotime.py
tests/test_autotime.py
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell("%load_ext autotime") ...
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell('%load_ext autotime') ...
Make unload test assertion explicit
Make unload test assertion explicit
Python
apache-2.0
cpcloud/ipython-autotime
daed28559cc16374f85830ef9d939ccddece64a1
tests/test_parser.py
tests/test_parser.py
# -*- coding: utf-8 -*- import codecs import pytest from poyo import parse_string @pytest.fixture def string_data(): with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile: return ymlfile.read() def test_parse_string(string_data): expected = { u'default_context': { u...
# -*- coding: utf-8 -*- import codecs import pytest from poyo import parse_string @pytest.fixture def string_data(): with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile: return ymlfile.read() def test_parse_string(string_data): expected = { u'default_context': { u...
Add list to expectation in test
Add list to expectation in test
Python
mit
hackebrot/poyo
3a5cbdbe4a79efd59114ca11f86e282aee0eac5c
tests/trunk_aware.py
tests/trunk_aware.py
import functools import sys import nose from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk __author__ = 'moskupols' _multiprocess_shared_ = True _all_trunks = set(trunks_registered()) _trunk_filter = _all_trunks def trunk_parametrized(trunks=set(trunks_registered()))...
import functools import sys import nose from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk __author__ = 'moskupols' _multiprocess_shared_ = True _all_trunks = set(trunks_registered()) _trunk_filter = _all_trunks def trunk_parametrized(trunks=set(trunks_registered()))...
Add ability to exclude trunks by passing % before it
Add ability to exclude trunks by passing % before it For example, ./run_nose -v %FilmTitles %BookTitles
Python
mit
hatbot-team/hatbot_resources
acba9a027eafb1877f0b6208613206674ba5d55d
tmc/models/employee.py
tmc/models/employee.py
# -*- coding: utf-8 -*- from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3, required=True ) docket_number = fields.Integer( required=True ) bank...
# -*- coding: utf-8 -*- from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3 ) docket_number = fields.Integer() bank_account_number = fields.Char() bank_branch =...
Remove required property on some fields
[DEL] Remove required property on some fields
Python
agpl-3.0
tmcrosario/odoo-tmc
3c9b49ef968c7e59028eb0bda78b1474a49339f3
numscons/tools/intel_common/common.py
numscons/tools/intel_common/common.py
# INPUTS: # ICC_ABI: x86, amd64 _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env): try: abi = env['ICC_ABI'] except KeyError: abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi)
# INPUTS: # ICC_ABI: x86, amd64 _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env, lang='C'): if lang == 'C' or lang == 'CXX': try: abi = env['ICC_ABI'] except KeyError: abi = 'default' elif lang == 'FORTRAN': try: abi...
Add a language argument to get abi for intel tools.
Add a language argument to get abi for intel tools.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
ecbb3ffdf063bc53eae0f8bd180e62ae61f99fee
opencontrail_netns/vrouter_control.py
opencontrail_netns/vrouter_control.py
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi def interface_register(vm, vmi, iface_name): api = ContrailVRouterApi() mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0] api.add_port(vm.uuid, vmi.uuid, iface_name, mac) def interface_unregister(vmi_uuid): api = Contrail...
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi def interface_register(vm, vmi, iface_name): api = ContrailVRouterApi() mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0] api.add_port(vm.uuid, vmi.uuid, iface_name, mac, port_type='NovaVMPort') def interface_unregister(vmi_u...
Use NovaVMPort type; otherwise the agent will believe it is a Use NovaVMPort as type; otherwise the agent will believe it is dealing with a service-instance and will not send a VM registration.
Use NovaVMPort type; otherwise the agent will believe it is a Use NovaVMPort as type; otherwise the agent will believe it is dealing with a service-instance and will not send a VM registration.
Python
apache-2.0
pedro-r-marques/opencontrail-netns,DreamLab/opencontrail-netns
8a080a94300403487dce023eec8467832af8ae79
tests/core/migrations/0004_bookwithchapters.py
tests/core/migrations/0004_bookwithchapters.py
from __future__ import unicode_literals from django import VERSION from django.db import migrations, models if VERSION >= (1, 8): from django.contrib.postgres.fields import ArrayField chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None) else: chapters_field = mo...
from __future__ import unicode_literals from django import VERSION from django.db import migrations, models can_use_arrayfield = False chapters_field = models.Field() # Dummy field if VERSION >= (1, 8): try: from django.contrib.postgres.fields import ArrayField chapters_field = ArrayField(base_fi...
Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed
Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed
Python
bsd-2-clause
brillgen/django-import-export,copperleaftech/django-import-export,bmihelac/django-import-export,jnns/django-import-export,copperleaftech/django-import-export,jnns/django-import-export,brillgen/django-import-export,PetrDlouhy/django-import-export,jnns/django-import-export,PetrDlouhy/django-import-export,brillgen/django-...
7a77b42691e051269a146fd218dd619ccefecc54
src/ansible/models.py
src/ansible/models.py
from django.db import models class Project(models.Model): project_name = models.CharField(max_length=200) playbook_path = models.CharField(max_length=200, default="~/") ansible_config_path = models.CharField(max_length=200, default="~/") default_inventory = models.CharField(max_length=200, default="hos...
from django.db import models class Project(models.Model): project_name = models.CharField(max_length=200) playbook_path = models.CharField(max_length=200, default="~/") ansible_config_path = models.CharField(max_length=200, default="~/") default_inventory = models.CharField(max_length=200, default="hos...
Fix plural form of Registry
Fix plural form of Registry TIL how to use meta class
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
4a4abb215684a169be4ba7e0a670000f25870cd7
nodeconductor/logging/serializers.py
nodeconductor/logging/serializers.py
from rest_framework import serializers from nodeconductor.core.serializers import GenericRelatedField from nodeconductor.core.fields import MappedChoiceField, JsonField from nodeconductor.logging import models, utils, log class AlertSerializer(serializers.HyperlinkedModelSerializer): scope = GenericRelatedField(...
from rest_framework import serializers from nodeconductor.core.serializers import GenericRelatedField from nodeconductor.core.fields import MappedChoiceField, JsonField from nodeconductor.logging import models, utils, log class AlertSerializer(serializers.HyperlinkedModelSerializer): scope = GenericRelatedField(...
Remove wrong serializer field (nc-553)
Remove wrong serializer field (nc-553)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
6528a426ffb7a9a55c9f84f3c134a195a5e17046
problems/examples/cryptography/ecb-1/challenge.py
problems/examples/cryptography/ecb-1/challenge.py
import string from hacksport.problem import ProtectedFile, Remote class Problem(Remote): program_name = "ecb.py" files = [ProtectedFile("flag"), ProtectedFile("key")] def initialize(self): # generate random 32 hexadecimal characters self.enc_key = "".join( self.random.choice(...
import secrets import string from hacksport.problem import ProtectedFile, Remote from hacksport.deploy import flag_fmt class Problem(Remote): program_name = "ecb.py" files = [ProtectedFile("flag"), ProtectedFile("key")] def initialize(self): # generate random 32 hexadecimal characters se...
Fix ecb-1 to assert flag length
Fix ecb-1 to assert flag length
Python
mit
picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF
35303ce7654e14a88fcb9db0690f72c07410dade
python/pythagorean-triplet/pythagorean_triplet.py
python/pythagorean-triplet/pythagorean_triplet.py
def triplets_with_sum(n): pass
from math import ceil, gcd, sqrt def triplets_in_range(range_start, range_end): for limit in range(range_start, range_end, 4): for x, y, z in primitive_triplets(limit): a, b, c = (x, y, z) # yield multiples of primitive triplet while a < range_start: a,...
Solve pythagorean_triple - reference solution
Solve pythagorean_triple - reference solution
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
af184be16c4bd0ea45f7e8c6dc59388c4d8893c5
main.py
main.py
import tweepy import app_config # Twitter API configuration consumer_key = app_config.twitter["consumer_key"] consumer_secret = app_config.twitter["consumer_secret"] access_token = app_config.twitter["access_token"] access_token_secret = app_config.twitter["access_token_secret"] # Start auth = tweepy.OAuthHandler(co...
import tweepy import json import unicodedata import sqlite3 import app_config import definitions API_launch() followers_list(followers_name[1]) create_db() create_table() tweet_info(followers_name[1],tweets_number=100)
Update Main.py to work with definitions.py
Update Main.py to work with definitions.py functions are loaded from definitions.py and the database can be created without modifying functions
Python
mit
franckbrignoli/twitter-bot-detection
47593fae71deb378bd60a14d1b6f4a3a2bb98bf6
pitz.py
pitz.py
#!/usr/bin/python import sys import subprocess cmd = sys.argv[1] new_args = sys.argv[2:] or [] subprocess.call(["pitz-%s" % cmd] + new_args)
#!/usr/bin/python import sys import subprocess def _help(): subprocess.call(['pitz-help']) sys.exit(1) if len(sys.argv) < 2: _help() cmd = sys.argv[1] new_args = sys.argv[2:] or [] try: subprocess.call(["pitz-%s" % cmd] + new_args) except OSError as exc: _help()
Add at least a minimal exception handling (missing subcommand).
Add at least a minimal exception handling (missing subcommand).
Python
bsd-3-clause
mw44118/pitz,mw44118/pitz,mw44118/pitz
1c2ea508bd0c4e687d6a46c438a476609b43d264
databroker/tests/test_document.py
databroker/tests/test_document.py
import copy import pytest from ..core import Document, NotMutable def test_immutable(): d = Document({'a': 1}) with pytest.raises(NotMutable): # Update existing key d['a'] = 2 with pytest.raises(NotMutable): # Add new key d['b'] = 2 with pytest.raises(NotMutable): ...
import copy import pytest from ..core import Document, NotMutable def test_immutable(): d = Document({'a': 1}) with pytest.raises(NotMutable): # Update existing key d['a'] = 2 with pytest.raises(NotMutable): # Add new key d['b'] = 2 with pytest.raises(NotMutable): ...
Make test stricter to be safe.
Make test stricter to be safe.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
869db9b392356912beebfc4ed1db97baa82e87e3
resin/models/config.py
resin/models/config.py
import sys from ..base_request import BaseRequest from ..settings import Settings class Config(object): """ This class implements configuration model for Resin Python SDK. Attributes: _config (dict): caching configuration. """ def __init__(self): self.base_request = BaseRequest...
import sys from ..base_request import BaseRequest from ..settings import Settings def _normalize_device_type(dev_type): if dev_type['state'] == 'PREVIEW': dev_type['state'] = 'ALPHA' dev_type['name'] = dev_type['name'].replace('(PREVIEW)', '(ALPHA)') if dev_type['state'] == 'EXPERIMENTAL': ...
Patch device types to be marked as ALPHA and BETA
Patch device types to be marked as ALPHA and BETA
Python
apache-2.0
resin-io/resin-sdk-python,resin-io/resin-sdk-python,nghiant2710/resin-sdk-python,nghiant2710/resin-sdk-python
732430fcfa1cfc6e7303ae1fb6d0f2eea43bdd00
deps/pyextensibletype/extensibletype/test/test_interning.py
deps/pyextensibletype/extensibletype/test/test_interning.py
from .. import intern def test_global_interning(): try: intern.global_intern("hello") except AssertionError as e: pass else: raise Exception("Expects complaint about uninitialized table") intern.global_intern_initialize() id1 = intern.global_intern("hello") id2 = intern...
from .. import intern def test_global_interning(): try: intern.global_intern("hello") except AssertionError as e: pass else: raise Exception("Expects complaint about uninitialized table") intern.global_intern_initialize() id1 = intern.global_intern("hello") id2 = intern...
Add more thorough intern test
Add more thorough intern test
Python
bsd-2-clause
stefanseefeld/numba,GaZ3ll3/numba,sklam/numba,stonebig/numba,stefanseefeld/numba,pitrou/numba,GaZ3ll3/numba,seibert/numba,ssarangi/numba,seibert/numba,pombredanne/numba,GaZ3ll3/numba,shiquanwang/numba,IntelLabs/numba,IntelLabs/numba,GaZ3ll3/numba,stonebig/numba,ssarangi/numba,IntelLabs/numba,gdementen/numba,numba/numba...
fd4ddd1a4978191fdb0d19960960c703569c6348
examples/rmg/minimal/input.py
examples/rmg/minimal/input.py
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List of species species( label='et...
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # List of species species( label='ethane', reactive=True, structur...
Set minimal example to 'default' kineticsFamilies.
Set minimal example to 'default' kineticsFamilies.
Python
mit
pierrelb/RMG-Py,faribas/RMG-Py,nickvandewiele/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,KEHANG/RMG-Py,nyee/RMG-Py,comocheng/RMG-Py,enochd/RMG-Py,pierrelb/RMG-Py,KEHANG/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,chatelak/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py
98389db2ae73147aeab9b56a0ea588843649a5ce
plugin/import-js-sublime/import-js.py
plugin/import-js-sublime/import-js.py
import sublime, sublime_plugin, subprocess, os importjs_path = os.path.expanduser('~/.rbenv/shims/import-js') class ImportJsCommand(sublime_plugin.TextCommand): def run(self, edit): entire_file_region = sublime.Region(0, self.view.size()) current_file_contents = self.view.substr(entire_file_region) env...
import sublime, sublime_plugin, subprocess, os importjs_path = os.path.expanduser('~/.rbenv/shims/import-js') class ImportJsCommand(sublime_plugin.TextCommand): def run(self, edit): entire_file_region = sublime.Region(0, self.view.size()) current_file_contents = self.view.substr(entire_file_region) env...
Check for exit code > 0 instead of existence of stderr
Check for exit code > 0 instead of existence of stderr I'm about to make messages appear in the Sublime plugin. In order to do that, I need a channel to post them that won't mess up the end results being posted to stdout.
Python
mit
lencioni/import-js,trotzig/import-js,trotzig/import-js,trotzig/import-js,lencioni/import-js,Galooshi/import-js,lencioni/import-js
ea60a04280533c00bcefdf3e0fa6d0bcd8692be0
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '9006e277b20109de165d4a17827c9b2029bf3831' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[...
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[...
Upgrade libchromiumcontent to fix chromiumviews.
Upgrade libchromiumcontent to fix chromiumviews.
Python
mit
egoist/electron,yalexx/electron,gerhardberger/electron,arturts/electron,tonyganch/electron,tincan24/electron,adamjgray/electron,fomojola/electron,jsutcodes/electron,minggo/electron,matiasinsaurralde/electron,adamjgray/electron,mattotodd/electron,shennushi/electron,seanchas116/electron,deepak1556/atom-shell,thompsonemer...
e9a849f311f54e92c86f149670a318b1e5f5f5e6
update_cloudflare.py
update_cloudflare.py
import pathlib import socket import pyflare import yaml s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 53)) myip = s.getsockname()[0] s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: update_list = yaml.load(r) for account in update_list: r...
import pathlib import socket import pyflare from yaml import load s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 53)) myip = s.getsockname()[0] s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: update_list = load(r) for account in update_list: ...
Change import statement for external library yaml
Change import statement for external library yaml
Python
mit
tkiapril/cloudflare-updater
d1324e8d29d01be3d9f7a83bed21737652a7bf71
feder/letters/utils.py
feder/letters/utils.py
from textwrap import TextWrapper BODY_FOOTER_SEPERATOR = "\n\n--\n" def email_wrapper(text): wrapper = TextWrapper() wrapper.subsequent_indent = '> ' wrapper.initial_indent = '> ' return "\n".join(wrapper.wrap(text)) def normalize_msg_id(msg_id): if msg_id[0] == '<': msg_id = msg_id[1:] ...
from textwrap import TextWrapper from django.utils import six BODY_FOOTER_SEPERATOR = "\n\n--\n" def email_wrapper(text): wrapper = TextWrapper() wrapper.subsequent_indent = '> ' wrapper.initial_indent = '> ' return "\n".join(wrapper.wrap(text)) def normalize_msg_id(msg_id): if msg_id[0] == '<'...
Fix encoding in reply footer
Fix encoding in reply footer
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
95686933911fb2720b0fad816056c9008ef1097d
kafka_influxdb/reader/kafka_reader.py
kafka_influxdb/reader/kafka_reader.py
# -*- coding: utf-8 -*- import logging import time from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer class KafkaReader(object): def __init__(self, host, port, group, topic, connection_wait_time=2): """ Initialize Kafka reader """ self.host = host self.port = p...
# -*- coding: utf-8 -*- import logging import time from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer class KafkaReader(object): def __init__(self, host, port, group, topic, connection_wait_time=2): """ Initialize Kafka reader """ self.host = host self.port = p...
Make kafka client a field in Reader
Make kafka client a field in Reader
Python
apache-2.0
mre/kafka-influxdb,mre/kafka-influxdb
0fec8460ae0d03aed6956137ec06757812f3f689
lc0199_binary_tree_right_side_view.py
lc0199_binary_tree_right_side_view.py
"""Leetcode 199. Binary Tree Right Side View Medium URL: https://leetcode.com/problems/binary-tree-right-side-view/ Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Ex...
"""Leetcode 199. Binary Tree Right Side View Medium URL: https://leetcode.com/problems/binary-tree-right-side-view/ Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Ex...
Complete level traversal last sol
Complete level traversal last sol
Python
bsd-2-clause
bowen0701/algorithms_data_structures
9b110b93ab8b2c7e58bb5447b3801138fedc4f51
src/config/vnc_openstack/vnc_openstack/context.py
src/config/vnc_openstack/vnc_openstack/context.py
import gevent import bottle import uuid class NeutronApiContext(object): def __init__(self, request=None, user_token=None): self.request = request self.user_token = user_token self.request_id = str(uuid.uuid4()) # end __init__ # end class NeutronApiContext def get_context(): return...
import gevent import bottle import uuid class NeutronApiContext(object): def __init__(self, request=None, user_token=None): self.request = request self.user_token = user_token self.request_id = request.json['context'].get('request_id', str(uuid.uuid4())) # end __init__ # end class Neutr...
Use request_id forwarded by neutron plugin
Use request_id forwarded by neutron plugin Change-Id: Id395e1bd225c99aafad57eaa48ae3ae3897e249d Closes-Bug: #1723193
Python
apache-2.0
eonpatapon/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller...
c9cd06f9bb2a3b7598a49e97bde93e6845394ec7
gvi/accounts/models.py
gvi/accounts/models.py
from django.db import models class Currency(models.Model): name = models.CharField(max_length=25) contraction = models.CarField(max_length=5) def __str__(self): return self.name class Account(models.Model): DEFAULT_CURRENCY_ID = 1 # pounds ? BANK = 'b' CASH = 'c' TYPE_CHOICES = (...
from django.db import models import datetime class Currency(models.Model): name = models.CharField(max_length=25) contraction = models.CarField(max_length=5) def __str__(self): return self.name class Account(models.Model): DEFAULT_CURRENCY_ID = 1 # pounds ? BANK = 'b' CASH = 'c' ...
Create the transfer model of accounts
Create the transfer model of accounts
Python
mit
m1k3r/gvi-accounts,m1k3r/gvi-accounts,m1k3r/gvi-accounts
8115116fb81fd5a121f9f94e47abbadd2c892b3d
pytablewriter/writer/binary/_interface.py
pytablewriter/writer/binary/_interface.py
# encoding: utf-8 import abc import six from .._table_writer import AbstractTableWriter @six.add_metaclass(abc.ABCMeta) class BinaryWriterInterface(object): @abc.abstractmethod def is_opened(self): # pragma: no cover pass @abc.abstractmethod def open(self, file_path): # pragma: no cover ...
# encoding: utf-8 import abc import six from .._table_writer import AbstractTableWriter @six.add_metaclass(abc.ABCMeta) class BinaryWriterInterface(object): @abc.abstractmethod def is_opened(self): # pragma: no cover pass @abc.abstractmethod def open(self, file_path): # pragma: no cover ...
Add stream verification for binary format writers
Add stream verification for binary format writers
Python
mit
thombashi/pytablewriter
ef2b13ec19d28b56647c0a11044cba6d400f9175
vimiv/image_enhance.py
vimiv/image_enhance.py
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
Use rowstride directly from GdkPixbuf in enhance
Use rowstride directly from GdkPixbuf in enhance The custom calculation of rowstride failed for images with weird dimensions and completely broke enhance. fixes #51
Python
mit
karlch/vimiv,karlch/vimiv,karlch/vimiv
1fb6166198d90166881230d9edb1dd4f6fc36963
aws/customise-stack-template.py
aws/customise-stack-template.py
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived",...
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived",...
Add site log received SNS topic
Add site log received SNS topic
Python
bsd-3-clause
GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services
0cd084550fc5c1315fe33fcb00e57c1c332be6ab
indra/tests/test_mesh.py
indra/tests/test_mesh.py
from indra.databases import mesh_client def test_mesh_id_lookup(): mesh_id = 'D003094' mesh_name = mesh_client.get_mesh_name(mesh_id) assert mesh_name == 'Collagen'
from indra.databases import mesh_client def test_mesh_id_lookup(): mesh_id = 'D003094' mesh_name = mesh_client.get_mesh_name(mesh_id) assert mesh_name == 'Collagen' def test_invalid_id(): mesh_name = mesh_client.get_mesh_name('34jkgfh') assert mesh_name is None
Add test for invalid MESH ID
Add test for invalid MESH ID
Python
bsd-2-clause
pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy
7aab3ca6cdf3cf8c4c2a1e01ededede5a4bad0f1
tests/test_cardinal/test_context.py
tests/test_cardinal/test_context.py
import pytest from cardinal.context import Context from cardinal.errors import IllegalSessionUse @pytest.fixture def base_ctor(mocker): return mocker.patch('cardinal.context.commands.Context.__init__') @pytest.fixture(params=[ {}, {'asdf': 123} ]) def ctx(base_ctor, request): yield Context(**reques...
import pytest from cardinal.context import Context from cardinal.errors import IllegalSessionUse @pytest.fixture def base_ctor(mocker): return mocker.patch('cardinal.context.commands.Context.__init__') @pytest.fixture def ctx(base_ctor, request): kwargs = getattr(request, 'param', {}) yield Context(**...
Adjust fixture usage in context tests
Adjust fixture usage in context tests
Python
mit
FallenWarrior2k/cardinal.py,FallenWarrior2k/cardinal.py
920bc2620533cb4c91d7b7dd186ba59fd09edbf9
datadog/api/screenboards.py
datadog/api/screenboards.py
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ActionAPIResourc...
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ActionAPIResourc...
Add `revoke` method to Screenboard
Add `revoke` method to Screenboard - This method allow to revoke the public access of a shared screenboard
Python
bsd-3-clause
percipient/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy,jofusa/datadogpy,rogst/datadogpy,rogst/datadogpy,percipient/datadogpy,jofusa/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy
f5e67a55535b48afd95272083336d61dd1175765
administrator/admin.py
administrator/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import User # Register your models here. admin.site.register(User)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as Admin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group from .models import User class Regist...
Add form for user creation
Add form for user creation
Python
mit
Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python
5b7a1a40ea43834feb5563f566d07bd5b31c589d
tests/test-recipes/metadata/always_include_files_glob/run_test.py
tests/test-recipes/metadata/always_include_files_glob/run_test.py
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set...
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set...
Add error messages to the asserts
Add error messages to the asserts
Python
bsd-3-clause
ilastik/conda-build,shastings517/conda-build,frol/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,ilastik/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,shastings517/conda-build,da...
f59852e0db6941ce0862545f552a2bc17081086a
schedule/tests/test_templatetags.py
schedule/tests/test_templatetags.py
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assert...
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assert...
Update unit test to use escaped ampersands in comparision.
Update unit test to use escaped ampersands in comparision.
Python
bsd-3-clause
Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-schedu...
ab7c15b791f42f90fa41dfd0557172ce520933f8
LibCharm/IO/__init__.py
LibCharm/IO/__init__.py
try: from Bio import SeqIO from Bio.Alphabet import IUPAC except ImportError as e: print('ERROR: {}'.format(e.msg)) exit(1) def load_file(filename, file_format="fasta"): """ Load sequence from file in FASTA file_format filename - Path and filename of input sequence file """ content ...
try: from Bio import SeqIO from Bio.Alphabet import IUPAC except ImportError as e: print('ERROR: {}'.format(e.msg)) exit(1) def load_file(filename, file_format="fasta"): """ Load sequence from file and returns sequence as Bio.Seq object filename - String; Path and filename of input seque...
Prepare for tagging release 0.1: Add comments to LibCharm.IO
Prepare for tagging release 0.1: Add comments to LibCharm.IO
Python
mit
Athemis/charm
c581d1aab8df44b3c4e8e809e390517432c67d93
skan/test/test_vendored_correlate.py
skan/test/test_vendored_correlate.py
from contextlib import contextmanager from time import time import numpy as np from skan.vendored import thresholding as th @contextmanager def timer(): result = [0.] t = time() yield result result[0] = time() - t def test_fast_sauvola(): image = np.random.rand(512, 512) w0 = 25 w1 = 251...
from time import time import numpy as np from skan.vendored import thresholding as th class Timer: def __init__(self): self.interval = 0 def __enter__(self): self.t0 = time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.interval = time() - self.t0 def...
Use timer class instead of weird list
Use timer class instead of weird list
Python
bsd-3-clause
jni/skan
923f6127eec0a6a576493f41d0f3b2fb9b6156d1
tests/Settings/TestContainerStack.py
tests/Settings/TestContainerStack.py
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. import UM.Settings def test_container_stack(): stack = UM.Settings.ContainerStack()
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. import pytest import uuid # For creating unique ID's for each container stack. import UM.Settings ## Creates a brand new container stack to test with. # # The container stack will get a new, unique ID. @pytest.fixtu...
Test creating container stack with fixture
Test creating container stack with fixture The fixture will automatically generate a unique ID. Contributes to issue CURA-1278.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
09835326d799cd05200856d6114b2df126d21bfb
wagtail/tests/routablepage/models.py
wagtail/tests/routablepage/models.py
from django.http import HttpResponse from django.conf.urls import url from wagtail.contrib.wagtailroutablepage.models import RoutablePage def routable_page_external_view(request, arg): return HttpResponse("EXTERNAL VIEW: " + arg) class RoutablePageTest(RoutablePage): @property def subpage_urls(self): ...
from django.http import HttpResponse from django.conf.urls import url from wagtail.contrib.wagtailroutablepage.models import RoutablePage def routable_page_external_view(request, arg): return HttpResponse("EXTERNAL VIEW: " + arg) class RoutablePageTest(RoutablePage): subpage_urls = ( url(r'^$', 'mai...
Revert "Make subpage_urls a property on RoutablePageTest"
Revert "Make subpage_urls a property on RoutablePageTest" This reverts commit d80a92cfe45907b9f91fd212a3b06fa0b2321364.
Python
bsd-3-clause
janusnic/wagtail,marctc/wagtail,nrsimha/wagtail,WQuanfeng/wagtail,nrsimha/wagtail,nilnvoid/wagtail,Klaudit/wagtail,WQuanfeng/wagtail,rv816/wagtail,timorieber/wagtail,mikedingjan/wagtail,thenewguy/wagtail,kaedroho/wagtail,bjesus/wagtail,jordij/wagtail,bjesus/wagtail,thenewguy/wagtail,nimasmi/wagtail,darith27/wagtail,ste...
758621d6b44ea546d96d631417088ef3eaed08a6
tvnamer/unicode_helper.py
tvnamer/unicode_helper.py
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Helpers to deal with strings, unicode objects and terminal output """ import sys def unicodify(obj, encoding = "utf-...
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Helpers to deal with strings, unicode objects and terminal output """ import sys def unicodify(obj, encoding = "utf-...
Support "encoding = None" argument
Support "encoding = None" argument
Python
unlicense
lahwaacz/tvnamer,dbr/tvnamer,m42e/tvnamer
5510f0990712381391dbffc38ae1bc796e2babf0
txircd/modules/umode_i.py
txircd/modules/umode_i.py
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fi...
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fi...
Make the usermode +i check for WHO slightly neater.
Make the usermode +i check for WHO slightly neater.
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
cc006a07a486ec6c88cd2b4deb929a3c723c5a2c
cupyx/fallback_mode/__init__.py
cupyx/fallback_mode/__init__.py
# Attributes and Methods for fallback_mode # Auto-execute numpy method when corresponding cupy method is not found # "NOQA" to suppress flake8 warning from cupyx.fallback_mode.fallback import numpy # NOQA
from cupy import util as _util # Attributes and Methods for fallback_mode # Auto-execute numpy method when corresponding cupy method is not found # "NOQA" to suppress flake8 warning from cupyx.fallback_mode.fallback import numpy # NOQA _util.experimental('cupyx.fallback_mode.numpy')
Support fallback-mode as an experimental feature
Support fallback-mode as an experimental feature
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
ec410ee0d8d51f2c12b4e8d52369956d6e846662
src/puzzle/problems/anagram_problem.py
src/puzzle/problems/anagram_problem.py
import collections from data import warehouse from puzzle.heuristics import analyze_word from puzzle.problems import problem class AnagramProblem(problem.Problem): @staticmethod def score(lines): # TODO: Support more input. if len(lines) > 1: return 0 return analyze_word.score_anagram(lines[0]...
import collections from data import warehouse from puzzle.heuristics import analyze_word from puzzle.problems import problem class AnagramProblem(problem.Problem): @staticmethod def score(lines): if len(lines) > 1: return 0 return analyze_word.score_anagram(lines[0]) def _solve(self): index...
Delete some TODOs of little value.
TODOs: Delete some TODOs of little value.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
29ef482dc43b2f4927a02b13adf9b24402ddb949
test_project/adam.py
test_project/adam.py
# A set of function which exercise specific mutation operators. This # is paired up with a test suite. The idea is that cosmic-ray should # kill every mutant when that suite is run; if it doesn't, then we've # got a problem. def constant_number(): return 42 def constant_true(): return True def constant_fal...
# A set of function which exercise specific mutation operators. This # is paired up with a test suite. The idea is that cosmic-ray should # kill every mutant when that suite is run; if it doesn't, then we've # got a problem. def constant_number(): return 42 def constant_true(): return True def constant_fal...
Modify the infinite loop function
Modify the infinite loop function Don't use `while True` b/c BooleanReplacer breaks this function's test. This is a bit ugly but until Issue #97 is fixed there is no other way around it.
Python
mit
sixty-north/cosmic-ray
9145bf291ffbe1ec43345aff53ac17ad5de38e4e
IPython/html/widgets/widget_image.py
IPython/html/widgets/widget_image.py
"""ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. #...
"""ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. #...
Use CUnicode for width and height in ImageWidget
Use CUnicode for width and height in ImageWidget
Python
bsd-3-clause
jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywi...
7c1612d954c38ea86d2dff91537a4103f15cc0cb
statsmodels/tsa/api.py
statsmodels/tsa/api.py
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp ...
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp ...
Use import * since __all__ is defined.
REF: Use import * since __all__ is defined.
Python
bsd-3-clause
josef-pkt/statsmodels,bert9bert/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,musically-ut/statsmodels,wwf5067/statsmodels,DonBeo/statsmodels,huongttlan/statsmodels,astocko/statsmodels,jstoxrocky/statsmodels,bashtage/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bashtage/statsmodels,nvoron23/statsmod...
43b5da74b17e313115e0576dbae2dd0e869b88af
course_discovery/apps/publisher/api/permissions.py
course_discovery/apps/publisher/api/permissions.py
from rest_framework.permissions import BasePermission from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access from course_discovery.apps.publisher.models import OrganizationExtension from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_use...
from rest_framework.permissions import BasePermission from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access from course_discovery.apps.publisher.models import OrganizationExtension from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_use...
Allow staff access to Publisher APIs
Allow staff access to Publisher APIs A few Publisher APIs were marked as only allowing publisher users. We should also let staff in. DISCO-1365
Python
agpl-3.0
edx/course-discovery,edx/course-discovery,edx/course-discovery,edx/course-discovery
07710f97883452cbe472ae9735700773aa59f492
falmer/content/models/selection_grid.py
falmer/content/models/selection_grid.py
from wagtail.core import blocks from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock from falmer.content.models.core import Page class GridItem(blocks.StructBlock): ...
from wagtail.core import blocks from wagtail.core.blocks import RichTextBlock from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock from falmer.content.models.core impor...
Add description to selectiongrid items
Add description to selectiongrid items
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
f3508aa348aa6f560953cbf48c6671ccf8558410
tests/test_forms.py
tests/test_forms.py
from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'field': '{% load sniplates %}{% form_field form.field %}' } def test_field_tag(self): ''' ...
from django import forms from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestForm(forms.Form): char = forms.CharField() class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'widgets': '''{% block Char...
Make first field test work
Make first field test work
Python
mit
kezabelle/django-sniplates,funkybob/django-sniplates,funkybob/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,kezabelle/django-sniplates,kezabelle/django-sniplates,sergei-maertens/django-sniplates