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 |
|---|---|---|---|---|---|---|---|---|---|
6de094b3b08751a8585c5a492bf009807ff3e1e1 | stringinfo.py | stringinfo.py | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
stringinfo STRING...
Options:
STRING One or more strings for which you want information
"""
from docopt import docopt
import plugins
__author__ = 'peter'
def main():
args = docopt(__doc__)
# Find plugins
ps = plugins.get_plugins()
... | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
stringinfo STRING...
Options:
STRING One or more strings for which you want information
"""
import colorama
from docopt import docopt
import plugins
__author__ = 'peter'
def main():
args = docopt(__doc__)
# Find plugins
ps = plugins.get... | Use colorama to print colors and print a plugin's short_description after running | Use colorama to print colors and print a plugin's short_description after running
| Python | mit | Sakartu/stringinfo |
6fa6ef07dd18794b75d63ffa2a5be83e2ec9b674 | bit/count_ones.py | bit/count_ones.py | """
Write a function that takes an unsigned integer and
returns the number of ’1' bits it has
(also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary
representation 00000000000000000000000000001011,
so the function should return 3.
"""
def count_ones(n):
"""
:type n: int
:rtyp... | """
Write a function that takes an unsigned integer and
returns the number of ’1' bits it has
(also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary
representation 00000000000000000000000000001011,
so the function should return 3.
"""
def count_ones(n):
"""
:type n: int
:rtyp... | Check if the input is negative | Check if the input is negative
As the comments mention, the code would work only for unsigned integers.
If a negative integer is provided as input, then the code runs into an
infinite loop. To avoid this, we are checking if the input is negative.
If yes, then return control before loop is entered.
| Python | mit | amaozhao/algorithms,keon/algorithms |
cdc63148c00a38ebbfd74879da8d646427627d1f | rasterio/rio/main.py | rasterio/rio/main.py | #!/usr/bin/env python
# main: loader of all the command entry points.
from pkg_resources import iter_entry_points
for entry_point in iter_entry_points('rasterio.rio_commands'):
entry_point.load()
| #!/usr/bin/env python
# main: loader of all the command entry points.
from pkg_resources import iter_entry_points
from rasterio.rio.cli import cli
for entry_point in iter_entry_points('rasterio.rio_commands'):
entry_point.load()
| Add back import of cli. | Add back import of cli.
| Python | bsd-3-clause | youngpm/rasterio,brendan-ward/rasterio,brendan-ward/rasterio,njwilson23/rasterio,kapadia/rasterio,brendan-ward/rasterio,perrygeo/rasterio,johanvdw/rasterio,perrygeo/rasterio,johanvdw/rasterio,johanvdw/rasterio,kapadia/rasterio,njwilson23/rasterio,youngpm/rasterio,youngpm/rasterio,perrygeo/rasterio,njwilson23/rasterio,c... |
28a457926921ef5e7f57c086d6e6b77a0221348c | carnifex/utils.py | carnifex/utils.py | """
@author: Geir Sporsheim
@license: see LICENCE for details
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
| """
@author: Geir Sporsheim
@license: see LICENCE for details
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
"""Build a string consisting of 'key=value' substrings for each keyword
argument in :kwargs:
@param filterKeys: list of key names to ignore
@param filterValues: list of values t... | Add documentation and touch up formatting of attr_string util method | Add documentation and touch up formatting of attr_string util method
| Python | mit | sporsh/carnifex |
b330afbcdc907343ab609a5b000f08e69671116e | sobotka/lib/ssh_config_util.py | sobotka/lib/ssh_config_util.py | from storm.parsers.ssh_config_parser import ConfigParser as StormParser
from os.path import expanduser
def add_host(name, user, hostname, key_file):
sconfig = StormParser(expanduser("~/.ssh/config"))
sconfig.load()
sconfig.add_host(name, {
'user': user,
'hostname': hostname,
'Identi... | from storm.parsers.ssh_config_parser import ConfigParser as StormParser
from os.path import expanduser
def add_host(name, user, hostname, key_file):
sconfig = StormParser(expanduser("~/.ssh/config"))
sconfig.load()
sconfig.add_host(name, {
'user': user,
'hostname': hostname,
'Identi... | Disable strict host checking for ssh | Disable strict host checking for ssh
| Python | mit | looneym/sobotka,looneym/sobotka |
f529198d385e63ea657c33c166eb05d43bdcf14a | sensor/core/models/event.py | sensor/core/models/event.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | Add datetime field to Event model in sensor.core | Add datetime field to Event model in sensor.core
| Python | mpl-2.0 | HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site |
d0ea4b585ef9523eac528c5a4fba4b0af653cad3 | tests/loginput/test_loginput_index.py | tests/loginput/test_loginput_index.py | from loginput_test_suite import LoginputTestSuite
class TestTestRoute(LoginputTestSuite):
routes = ['/test', '/test/']
status_code = 200
body = ''
# Routes left need to have unit tests written for:
# @route('/veris')
# @route('/veris/')
# @post('/blockip', methods=['POST'])
# @post('/blockip/', methods=... | from loginput_test_suite import LoginputTestSuite
class TestTestRoute(LoginputTestSuite):
routes = ['/test', '/test/']
status_code = 200
body = ''
# Routes left need to have unit tests written for:
# @route('/_bulk',method='POST')
# @route('/_bulk/',method='POST')
# @route('/_status')
# @route('/_status... | Update comments for loginput tests | Update comments for loginput tests
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mpl-2.0 | jeffbryner/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,mozilla/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,mozilla/MozDef,ameihm0912/MozDef,mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/... |
4a37433c43ffda2443f80cc93c99f9cd76aa6475 | examples/miniapps/movie_lister/movies/__init__.py | examples/miniapps/movie_lister/movies/__init__.py | """Movies package.
Top-level package of movies library. This package contains IoC container of
movies module component providers - ``MoviesModule``. It is recommended to use
movies library functionality by fetching required instances from
``MoviesModule`` providers.
``MoviesModule.finder`` is a factory that provides ... | """Movies package.
Top-level package of movies library. This package contains IoC container of
movies module component providers - ``MoviesModule``. It is recommended to use
movies library functionality by fetching required instances from
``MoviesModule`` providers.
``MoviesModule.finder`` is a factory that provides ... | Add minor fixes to movie lister miniapp | Add minor fixes to movie lister miniapp
| Python | bsd-3-clause | rmk135/objects,ets-labs/python-dependency-injector,ets-labs/dependency_injector,rmk135/dependency_injector |
3aa8734ac9790a8869e01d5d56498dfaf697fe28 | cea/interfaces/dashboard/api/dashboard.py | cea/interfaces/dashboard/api/dashboard.py | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c... | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c... | Include plot title to plots | Include plot title to plots
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst |
8440ffcfd87814e04188fe4077717e132f285cb2 | ckanext/requestdata/tests/test_helpers.py | ckanext/requestdata/tests/test_helpers.py | # encoding: utf-8
import nose
from datetime import datetime, timedelta
from ckanext.requestdata import helpers as h
import ckan.plugins as p
from ckan.tests import helpers, factories
from ckan import logic
ok_ = nose.tools.ok_
eq_ = nose.tools.eq_
raises = nose.tools.raises
class ActionBase(object):
@classmetho... | # encoding: utf-8
import nose
from datetime import datetime, timedelta
from ckanext.requestdata import helpers as h
import ckan.plugins as p
from ckan.tests import helpers, factories
from ckan import logic
ok_ = nose.tools.ok_
eq_ = nose.tools.eq_
raises = nose.tools.raises
class ActionBase(object):
@classmetho... | Add tests for valid email converter | Add tests for valid email converter
| Python | agpl-3.0 | ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata |
d4ffa7a0dd5462ad7d2b7eaf720bc8056ca1b859 | medical_medication_us/models/medical_medicament.py | medical_medication_us/models/medical_medicament.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class MedicalMedicament(models.Model):
_inherit = 'medical.medicament'
ndc = fields.Char(
string='NDC',
help='National Drug Code for medication... | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class MedicalMedicament(models.Model):
_inherit = 'medical.medicament'
ndc = fields.Char(
string='NDC',
help='National Drug Code for medication... | Add gpi and gcn to medicament in medical_medication_us | Add gpi and gcn to medicament in medical_medication_us
| Python | agpl-3.0 | laslabs/vertical-medical,laslabs/vertical-medical |
b7dfb33e6cf4dd18a2ab626372bedc6b7c269780 | src/adhocracy/adhocracy/catalog/__init__.py | src/adhocracy/adhocracy/catalog/__init__.py | """ Catalog utilities."""
from substanced import catalog
from substanced.interfaces import IIndexingActionProcessor
from zope.interface import Interface
@catalog.catalog_factory('adhocracy')
class AdhocracyCatalogFactory:
tag = catalog.Keyword()
def includeme(config):
"""Register catalog utilities."""
c... | """ Catalog utilities."""
from substanced import catalog
from substanced.interfaces import IIndexingActionProcessor
from zope.interface import Interface
@catalog.catalog_factory('adhocracy')
class AdhocracyCatalogFactory:
tag = catalog.Keyword()
def includeme(config):
"""Register catalog utilities."""
c... | Fix regression: 'import pytest' error when starting adhocracy | Fix regression: 'import pytest' error when starting adhocracy
| Python | agpl-3.0 | liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adh... |
82fec866f384813118411d0485e31b12deaed9f0 | pmst/examples/isotropic_point_source/isotropic_point_source.py | pmst/examples/isotropic_point_source/isotropic_point_source.py | from pmst.source import DirectedPointSource
from pmst.microscope import Microscope
from pmst.detector import Detector
from pmst.geometry import Point
import numpy as np
s = DirectedPointSource(Point(0, 0, 0), n_rays=1e5, direction=Point(0, 0, 1), psi=np.pi/2)
center = Point(0, 0, 2)
x_edge = Point(5, 0, 2)
y_edge = P... | from pmst.source import DirectedPointSource
from pmst.microscope import Microscope
from pmst.detector import Detector
from pmst.geometry import Point
import numpy as np
import time; start = time.time(); print('Running...')
s = DirectedPointSource(Point(0, 0, 0), n_rays=1e5, direction=Point(0, 0, 1), psi=np.pi/2)
cent... | Add timing message to example | Add timing message to example
| Python | mit | talonchandler/pmst |
ebfcef6ecf0acc202af081e7aa487e50fd7785af | soulmate_finder/__init__.py | soulmate_finder/__init__.py | # allow `soulmate_finder` to be imported
# FIXME: This is bad
# FIXME: WHY IS THIS CAUSING A RUNTIMEWARNING???
# from .__main__ import *
| from .core import *
| Allow package to be imported | Allow package to be imported
| Python | mit | erkghlerngm44/r-anime-soulmate-finder |
42e78f7ff795202843085daa65d241cf3fe29d08 | xoinvader/tests/test_level.py | xoinvader/tests/test_level.py | """Test xoinvader.level module."""
from xoinvader.level import Level
# pylint: disable=invalid-name,protected-access,missing-docstring
def test_wave():
e = Level()
# pylint: disable=too-few-public-methods
class MockObject(object):
def __init__(self):
self.value = 0
def add(s... | """Test xoinvader.level module."""
from xoinvader.level import Level
# pylint: disable=invalid-name,protected-access,missing-docstring
def test_level():
e = Level()
# pylint: disable=too-few-public-methods
class MockObject(object):
def __init__(self):
self.value = 0
def add(... | Fix test name, cover speed getter | Fix test name, cover speed getter
Signed-off-by: pkulev <661f9993ccc93424ad20871d2ea98bc2860e5968@gmail.com>
| Python | mit | pkulev/xoinvader,pankshok/xoinvader |
0c5888aeab12c82d84ead79e4005133e0e91ef21 | dj/manage.py | dj/manage.py | #!/usr/bin/env python
###################################################################
#
# Copyright (c) 2011 Canonical Ltd.
# Copyright (c) 2013 Miing.org <samuel.miing@gmail.com>
#
# This software is licensed under the GNU Affero General Public
# License version 3 (AGPLv3), as published by the Free Software
# F... | #!/usr/bin/env python
###################################################################
#
# Copyright (c) 2011 Canonical Ltd.
# Copyright (c) 2013 Miing.org <samuel.miing@gmail.com>
#
# This software is licensed under the GNU Affero General Public
# License version 3 (AGPLv3), as published by the Free Software
# F... | Fix 'not import from sys' | Fix 'not import from sys'
| Python | agpl-3.0 | miing/mci_migo,miing/mci_migo,miing/mci_migo |
d8b3fcb34761af01e87026e3bc5b929bd6b68fc2 | frappe/patches/v11_0/copy_fetch_data_from_options.py | frappe/patches/v11_0/copy_fetch_data_from_options.py | import frappe
def execute():
frappe.reload_doc("core", "doctype", "docfield", force=True)
frappe.reload_doc("custom", "doctype", "custom_field", force=True)
frappe.reload_doc("custom", "doctype", "customize_form_field", force=True)
frappe.reload_doc("custom", "doctype", "property_setter", force=True)
frappe.db.s... | import frappe
def execute():
frappe.reload_doc("core", "doctype", "docfield", force=True)
frappe.reload_doc("custom", "doctype", "custom_field", force=True)
frappe.reload_doc("custom", "doctype", "customize_form_field", force=True)
frappe.reload_doc("custom", "doctype", "property_setter", force=True)
frappe.db.s... | Rename property setter for fetch_from | [fix] Rename property setter for fetch_from
| Python | mit | mhbu50/frappe,frappe/frappe,vjFaLk/frappe,RicardoJohann/frappe,ESS-LLP/frappe,mhbu50/frappe,saurabh6790/frappe,mhbu50/frappe,vjFaLk/frappe,yashodhank/frappe,almeidapaulopt/frappe,RicardoJohann/frappe,yashodhank/frappe,adityahase/frappe,vjFaLk/frappe,ESS-LLP/frappe,yashodhank/frappe,saurabh6790/frappe,RicardoJohann/frap... |
ee61414cb53dd883d9f5ab60b0148bf0ed9bf3d7 | us_ignite/people/tests/integration_tests.py | us_ignite/people/tests/integration_tests.py | from nose.tools import eq_
from django.contrib.auth.models import User
from django.test import TestCase
from django_nose.tools import assert_redirects
from us_ignite.common.tests import utils
from us_ignite.profiles.tests import fixtures
def _teardown_profiles():
for model in [User]:
model.objects.all()... | from nose.tools import eq_
from django.contrib.auth.models import User
from django.test import TestCase
from django_nose.tools import assert_redirects
from us_ignite.common.tests import utils
from us_ignite.profiles.tests import fixtures
def _teardown_profiles():
for model in [User]:
model.objects.all()... | Update tests to refelct the removal of the users list view. | Update tests to refelct the removal of the users list view.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
499b7e95b10c453083d2e0438bfef8a57b330d9a | gui/status/TrayIconView.py | gui/status/TrayIconView.py | import trayjenkins
from PySide import QtGui
from pyjenkins.Event import Event
from trayjenkins.status.interfaces import IView
class TrayIconView(IView):
def __init__(self, parentWidget, delayInSecons):
"""
@type parentWidget: QtGui.QWidget
"""
self._statusRefreshEvent= Event()
... | import trayjenkins
from PySide import QtGui
from pyjenkins.Event import Event
from trayjenkins.status.interfaces import IView
class TrayIconView(IView):
def __init__(self, parentWidget, delayInSecons):
"""
@type parentWidget: QtGui.QWidget
"""
self._statusRefreshEvent= Event()
... | Set icon before calling show() to avoid warning. | Set icon before calling show() to avoid warning.
| Python | mit | coolhandmook/trayjenkins,coolhandmook/trayjenkins |
27a1d78611cef1ab23044db22bd4bf7c61582efe | src/data/Track/UploadHandlers/YoutubeUploadHandler.py | src/data/Track/UploadHandlers/YoutubeUploadHandler.py | import os
from data.Track.UploadHandler import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
class YoutubeUploadHandler(UploadHandler):
def __init__(self, workingDir):
super().__init__(workingDir)
self.attributes.update({
"URL": ["string", "required", "url"]
... | import os
from src.data.Track import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
class YoutubeUploadHandler(UploadHandler):
def __init__(self, workingDir):
super().__init__(workingDir)
self.attributes.update({
"URL": ["string", "required", "url"]
})
def... | Fix wrong import from UploadHandler | Fix wrong import from UploadHandler
| Python | agpl-3.0 | Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus,Pynitus-Universe/Pynitus |
cf94fb86cab2fc892b762b66b760a80ed268e8b3 | social/accounts/__init__.py | social/accounts/__init__.py | """Import and register all account types."""
from abc import ABC, abstractmethod
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned truthy about matching ... | """Import and register all account types."""
from abc import ABC, abstractmethod
__all__ = ['github']
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned ... | Add github to the accounts package. | Add github to the accounts package.
| Python | bsd-3-clause | brenns10/social,brenns10/social |
504bd5d8bb7ec63747318d16f90d24930e640fc6 | ipython_notebook_config.py | ipython_notebook_config.py | # See http://ipython.org/ipython-doc/1/interactive/public_server.html for more information.
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import yaml
with open('/import/conf.yaml','... | # See http://ipython.org/ipython-doc/1/interactive/public_server.html for more information.
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import os
import yaml
config_file_path = ... | Implement fallback mode to make the image unsable without Galaxy | Implement fallback mode to make the image unsable without Galaxy
| Python | mit | bgruening/docker-jupyter-notebook,bgruening/docker-jupyter-notebook,bgruening/docker-ipython-notebook,bgruening/docker-ipython-notebook,bgruening/docker-jupyter-notebook,bgruening/docker-ipython-notebook |
2e8d7952f4508e1cbf8d5d9b321a15bcd3bcf2ed | pylearn2/packaged_dependencies/theano_linear/util.py | pylearn2/packaged_dependencies/theano_linear/util.py |
_ndarray_status_fmt='%(msg)s shape=%(shape)s min=%(min)f max=%(max)f'
def ndarray_status(x, fmt=_ndarray_status_fmt, msg="", **kwargs):
kwargs.update(dict(
msg=msg,
min=x.min(),
max=x.max(),
mean=x.mean(),
var = x.var(),
shape=x.shape))
... |
from imaging import tile_slices_to_image
_ndarray_status_fmt='%(msg)s shape=%(shape)s min=%(min)f max=%(max)f'
def ndarray_status(x, fmt=_ndarray_status_fmt, msg="", **kwargs):
kwargs.update(dict(
msg=msg,
min=x.min(),
max=x.max(),
mean=x.mean(),
var =... | Remove pylearn1 dependency from packaged_dependencies/theano_linear | Remove pylearn1 dependency from packaged_dependencies/theano_linear
| Python | bsd-3-clause | caidongyun/pylearn2,hantek/pylearn2,msingh172/pylearn2,junbochen/pylearn2,sandeepkbhat/pylearn2,pkainz/pylearn2,lunyang/pylearn2,skearnes/pylearn2,cosmoharrigan/pylearn2,lunyang/pylearn2,aalmah/pylearn2,goodfeli/pylearn2,woozzu/pylearn2,mkraemer67/pylearn2,matrogers/pylearn2,goodfeli/pylearn2,skearnes/pylearn2,theoryno... |
b52037176cd1b8a4d99ff195d72680928ba3790f | cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py | cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py | """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
... | """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
... | Change how we get course ids to avoid memory issues | Change how we get course ids to avoid memory issues
| Python | agpl-3.0 | angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,angel... |
a8eff550934730b1b9289796366cc4fe23c669db | stanford/bin/send-email.py | stanford/bin/send-email.py | #!/usr/bin/env python
from email.mime.text import MIMEText
import smtplib
import sys
def send(recipient, sender, subject, body):
message = MIMEText(body, _charset='UTF-8')
message['Subject'] = subject
message['From'] = sender
message['To'] = recipient
smtp = smtplib.SMTP('localhost')
result = s... | #!/usr/bin/env python
from email.mime.text import MIMEText
from subprocess import call
import sys
def send(recipient, sender, sender_name, subject, body):
with open('configuration/stanford/bin/email_params.txt', 'rt') as fin:
with open('email.txt', 'wt') as fout:
for line in fin:
... | Use AWS SMTP server in cut release script. | Use AWS SMTP server in cut release script.
| Python | agpl-3.0 | Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration |
64042be2b6febf64d601adaa6f85a542ae9b876d | sunpy/instr/iris/iris.py | sunpy/instr/iris/iris.py | """
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None):
"""
Read a SJI file and return a MapCube
..warning::
This function is a very early beta and is not stable. Further work is
... | """
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None, hdu=0):
"""
Read a SJI file and return a MapCube
..warning::
This function is a very early beta and is not stable. Further work is ... | Change hdu[0] to hdu for optional indexing | Change hdu[0] to hdu for optional indexing
| Python | bsd-2-clause | Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy |
2d5c5a1bf693f428b53f8d4a6e788f7be864aa9e | image_site_app/forms.py | image_site_app/forms.py | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30, label='First name (optional)', required=False)
last_name = forms.CharField(max_length=30, label='Last name (optional)'... | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30,
label='First name (optional)',
required=False,
... | Add placeholder to first_name and last_name fields in signup form | Add placeholder to first_name and last_name fields in signup form
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq |
64bc8ff452d03c7bb026be0b2edd9a047a88b386 | foyer/forcefields/forcefields.py | foyer/forcefields/forcefields.py | import os
import glob
from pkg_resources import resource_filename
from foyer import Forcefield
def get_ff_path():
return [resource_filename('foyer', 'forcefields')]
def get_forcefield_paths(forcefield_name=None):
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, 'xml/*.xml')
... | import os
import glob
from pkg_resources import resource_filename
from foyer import Forcefield
def get_ff_path():
return [resource_filename('foyer', 'forcefields')]
def get_forcefield_paths(forcefield_name=None):
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, 'xml/*.xml')
... | Make discrete functions for each force field | Make discrete functions for each force field
| Python | mit | mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer |
3fbca600b1b90ad3499d941e178aae89d1c7df70 | regulations/generator/layers/external_citation.py | regulations/generator/layers/external_citation.py | from django.template import loader
import utils
from regulations.generator.layers.base import SearchReplaceLayer
class ExternalCitationLayer(SearchReplaceLayer):
shorthand = 'external'
data_source = 'external-citations'
def __init__(self, layer):
self.layer = layer
self.template = loader... | from django.template import loader
from regulations.generator.layers import utils
from regulations.generator.layers.base import SearchReplaceLayer
class ExternalCitationLayer(SearchReplaceLayer):
shorthand = 'external'
data_source = 'external-citations'
def __init__(self, layer):
self.layer = la... | Make external citations Python3 compatible | Make external citations Python3 compatible
| Python | cc0-1.0 | 18F/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site |
d7f25a05622f115babacc74e05e20f8c147867c3 | accelerator_abstract/models/base_application_answer.py | accelerator_abstract/models/base_application_answer.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from accelerator_abstract.models.accelerator_model import AcceleratorModel
@python_2_unicode_compatible
class Base... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from accelerator_abstract.models.accelerator_model import AcceleratorModel
@python_2_unicode_compatible
class Base... | Change field type for answer_text | [AC-8296] Change field type for answer_text
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
6963b2d42cfee97b57c512a2776df02604da8e5f | polling_stations/apps/data_importers/management/commands/import_reading.py | polling_stations/apps/data_importers/management/commands/import_reading.py | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15... | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15... | Fix an incorrect postcode for Reading | Fix an incorrect postcode for Reading
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
d994294d2c5297635fa36bf7911fbaef6e8e0345 | admin/base/urls.py | admin/base/urls.py | from django.conf.urls import include, url, patterns
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(base_pattern,
include(patterns('',
url(r'^$', views.home, name='h... | from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.views.generic import RedirectView
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(base_pattern,
include(patterns('',
... | Add redirect to /admin/ on Admin app w/ empty URL | Add redirect to /admin/ on Admin app w/ empty URL
| Python | apache-2.0 | crcresearch/osf.io,jnayak1/osf.io,felliott/osf.io,zachjanicki/osf.io,icereval/osf.io,kwierman/osf.io,zamattiac/osf.io,wearpants/osf.io,cwisecarver/osf.io,leb2dg/osf.io,RomanZWang/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,asanfilippo7/osf.io,brandonPur... |
9a84ffde3909c74a47049c65e3b2bb5038a2cfaa | sillymap/burrows_wheeler.py | sillymap/burrows_wheeler.py |
def burrows_wheeler(text):
"""Returns the burrows wheeler transform of <text>.
The text is assumed to not contain the character $"""
text += "$"
all_permutations = []
for i in range(len(text)):
all_permutations.append(text[i:] + text[:i])
all_permutations.sort()
return "".join([w... |
def burrows_wheeler(text):
"""Calculates the burrows wheeler transform of <text>.
returns the burrows wheeler string and the suffix array indices
The text is assumed to not contain the character $"""
text += "$"
all_permutations = []
for i in range(len(text)):
all_permutations.append(... | Return suffix array indices from burrows wheeler | Return suffix array indices from burrows wheeler
| Python | mit | alneberg/sillymap |
a8d1812532211312287e58093ca966a7ea2050f4 | core/ModificationEntities.py | core/ModificationEntities.py | # coding: utf8
from core.ParsingEntities import Entity
class ModificationEntity(Entity):
def __add__(self, other):
if isinstance(self, ModificationEntity) and isinstance(other, ModificationEntity):
modification_operator = ModificationOperator()
return modification_operator
... | # coding: utf8
from core.ParsingEntities import Entity
class ModificationEntity(Entity):
def __add__(self, other):
if isinstance(self, ModificationEntity) and isinstance(other, ModificationEntity):
modification_operator = ModificationOperator()
return modification_operator
... | Implement ModificationOperator and ModificationCondition classes | Implement ModificationOperator and ModificationCondition classes
| Python | mit | JCH222/matriochkas |
54f99c5c62c170b538a7a6ea4bf786c897151e5a | pylcp/url.py | pylcp/url.py | def url_path_join(url, path_part):
"""Join a path part to the end of a URL adding/removing slashes as necessary."""
result = url + '/' if url[-1] != '/' else url
index = 1 if path_part[0] == '/' else 0
return result + path_part[index:]
| def url_path_join(url, path_part):
"""Join a path part to the end of a URL adding/removing slashes as necessary."""
result = url + '/' if not url.endswith('/') else url
index = 1 if path_part.startswith('/') else 0
return result + path_part[index:]
| Use startswith/endswith instead of indices for readability. | Use startswith/endswith instead of indices for readability.
| Python | bsd-3-clause | bradsokol/PyLCP,Points/PyLCP,bradsokol/PyLCP,Points/PyLCP |
6e17e781f6cb8e29a7284beffe10463c843b86b3 | tests/test_vector2_equality.py | tests/test_vector2_equality.py | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors())
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
@given(x=vectors(), y=vectors())
def test_not_equal_... | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors())
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
assert x != -x
@given(x=vectors(), y=vectors())
de... | Add another (generated) negative example | tests/equality: Add another (generated) negative example
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
132a10f38c6c5d29c38a388af7d50e7ceb71e8fa | zipline_extension/calendars/exchange_calendar_forex.py | zipline_extension/calendars/exchange_calendar_forex.py | import pytz
from datetime import time
from zipline.utils.calendars import TradingCalendar
class ForexCalendar(TradingCalendar):
@property
def name(self):
return "forex"
@property
def tz(self):
return pytz.UTC
@property
def open_time(self):
return time(0, 0)
@prope... | import pytz
import pandas as pd
from datetime import time
from zipline.utils.calendars import TradingCalendar
class ForexCalendar(TradingCalendar):
NYT_5PM = time(9)
@property
def name(self):
return "forex"
@property
def tz(self):
return pytz.UTC
@property
def open_time... | Add weekend close and open times | Add weekend close and open times
| Python | mit | bernoullio/toolbox |
c33f011d3ea9e1783149a9fb34d941a899f7cedc | blog/forms.py | blog/forms.py | from .models import BlogPost, Comment
from django.forms import ModelForm
class BlogPostForm(ModelForm):
class Meta:
model = BlogPost
exclude = ('user',)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('post',)
| from .models import BlogPost, Comment
from django.forms import ModelForm
class BlogPostForm(ModelForm):
class Meta:
model = BlogPost
exclude = ('user',)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('post', 'user', 'date',)
| Exclude fields from CommentForm that will be automatically inserted | Exclude fields from CommentForm that will be automatically inserted
| Python | mit | andreagrandi/bloggato,andreagrandi/bloggato |
e03426b8fd696b8794e21ef52c76a0a5140e1463 | Maths/fibonacciSeries.py | Maths/fibonacciSeries.py | # Fibonacci Sequence Using Recursion
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
limit = int(input("How many terms to include in fibonacci series: "))
if limit <= 0:
print("Please enter a positive integer: ")
else:
print(f"The first {limit} ter... | # Fibonacci Sequence Using Recursion
def recur_fibo(n):
return n if n <= 1 else (recur_fibo(n-1) + recur_fibo(n-2))
def isPositiveInteger(limit):
return limit >= 0
def main():
limit = int(input("How many terms to include in fibonacci series: "))
if isPositiveInteger:
print(f"The first {li... | Improve and Refactor the fibonnaciSeries.py (Recursion) | Improve and Refactor the fibonnaciSeries.py (Recursion)
| Python | mit | TheAlgorithms/Python |
00222bb47818ea2fdf60847e6ad42ba96c39f16b | whacked4/whacked4/dehacked/filters.py | whacked4/whacked4/dehacked/filters.py | #!/usr/bin/env python
#coding=utf8
"""
This module contains functions used by a Dehacked table entry to filter certain values when reading or writing
them.
"""
import math
import re
def filter_thing_flags_read(value, table):
"""
Filters a thing's flags value.
Extended patches can use mnemonics for ... | #!/usr/bin/env python
#coding=utf8
"""
This module contains functions used by a Dehacked table entry to filter certain values when reading or writing
them.
"""
import math
import re
def filter_thing_flags_read(value, table):
"""
Filters a thing's flags value.
Extended patches can use mnemonics for ... | Fix flag delimiter support from 30ec188. | Fix flag delimiter support from 30ec188.
| Python | bsd-2-clause | GitExl/WhackEd4,GitExl/WhackEd4 |
45e2651325ebf3d4554816d5c7bef04030d147b2 | tests/test_middleware.py | tests/test_middleware.py | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
... | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
... | Add test for non-GET requests | Add test for non-GET requests
* Check that we get a 403 result.
| Python | bsd-2-clause | incuna/incuna-auth,incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth |
85c509913cc9a6b22036c33eccb07277b39260e3 | pygraphc/anomaly/AnomalyScore.py | pygraphc/anomaly/AnomalyScore.py | import csv
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
class AnomalyScore(object):
"""A class to calculate anomaly score in a cluster.
"""
def __init__(self, graph, clusters, filename):
"""The constructor of ... | import csv
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
class AnomalyScore(object):
"""A class to calculate anomaly score in a cluster.
"""
def __init__(self, graph, clusters, filename):
"""The constructor of c... | Add description of Parameters section in docstring | Add description of Parameters section in docstring
| Python | mit | studiawan/pygraphc |
65e6c8466482464333e77a2892fd0ac33ab5c3cb | q_and_a/apps/token_auth/views.py | q_and_a/apps/token_auth/views.py | from django.views.generic import RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth import login, authenticate, login
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
class BaseAuthView(SingleObjectMixin, RedirectView):
d... | from django.views.generic import RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth import login, authenticate
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
class BaseAuthView(SingleObjectMixin, RedirectView):
def get_... | Fix indent, PEP-8 style and remove dup import. | Fix indent, PEP-8 style and remove dup import.
| Python | bsd-3-clause | DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions |
a03fe14d4dba7b9a54efdebeb768551bda53e3c1 | admin/common_auth/models.py | admin/common_auth/models.py | from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
class Meta:
# custom permissions f... | from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
def __unicode__(self):
return self.... | Fix the display name of admin profile in the admin admin | Fix the display name of admin profile in the admin admin
| Python | apache-2.0 | HalcyonChimera/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,sloria/osf.io,chrisseto/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,icereval/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,cslzchen/osf.io,felliott/osf.io,chennan47/osf.io,binoculars/o... |
88426415053f44202596e8bd573ca2ca6c056e04 | schwifty/registry.py | schwifty/registry.py | import json
from pkg_resources import resource_filename
_registry = {}
def has(name):
return name in _registry
def get(name):
if not has(name):
with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp:
save(name, json.load(fp))
return _registry[name]
def save(na... | import json
from collections import defaultdict
from pkg_resources import resource_filename
_registry = {}
def has(name):
return name in _registry
def get(name):
if not has(name):
with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp:
save(name, json.load(fp))
... | Allow index to be accumulate values with same key | Allow index to be accumulate values with same key
| Python | mit | figo-connect/schwifty |
1642bf91ab9042fddb3fcdeb7d2d8d010979c978 | disasm.py | disasm.py | import MOS6502
import instructions
def disasm(memory, maxLines=0, address=-1):
index = 0
lines = []
while index < len(memory):
currInst = instructions.instructions[memory[index]]
if address > 0:
line = format(address+index, '04x') + ": "
else:
line ... | import MOS6502
import instructions
import code
def disasm(memory, maxLines=0, address=-1):
index = 0
lines = []
while index < len(memory):
opcode = memory[index]
if opcode not in instructions.instructions.keys():
print "Undefined opcode: " + hex(opcode)
code.interac... | Add catch for undefined opcodes | Add catch for undefined opcodes
| Python | bsd-2-clause | pusscat/refNes |
bb5d6d94d555a91b2f9da1258aee90146ccd9998 | openstack/common/messaging/_executors/impl_eventlet.py | openstack/common/messaging/_executors/impl_eventlet.py | # Copyright 2013 Red Hat, Inc.
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# 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-... | # Copyright 2013 Red Hat, Inc.
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# 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-... | Add forgotten piece of eventlet executor | Add forgotten piece of eventlet executor
| Python | apache-2.0 | hkumarmk/oslo.messaging,dims/oslo.messaging,dukhlov/oslo.messaging,hkumarmk/oslo.messaging,ozamiatin/oslo.messaging,redhat-openstack/oslo.messaging,dukhlov/oslo.messaging,zhurongze/oslo.messaging,isyippee/oslo.messaging,viggates/oslo.messaging,markmc/oslo.messaging,apporc/oslo.messaging,apporc/oslo.messaging,stevei101/... |
fd98c81f315bf8c1699aed0b7eb46a7c1add73dd | eccodes/highlevel/message.py | eccodes/highlevel/message.py |
import io
import eccodes
class Message:
def __init__(self, handle):
self.handle = handle
def __del__(self):
eccodes.codes_release(self.handle)
def copy(self):
return Message(eccodes.codes_clone(self.handle))
def __copy__(self):
return self.copy()
def get(self, ... |
import io
import eccodes
class Message:
def __init__(self, handle):
self.handle = handle
def __del__(self):
try:
eccodes.codes_release(self.handle)
except Exception:
pass
def copy(self):
return Message(eccodes.codes_clone(self.handle))
def __... | Make Message.__del__ immune to teardown errors | Make Message.__del__ immune to teardown errors
| Python | apache-2.0 | ecmwf/eccodes-python,ecmwf/eccodes-python |
bc401d0073ddf9d693bd182317738d4be4f4ec70 | benchexec/tools/witnesslint.py | benchexec/tools/witnesslint.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | Add version and distinguish linter error from faulty witness. | Add version and distinguish linter error from faulty witness.
| Python | apache-2.0 | ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec |
ad0151eee0027237c8cdd433ef2f24bfa47af5df | pyreaclib/nucdata/tests/test_binding.py | pyreaclib/nucdata/tests/test_binding.py | # unit tests for Binding Energy database taken from AME 2016.
import os
from pyreaclib.nucdata import BindingTable
class TestAME(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmethod
def teardown_class(cls):
"""... | # unit tests for Binding Energy database taken from AME 2016.
import os
from pyreaclib.nucdata import BindingTable
class TestAME(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmethod
def teardown_class(cls):
"""... | Add some more binding energy table tests. | Add some more binding energy table tests.
| Python | bsd-3-clause | pyreaclib/pyreaclib |
629fab227cb5d564d6cb7d9469c76915eb6c72ac | backend/breach/helpers/network.py | backend/breach/helpers/network.py | import netifaces
def get_interface():
return netifaces.gateways()['default'][netifaces.AF_INET][1]
| import netifaces
def get_interface():
return netifaces.gateways()['default'][netifaces.AF_INET][1]
def get_local_IP():
def_gw_device = get_interface()
return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
| Add function to get the machine's local IP | Add function to get the machine's local IP
| Python | mit | esarafianou/rupture,dimriou/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture... |
9dce07895a773998469aeed8c1cfb8476d4264eb | application.py | application.py | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager
application = create_app(os.getenv('FLASH_CONFIG') or 'development')
manager = Manager(application)
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
application = create_app(os.getenv('FLASH_CONFIG') or 'development')
manager = Manager(application)
manager.add_command("runserver", Server(port=5001))
if __name__ == '__main__':
manager.run()
| Update to run on port 5001 | Update to run on port 5001
For development we will want to run multiple apps, so they should each bind to a different port number.
| Python | mit | RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api |
384eab108578d372c9755cf1a1a22738f7cd3dea | app/utils/__init__.py | app/utils/__init__.py | # Copyright (C) 2014 Linaro Ltd.
#
# This program 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
# License, or (at your option) any later version.
#
# This program is distribute... | # Copyright (C) 2014 Linaro Ltd.
#
# This program 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
# License, or (at your option) any later version.
#
# This program is distribute... | Create function to test hidden files/dirs. | Create function to test hidden files/dirs.
Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0
| Python | agpl-3.0 | joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend |
74bfe9bf1501d5c31e2ab6d8dc174467e47e200e | app/dao/magazines_dao.py | app/dao/magazines_dao.py | from app import db
from app.dao.decorators import transactional
from app.models import Magazine
def dao_get_magazines():
return Magazine.query.order_by(Magazine.created_at.desc()).all()
def dao_get_magazine_by_old_id(old_id):
return Magazine.query.filter_by(old_id=old_id).first()
| from app import db
from app.dao.decorators import transactional
from app.models import Magazine
def dao_get_magazines():
return Magazine.query.order_by(Magazine.created_at.desc()).all()
def dao_get_magazine_by_id(id):
return Magazine.query.filter_by(id=id).one()
def dao_get_magazine_by_old_id(old_id):
... | Add get magazine by id to magazine dao | Add get magazine by id to magazine dao
| Python | mit | NewAcropolis/api,NewAcropolis/api,NewAcropolis/api |
e9fe831427d59e2a5889d0e6744a6c9809b4ffd2 | cellular.py | cellular.py | import random
class TotalisticCellularAutomaton:
def __init__(self):
self.n_cells = 200
self.n_states = 5
self.symbols = ' .oO0'
self.radius = 1
self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)]
n_rules = (2*self.radius + 1) * (self.n_st... | import random
from PIL import Image, ImageDraw
class TotalisticCellularAutomaton:
def __init__(self):
self.n_cells = 200
self.n_states = 5
self.symbols = ' .oO0'
self.radius = 1
self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)]
self.co... | Add visualization of CA using Pillow | Add visualization of CA using Pillow
| Python | unlicense | joseph346/cellular |
22f9fc8a56882f0595d051cb8c5d20fd97091e8c | custom/opm/tests/test_snapshot.py | custom/opm/tests/test_snapshot.py | from datetime import date
from unittest import TestCase
from couchforms.models import XFormInstance
from ..constants import *
from ..reports import get_report, BeneficiaryPaymentReport, MetReport
from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider
class TestGetReportUtil(TestCase):
def get_... | from datetime import date
from unittest import TestCase
from mock import patch
from corehq.apps.users.models import CommCareUser
from couchforms.models import XFormInstance
from ..constants import *
from ..reports import get_report, BeneficiaryPaymentReport, MetReport
from .case_reports import Report, OPMCase, MockCas... | Fix for test (add mock for CommCareUser) | Fix for test (add mock for CommCareUser)
| Python | bsd-3-clause | puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
5e03af4b0f920e97507b3ada6b4b925136ddbf07 | froide/upload/serializers.py | froide/upload/serializers.py | from rest_framework import serializers
from .models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['guid'].required = True
| from rest_framework import serializers
from .models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = '__all__'
def __init__(self, *args, **kwargs):
'''
Add required marker, so OpenAPI schema generator can remove it again
... | Add some documentation for weird init | Add some documentation for weird init | Python | mit | fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide |
5cb497d0741f6dbd29a6e41fa9f1cb3374e8f062 | jsontosql.py | jsontosql.py | import os
import os.path
from json import loads
import click
from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB
class JSONToSQL(object):
def __init__(self, json, user, password, database):
self.data = loads(json.read())
self.db = VendCrawlerDB(user, password, database)
... | import os
import os.path
from json import loads
import click
from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB
class JSONToSQL(object):
def __init__(self, json, user, password, database):
data = loads(json.read())
db = VendCrawlerDB(user, password, database)
table = '... | Fix json to sql converter. | Fix json to sql converter.
| Python | mit | josetaas/vendcrawler,josetaas/vendcrawler,josetaas/vendcrawler |
4217f587606c4e326b4df97681ae4f5187b6e6d9 | falmer/content/serializers.py | falmer/content/serializers.py | from django.conf import settings
from django.urls import reverse
from rest_framework import serializers
from falmer.content.models import StaffMemberSnippet
from falmer.matte.models import MatteImage
def generate_image_url(image, filter_spec):
from wagtail.wagtailimages.views.serve import generate_signature
... | from django.conf import settings
from django.urls import reverse
from rest_framework import serializers
from falmer.content.models import StaffMemberSnippet
from falmer.matte.models import MatteImage
def generate_image_url(image, filter_spec):
from wagtail.wagtailimages.views.serve import generate_signature
... | Remove wagtail_image from image resources | Remove wagtail_image from image resources
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer |
20c7905ea062fb6e83ddf641b0a12619044c39e3 | blog/models.py | blog/models.py | from django.db import models
from django.contrib.auth.models import User
from hadrian.utils import slugs
from ckeditor.fields import RichTextField
from taggit.managers import TaggableManager
from .managers import PostManager
class Post(models.Model):
title = models.CharField(blank=False, max_length=450)
slu... | from django.db import models
from django.contrib.auth.models import User
from hadrian.utils import slugs
from ckeditor.fields import RichTextField
from taggit.managers import TaggableManager
from .managers import PostManager
class Post(models.Model):
title = models.CharField(blank=False, max_length=450)
slu... | Add sort by publish date. | Add sort by publish date.
| Python | bsd-3-clause | divisible-by-hero/dbh-blog |
b452e9a42d507c000bf6d3068af425d9c0eda8fd | validation/validate_poi.py | validation/validate_poi.py | #!/usr/bin/python
"""
starter code for the validation mini-project
the first step toward building your POI identifier!
start by loading/formatting the data
after that, it's not our code anymore--it's yours!
"""
import pickle
import sys
sys.path.append("../tools/")
from feature_format import feature... | #!/usr/bin/python
"""
starter code for the validation mini-project
the first step toward building your POI identifier!
start by loading/formatting the data
after that, it's not our code anymore--it's yours!
"""
import pickle
import sys
sys.path.append("../tools/")
from feature_format import feature... | Improve instructions for Lesson 13 mini-project. | Improve instructions for Lesson 13 mini-project. | Python | mit | selva86/python-machine-learning,ncfausti/udacity-machine-learning |
bfe779aa65abaff7430b1870a1023b0d5b2e02f8 | lib/pyfrc/tests/__init__.py | lib/pyfrc/tests/__init__.py | '''
These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot`
and :class:`wpilib.samplerobot.SampleRobot` based robots.
'''
# import basic tests
from .basic import (
test_autonomous,
test_disabled,
test_operator_control,
test_practice
)
# import common test typ... | '''
These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot`
and :class:`wpilib.samplerobot.SampleRobot` based robots.
'''
# import basic tests
from .basic import (
test_autonomous,
test_disabled,
test_operator_control,
test_practice
)
# Other test types
from ... | Remove docstring tests from default tests | Remove docstring tests from default tests
| Python | mit | robotpy/pyfrc |
fc09e847a5435581738a32f8aa158e7d03491b94 | calico_containers/tests/st/test_container_to_host.py | calico_containers/tests/st/test_container_to_host.py | from subprocess import CalledProcessError
from test_base import TestBase
from tests.st.utils.docker_host import DockerHost
class TestContainerToHost(TestBase):
def test_container_to_host(self):
"""
Test that a container can ping the host. (Without using the docker
network driver, since i... | from subprocess import CalledProcessError
from test_base import TestBase
from tests.st.utils.docker_host import DockerHost
class TestContainerToHost(TestBase):
def test_container_to_host(self):
"""
Test that a container can ping the host.
This function is important for Mesos, since the c... | Clarify test_containers_to_host not using libnetwork | Clarify test_containers_to_host not using libnetwork
Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291 | Python | apache-2.0 | plwhite/libcalico,TrimBiggs/libcalico,caseydavenport/libcalico,alexhersh/libcalico,insequent/libcalico,tomdee/libnetwork-plugin,projectcalico/libcalico,TrimBiggs/libnetwork-plugin,djosborne/libcalico,TrimBiggs/libnetwork-plugin,tomdee/libcalico,L-MA/libcalico,robbrockbank/libcalico,Symmetric/libcalico,projectcalico/lib... |
37337298d881280a45dad7f0f47ad719feb4baa6 | addons/bestja_configuration_fpbz/__openerp__.py | addons/bestja_configuration_fpbz/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Bestja: FBŻ",
'summary': "Installation configuration for FPBŻ",
'description': "Installation configuration for Federacja Polskich Banków Żywności",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific... | # -*- coding: utf-8 -*-
{
'name': "Bestja: FBŻ",
'summary': "Installation configuration for FPBŻ",
'description': "Installation configuration for Federacja Polskich Banków Żywności",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific... | Add bestja_project_hierarchy to the list of FPBZ's modules | Add bestja_project_hierarchy to the list of FPBZ's modules
| Python | agpl-3.0 | ludwiktrammer/bestja,KamilWo/bestja,EE/bestja,KamilWo/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja,EE/bestja,KrzysiekJ/bestja,KamilWo/bestja,ludwiktrammer/bestja,EE/bestja,KrzysiekJ/bestja |
f9a1ac08fdffc464010c7c493c43a475342c821b | bot.py | bot.py | import zirc, ssl, socket
class Bot(zirc.Client):
def __init__(self):
self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket)
self.config = zirc.IRCConfig(host="irc.freenode.net",
port=6697,
nickname="wolfyzIRCBot",
ident="zirc",
... | import zirc
import ssl
import socket
class Bot(zirc.Client):
def __init__(self):
self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket)
self.config = zirc.IRCConfig(host="irc.freenode.net",
port=6697,
nickname="wolfyzIRCBot",
ident="zirc",... | Move imports to their own line | Move imports to their own line
| Python | mit | wolfy1339/Python-IRC-Bot |
292f78cfe2700ebcfdc83bfbd53717aec3d98d47 | bowser/main.py | bowser/main.py | from bowser.Bot import Bot
def main():
bot = Bot()
try:
token = open('token.txt').read().replace('\n', '')
bot.run(token)
except Exception as ex:
bot.loop.run_until_complete(bot.close())
raise ex
def init():
if __name__ == '__main__':
main()
init()
| from bowser.Bot import Bot
def main():
bot = Bot()
try:
token = open('token.txt').read().replace('\n', '')
bot.run(token)
except Exception as ex:
raise ex
finally:
bot.loop.run_until_complete(bot.close())
def init():
if __name__ == '__main__':
main()
ini... | Remove one of the unclosed client session warnings | test: Remove one of the unclosed client session warnings
| Python | mit | kevinkjt2000/discord-minecraft-server-status |
03d10411b11133a8f371fb94b4dc4476373190a8 | IPython/core/magics/display.py | IPython/core/magics/display.py | """Simple magics for display formats"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----... | """Simple magics for display formats"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----... | Clarify that the MathJax comment is Notebook specific. | Clarify that the MathJax comment is Notebook specific.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
978106fb47ef5d9974678bc1ac2c71ce6e95a311 | plugins/notes_plugin.py | plugins/notes_plugin.py | # -*- coding: utf-8 -*-
# vim: set ts=4 et
import sqlite3
from plugin import *
class Plugin(BasePlugin):
def on_load(self, reloading):
self.db = sqlite3.connect('data/notes.db')
c = self.db.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS notes
(channel text, sender ... | # -*- coding: utf-8 -*-
# vim: set ts=4 et
import sqlite3
from plugin import *
class Plugin(BasePlugin):
def on_load(self, reloading):
self.db = sqlite3.connect('data/notes.db')
c = self.db.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS notes
(channel text, sender ... | Change note trigger to tell, and make it reply | Change note trigger to tell, and make it reply
| Python | mit | jrspruitt/jkent-pybot,jkent/jkent-pybot |
dab7eaadbc6fc0dd867358b096a846ec39bc0440 | pnnl/models/__init__.py | pnnl/models/__init__.py | import importlib
import logging
from volttron.platform.agent import utils
_log = logging.getLogger(__name__)
utils.setup_logging()
__version__ = "0.1"
__all__ = ['Model']
class Model(object):
def __init__(self, config, **kwargs):
base_module = "volttron.pnnl.models."
try:
model_type ... | import importlib
import logging
from volttron.platform.agent import utils
_log = logging.getLogger(__name__)
utils.setup_logging()
__version__ = "0.1"
__all__ = ['Model']
class Model(object):
def __init__(self, config, **kwargs):
base_module = "volttron.pnnl.models."
try:
model_type ... | Add return statement to Model.get_q | Add return statement to Model.get_q
| Python | bsd-3-clause | VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications |
c5279db4e24499d6ee49f1b444087be50f74ed90 | test_spec.py | test_spec.py | #!/usr/bin/python
import unittest
import os
import json
from entei import render
SPECS_PATH = os.path.join('spec', 'specs')
SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')]
STACHE = render
def _test_case_from_path(json_path):
class MustacheTestCase(unittest.TestCase):
"""A si... | #!/usr/bin/python
import unittest
import os
import json
from entei import render
SPECS_PATH = os.path.join('spec', 'specs')
SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')]
STACHE = render
def _test_case_from_path(json_path):
json_path = '%s.json' % json_path
class MustacheTestCa... | Make unittests easier to deal with. | Make unittests easier to deal with.
- Test everything
./test_spec.py
- Test suite
./test_spec.py inverted
- Test unit
./test_spec.py inverted.test_7
| Python | mit | noahmorrison/chevron,noahmorrison/chevron |
1b58fed32fe583863812613604383eb9d8821ee1 | tools/sci.py | tools/sci.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import division, print_function
import numpy as np
from scipy.integrate import ode
def zodeint(func, y0, t):
"""Simple wraper around scipy.integrate.ode for complex valued problems.
:param func: Right hand side of the equation dy/dt = f(t, y)
:para... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import division, print_function
import numpy as np
from scipy.integrate import ode
def zodeint(func, y0, t, **kwargs):
"""Simple wraper around scipy.integrate.ode for complex valued problems.
:param func: Right hand side of the equation dy/dt = f(t, y)... | Correct complex integrator for scalar equations | Correct complex integrator for scalar equations
| Python | unlicense | dseuss/pythonlibs |
2facb0c8794c9529ccb17631a90b0ee181c4eb5b | xml_json_import/__init__.py | xml_json_import/__init__.py | from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImp... | from django.conf import settings
from os import path, listdir
from lxml import etree
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_... | Add exception handling for invalid XSLT files | Add exception handling for invalid XSLT files
| Python | mit | lev-veshnyakov/django-import-data,lev-veshnyakov/django-import-data |
0a38c3f83174042ca4967bff925036af2339808f | job-logs/python/check_log.py | job-logs/python/check_log.py | import sys
import argparse
import csv
def examine_log(filename, save_raw=False):
"""
Download job log files from Amazon EC2 machines
parameters:
filename - beginning date to start downloading from
work_directory - directory to download files to
"""
input_file =- open(filename, 'r')
c... | #!/usr/bin/env python
import sys
import argparse
import csv
def examine_log(filename, save_raw=False):
"""
Download job log files from Amazon EC2 machines
parameters:
filename - beginning date to start downloading from
work_directory - directory to download files to
"""
input_file = ope... | Write bad lines to file for examination | Write bad lines to file for examination
| Python | apache-2.0 | DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs |
ee8acd5a476b0dcce9b79f70e4c70186ea4d5dc0 | miniutils.py | miniutils.py | import __builtin__
def any(it):
for obj in it:
if obj:
return True
def all(it):
for obj in it:
if not obj:
return False
return True
def max(it, key=None):
if key is not None:
k, value = max((key(value), value) for value in it)
return value
r... | import __builtin__
def any(it):
for obj in it:
if obj:
return True
return False
def all(it):
for obj in it:
if not obj:
return False
return True
def max(it, key=None):
if key is not None:
k, value = max((key(value), value) for value in it)
r... | Return an actual bool from any() | Return an actual bool from any()
| Python | bsd-2-clause | markflorisson/minivect,markflorisson/minivect |
e5803617b27144cb88563b3533b66f0b96482143 | guv/green/time.py | guv/green/time.py | __time = __import__('time')
from ..patcher import slurp_properties
__patched__ = ['sleep']
slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time))
from ..greenthread import sleep
sleep # silence pyflakes
| """Greenified :mod:`time` module
The only thing that needs to be patched from :mod:`time` is :func:`time.sleep` to yield instead
of block the thread.
"""
__time = __import__('time')
from ..patcher import slurp_properties
__patched__ = ['sleep']
slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__tim... | Declare sleep as a global instead of relying on import | Declare sleep as a global instead of relying on import
This is a nicer way to define it in the greenified module. Unused imports may
accidentally disappear after using your IDE's "optimize imports" function.
| Python | mit | veegee/guv,veegee/guv |
3a0b65b6698eea40c949a11e733a7f0337fe6e11 | kolibri/plugins/app/utils.py | kolibri/plugins/app/utils.py | from kolibri.plugins.app.kolibri_plugin import App
from kolibri.plugins.registry import registered_plugins
SHARE_FILE = "share_file"
CAPABILITES = (SHARE_FILE,)
class AppInterface(object):
__slot__ = "_capabilities"
def __init__(self):
self._capabilities = {}
def __contains__(self, capability... | from django.core.urlresolvers import reverse
from kolibri.plugins.app.kolibri_plugin import App
from kolibri.plugins.registry import registered_plugins
SHARE_FILE = "share_file"
CAPABILITES = (SHARE_FILE,)
class AppInterface(object):
__slot__ = "_capabilities"
def __init__(self):
self._capabiliti... | Add method to get initialize url. | Add method to get initialize url.
| Python | mit | indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri |
c269debb2819db246483551d512c33b784bbfd22 | test.py | test.py | print "----- import lua -----"
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
lg.tmp = []
print "----- print lg.tmp -----"
print lg.tmp
print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----"
lua.execute("xxx ... | print "----- import lua -----"
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "lg:", lg
print "lg._G:", lg._G
print "lg['_G']:", lg['_G']
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
lg.tmp = []
print "----- print lg.tmp -----"
print lg.tmp
print "-----... | Test Lua's globals() and require() from Python | Test Lua's globals() and require() from Python
| Python | lgpl-2.1 | albanD/lunatic-python,bastibe/lunatic-python,bastibe/lunatic-python,greatwolf/lunatic-python,alexsilva/lunatic-python,greatwolf/lunatic-python,hughperkins/lunatic-python,alexsilva/lunatic-python,hughperkins/lunatic-python,alexsilva/lunatic-python,albanD/lunatic-python |
e14a92e26fe3a8fd14617a57dbf3d4630ba1e50b | impala_udt.py | impala_udt.py | """
A simple demonstration of Impala UDF generation.
"""
from numba.ext.impala import udf, IntVal, FunctionContext
@udf(IntVal(FunctionContext, IntVal, IntVal))
def add_udf(context, arg1, arg2):
if arg1.is_null or arg2.is_null:
return IntVal.null
return IntVal(arg1.val + arg2.val)
# Simply print the ... | """
A simple demonstration of Impala UDF generation.
"""
from numba.ext.impala import (udf, IntVal, FunctionContext, BooleanVal,
DoubleVal, TinyIntVal)
@udf(IntVal(FunctionContext, IntVal, IntVal))
def add_udf(context, arg1, arg2):
if arg1.is_null or arg2.is_null:
return IntV... | Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal | Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal
| Python | bsd-2-clause | cpcloud/numba,GaZ3ll3/numba,sklam/numba,seibert/numba,stuartarchibald/numba,IntelLabs/numba,stefanseefeld/numba,GaZ3ll3/numba,gdementen/numba,jriehl/numba,gmarkall/numba,ssarangi/numba,seibert/numba,pitrou/numba,ssarangi/numba,stonebig/numba,stuartarchibald/numba,numba/numba,numba/numba,cpcloud/numba,sklam/numba,stefan... |
d61540551943df57aa0dece5e44e130309dcafec | requests/packages/__init__.py | requests/packages/__init__.py | from __future__ import absolute_import
from . import urllib3
| """
pip._vendor is for vendoring dependencies of pip to prevent needing pip to
depend on something external.
Files inside of pip._vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
import sys
class VendorAlias(object):
def __in... | Copy pip's import machinery wholesale | Copy pip's import machinery wholesale
| Python | apache-2.0 | psf/requests |
c90c851391a32472d9937930543698d09ee017e9 | distarray/tests/test_client.py | distarray/tests/test_client.py | import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain van... | import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain van... | Add failing test for DistArrayProxy.__setitem__ | Add failing test for DistArrayProxy.__setitem__ | Python | bsd-3-clause | enthought/distarray,RaoUmer/distarray,RaoUmer/distarray,enthought/distarray |
b7047bd09a6bda21dfd1c69cc4cdd08ae328a03b | autotests/tests/sample_false_assert.py | autotests/tests/sample_false_assert.py | import time
from unittest import TestCase
class Sample(TestCase):
def test_sameple_with_big_timeout(self):
print("Testing false assert")
self.assertEquals(1, 2)
| from unittest import TestCase
class Sample(TestCase):
def test_sameple_with_big_timeout(self):
print("Testing false assert")
self.assertEqual(1, 2)
| Fix deprecated use of function on sample test | Fix deprecated use of function on sample test
| Python | mit | jfelipefilho/test-manager,jfelipefilho/test-manager,jfelipefilho/test-manager |
6d8b6cfe9e2de860b4b39a1e0f0bb8fa45e6b96f | manage.py | manage.py | #-*- coding: utf-8 -*-
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
import os
if os.path.exists('.e... | #-*- coding: utf-8 -*-
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from ... | Fix import location of environment variables | Fix import location of environment variables
| Python | mit | moremorefor/Logpot,moremorefor/Logpot,moremorefor/Logpot |
52f1c57c2aebd6d371ce95d35442c5eb6f59ea0b | zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py | zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0126_prereg_remove_users_without_realm'),
]
operations = [
# There was a migration here, which wasn't ready for wide deployment
# and was backed out. This ... | # -*- coding: utf-8 -*-
from typing import Any, List
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0126_prereg_remove_users_without_realm'),
]
operations = [
# There was a migration here, which wasn't ready for wide deployment
... | Fix mypy error in placeholder migration. | migrations: Fix mypy error in placeholder migration.
| Python | apache-2.0 | eeshangarg/zulip,timabbott/zulip,brainwane/zulip,tommyip/zulip,zulip/zulip,rishig/zulip,punchagan/zulip,eeshangarg/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,brainwane/zulip,rishig/zulip,punchagan/zulip,hackerkid/zulip,showell/zulip,andersk/zulip,jackrzhang/zulip,tommyip/zulip,synicalsyntax/zulip,timabbot... |
4649ea618a4f41f5a2f54eb73806d3e1b98e5e00 | Python/number-complement.py | Python/number-complement.py | # Time: O(1)
# Space: O(1)
# Given a positive integer, output its complement number.
# The complement strategy is to flip the bits of its binary representation.
#
# Note:
# The given integer is guaranteed to fit within the range of a 32-bit signed integer.
# You could assume no leading zero bit in the integer’s binar... | # Time: O(1)
# Space: O(1)
# Given a positive integer, output its complement number.
# The complement strategy is to flip the bits of its binary representation.
#
# Note:
# The given integer is guaranteed to fit within the range of a 32-bit signed integer.
# You could assume no leading zero bit in the integer’s binar... | Add another solution for 'Number complement' problem | Add another solution for 'Number complement' problem
| Python | mit | kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015 |
a4b3c62660f394bb6205f5a4bd915782752ddb8d | byceps/announce/discord/connections.py | byceps/announce/discord/connections.py | """
byceps.announce.discord.connections
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Announce events on Discord.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Optional
from ...events.board import BoardPostingCreated, BoardTopicCreated
from ...events.... | """
byceps.announce.discord.connections
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Announce events on Discord.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Optional
from ...events.base import _BaseEvent
from ...events.board import BoardPostingCrea... | Compress Discord event connectors into single function | Compress Discord event connectors into single function
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
acccb727054d919a2a36854d8bac502274ed3bdd | mp3-formatter/rename_mp3.py | mp3-formatter/rename_mp3.py | #!/usr/bin/python3
import ID3
import os
import sys
def read_tracklist():
tracklist = []
for line in sys.stdin:
tracklist.append(line)
return tracklist
tracklist = read_tracklist()
mp3_extension = ".mp3"
files_all = os.listdir('.')
files = []
for f in files_all:
# Prune directories
if n... | #!/usr/bin/python3
import ID3
import os
import sys
def read_tracklist():
tracklist = []
for line in sys.stdin:
tracklist.append(line)
return tracklist
def match_length(files, tracklist):
if len(files) != len(tracklist):
raise RuntimeError(
str(len(tracklist)) +
... | Move files/tracklist count check to function | MP3: Move files/tracklist count check to function
| Python | mit | jleung51/scripts,jleung51/scripts,jleung51/scripts |
fc2b587d792c19afe00caf129057afa686bdc684 | web_utils.py | web_utils.py | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorat... | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import (
json_response, HTTPError,
HTTPSuccessful, HTTPRedirection
)
def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs):
"""Turn dict ou... | Handle HTTP errors raised within web handlers | Handle HTTP errors raised within web handlers
| Python | mit | open-craft-guild/aio-feature-flags |
73f4c29d47e23b26483733ab25ea33367657f758 | test/selenium/src/lib/page/modal/create_new_object.py | test/selenium/src/lib/page/modal/create_new_object.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""Modals for creating new objects"""
from lib.page.modal import base
cla... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""Modals for creating new objects"""
from lib.page.modal import base
cla... | Add modals for creating objects | Add modals for creating objects
| Python | apache-2.0 | plamut/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,Al... |
53309f9c85739a57388902804e875d67404957b2 | modules/add_random.py | modules/add_random.py | def add_random(self, command):
import random
global selected_songs
filelist = []
for root, dirs, files in os.walk(MUSIC_PATH):
for name in files:
root = root.replace(MUSIC_PATH + os.sep, "")
filelist.append(os.path.join(root, name))
numsongs = int(self.confman.get_val... | def add_random(self, command):
import random
global selected_songs
filelist = []
for root, dirs, files in os.walk(MUSIC_PATH):
for name in files:
root = root.replace(MUSIC_PATH + os.sep, "")
filelist.append(os.path.join(root, name))
numsongs = int(self.confman.get_val... | Fix random module's help message | Fix random module's help message
| Python | agpl-3.0 | Flat/JiyuuBot,Zaexu/JiyuuBot |
440593615adca029b11575e604d251c7b68942b4 | api/licenses/serializers.py | api/licenses/serializers.py | from rest_framework import serializers as ser
from api.base.serializers import (
JSONAPISerializer, LinksField, IDField, TypeField
)
from api.base.utils import absolute_reverse
class LicenseSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'id',
])
non_anonymized_... | from rest_framework import serializers as ser
from api.base.serializers import (
JSONAPISerializer, LinksField, IDField, TypeField
)
from api.base.utils import absolute_reverse
class LicenseSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'id',
])
non_anonymized_... | Add url to the license api serializer | Add url to the license api serializer
| Python | apache-2.0 | felliott/osf.io,baylee-d/osf.io,sloria/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,adlius/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,felliott/osf.io,mfraezz/osf.io,cslzchen/osf.io,icereval/osf.io,felliott/osf.io,adlius/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.... |
edcce0e44c453f459e82774efeb0996457d84306 | integration_tests/tests/test_experiment_detumbling.py | integration_tests/tests/test_experiment_detumbling.py | from datetime import timedelta, datetime
import telecommand
from obc.experiments import ExperimentType
from system import auto_power_on
from tests.base import BaseTest
from utils import TestEvent
class TestExperimentDetumbling(BaseTest):
@auto_power_on(auto_power_on=False)
def __init__(self, *args... | from datetime import timedelta, datetime
import telecommand
from obc.experiments import ExperimentType
from system import auto_power_on
from tests.base import BaseTest
from utils import TestEvent
class TestExperimentDetumbling(BaseTest):
@auto_power_on(auto_power_on=False)
def __init__(self, *args... | Fix race condition in detumbling experiment test | Fix race condition in detumbling experiment test
In detumbling experiment test, experiment was commanded to run for 4
hours. After that OBC time was advanced also by 4 hours, however it was
not enough as during next mission loop OBC time was few milliseconds
before scheduled experiment end.
| Python | agpl-3.0 | PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC |
0fca8a2c694db53d214d927606e2b0fed78ae31c | knights/dj.py | knights/dj.py | from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params... | from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEn... | Make context a defaultdict so unknown values yield empty string | Make context a defaultdict so unknown values yield empty string
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
ab55f28592956cc6c9abbea31c2b0d66e13cddc1 | src/pygrapes/adapter/__init__.py | src/pygrapes/adapter/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "mib"
__date__ = "$2011-01-22 12:02:41$"
from abstract import Abstract
from local import Local
__all__ = ['Abstract', 'Local']
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "mib"
__date__ = "$2011-01-22 12:02:41$"
from pygrapes.util import not_implemented
from pygrapes.adapter.abstract import Abstract
from pygrapes.adapter.local import Local
try:
from pygrapes.adapter.zeromq import Zmq
except ImportError:
Zmq = not_imple... | Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module | Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module
| Python | bsd-3-clause | michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes |
464c52d5ffd3ea4262bf826e11e6b890976bf589 | cherrypy/wsgiserver/__init__.py | cherrypy/wsgiserver/__init__.py | __all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer',
'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile',
'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert',
'WorkerThread', 'ThreadPool', 'SSLAdapter',
'CherryPyWSGIServer',
'Gateway', 'WSGIGateway', 'WSGIGate... | __all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer',
'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile',
'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert',
'WorkerThread', 'ThreadPool', 'SSLAdapter',
'CherryPyWSGIServer',
'Gateway', 'WSGIGateway', 'WSGIGate... | Use uniform syntax for wsgiserver imports | Use uniform syntax for wsgiserver imports
| Python | bsd-3-clause | cherrypy/cherrypy,cherrypy/cheroot,Safihre/cherrypy,cherrypy/cherrypy,Safihre/cherrypy |
3b5ac5f7e0b10b06be042037278634fc42bd9b35 | tmc/models/document_type.py | tmc/models/document_type.py | # -*- coding: utf-8 -*-
from odoo import models, fields, _
class Document_Type(models.Model):
_name = 'tmc.document_type'
name = fields.Char(
string='Document Type'
)
abbreviation = fields.Char(
size=3,
required=True
)
model = fields.Char(
required=True
... | # -*- coding: utf-8 -*-
from odoo import _, fields, models
class Document_Type(models.Model):
_name = 'tmc.document_type'
name = fields.Char(
string='Document Type'
)
abbreviation = fields.Char(
size=4,
required=True
)
model = fields.Char(
required=True
... | Increase size for abbreviation field | [FIX] Increase size for abbreviation field
| Python | agpl-3.0 | tmcrosario/odoo-tmc |
b3f7b677edb0a87abff2ef64dadb64547d757d6b | elasticsearch_django/migrations/0004_auto_20161129_1135.py | elasticsearch_django/migrations/0004_auto_20161129_1135.py | # Generated by Django 1.9 on 2016-11-29 11:35
from django.db import migrations
from ..db.fields import JSONField
class Migration(migrations.Migration):
dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")]
operations = [
migrations.AlterField(
model_name="searchquery",
... | # Generated by Django 1.9 on 2016-11-29 11:35
from django.contrib.postgres.fields import JSONField
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")]
operations = [
migrations.AlterField(
model_nam... | Update migration to use native JSONField | Update migration to use native JSONField
| Python | mit | yunojuno/elasticsearch-django |
529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc | openquake/__init__.py | openquake/__init__.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake 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 Licen... | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake 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 Licen... | Make the openquake namespace compatible with old setuptools | Make the openquake namespace compatible with old setuptools
Former-commit-id: e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb | Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine |
0c8e67f51ac6271ea4fed1f524144cfccbf6e215 | form_designer/contrib/cms_plugins/form_designer_form/migrations/0001_initial.py | form_designer/contrib/cms_plugins/form_designer_form/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0001_initial'),
('form_designer', '0001_initial'),
]
operations = [
migrations.CreateModel(
name=... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cms
from django.db import migrations, models
from pkg_resources import parse_version as V
# Django CMS 3.3.1 is oldest release where the change affects.
# Refs https://github.com/divio/django-cms/commit/871a164
if V(cms.__version__) >= V('3.3.1'):... | Add related name for cmsplugin ptr | Add related name for cmsplugin ptr
Add the related name for the cmsplugin_ptr field if the Django CMS version is 3.3.1 or newer. The related name is added to the base model in Django CMS see: https://github.com/divio/django-cms/commit/871a16433f713249ee20b52574803f51941ac20c
| Python | bsd-3-clause | andersinno/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer-ai,andersinno/django-form-designer,andersinno/django-form-designer-ai,kcsry/django-form-designer |
4bbfdfc63cdfa0a6f54b09683033f23a71115547 | src/pyws/protocols/rest.py | src/pyws/protocols/rest.py | from functools import partial
from pyws.errors import BadRequest
from pyws.functions.args.types.complex import List
from pyws.response import Response
from pyws.utils import json
from pyws.protocols.base import Protocol
__all__ = ('RestProtocol', 'JsonProtocol', )
create_response = partial(Response, content_type='a... | from functools import partial
from pyws.errors import BadRequest
from pyws.functions.args.types.complex import List
from pyws.response import Response
from pyws.utils import json
class encoder( json.JSONEncoder ):
# JSON Serializer with datetime support
def default(self,obj):
if isinstance(obj, dateti... | Add custom JSON serialize for Python datetime | Add custom JSON serialize for Python datetime
This adds a custom JSON serializer class which stringifies Python
datetime objects in to ISO 8601. JSON does not specify a date/time
format, and many parsers break trying to parse a Date() javascript
object. 8601 seems a resonable compromise.
| Python | mit | stepank/pyws,stepank/pyws,stepank/pyws,stepank/pyws,stepank/pyws |
b0aad0ba83557fc529e803547f93a54d272f5817 | fmn/lib/tests/example_rules.py | fmn/lib/tests/example_rules.py | """ Some example rules for the test suite. """
def wat_rule(config, message):
return message['wat'] == 'blah'
def not_wat_rule(config, message):
return message['wat'] != 'blah'
| """ Some example rules for the test suite. """
import fmn.lib.hinting
def wat_rule(config, message):
return message['wat'] == 'blah'
def not_wat_rule(config, message):
return message['wat'] != 'blah'
@fmn.lib.hinting.hint(categories=['whatever'])
def hint_masked_rule(config, message, argument1):
""" ... | Add example rule for test. | Add example rule for test.
| Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.