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
75f01ff3be060e033b24d141b0ca824cb7f81c22
tests/twisted/avahi/test-register.py
tests/twisted/avahi/test-register.py
from saluttest import exec_test import avahitest from avahitest import AvahiListener import time def test(q, bus, conn): a = AvahiListener(q) a.listen_for_service("_presence._tcp") conn.Connect() q.expect('service-added', name='test-register@' + avahitest.get_host_name()) if __name__ == '__ma...
from saluttest import exec_test import avahitest from avahitest import AvahiListener from avahitest import txt_get_key from avahi import txt_array_to_string_array import time PUBLISHED_NAME="test-register" FIRST_NAME="lastname" LAST_NAME="lastname" def test(q, bus, conn): a = AvahiListener(q) a.listen_for_se...
Test that the service is register with the correct txt record
Test that the service is register with the correct txt record
Python
lgpl-2.1
freedesktop-unofficial-mirror/telepathy__telepathy-salut,freedesktop-unofficial-mirror/telepathy__telepathy-salut,freedesktop-unofficial-mirror/telepathy__telepathy-salut,freedesktop-unofficial-mirror/telepathy__telepathy-salut
f898d1cc96fe66a097def29552f3774f3509be83
insultgenerator/words.py
insultgenerator/words.py
import pkg_resources import random _insulting_adjectives = [] def _load_wordlists(): global _insulting_adjectives insulting_adjective_list = pkg_resources.resource_string(__name__, "wordlists/insulting_adjectives.txt") _insulting_adjectives = insulting_adjective_list.decode().split('\n') def get_insulting_adjecti...
import pkg_resources import random _insulting_adjectives = [] def _load_wordlists(): global _insulting_adjectives insulting_adjective_list = pkg_resources.resource_string(__name__, "wordlists/insulting_adjectives.txt") _insulting_adjectives = insulting_adjective_list.decode().split('\n') def get_insulting_adjecti...
Revert "Adding test failure to ensure that CI is functioning correctly"
Revert "Adding test failure to ensure that CI is functioning correctly" This reverts commit 754be81c1ccc385d8e7b418460271966d7db2361.
Python
mit
tr00st/insult_generator
6fbe58692005e5c8b7a9c4f4e98984ae86d347a2
pinax/messages/context_processors.py
pinax/messages/context_processors.py
from .models import Thread def user_messages(request): c = {} if request.user.is_authenticated(): c["inbox_count"] = Thread.inbox(request.user).count() return c
from .models import Thread def user_messages(request): c = {} if request.user.is_authenticated(): c["inbox_threads"] = Thread.inbox(request.user) c["unread_threads"] = Thread.unread(request.user) return c
Return querysets in context processor to be more useful
Return querysets in context processor to be more useful
Python
mit
eldarion/user_messages,pinax/pinax-messages,pinax/pinax-messages,arthur-wsw/pinax-messages,eldarion/user_messages,arthur-wsw/pinax-messages
c63a1c2bc92267ac2b5ffc52c7189942d034c37b
src/dashboard/src/installer/views.py
src/dashboard/src/installer/views.py
# This file is part of Archivematica. # # Copyright 2010-2012 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the ...
# This file is part of Archivematica. # # Copyright 2010-2012 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the ...
Define skeleton for the function that will create the superuser
Define skeleton for the function that will create the superuser Autoconverted from SVN (revision:2929)
Python
agpl-3.0
artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history
c555c53290c8894c80dc7991081dd5d7591fda8c
helpers/run_feeds.py
helpers/run_feeds.py
from core.feed import Feed import core.config.celeryimports if __name__ == '__main__': all_feeds = Feed.objects() for n in all_feeds: print "Testing: {}".format(n) n.update()
import sys from core.feed import Feed import core.config.celeryimports if __name__ == '__main__': if len(sys.argv) == 1: all_feeds = Feed.objects() elif len(sys.argv) >= 2: all_feeds = [Feed.objects.get(name=sys.argv[1])] print all_feeds for n in all_feeds: print "Testing: {...
Add argument to run single feed
Add argument to run single feed
Python
apache-2.0
yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti
12254ea15b1f761ad63095ed7244f347d42e4c85
file_encryptor/__init__.py
file_encryptor/__init__.py
from file_encryptor import (convergence, key_generators)
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2014 Storj Labs # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including witho...
Add copyright, license and version information.
Add copyright, license and version information.
Python
mit
Storj/file-encryptor
864dac9b2586891f62700e3170421617aca48a88
deployment/config.py
deployment/config.py
class Azure: resource_group = "MajavaShakki" location = "northeurope" cosmosdb_name = f"{resource_group}mongo".lower() plan_name = f"{resource_group}Plan" site_name = f"{resource_group}Site" class Mongo: database_name = "Majavashakki" collection_throughput = 500 collections = ["gamemodels", "sessions",...
class Azure: resource_group = "MajavaShakki" location = "northeurope" cosmosdb_name = f"{resource_group}mongo".lower() plan_name = f"{resource_group}Plan" site_name = f"{resource_group}Site" class Mongo: database_name = "Majavashakki" collection_throughput = 500 system_indexes_collection = "undefined" ...
Configure throughput for 'undefined' collection
Configure throughput for 'undefined' collection https://github.com/Automattic/mongoose/issues/6989 https://jira.mongodb.org/browse/NODE-1662
Python
mit
Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki
3eb3cc047f2f5a358066eac8f806580089d70df2
setup.py
setup.py
from distutils.core import setup setup(name='dscsrf', version='1.0', description='Global double-submit Flask CSRF', packages=['dscsrf'], py_modules=['flask'], )
from distutils.core import setup setup(name='dscsrf', version='1.0', description='Global double-submit Flask CSRF', packages=['dscsrf'], py_modules=['flask'], author='sc4reful', url = 'https://github.com/sc4reful/dscsrf', keywords = ['security', 'flask', 'website', 'csrf'], download_url = 'https://github.com/s...
Prepare for tagging for PyPI
Prepare for tagging for PyPI
Python
mit
wkoathp/dscsrf
5a92773a1d9c40e745026ca318ae21bfce2d4fb6
flaskext/cache/backends.py
flaskext/cache/backends.py
from werkzeug.contrib.cache import (NullCache, SimpleCache, MemcachedCache, GAEMemcachedCache, FileSystemCache) def null(app, args, kwargs): return NullCache() def simple(app, args, kwargs): kwargs.update(dict(threshold=app.config['CACHE_THRESHOLD'])) return SimpleCache...
from werkzeug.contrib.cache import (NullCache, SimpleCache, MemcachedCache, GAEMemcachedCache, FileSystemCache) def null(app, args, kwargs): return NullCache() def simple(app, args, kwargs): kwargs.update(dict(threshold=app.config['CACHE_THRESHOLD'])) return SimpleCache...
Make CACHE_REDIS_PASSWORD really optional, because it does not work with older Werkzeug.
Make CACHE_REDIS_PASSWORD really optional, because it does not work with older Werkzeug.
Python
bsd-3-clause
kazeeki/mezmorize,kazeeki/mezmorize,j-fuentes/flask-cache,ordbogen/flask-cache,j-fuentes/flask-cache,thadeusb/flask-cache,alexey-sveshnikov/flask-cache,ordbogen/flask-cache,alexey-sveshnikov/flask-cache,thadeusb/flask-cache,gerasim13/flask-cache,gerasim13/flask-cache
c9c0104456ef7d5dcda29db67788112a8435945b
scripts/createDataModel.py
scripts/createDataModel.py
# script :: creating a datamodel that fits mahout from ratings.dat ratings_dat = open('../data/movielens-1m/ratings.dat', 'r') ratings_csv = open('../data/movielens-1m/ratings_without_timestamp.txt', 'w') for line in ratings_dat: arr = line.split('::') new_line = ','.join(arr[:3])+'\n'; ratings_csv.write(new_lin...
#!/usr/bin/env python # script :: creating a datamodel that fits mahout from ratings.dat ratings_dat = open('../data/movielens-1m/users.dat', 'r') ratings_csv = open('../data/movielens-1m/users.txt', 'w') for line in ratings_dat: arr = line.split('::') new_line = '\t'.join(arr) ratings_csv.write(new_line) rati...
Convert data delimiter from :: to tab character.
Convert data delimiter from :: to tab character.
Python
mit
monsendag/goldfish,ntnu-smartmedia/goldfish,ntnu-smartmedia/goldfish,monsendag/goldfish,ntnu-smartmedia/goldfish,monsendag/goldfish
a71bd3f953b0363df82d1e44b0d6df6cbe4d449b
vocab.py
vocab.py
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: ...
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: ...
Print number of terms loaded to Airtable.
Print number of terms loaded to Airtable.
Python
mit
zqureshi/vocab
c354d130cb542c2a5d57e519ce49175daa597e9c
froide/accesstoken/apps.py
froide/accesstoken/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class AccessTokenConfig(AppConfig): name = 'froide.accesstoken' verbose_name = _('Secret Access Token') def ready(self): from froide.account import account_canceled account_canceled.connect(cancel_u...
import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class AccessTokenConfig(AppConfig): name = 'froide.accesstoken' verbose_name = _('Secret Access Token') def ready(self): from froide.account import account_canceled from froide.account.e...
Add user data export for accesstokens
Add user data export for accesstokens
Python
mit
fin/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide
9ad1929ee16a805acb9e8fbc57312466fdb1770e
cnxepub/tests/scripts/test_collated_single_html.py
cnxepub/tests/scripts/test_collated_single_html.py
# -*- coding: utf-8 -*- # ### # Copyright (c) 2016, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import mimetypes import os.path import tempfile import unittest try: from unittest import mock except ...
# -*- coding: utf-8 -*- # ### # Copyright (c) 2016, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import io import mimetypes import os.path import sys import tempfile import unittest from lxml import etre...
Add a test for the validate-collated tree output
Add a test for the validate-collated tree output
Python
agpl-3.0
Connexions/cnx-epub,Connexions/cnx-epub,Connexions/cnx-epub
eba354cfaa96754b814daeb7fa453e538b07a879
krcurrency/utils.py
krcurrency/utils.py
""":mod:`krcurrency.utils` --- Helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from bs4 import BeautifulSoup as BS import requests __all__ = 'request', def request(url, encoding='utf-8', parselib='lxml'): """url๋กœ ์š”์ฒญํ•œ ํ›„ ๋Œ๋ ค๋ฐ›์€ ๊ฐ’์„ BeautifulSoup ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•ด์„œ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. """ r = requests.get(url) if r.status_c...
""":mod:`krcurrency.utils` --- Helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from bs4 import BeautifulSoup as BS import requests __all__ = 'request', 'tofloat', def request(url, encoding='utf-8', parselib='lxml'): """url๋กœ ์š”์ฒญํ•œ ํ›„ ๋Œ๋ ค๋ฐ›์€ ๊ฐ’์„ BeautifulSoup ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•ด์„œ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. """ r = requests.get(url) if...
Add tofloat function that transforms from any float-based string into float
Add tofloat function that transforms from any float-based string into float
Python
mit
ssut/py-krcurrency
c1da1e8d15990efa7b30de241e3604bc824792dc
py101/introduction/__init__.py
py101/introduction/__init__.py
"""" Introduction Adventure Author: igui """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): "Introduction Adventure test" def __init__(self, sourcefile): ...
"""" Introduction Adventure Author: Ignacio Avas (iavas@sophilabs.com) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): "Introduction Adventure test" de...
Correct Author string in module
Correct Author string in module
Python
mit
sophilabs/py101
2651ddf1946ec489195ec9c3fb23e00e5735c79c
sites/cozylan/extension.py
sites/cozylan/extension.py
""" Site-specific code extension """ from __future__ import annotations from typing import Any from flask import g from byceps.services.seating import seat_service from byceps.services.ticketing import ticket_service def template_context_processor() -> dict[str, Any]: """Extend template context.""" if g.pa...
""" Site-specific code extension """ from __future__ import annotations from typing import Any from flask import g from byceps.services.seating import seat_service from byceps.services.ticketing import ticket_service def template_context_processor() -> dict[str, Any]: """Extend template context.""" context...
Restructure context assembly for CozyLAN site
Restructure context assembly for CozyLAN site
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
624ce97b011100cc1aac9446c7f1c8a97eae5f34
workshops/migrations/0040_add_country_to_online_events.py
workshops/migrations/0040_add_country_to_online_events.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_country_to_online_events(apps, schema_editor): """Add an 'Online' country to all events tagged with 'online' tag.""" Event = apps.get_model('workshops', 'Event') Tag = apps.get_model('worksho...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_country_to_online_events(apps, schema_editor): """Add an 'Online' country to all events tagged with 'online' tag.""" Event = apps.get_model('workshops', 'Event') Tag = apps.get_model('worksho...
Migrate online events to the Pole of Inaccessibility lat/long
Migrate online events to the Pole of Inaccessibility lat/long ...and 'internet' as a venue.
Python
mit
pbanaszkiewicz/amy,vahtras/amy,swcarpentry/amy,swcarpentry/amy,wking/swc-amy,vahtras/amy,wking/swc-amy,wking/swc-amy,vahtras/amy,pbanaszkiewicz/amy,wking/swc-amy,pbanaszkiewicz/amy,swcarpentry/amy
9ad98b4bbed0c67f25576187996e7e1d534f6a90
mammoth/__init__.py
mammoth/__init__.py
from .results import Result from . import docx, conversion, style_reader def convert_to_html(fileobj): return docx.read(fileobj).bind(lambda document: conversion.convert_document_element_to_html(document, styles=_create_default_styles()) ) def _create_default_styles(): lines = filter(None, map(...
from .results import Result from . import docx, conversion, style_reader def convert_to_html(fileobj): return docx.read(fileobj).bind(lambda document: conversion.convert_document_element_to_html(document, styles=_create_default_styles()) ) def _create_default_styles(): lines = filter(None, map(...
Add full list of default styles
Add full list of default styles
Python
bsd-2-clause
mwilliamson/python-mammoth,JoshBarr/python-mammoth
afd6b5b29b60c59689e0a1be38a0483a7e4db312
miniraf/__init__.py
miniraf/__init__.py
import argparse import astropy.io.fits as fits import numpy as np import calc import combine if __name__=="__main__": argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) args = argpars...
import argparse import calc import combine from combine import stack_fits_data from calc import load_fits_data def _argparse(): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) ret...
Create main() entry point for final script
Create main() entry point for final script Signed-off-by: Lizhou Sha <d6acb26e253550574bc1141efa0eb5e6de15daeb@mit.edu>
Python
mit
vulpicastor/miniraf
60bb1425e94e15b59a05b485113cc68ed0146ac8
nbtutor/__init__.py
nbtutor/__init__.py
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearEx...
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearEx...
Create solutions directory if it does not exist
Create solutions directory if it does not exist
Python
bsd-2-clause
jorisvandenbossche/nbtutor,jorisvandenbossche/nbtutor
09195f50e328d3aee4cc60f0702d8605ea520eb3
tests/sentry/utils/models/tests.py
tests/sentry/utils/models/tests.py
from __future__ import absolute_import from django.db import models from sentry.utils.models import Model from sentry.testutils import TestCase # There's a good chance this model wont get created in the db, so avoid # assuming it exists in these tests. class DummyModel(Model): foo = models.CharField(max_length=3...
from __future__ import absolute_import from django.db import models from sentry.utils.models import Model from sentry.testutils import TestCase # There's a good chance this model wont get created in the db, so avoid # assuming it exists in these tests. class DummyModel(Model): foo = models.CharField(max_length=3...
Add missing assertion in test
Add missing assertion in test
Python
bsd-3-clause
NickPresta/sentry,jokey2k/sentry,1tush/sentry,zenefits/sentry,SilentCircle/sentry,wujuguang/sentry,ifduyue/sentry,Kryz/sentry,JamesMura/sentry,Natim/sentry,NickPresta/sentry,BuildingLink/sentry,rdio/sentry,BuildingLink/sentry,ngonzalvez/sentry,JamesMura/sentry,mvaled/sentry,JackDanger/sentry,SilentCircle/sentry,ifduyue...
57d49b185d1daf0e6a27e0daee8960c2816615cc
alg_kruskal_minimum_spanning_tree.py
alg_kruskal_minimum_spanning_tree.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function def kruskal(): """Kruskal's algorithm for minimum spanning tree in weighted graph. Time complexity for graph G(V, E): TBD. """ pass def main(): w_graph_d = { 'a': {'b': 1, 'd': 4, 'e': 3}, ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function def kruskal(): """Kruskal's algorithm for minimum spanning tree in weighted graph. Time complexity for graph G(V, E): O(|E|+|V|+|E|log(|V|)) = O(|E|log(|V|^2)) = O(|E|log(|V|)). """ pass def ma...
Revise doc string and add time complexity
Revise doc string and add time complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
c1dc5494c461677e15be52576c55585742ad4a7a
bluebottle/bb_follow/migrations/0003_auto_20180530_1621.py
bluebottle/bb_follow/migrations/0003_auto_20180530_1621.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-05-30 14:21 from __future__ import unicode_literals from django.db import migrations def fix_followers(apps, schema_editor): Donation = apps.get_model('donations', 'Donation') Follow = apps.get_model('bb_follow', 'Follow') ContentType = apps.ge...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-05-30 14:21 from __future__ import unicode_literals from django.db import migrations def fix_followers(apps, schema_editor): Donation = apps.get_model('donations', 'Donation') Follow = apps.get_model('bb_follow', 'Follow') ContentType = apps.ge...
Add donation migration dependancy in bb_follow
Add donation migration dependancy in bb_follow
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
1c5a4afa06f56ca8fd7c36b633b7f73d259f1281
lib/filesystem/__init__.py
lib/filesystem/__init__.py
import os __author__ = 'mfliri' def create_directory(output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir)
import os def create_directory(output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir)
Remove author notice and add newline at end of file
Remove author notice and add newline at end of file
Python
mit
alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer
96a6b929d80bd5ad8a7bf5d09955b3e45e5bbe56
test/test_Spectrum.py
test/test_Spectrum.py
#!/usr/bin/env python from __future__ import division, print_function import pytest import sys # Add Spectrum location to path sys.path.append('../') import Spectrum # Test using hypothesis from hypothesis import given import hypothesis.strategies as st @given(st.lists(st.floats()), st.lists(st.floats()), st.boolea...
#!/usr/bin/env python from __future__ import division, print_function import pytest import sys # Add Spectrum location to path sys.path.append('../') import Spectrum # Test using hypothesis from hypothesis import given import hypothesis.strategies as st @given(st.lists(st.floats()), st.lists(st.floats()), st.boolea...
Test property of wavelength selection
Test property of wavelength selection That afterwards the values are all above and below the min and max values used.
Python
mit
jason-neal/spectrum_overload,jason-neal/spectrum_overload,jason-neal/spectrum_overload
c61e595098cd4b03828a81db98fb1e2b91b2eec0
anna/model/utils.py
anna/model/utils.py
import tensorflow as tf def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None): dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0 cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse) if dropout > 0.0: keep_prop = (1.0 - dropout) cell...
import tensorflow as tf def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None): dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0 cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse) if dropout > 0.0: keep_prop = (1.0 - dropout) cell...
Remove dropout from output/state in rnn cells
Remove dropout from output/state in rnn cells
Python
mit
jpbottaro/anna
66946f72d243f1836df0dbd8917f204011ec1701
hs_core/autocomplete_light_registry.py
hs_core/autocomplete_light_registry.py
from autocomplete_light import shortcuts as autocomplete_light from django.contrib.auth.models import User, Group class UserAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['username', 'first_name', 'last_name'] split_words = True def choices_for_request(self): self.choices...
from autocomplete_light import shortcuts as autocomplete_light from django.contrib.auth.models import User, Group class UserAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['username', 'first_name', 'last_name'] split_words = True def choices_for_request(self): self.choice...
Add middle name display to autocomplete widget
Add middle name display to autocomplete widget
Python
bsd-3-clause
hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare
f5d36900f7b0503a60a526fd70b57ecb91625fa0
armstrong/core/arm_sections/views.py
armstrong/core/arm_sections/views.py
from django.core.urlresolvers import reverse from django.views.generic import DetailView from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Section class SimpleSectionView(DetailView): context_object_name = 'section' model = Section def g...
from django.core.urlresolvers import reverse from django.views.generic import DetailView from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Section class SimpleSectionView(DetailView): context_object_name = 'section' model = Section def g...
Handle queryset argument to get_object
Handle queryset argument to get_object
Python
apache-2.0
texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections
7e766747dbda4548b63b278e062335c8a10fe008
src/vimapt/library/vimapt/data_format/yaml.py
src/vimapt/library/vimapt/data_format/yaml.py
from pureyaml import dump as dumps from pureyaml import load as loads __all__ = ['dumps', 'loads']
from __future__ import absolute_import import functools from yaml import dump, Dumper, load, Loader dumps = functools.partial(dump, Dumper=Dumper) loads = functools.partial(load, Loader=Loader) __all__ = ['dumps', 'loads']
Use PyYAML as YAML's loader and dumper
Use PyYAML as YAML's loader and dumper
Python
mit
howl-anderson/vimapt,howl-anderson/vimapt
f600ec497a6ff20c4cd8c983e27482fc77ab4deb
moksha/api/hub/consumer.py
moksha/api/hub/consumer.py
""" Consumers ========= A `Consumer` is a simple consumer of messages. Based on a given `routing_key`, your consumer's :meth:`consume` method will be called with the message. Example consumers: -tapping into a koji build, and sending a notification? - hook into a given RSS feed and save data in a DB? Addin...
# This file is part of Moksha. # # Moksha 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. # # Moksha is distributed in the hope that it...
Update our message Consumer api to consume a `topic`, not a `queue`.
Update our message Consumer api to consume a `topic`, not a `queue`.
Python
apache-2.0
lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha,pombredanne/moksha,mokshaproject/moksha,ralphbean/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,lmacken/moksha
357a445021bd459cc0196269033ea181594a1456
UliEngineering/Physics/NTC.py
UliEngineering/Physics/NTC.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utilities regarding NTC thermistors See http://www.vishay.com/docs/29053/ntcintro.pdf for details """ from UliEngineering.Physics.Temperature import zero_point_celsius, normalize_temperature from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.U...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utilities regarding NTC thermistors See http://www.vishay.com/docs/29053/ntcintro.pdf for details """ from UliEngineering.Physics.Temperature import normalize_temperature from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.Units import Unit imp...
Fix build error due to replacing zero_point_celsius by scipy equivalent
Fix build error due to replacing zero_point_celsius by scipy equivalent
Python
apache-2.0
ulikoehler/UliEngineering
cddb0ae5c9c2d96c5902943f8b341ab2b698235f
paveldedik/forms.py
paveldedik/forms.py
# -*- coding: utf-8 -*- from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post post_args = { 'title': {'label': u'Title'}, 'leading': {'label': u'Leading'}, 'content': {'label': u'Content'}, } UserForm = model_form(User) PostForm = model_form(Post, field_args=post_...
# -*- coding: utf-8 -*- from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post #: Model the user form. Additional field arguments can be included using #: the key-word argument ``field_args``. For more information about using #: WTForms follow `this link<http://flask.pocoo.org/sn...
Exclude post_id from the wtform.
Exclude post_id from the wtform.
Python
mit
paveldedik/blog,paveldedik/blog
bbff08c49df269ad24851d4264fd3f1dbd141358
test/contrib/test_securetransport.py
test/contrib/test_securetransport.py
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() exce...
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() exce...
Fix whitespace issue in SecureTransport test
Fix whitespace issue in SecureTransport test
Python
mit
urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3,urllib3/urllib3
141b46d1f5178df7e110aee7b2b50ce6f5b44b7a
contrib/python-copper/t/test_wsgi.py
contrib/python-copper/t/test_wsgi.py
# -*- coding: utf-8 -*- from copper.wsgi_support import wsgi def test_http_handler(copper_client, copper_http_client): def application(environ, start_response): message = 'Hello, %s!' % (environ['PATH_INFO'],) start_response('200 OK', [ ('Content-Type', 'text/plain; charset=UTF-8'), ...
# -*- coding: utf-8 -*- from copper.wsgi_support import wsgi def test_http_handler(copper_client, copper_http_client): def application(environ, start_response): message = 'Hello, %s!' % (environ['PATH_INFO'],) start_response('200 OK', [ ('Content-Type', 'text/plain; charset=UTF-8'), ...
Fix python tests re: http routing
Fix python tests re: http routing
Python
mit
snaury/copper,snaury/copper,snaury/copper
4bc55a6b1bdef357acd24e6aba34a57f689e9da0
bokeh/command/subcommands/__init__.py
bokeh/command/subcommands/__init__.py
def _collect(): from importlib import import_module from os import listdir from os.path import dirname from ..subcommand import Subcommand results = [] for file in listdir(dirname(__file__)): if not file.endswith(".py") or file in ("__init__.py", "__main__.py"): continue...
def _collect(): from importlib import import_module from os import listdir from os.path import dirname from ..subcommand import Subcommand results = [] for file in listdir(dirname(__file__)): if not file.endswith(".py") or file in ("__init__.py", "__main__.py"): continue...
Sort subcommands.all so the tested results are deterministic
Sort subcommands.all so the tested results are deterministic
Python
bsd-3-clause
phobson/bokeh,clairetang6/bokeh,aiguofer/bokeh,jakirkham/bokeh,msarahan/bokeh,mindriot101/bokeh,philippjfr/bokeh,schoolie/bokeh,stonebig/bokeh,azjps/bokeh,percyfal/bokeh,bokeh/bokeh,draperjames/bokeh,percyfal/bokeh,draperjames/bokeh,msarahan/bokeh,ptitjano/bokeh,msarahan/bokeh,quasiben/bokeh,KasperPRasmussen/bokeh,aigu...
4fce2955ce76c1f886b2a234fe9d0c576843fefd
Dice.py
Dice.py
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) ...
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) ...
Add hold all function to dicebag
Add hold all function to dicebag
Python
mit
achyutreddy24/DiceGame
628de346d3cf22342bf09e9ad3337a4408ed5662
properties/files.py
properties/files.py
from __future__ import absolute_import, unicode_literals, print_function, division from builtins import open from future import standard_library standard_library.install_aliases() import six import json, numpy as np, os, io from .base import Property from . import exceptions class File(Property): mode = 'r' #: m...
from __future__ import absolute_import, print_function, division from builtins import open from future import standard_library standard_library.install_aliases() import six import json, numpy as np, os, io from .base import Property from . import exceptions class File(Property): mode = 'r' #: mode for opening th...
Fix png for python 2/3 compatibility
Fix png for python 2/3 compatibility
Python
mit
aranzgeo/properties,3ptscience/properties
7fcccea5d7fdfb823d17f1db56f5ece42ef2fd8b
tools/bundle.py
tools/bundle.py
#!/usr/bin/env python import os import sys import glob import getopt def file_list(path): files = [] if os.path.isfile(path): return [path] for f in os.listdir(path): new_dir = os.path.join(path, f) if os.path.isdir(new_dir) and not os.path.islink(new_dir): files.extend(file_list(new_dir)) ...
#!/usr/bin/env python import os import sys import glob import getopt def file_list(path): files = [] if os.path.isfile(path): return [path] for f in os.listdir(path): new_dir = path + '/' + f if os.path.isdir(new_dir) and not os.path.islink(new_dir): files.extend(file_list(new_dir)) else...
Stop using os.path.join, because Visual Studio can actually handle forward slash style paths, and the os.path method was creating mixed \\ and / style paths, b0rking everything.
Stop using os.path.join, because Visual Studio can actually handle forward slash style paths, and the os.path method was creating mixed \\ and / style paths, b0rking everything.
Python
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
dfd6793f16d0128b3d143d0f1ebc196bb79505c2
chnnlsdmo/chnnlsdmo/models.py
chnnlsdmo/chnnlsdmo/models.py
from django.db import models from django.contrib.auth.models import User class Voter(models.Model): ''' Models someone who may vote ''' user = models.OneToOneField(User) def __str__(self): return self.user.username class Flag(models.Model): ''' Models a flag which may be voted o...
from django.db import models from django.contrib.auth.models import User class Voter(models.Model): ''' Models someone who may vote ''' user = models.OneToOneField(User) def __str__(self): return self.user.username class Flag(models.Model): ''' Models a flag which may be voted o...
Add date/time created timestamp to Vote model
Add date/time created timestamp to Vote model
Python
bsd-3-clause
shearichard/django-channels-demo,shearichard/django-channels-demo,shearichard/django-channels-demo
34d7a7ea41843ef4761804e973ec9ded1bb2a03b
cla_backend/apps/cla_butler/management/commands/reverthousekeeping.py
cla_backend/apps/cla_butler/management/commands/reverthousekeeping.py
# -*- coding: utf-8 -*- import os from django.conf import settings from django.contrib.admin.models import LogEntry from django.core.management.base import BaseCommand from cla_eventlog.models import Log from cla_provider.models import Feedback from complaints.models import Complaint from diagnosis.models import Diag...
# -*- coding: utf-8 -*- import os from django.conf import settings from django.contrib.admin.models import LogEntry from django.core.management.base import BaseCommand from cla_eventlog.models import Log from cla_provider.models import Feedback from complaints.models import Complaint from diagnosis.models import Diag...
Refactor args in manage task
Refactor args in manage task
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
f7777c858baf049af83bd39168d0640e4dedf29c
main.py
main.py
import slackclient import time import os slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"]) slackClient.rtm_connect() lastPingTime = 0 print(os.environ) while True: for message in slackClient.rtm_read(): if message["type"] == "team_join": username = message["user"]["name"] ...
import slackclient import time import os slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"]) slackClient.rtm_connect() lastPingTime = 0 while True: raise Exception(str(os.environ)) for message in slackClient.rtm_read(): if message["type"] == "team_join": username = message["use...
Change debug message to exception
Change debug message to exception
Python
mit
ollien/Slack-Welcome-Bot
f5cc3275a11c809bb6f5ab097414d0a5ccda2341
main.py
main.py
def main(): website = input("Input website(cnn, nytimes, bbc, nzherald): ") url = input("Input url: ") scraper(website, url) def scraper(website, url): print("%s, %s" % (website, url)) if __name__ == '__main__': main()
def main(): website = input("Input website(cnn, nytimes, bbc, nzherald): ") url = input("Input url: ") scraper(website, url) def scraper(website, url): if ".com" not in url: print("Invalid url") exit() print("%s, %s" % (website, url)) if __name__ == '__main__': main()
Check for .com in url
Check for .com in url
Python
mit
Alex-Gurung/ScrapeTheNews
e3e98b0533460837c4ea2eac67c4281eb0ba0012
test/requests/parametrized_test.py
test/requests/parametrized_test.py
import logging import unittest from wqflask import app from elasticsearch import Elasticsearch, TransportError class ParametrizedTest(unittest.TestCase): def __init__(self, methodName='runTest', gn2_url="http://localhost:5003", es_url="localhost:9200"): super(ParametrizedTest, self).__init__(methodName=me...
import logging import unittest from wqflask import app from utility.elasticsearch_tools import get_elasticsearch_connection, get_user_by_unique_column from elasticsearch import Elasticsearch, TransportError class ParametrizedTest(unittest.TestCase): def __init__(self, methodName='runTest', gn2_url="http://localho...
Use existing code. Delay after delete.
Use existing code. Delay after delete. * Use existing code to get the elasticsearch connection. This should prevent tests from failing in case the way connections to elasticsearch are made change. * Delay a while after deleting to allow elasticsearch to re-index the data, thus preventing subtle bugs in the test....
Python
agpl-3.0
DannyArends/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/gen...
cdb4fa00328f3bc5852b9cae799d4d3ed99f1280
pyramid_authsanity/util.py
pyramid_authsanity/util.py
from pyramid.interfaces import ( ISessionFactory, ) from .interfaces import ( IAuthService, IAuthSourceService, ) def int_or_none(x): return int(x) if x is not None else x def kw_from_settings(settings, from_prefix='authsanity.'): return dict((k.replace(from_prefix, ''), v) for (k, v) in ...
from pyramid.interfaces import ( ISessionFactory, ) from .interfaces import ( IAuthService, IAuthSourceService, ) def int_or_none(x): return int(x) if x is not None else x def kw_from_settings(settings, from_prefix='authsanity.'): return { k.replace(from_prefix, ''): v for k, v in setting...
Revert "Py 2.6 support is back"
Revert "Py 2.6 support is back" This reverts commit 463c1ab6a7f5a7909b967e0dfa0320a77e166b95.
Python
isc
usingnamespace/pyramid_authsanity
977c8cc25c3978931e0d908589232db1bcac5b3f
fitizen/body_weight_workout/views.py
fitizen/body_weight_workout/views.py
# from datetime import datetime from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy from .models import BodyWeightWorkout from braces import views # Create your views here. class CreateWorkout( views.LoginRequiredMixin, views.MessageMixin, RedirectView ): ...
from datetime import datetime from django.utils import timezone from django.shortcuts import redirect from django.views.generic import View from django.core.urlresolvers import reverse_lazy from .models import BodyWeightWorkout from braces import views # Create your views here. class CreateWorkout( views.Login...
Create Workout now checks to see if you worked out once today already, if so tells user they already worked out on that day. fixed error where redirect would not re-instantiate get request to createview
Create Workout now checks to see if you worked out once today already, if so tells user they already worked out on that day. fixed error where redirect would not re-instantiate get request to createview
Python
mit
johnshiver/fitizen,johnshiver/fitizen
6567120249b82477bcf0ef82554b057f93618e7e
tools/gyp/find_mac_gcc_version.py
tools/gyp/find_mac_gcc_version.py
#!/usr/bin/env python # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import re import subprocess import sys def main(): job = subprocess.Popen(['xcode...
#!/usr/bin/env python # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import re import subprocess import sys def main(): job = subprocess.Popen(['xcode...
Revert "Use clang on mac if XCode >= 4.5"
Revert "Use clang on mac if XCode >= 4.5" We cannot build v8 after this change because clang reports a warning in v8/src/parser.cc about an unused field (and we turn warnings into errors). We can enable this change again after we update to a new v8 version (this seems to be fixed in v3.17). Review URL: https://coder...
Python
bsd-3-clause
dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-s...
8218b398731e8d9093a91de9bb127e2e933fa6db
json_editor/admin.py
json_editor/admin.py
import json import copy from django import forms from django.utils.safestring import mark_safe from django.template.loader import render_to_string class JSONEditorWidget(forms.Widget): template_name = 'django_json_editor/django_json_editor.html' def __init__(self, schema, collapsed=True): super()._...
import json import copy from django import forms from django.utils.safestring import mark_safe from django.template.loader import render_to_string class JSONEditorWidget(forms.Widget): template_name = 'django_json_editor/django_json_editor.html' def __init__(self, schema, collapsed=True): super()._...
Load value from json field as string.
Load value from json field as string.
Python
mit
abogushov/django-admin-json-editor,abogushov/django-admin-json-editor
414f6e9174b8c7b88866319af19a5e36fcec643d
kk/admin/__init__.py
kk/admin/__init__.py
from django.contrib import admin from kk.models import Hearing, Label, Introduction, Scenario, Comment admin.site.register(Label) admin.site.register(Hearing) admin.site.register(Introduction) admin.site.register(Scenario) admin.site.register(Comment)
from django.contrib import admin from kk import models ### Inlines class IntroductionInline(admin.StackedInline): model = models.Introduction extra = 0 exclude = ["id"] class ScenarioInline(admin.StackedInline): model = models.Scenario extra = 0 exclude = ["id"] class HearingImageInline(a...
Make the admin a little bit more palatable
Make the admin a little bit more palatable Refs #25
Python
mit
stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi
b0029cffae96e25611d7387e699774de4d9682d3
corehq/apps/es/tests/utils.py
corehq/apps/es/tests/utils.py
import json from nose.plugins.attrib import attr class ElasticTestMixin(object): def checkQuery(self, query, json_output, is_raw_query=False): if is_raw_query: raw_query = query else: raw_query = query.raw_query msg = "Expected Query:\n{}\nGenerated Query:\n{}".for...
import json from nose.plugins.attrib import attr from nose.tools import nottest class ElasticTestMixin(object): def checkQuery(self, query, json_output, is_raw_query=False): if is_raw_query: raw_query = query else: raw_query = query.raw_query msg = "Expected Query:...
Mark es_test decorator as nottest
Mark es_test decorator as nottest Second try...
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
913ae38e48591000195166a93e18e96a82d1d222
lily/messaging/email/migrations/0013_fix_multple_default_templates.py
lily/messaging/email/migrations/0013_fix_multple_default_templates.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'Lily...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'Lily...
Remove print statements, not usefull anymore.
Remove print statements, not usefull anymore.
Python
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
517e22b331f63e80cb344e257789463627b44508
utilities/rename-random-number.py
utilities/rename-random-number.py
''' rename files in local directory with random integer names. windows screen saver isn't very good at randomizing fotos shown. Change file names regularly to provide more variety ''' import os import re import random random.seed() new_names = set() original_files = [] for entry in os.listdir(): if os.path.is...
#! python3 ''' rename files in local directory with random integer names. windows screen saver isn't very good at randomizing fotos shown. Change file names regularly to provide more variety ''' import os import re import random import time random.seed() new_names = set() original_files = [] for entry in os.lis...
Increase namespace, sleep before cmd window closes
Increase namespace, sleep before cmd window closes
Python
mit
daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various
69ae2f5b825ae6a404d78120b60727b59dbbcbac
xos/model_policies/model_policy_ControllerSlice.py
xos/model_policies/model_policy_ControllerSlice.py
def handle(controller_slice): from core.models import ControllerSlice, Slice try: my_status_code = int(controller_slice.backend_status[0]) try: his_status_code = int(controller_slice.slice.backend_status[0]) except: his_status_code = 0 if (my_status_...
def handle(controller_slice): from core.models import ControllerSlice, Slice try: my_status_code = int(controller_slice.backend_status[0]) try: his_status_code = int(controller_slice.slice.backend_status[0]) except: his_status_code = 0 fields = [] ...
Copy backend_register from ControllerSlice to Slice
Copy backend_register from ControllerSlice to Slice
Python
apache-2.0
jermowery/xos,xmaruto/mcord,xmaruto/mcord,jermowery/xos,cboling/xos,jermowery/xos,cboling/xos,cboling/xos,jermowery/xos,xmaruto/mcord,xmaruto/mcord,cboling/xos,cboling/xos
5d6d2a02963cadd9b0a5c148fb6906fa63148052
booster_bdd/features/environment.py
booster_bdd/features/environment.py
"""Module with code to be run before and after certain events during the testing.""" import os from src.support import helpers def before_all(_context): """Perform the setup before the first event.""" if not helpers.is_user_logged_in(): username = os.getenv("OSIO_USERNAME") password = os.geten...
"""Module with code to be run before and after certain events during the testing.""" import os from src.support import helpers def before_all(_context): """Perform the setup before the first event.""" if not helpers.is_user_logged_in(): username = os.getenv("OSIO_USERNAME") password = os.geten...
Check for env. variable existence
Check for env. variable existence
Python
apache-2.0
ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test
08113ee79785f394a1c5244cdb87bef9f7fc5ff3
catplot/__init__.py
catplot/__init__.py
__all__ = ['en_profile'] __version__ = '0.1.0'
__all__ = ['en_profile', 'functions', 'chem_parser'] __version__ = '0.1.0'
Add more modules to __all__
Add more modules to __all__
Python
mit
PytLab/catplot
338a6e8da75a5b950949638b1a810510419450e9
scripts/state_and_transition.py
scripts/state_and_transition.py
#!/usr/bin/env python # # Copyright 2017 Robot Garden, Inc. # # 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 applicab...
#!/usr/bin/env python # # Copyright 2017 Robot Garden, Inc. # # 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 applicab...
Add new state for driving away from cone
Add new state for driving away from cone
Python
apache-2.0
ProgrammingRobotsStudyGroup/robo_magellan,ProgrammingRobotsStudyGroup/robo_magellan,ProgrammingRobotsStudyGroup/robo_magellan,ProgrammingRobotsStudyGroup/robo_magellan
7f5392d2581e789917b8ba5352d821277d5de8ab
numpy/typing/_scalars.py
numpy/typing/_scalars.py
from typing import Union, Tuple, Any import numpy as np # NOTE: `_StrLike` and `_BytesLike` are pointless, as `np.str_` and `np.bytes_` # are already subclasses of their builtin counterpart _CharLike = Union[str, bytes] _BoolLike = Union[bool, np.bool_] _IntLike = Union[int, np.integer] _FloatLike = Union[_IntLike,...
from typing import Union, Tuple, Any import numpy as np # NOTE: `_StrLike` and `_BytesLike` are pointless, as `np.str_` and `np.bytes_` # are already subclasses of their builtin counterpart _CharLike = Union[str, bytes] # The 6 `<X>Like` type-aliases below represent all scalars that can be # coerced into `<X>` (wit...
Add `_BoolLike` to the union defining `_IntLike`
ENH: Add `_BoolLike` to the union defining `_IntLike`
Python
bsd-3-clause
seberg/numpy,pdebuyl/numpy,mhvk/numpy,pbrod/numpy,madphysicist/numpy,endolith/numpy,mattip/numpy,simongibbons/numpy,numpy/numpy,endolith/numpy,jakirkham/numpy,rgommers/numpy,mattip/numpy,madphysicist/numpy,mhvk/numpy,jakirkham/numpy,pdebuyl/numpy,simongibbons/numpy,charris/numpy,simongibbons/numpy,anntzer/numpy,charris...
239e759eed720f884e492e47b82e64f25fdc215f
core/views.py
core/views.py
# views.py from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query def search(request): # Search search_query = request.GET.get("q", None) if search_query: search_results = Page.objects.live().search(search_query) # Log the query ...
# views.py from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query def search(request): # Search search_query = request.GET.get("q", None) page = request.GET.get("page", 1) ...
Add pagination to the reinstated search view
Add pagination to the reinstated search view
Python
mit
springload/madewithwagtail,springload/madewithwagtail,springload/madewithwagtail,springload/madewithwagtail
f3d3c0ce81ba8717f5839b502e57d75ebbc1f6e7
meetuppizza/views.py
meetuppizza/views.py
from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from meetuppizza.forms import RegistrationForm from meetup.models import Meetup from meetup.services.meetup_service import MeetupService def index(request): meetups = Meetup.objects.all() meetup_presenters = ...
from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from meetuppizza.forms import RegistrationForm from meetup.models import Meetup from meetup.services.meetup_service import MeetupService def index(request): meetups = Meetup.objects.all() meetup_presenters = ...
Use list comprehension to generate MeetupPresentor list in index view
Use list comprehension to generate MeetupPresentor list in index view
Python
mit
nicole-a-tesla/meetup.pizza,nicole-a-tesla/meetup.pizza
c6ef5bcac4d5daddac97ff30ff18645249928ac0
nap/engine.py
nap/engine.py
import json try: import msgpack except ImportError: pass from decimal import Decimal from datetime import date, datetime, time class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' ...
import json class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' ...
Remove unused imports Only define MsgPackEngine if we can import MsgPack
Remove unused imports Only define MsgPackEngine if we can import MsgPack
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
ed69ace7f6065ec1b3dd2f2de3a0d5b56ac28366
climatemaps/data.py
climatemaps/data.py
import numpy def import_climate_data(): ncols = 720 nrows = 360 digits = 5 with open('./data/cloud/ccld6190.dat') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 xmin = 0.25 xmax = 360.25 ymin = -89.75 ymax = 90.25 lon...
import numpy def import_climate_data(): ncols = 720 nrows = 360 digits = 5 monthnr = 3 with open('./data/cloud/ccld6190.dat', 'r') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 xmin = 0.25 xmax = 360.25 ymin = -89.75 yma...
Create argument to select month to import
Create argument to select month to import
Python
mit
bartromgens/climatemaps,bartromgens/climatemaps,bartromgens/climatemaps
c15174d9bd7728dd5d397e6de09291853e65ed4d
scripts/test_deployment.py
scripts/test_deployment.py
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == ...
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"template_key": "iw", "text_lines": ["test", "deployment"]} response = requests.post(f"{url}/images", json=params) expect(response.status...
Update tests for new API routes
Update tests for new API routes
Python
mit
jacebrowning/memegen,jacebrowning/memegen
057d7a95031ba8c51ae10ea1b742534fcb5e82a3
bidb/keys/tasks.py
bidb/keys/tasks.py
import celery import subprocess from bidb.utils.tempfile import TemporaryDirectory from bidb.utils.subprocess import check_output2 from .models import Key @celery.task(soft_time_limit=60) def update_or_create_key(uid): with TemporaryDirectory() as homedir: try: check_output2(( ...
import celery import subprocess from bidb.utils.tempfile import TemporaryDirectory from bidb.utils.subprocess import check_output2 from .models import Key @celery.task(soft_time_limit=60) def update_or_create_key(uid): with TemporaryDirectory() as homedir: try: check_output2(( ...
Use pgpkeys.mit.edu as our keyserver; seems to work.
Use pgpkeys.mit.edu as our keyserver; seems to work.
Python
agpl-3.0
lamby/buildinfo.debian.net,lamby/buildinfo.debian.net
63f40971f8bc4858b32b41595d14315d2261169f
proselint/checks/garner/mondegreens.py
proselint/checks/garner/mondegreens.py
# -*- coding: utf-8 -*- """Mondegreens. --- layout: post source: Garner's Modern American Usage source_url: http://amzn.to/15wF76r title: mondegreens date: 2014-06-10 12:31:19 categories: writing --- Points out preferred form. """ from tools import memoize, preferred_forms_check @memoize def che...
# -*- coding: utf-8 -*- """Mondegreens. --- layout: post source: Garner's Modern American Usage source_url: http://amzn.to/15wF76r title: mondegreens date: 2014-06-10 12:31:19 categories: writing --- Points out preferred form. """ from tools import memoize, preferred_forms_check @memoize def che...
Fix bug in mondegreen rule
Fix bug in mondegreen rule (The correct versions should all be in the left column.)
Python
bsd-3-clause
jstewmon/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint
abaa882aaa1b7e251d989d60391bd2e06801c2a2
py/desiUtil/install/most_recent_tag.py
py/desiUtil/install/most_recent_tag.py
# License information goes here # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals # The line above will help with 2to3 support. def most_recent_tag(tags,username=None): """Scan an SVN tags directory and return the most recent tag. Parameters --------...
# License information goes here # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals # The line above will help with 2to3 support. def most_recent_tag(tags,username=None): """Scan an SVN tags directory and return the most recent tag. Parameters --------...
Add more careful version checks
Add more careful version checks
Python
bsd-3-clause
desihub/desiutil,desihub/desiutil
f60fe11653d71f278aa04e71a522a89fc86c284a
bse/api.py
bse/api.py
''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, ...
''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, ...
Switch which name is used as a metadata key
Switch which name is used as a metadata key
Python
bsd-3-clause
MOLSSI-BSE/basis_set_exchange
8d46e411b2e7091fc54c676665905da8ec6906f3
controllers/dotd.py
controllers/dotd.py
def form(): db.raw_log.uuid.default = uuid_generator() db.raw_log.date.default = dbdate() #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False form = SQLFORM(db.raw_log, sho...
def form(): db.raw_log.uuid.default = uuid_generator() db.raw_log.date.default = dbdate() #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False if form.accepted: redirect(U...
Remove selection of all raw_log rows, since it was used for debugging purposes only
Remove selection of all raw_log rows, since it was used for debugging purposes only
Python
mit
tsunam/dotd_parser,tsunam/dotd_parser,tsunam/dotd_parser,tsunam/dotd_parser
47b52333a74aeeb0ec2d7184455f70aa07633e62
createGlyphsPDF.py
createGlyphsPDF.py
# Some configuration page_format = 'A4' newPage(page_format) class RegisterGlyph(object): def __init__(self, glyph): self.glyph = glyph print 'Registered', self.glyph.name self.proportion_ratio = self.getProportionRatio() def getProportionRatio(self): print self.glyph...
# Some configuration page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values my_selection = CurrentFont() # May also be CurrentFont.selection or else class RegisterGlyph(object): def __init__(self, glyph): self.glyph = glyph print 'Register...
Create Page for every glyph
Create Page for every glyph
Python
mit
AlphabetType/DrawBot-Scripts
10aaa22cbcbb844a4393ac9eae526c3e50c121ab
src/ggrc/migrations/versions/20131209164454_49c670c7d705_add_private_column_t.py
src/ggrc/migrations/versions/20131209164454_49c670c7d705_add_private_column_t.py
"""Add private column to programs table. Revision ID: 49c670c7d705 Revises: a3afeab3302 Create Date: 2013-12-09 16:44:54.222398 """ # revision identifiers, used by Alembic. revision = '49c670c7d705' down_revision = 'a3afeab3302' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( ...
"""Add private column to programs table. Revision ID: 49c670c7d705 Revises: a3afeab3302 Create Date: 2013-12-09 16:44:54.222398 """ # revision identifiers, used by Alembic. revision = '49c670c7d705' down_revision = 'a3afeab3302' from alembic import op from sqlalchemy.sql import table, column import sqlalchemy as s...
Make sure to properly set private for existing private programs.
Make sure to properly set private for existing private programs.
Python
apache-2.0
hyperNURb/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,vladan-m/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,andrei-karalionak/g...
63af9aa63dac1b3601ab5bfee5fd29b5e3602389
bonfiremanager/models.py
bonfiremanager/models.py
from django.db import models class Event(models.Model): name = models.CharField(max_length=1024, unique=True) slug = models.SlugField(max_length=1024) def __str__(self): return self.name class TimeSlot(models.Model): event = models.ForeignKey(Event) bookable = models.BooleanField(...
from django.db import models class Event(models.Model): name = models.CharField(max_length=1024, unique=True) slug = models.SlugField(max_length=1024) def __str__(self): return self.name class TimeSlot(models.Model): event = models.ForeignKey(Event) bookable = models.BooleanField(...
Make timeslot a FK on talk model
Make timeslot a FK on talk model
Python
agpl-3.0
yamatt/bonfiremanager
2fb0678363479c790e5a63de8b92a19de3ac2359
src/Camera.py
src/Camera.py
from traits.api import HasTraits, Int, Str, Tuple, Array, Range class CameraError(Exception): def __init__(self, msg, cam): self.msg = msg self.camera_number = cam def __str__(self): return '{0} on camera {1}'.format(self.msg, self.camera_number) class Camera(HasTraits):...
from traits.api import HasTraits, Int, Str, Tuple, Array, Range from traitsui.api import View, Label class CameraError(Exception): def __init__(self, msg, cam): self.msg = msg self.camera_number = cam def __str__(self): return '{0} on camera {1}'.format(self.msg, self.camera_n...
Add default view for camera
Add default view for camera
Python
mit
ptomato/Beams
0a05f423ad591454a25c515d811556d10e5fc99f
Browser.py
Browser.py
from Zeroconf import * import socket class MyListener(object): def __init__(self): self.r = Zeroconf() pass def removeService(self, zeroconf, type, name): print "Service", name, "removed" def addService(self, zeroconf, type, name): print "Service", name, "added" print "Type is", type inf...
from Zeroconf import * import socket class MyListener(object): def __init__(self): self.r = Zeroconf() pass def removeService(self, zeroconf, type, name): print "Service", name, "removed" def addService(self, zeroconf, type, name): print "Service", name, "added" print "Type is", type inf...
Allow for the failure of getServiceInfo(). Not sure why it's happening, though.
Allow for the failure of getServiceInfo(). Not sure why it's happening, though.
Python
lgpl-2.1
jantman/python-zeroconf,decabyte/python-zeroconf,nameoftherose/python-zeroconf,balloob/python-zeroconf,AndreaCensi/python-zeroconf,giupo/python-zeroconf,jstasiak/python-zeroconf,wmcbrine/pyzeroconf,basilfx/python-zeroconf,daid/python-zeroconf,gbiddison/python-zeroconf
e155d7b96c5b834f4c062b93cbd564a5317905f1
tools/po2js.py
tools/po2js.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os.path import codecs import dfstrings import time def make_js_from_po(path): strings = [] for po in [p for p in dfstrings.get_po_strings(path) if "scope" in p and "dragonfly" in p["scope"] ]: strings.append(u"""ui_strings.%s="%s";""...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os.path import codecs import dfstrings import time def make_js_from_po(path): strings = [] for po in [p for p in dfstrings.get_po_strings(path) if "scope" in p and "dragonfly" in p["scope"] ]: strings.append(u"""ui_strings.%s="%s";""...
Add the language code to the translated file
Add the language code to the translated file
Python
apache-2.0
operasoftware/dragonfly,operasoftware/dragonfly,operasoftware/dragonfly,operasoftware/dragonfly
afc658c6ae125042182976dd95af68881865a2da
handoverservice/handover_api/views.py
handoverservice/handover_api/views.py
from handover_api.models import User, Handover, Draft from rest_framework import viewsets from serializers import UserSerializer, HandoverSerializer, DraftSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() ...
from rest_framework import viewsets from handover_api.models import User, Handover, Draft from handover_api.serializers import UserSerializer, HandoverSerializer, DraftSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.ob...
Update import of serializers for python3 compatibility
Update import of serializers for python3 compatibility
Python
mit
Duke-GCB/DukeDSHandoverService,Duke-GCB/DukeDSHandoverService,Duke-GCB/DukeDSHandoverService
a50edf34659acb63f1fa6dda5494812fa1c4ff7d
models/ras_pathway/run_ras_pathway.py
models/ras_pathway/run_ras_pathway.py
import sys import pickle from indra import reach from indra.assemblers import GraphAssembler if len(sys.argv) < 2: process_type = 'text' else: process_type = sys.argv[1] if process_type == 'text': txt = open('ras_pathway.txt', 'rt').read() rp = reach.process_text(txt, offline=True) st = rp.stateme...
import sys import pickle from indra import trips from indra import reach from indra.assemblers import GraphAssembler def process_reach(txt, reread): if reread: rp = reach.process_text(txt, offline=True) st = rp.statements else: rp = reach.process_json_file('reach_output.json') ...
Add TRIPS reading option to RAS pathway map
Add TRIPS reading option to RAS pathway map
Python
bsd-2-clause
sorgerlab/belpy,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,bgyori/indra
c7825a2ec9be702b05c58118249fe13e7e231ecb
cheroot/test/conftest.py
cheroot/test/conftest.py
import threading import time import pytest import cheroot.server import cheroot.wsgi config = { 'bind_addr': ('127.0.0.1', 54583), 'wsgi_app': None, } def cheroot_server(server_factory): conf = config.copy() httpserver = server_factory(**conf) # create it threading.Thread(target=httpserver.s...
import threading import time import pytest import cheroot.server import cheroot.wsgi config = { 'bind_addr': ('127.0.0.1', 54583), 'wsgi_app': None, } def cheroot_server(server_factory): conf = config.copy() httpserver = server_factory(**conf) # create it threading.Thread(target=httpserver.s...
Drop `yield from` to keep compat w/ 2.7
Drop `yield from` to keep compat w/ 2.7
Python
bsd-3-clause
cherrypy/cheroot
2e3045ed1009a60fe6e236387cae68ddf63bb9b5
distarray/core/tests/test_distributed_array_protocol.py
distarray/core/tests/test_distributed_array_protocol.py
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTes...
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTes...
Test if `__distarray__()['buffer']` returns a buffer.
Test if `__distarray__()['buffer']` returns a buffer.
Python
bsd-3-clause
enthought/distarray,enthought/distarray,RaoUmer/distarray,RaoUmer/distarray
52443c468a446638171f45b080dcf62f73e62866
src/wirecloud_fiware/tests/selenium.py
src/wirecloud_fiware/tests/selenium.py
from wirecloudcommons.test import WirecloudSeleniumTestCase __test__ = False class FiWareSeleniumTestCase(WirecloudSeleniumTestCase): tags = ('current',) def test_add_fiware_marketplace(self): self.login() self.add_marketplace('fiware', 'http://localhost:8080', 'fiware') def test_de...
from wirecloudcommons.test import WirecloudSeleniumTestCase __test__ = False class FiWareSeleniumTestCase(WirecloudSeleniumTestCase): def test_add_fiware_marketplace(self): self.login() self.add_marketplace('fiware', 'http://localhost:8080', 'fiware') def test_delete_fiware_marketplace(s...
Remove 'current' tag from FiWareSeleniumTestCase
Remove 'current' tag from FiWareSeleniumTestCase
Python
agpl-3.0
rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud
6fe2e1dfbce465fee8a12475b3bfcda3ea10594e
staticgen_demo/blog/staticgen_views.py
staticgen_demo/blog/staticgen_views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
Add print statements to debug BlogPostListView
Add print statements to debug BlogPostListView
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
abfe0538769145ac83031062ce3b22d2622f18bf
opwen_email_server/utils/temporary.py
opwen_email_server/utils/temporary.py
from contextlib import contextmanager from contextlib import suppress from os import close from os import remove from tempfile import mkstemp def create_tempfilename() -> str: file_descriptor, filename = mkstemp() close(file_descriptor) return filename @contextmanager def removing(path: str) -> str: ...
from contextlib import contextmanager from contextlib import suppress from os import close from os import remove from tempfile import mkstemp from typing import Generator def create_tempfilename() -> str: file_descriptor, filename = mkstemp() close(file_descriptor) return filename @contextmanager def re...
Fix type annotation for context manager
Fix type annotation for context manager
Python
apache-2.0
ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver
d154cd852bdb02743e9752179559a91b9f1a7f8c
example/tests/unit/test_renderer_class_methods.py
example/tests/unit/test_renderer_class_methods.py
from django.contrib.auth import get_user_model from rest_framework_json_api import serializers from rest_framework_json_api.renderers import JSONRenderer class ResourceSerializer(serializers.ModelSerializer): class Meta: fields = ('username',) model = get_user_model() def test_build_json_resour...
from django.contrib.auth import get_user_model from rest_framework_json_api import serializers from rest_framework_json_api.renderers import JSONRenderer pytestmark = pytest.mark.django_db class ResourceSerializer(serializers.ModelSerializer): class Meta: fields = ('username',) model = get_user_m...
Fix for Database access not allowed, use the "django_db" mark to enable it.
Fix for Database access not allowed, use the "django_db" mark to enable it.
Python
bsd-2-clause
django-json-api/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,scottfisk/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,leo-naeka/rest_framework_ember,django-json-api/django-rest-fram...
d32ec29dfae5a3ea354266dfda0438d9c69398e3
daiquiri/wordpress/utils.py
daiquiri/wordpress/utils.py
from django.conf import settings from .tasks import ( update_wordpress_user as update_wordpress_user_task, update_wordpress_role as update_wordpress_role_task ) def update_wordpress_user(user): if not settings.ASYNC: update_wordpress_user_task.apply((user.username, user.email, user.first_name, us...
import random import string from django.conf import settings from .tasks import ( update_wordpress_user as update_wordpress_user_task, update_wordpress_role as update_wordpress_role_task ) def update_wordpress_user(user): if user.email: email = user.email else: random_string = ''.joi...
Fix update_wordpress_user for missing email
Fix update_wordpress_user for missing email
Python
apache-2.0
aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri
f6518a7bd554c87b4dcb68d1ca618babcf278c63
tests/extmod/machine1.py
tests/extmod/machine1.py
# test machine module import machine import uctypes print(machine.mem8) buf = bytearray(8) addr = uctypes.addressof(buf) machine.mem8[addr] = 123 print(machine.mem8[addr]) machine.mem16[addr] = 12345 print(machine.mem16[addr]) machine.mem32[addr] = 123456789 print(machine.mem32[addr]) try: machine.mem16[1] e...
# test machine module try: import machine except ImportError: print("SKIP") import sys sys.exit() import uctypes print(machine.mem8) buf = bytearray(8) addr = uctypes.addressof(buf) machine.mem8[addr] = 123 print(machine.mem8[addr]) machine.mem16[addr] = 12345 print(machine.mem16[addr]) machine.m...
Check that machine module exists and print SKIP if it doesn't.
tests: Check that machine module exists and print SKIP if it doesn't.
Python
mit
vitiral/micropython,lowRISC/micropython,adafruit/circuitpython,danicampora/micropython,ryannathans/micropython,pfalcon/micropython,mgyenik/micropython,adafruit/micropython,blazewicz/micropython,vitiral/micropython,chrisdearman/micropython,dxxb/micropython,dinau/micropython,tdautc19841202/micropython,utopiaprince/microp...
ddd4a0d1ba607f49f75f9516c378159f1204d9fb
readthedocs/rtd_tests/tests/test_search_json_parsing.py
readthedocs/rtd_tests/tests/test_search_json_parsing.py
import os from django.test import TestCase from search.parse_json import process_file base_dir = os.path.dirname(os.path.dirname(__file__)) class TestHacks(TestCase): def test_h2_parsing(self): data = process_file( os.path.join( base_dir, 'files/api.fjson', ...
import os from django.test import TestCase from search.parse_json import process_file base_dir = os.path.dirname(os.path.dirname(__file__)) class TestHacks(TestCase): def test_h2_parsing(self): data = process_file( os.path.join( base_dir, 'files/api.fjson', ...
Fix tests now that we have H1 capturing
Fix tests now that we have H1 capturing
Python
mit
wanghaven/readthedocs.org,wijerasa/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,d0ugal/readthedocs.org,takluyver/readthedocs.org,wanghaven/readthedocs.org,emawind84/readthedocs.org,KamranMackey/readthedocs.org,attakei/readthedocs-oauth,agjohnson/readthedocs.org,michaelmcandrew/readthedocs.org,asampat3090/r...
135a97a58a95c04d2635fff68d2c080413f1d804
tests/test_conditions.py
tests/test_conditions.py
import json import unittest import awacs.aws as aws import awacs.s3 as s3 class TestConditions(unittest.TestCase): def test_for_all_values(self): c = aws.Condition( aws.ForAllValuesStringLike( "dynamodb:requestedAttributes", ["PostDateTime", "Message", "Tags"] ) ...
import json import unittest import awacs.aws as aws import awacs.s3 as s3 class TestConditions(unittest.TestCase): def test_for_all_values(self): c = aws.Condition( aws.ForAllValuesStringLike( "dynamodb:requestedAttributes", ["PostDateTime", "Message", "Tags"] ) ...
Remove 'u' prefix from strings
Remove 'u' prefix from strings
Python
bsd-2-clause
cloudtools/awacs
07cffdaa6e131c4f02c570de3925d6238656fc87
tests/test_invocation.py
tests/test_invocation.py
import sys import subprocess import re def test_runpy_invoke(): """ Ensure honcho can also be invoked using runpy (python -m) """ cmd = [sys.executable, '-m', 'honcho', 'version'] output = subprocess.check_output(cmd, universal_newlines=True) assert re.match(r'honcho \d\.\d\.\d.*\n', output)
import sys import subprocess import re import pytest @pytest.mark.skipif(sys.version_info < (2, 7), reason="check_output not available") def test_runpy_invoke(): """ Ensure honcho can also be invoked using runpy (python -m) """ cmd = [sys.executable, '-m', 'honcho', 'version'] output = subprocess...
Disable test on Python 2.6.
Disable test on Python 2.6.
Python
mit
nickstenning/honcho,nickstenning/honcho
f052666502ef0108d991940ca713ebc0c5d0c036
MyBot.py
MyBot.py
from hlt import * from networking import * myID, gameMap = getInit() sendInit("MyPythonBot") while True: moves = [] gameMap = getFrame() for y in range(gameMap.height): for x in range(gameMap.width): location = Location(x, y) if gameMap.getSite(location).owner == myID: ...
from hlt import * from networking import * myID, gameMap = getInit() sendInit("dpetkerPythonBot") def create_move(location): site = gameMap.getSite(location) # See if there's an enemy adjacent to us with less strength. If so, capture it for d in CARDINALS: neighbour_site = gameMap.getSite(location, d) ...
Improve my bot according to tutorial
Improve my bot according to tutorial
Python
mit
dpetker/halite,dpetker/halite
9eabdbc6b73661865c4d785cbc57d7ee51fe59cd
future/tests/test_imports_urllib.py
future/tests/test_imports_urllib.py
from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): """ This should perhaps fail: importing urllib first means that the import hooks won't be consulted when importing urllib.response. ""...
from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): import urllib orig_file = urllib.__file__ from future.standard_library.urllib import response as urllib_response self.assertEqual(orig...
Change urllib test to use an explicit import
Change urllib test to use an explicit import
Python
mit
QuLogic/python-future,michaelpacer/python-future,PythonCharmers/python-future,krischer/python-future,krischer/python-future,QuLogic/python-future,michaelpacer/python-future,PythonCharmers/python-future
cad4e7e9feaf7fefe9ef91dea18594b095861204
content_editor/models.py
content_editor/models.py
from types import SimpleNamespace from django.db import models __all__ = ("Region", "Template", "create_plugin_base") class Region(SimpleNamespace): key = "" title = "unnamed" inherited = False class Template(SimpleNamespace): key = "" template_name = None title = "" regions = [] de...
from types import SimpleNamespace from django.db import models __all__ = ("Region", "Template", "create_plugin_base") class Region(SimpleNamespace): key = "" title = "unnamed" inherited = False class Template(SimpleNamespace): key = "" template_name = None title = "" regions = [] de...
Fix the docstring of create_plugin_base: Not internal, it's the main API
Fix the docstring of create_plugin_base: Not internal, it's the main API
Python
bsd-3-clause
matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor
0ecff906f8d504576f00f28c46be6d4594008f38
parcels/interaction/distance_utils.py
parcels/interaction/distance_utils.py
import numpy as np def fast_distance(lat1, lon1, lat2, lon2): '''Compute the arc distance assuming the earth is a sphere.''' g = np.sin(lat1)*np.sin(lat2)+np.cos(lat1)*np.cos(lat2)*np.cos(lon1-lon2) return np.arccos(np.minimum(1, g)) def spherical_distance(depth1_m, lat1_deg, lon1_deg, depth2_m, lat2_de...
import numpy as np def fast_distance(lat1, lon1, lat2, lon2): '''Compute the arc distance assuming the earth is a sphere. This is not the only possible implementation. It was taken from: https://www.mkompf.com/gps/distcalc.html ''' g = np.sin(lat1)*np.sin(lat2)+np.cos(lat1)*np.cos(lat2)*np.cos(lo...
Add link for distance computation
Add link for distance computation
Python
mit
OceanPARCELS/parcels,OceanPARCELS/parcels
c07234bb3142df96dc9e02a236975bc3de2415cc
nailgun/nailgun/test/test_plugin.py
nailgun/nailgun/test/test_plugin.py
# -*- coding: utf-8 -*- from nailgun.test.base import BaseHandlers class TestPluginStateMachine(BaseHandlers): def test_attrs_creation(self): pass
# -*- coding: utf-8 -*- from nailgun.test.base import BaseHandlers from nailgun.plugin.process import get_queue, PluginProcessor from nailgun.api.models import Task class TestPluginProcess(BaseHandlers): def setUp(self): super(TestPluginProcess, self).setUp() self.plugin_processor = PluginProcessor...
Implement plugin test on exception handling
Implement plugin test on exception handling
Python
apache-2.0
SmartInfrastructures/fuel-main-dev,ddepaoli3/fuel-main-dev,zhaochao/fuel-main,zhaochao/fuel-main,huntxu/fuel-main,prmtl/fuel-web,huntxu/fuel-web,huntxu/fuel-main,SmartInfrastructures/fuel-main-dev,huntxu/fuel-web,teselkin/fuel-main,ddepaoli3/fuel-main-dev,teselkin/fuel-main,SmartInfrastructures/fuel-web-dev,SergK/fuel-...
09edd3b548baaa4f6d1e31d5a9891f2b6eef45d6
noopy/project_template/dispatcher.py
noopy/project_template/dispatcher.py
from noopy import lambda_functions from noopy.endpoint import Endpoint from noopy.endpoint import methods def dispatch(event, context): print event if event['type'] == 'APIGateway': path = event['path'] method = getattr(methods, event['method']) endpoint = Endpoint.endpoints[Endpoint(...
from noopy import lambda_functions from noopy.endpoint import Endpoint from noopy.endpoint import methods def dispatch(event, context): print event if event['type'] == 'APIGateway': path = event['path'] method = getattr(methods, event['method']) endpoint = Endpoint.endpoints[Endpoint(...
Raise error on undefined type
Raise error on undefined type
Python
mit
acuros/noopy
e861e74374d22d3684dccfa5e0063ff37549bcfc
api/app.py
api/app.py
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = m...
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = m...
Refactor to change the comparator of dict
Refactor to change the comparator of dict
Python
mit
joaojunior/y_text_recommender_system
89fd94bb06e81f38b40bd75d793107599a1b7c48
freedomain.py
freedomain.py
from flask import Flask app = Flask(__name__) @app.route('/') def start(count): return 'SETUP APP' if __name__ == '__main__': app.run(host="172.31.27.41", port=8080)
from flask import Flask import time app = Flask(__name__) alphabet = 'abcdefghijklmnopqrstuwxyz' number = '1234567890' def numbering_system(): base_system = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' result = {} for csc_n in base_system: result[csc_n] = base_system.find(csc_n) return result ns ...
Add base methods for generation dictionary
Add base methods for generation dictionary
Python
mit
cludtk/freedomain,cludtk/freedomain
1f4ee4e9d978322938579abc4c6723fdc783937d
build.py
build.py
#!/usr/bin/env python import os import subprocess import sys def build(pkgpath): os.chdir(pkgpath) targets = [ 'build', 'package', 'install', 'clean', 'clean-depends', ] for target in targets: p = subprocess.Popen( ['bmake', target], ...
#!/usr/bin/env python from __future__ import print_function import os import subprocess import sys def build(pkgpath): os.chdir(pkgpath) targets = [ 'build', 'package', 'install', 'clean', 'clean-depends', ] for target in targets: p = subprocess.Popen(...
Use the Python 3 print function.
Use the Python 3 print function.
Python
isc
eliteraspberries/minipkg,eliteraspberries/minipkg
c12cbae226f42405a998b93c6fd7049aadc6a19c
build.py
build.py
import os import string if __name__ == '__main__': patch_file = 'example.patch' base_name, _ = os.path.splitext(patch_file) values = { 'name': 'kpatch-module-{}'.format(base_name), 'patch_file': patch_file, 'kmod_filename': 'kpatch-{}.ko'.format(base_name), 'description': '...
import os import string def generate_rpm_spec(template, patch_file): spec_template = string.Template(template) base_name, _ = os.path.splitext(patch_file) values = { 'name': 'kpatch-module-{}'.format(base_name), 'patch_file': patch_file, 'kmod_filename': 'kpatch-{}.ko'.format(base...
Split spec generation into function
Split spec generation into function
Python
mit
centos-livepatching/kpatch-package-builder
916a02a609af6dc125b0a82215adb94858f4d597
yutu.py
yutu.py
import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ''' await ctx.send('{0....
import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ''' await ctx.send('{0....
Add help text for cute
Add help text for cute
Python
mit
HarkonenBade/yutu
e35767544e7c6b4461e511eaad42c047abcbe911
openprocurement/tender/esco/utils.py
openprocurement/tender/esco/utils.py
# -*- coding: utf-8 -*- from openprocurement.api.utils import get_now def request_get_now(request): return get_now()
# -*- coding: utf-8 -*- from decimal import Decimal from openprocurement.api.utils import get_now def request_get_now(request): return get_now() def to_decimal(fraction): return Decimal(fraction.numerator) / Decimal(fraction.denominator)
Add function to convert fraction to decimal
Add function to convert fraction to decimal
Python
apache-2.0
openprocurement/openprocurement.tender.esco
aeac11d889695f17aab3b972b64101eaefd322f2
fuzzycount.py
fuzzycount.py
from django.conf import settings from django.db import connections from django.db.models.query import QuerySet from model_utils.managers import PassThroughManager class FuzzyCountQuerySet(QuerySet): def count(self): is_postgresql = settings.DATABASES[self.db]["ENGINE"].endswith(("postgis", "postgresql"...
from django.conf import settings from django.db import connections from django.db.models.query import QuerySet from model_utils.managers import PassThroughManager class FuzzyCountQuerySet(QuerySet): def count(self): postgres_engines = ("postgis", "postgresql", "django_postgrespool") engine = se...
Fix engine check and added check for django_postgrespool.
Fix engine check and added check for django_postgrespool.
Python
bsd-2-clause
stephenmcd/django-postgres-fuzzycount
acce959e4885a52ba4a80beaed41a56aac63844e
tests/opwen_email_server/api/test_client_read.py
tests/opwen_email_server/api/test_client_read.py
from contextlib import contextmanager from os import environ from unittest import TestCase class DownloadTests(TestCase): def test_denies_unknown_client(self): with self._given_clients('{"client1": "id1"}') as download: message, status = download('unknown_client') self.assertEqual(...
from contextlib import contextmanager from unittest import TestCase from opwen_email_server.api import client_read from opwen_email_server.services.auth import EnvironmentAuth class DownloadTests(TestCase): def test_denies_unknown_client(self): with self.given_clients({'client1': 'id1'}): mes...
Remove need to set environment variables in test
Remove need to set environment variables in test
Python
apache-2.0
ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver
bfc7e08ba70ba0e3acb9e4cc69b70c816845b6cb
djofx/views/home.py
djofx/views/home.py
from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView): template_name = "djofx/home.html" ...
from datetime import date, timedelta from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models from operator import itemgetter class HomePageView(PageTitleMixin, UserRe...
Include uncategorised spending in overview pie chart
Include uncategorised spending in overview pie chart Also, only show last 120 days
Python
mit
dominicrodger/djofx,dominicrodger/djofx,dominicrodger/djofx