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
fa89ac95954502c14105857dfbb8dece271408e0
fiesta/fiesta.py
fiesta/fiesta.py
import base64, json, urllib2 api_client_id = "To3-IKknn36qAAAA" api_client_secret = "46d028xWl8zXGa3GCOYJMeXlr5pUebCNZcz3SCJj" basic_auth = base64.b64encode("%s:%s" % (api_client_id, api_client_secret)) def _create_and_send_request(uri, api_inputs): request = urllib2.Request(uri) request.add_header("Authoriza...
import base64, json, urllib2 api_client_id = "" api_client_secret = "" basic_auth = base64.b64encode("%s:%s" % (api_client_id, api_client_secret)) def _create_and_send_request(uri, api_inputs): request = urllib2.Request(uri) request.add_header("Authorization", "Basic %s" % (basic_auth)) request.add_header...
Remove accidental commit of credentials
Remove accidental commit of credentials
Python
apache-2.0
fiesta/fiesta-python
a98f1291df2a9d7a232e96f6b65369c03b5f8e12
dmoj/executors/ZIG.py
dmoj/executors/ZIG.py
from dmoj.executors.compiled_executor import CompiledExecutor class Executor(CompiledExecutor): ext = 'zig' name = 'ZIG' command = 'zig' test_program = ''' const std = @import("std"); pub fn main() !void { const io = std.io; const stdin = std.io.getStdIn().inStream(); const stdout = std.i...
from dmoj.executors.compiled_executor import CompiledExecutor class Executor(CompiledExecutor): ext = 'zig' name = 'ZIG' command = 'zig' test_program = ''' const std = @import("std"); pub fn main() !void { const io = std.io; const stdin = std.io.getStdIn().inStream(); const stdout = std.i...
Move Zig source normalization to `create_files`
Move Zig source normalization to `create_files` This actually works, even if I don't know why.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
a426a460555e17d6969444f6dea2ef4e131d6eaf
iatidataquality/registry.py
iatidataquality/registry.py
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3...
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3...
Add URL for checking for deleted packages
Add URL for checking for deleted packages
Python
agpl-3.0
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
9109d7d148abd8764b750becced3487f6d9ea8fc
rpcdaemon/lib/pidfile.py
rpcdaemon/lib/pidfile.py
import os class PIDFile(): def __init__(self, path): if not path: raise IOError('File not found. Please specify PID file path.') self.path = path def __enter__(self): if not os.path.exists(self.path): # Create it with open(self.path, 'w') as pidfil...
import os class PIDFile(): def __init__(self, path): if not path: raise IOError('File not found. Please specify PID file path.') self.path = path def __enter__(self): if not os.path.exists(self.path): # Create it with open(self.path, 'w') as pidfil...
Fix change in args between versions of python-daemon
Fix change in args between versions of python-daemon Newer version call __exit__ with exception data, old versions merely call __exit__().
Python
apache-2.0
Apsu/rpcdaemon
3ec6dda43e617ddf6ad6b755cbcf2e93d5ff0983
feebb/preprocessor.py
feebb/preprocessor.py
import json class Preprocessor: def __init__(self): self.reset() def reset(self): self.number_elements = 0 self.length_elements = [] self.E_elements = [] self.I_elements = [] self.loads = [] self.supports = [] def load_json(self, infile): s...
import json class Preprocessor: def __init__(self): self.reset() def __str__(self): return json.dumps(self.__dict__, indent=2, separators=(',', ': ')) def reset(self): self.number_elements = 0 self.length_elements = [] self.E_elements = [] self.I_elements ...
Add __str__ to Preprocessor class
Add __str__ to Preprocessor class
Python
mit
rbn920/feebb
8182b0b053d45252c7800aa1bf1f750fdfa7f876
examples/jumbo_fields.py
examples/jumbo_fields.py
from __future__ import print_function import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): ...
from __future__ import print_function import os from simpleflow import Workflow, activity @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboF...
Make JumboFieldsWorkflow fail if no env var
Make JumboFieldsWorkflow fail if no env var If SIMPLEFLOW_JUMBO_FIELDS_BUCKET is not set, the example doesn't work; make this clear. Signed-off-by: Yves Bastide <3b1fe340dba76bf37270abad774f327f50b5e1d8@botify.com>
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
09bf3b9883096e7a433508a6d6e03efad2a137df
httpavail.py
httpavail.py
import sys, requests, argparse from retrying import retry argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) argparser.add_argument('url') argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available') argpa...
import sys, requests, argparse from retrying import retry argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) argparser.add_argument('url') argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available') argpa...
Make the expected HTTP status code configurable
Make the expected HTTP status code configurable
Python
mit
ulich/docker-httpavail
12edf5a5d77f96986a12105f922fabea83032bad
tests/scratchtest2.py
tests/scratchtest2.py
#!/usr/bin/env python import sys sys.path.append("../zvm") from zmemory import ZMemory from zlexer import ZLexer story = file("../stories/zork.z1").read() mem = ZMemory(story) lexer = ZLexer(mem) print "This story is z version", mem.version print "Standard dictionary:" print " word separators are", lexer._separ...
#!/usr/bin/env python import sys sys.path.append("../zvm") from zmemory import ZMemory from zlexer import ZLexer story = file("../stories/zork.z1").read() mem = ZMemory(story) lexer = ZLexer(mem) print "This story is z version", mem.version print "Standard dictionary:" print " word separators are", lexer._separ...
Revert r67, which was not the changeset intended for commit.
Revert r67, which was not the changeset intended for commit.
Python
bsd-3-clause
BGCX262/zvm-hg-to-git,BGCX262/zvm-hg-to-git
8e2cfa2845b6fadba1914246ed2169741164aa32
mastertickets/db_default.py
mastertickets/db_default.py
# Created by Noah Kantrowitz on 2007-07-04. # Copyright (c) 2007 Noah Kantrowitz. All rights reserved. from trac.db import Table, Column name = 'mastertickets' version = 2 tables = [ Table('mastertickets', key=('source','dest'))[ Column('source', type='integer'), Column('dest', type='integer'), ...
# Created by Noah Kantrowitz on 2007-07-04. # Copyright (c) 2007 Noah Kantrowitz. All rights reserved. from trac.db import Table, Column name = 'mastertickets' version = 2 tables = [ Table('mastertickets', key=('source','dest'))[ Column('source', type='integer'), Column('dest', type='integer'), ...
Fix the migration to actual work.
Fix the migration to actual work.
Python
bsd-3-clause
thmo/trac-mastertickets,pombredanne/trac-mastertickets,pombredanne/trac-mastertickets,thmo/trac-mastertickets
369efdb0074ec29259e519b5d3974d55a17af56d
test_groupelo.py
test_groupelo.py
import groupelo def test_win_expectancy(): assert groupelo.win_expectancy(1500, 1500) == 0.5 assert groupelo.win_expectancy(1501, 1499) > 0.5 assert groupelo.win_expectancy(1550, 1450) > 0.6 assert groupelo.win_expectancy(1600, 1400) > 0.7 assert groupelo.win_expectancy(1700, 1300) > 0.9 assert...
# Run this with py.test or nose import groupelo def test_win_expectancy(): assert groupelo.win_expectancy(1500, 1500) == 0.5 assert groupelo.win_expectancy(1501, 1499) > 0.5 assert groupelo.win_expectancy(1550, 1450) > 0.6 assert groupelo.win_expectancy(1600, 1400) > 0.7 assert groupelo.win_expect...
Add a comment explaining how to run this unit test.
Add a comment explaining how to run this unit test.
Python
mit
dripton/groupelo
dca0598633350dfda2450552760ffbc774e63cb8
myfedora/lib/app_globals.py
myfedora/lib/app_globals.py
"""The application's Globals object""" from tg import config from shove import Shove from feedcache.cache import Cache from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): ...
"""The application's Globals object""" from tg import config from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during applicati...
Remove the feed cache and storage from the globals. This lives in moksha.
Remove the feed cache and storage from the globals. This lives in moksha.
Python
agpl-3.0
fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages
a52345306a1561496e2630fa12d938af84ff3f7d
management/commands/import_unit_data.py
management/commands/import_unit_data.py
# -*- encoding: UTF-8 -*- # # Copyright 2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of CVN. # # CVN 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 ...
# -*- encoding: UTF-8 -*- # # Copyright 2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of CVN. # # CVN 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 ...
Delete Report models before reloading them
Delete Report models before reloading them
Python
agpl-3.0
tic-ull/portal-del-investigador-cvn,tic-ull/portal-del-investigador-cvn
3ed6c303e935a78781d096ab90e77a6c1360322d
wutu/tests/modules/test_module/test_module.py
wutu/tests/modules/test_module/test_module.py
from wutu.module import Module class TestModule(Module): def __init__(self): super(TestModule, self).__init__() def ping(self): return "pong" def get(self): return {"result": "Hello"}
from wutu.module import Module class TestModule(Module): def __init__(self): super(TestModule, self).__init__() def ping(self): return "pong" def get(self, id): return {"result": id}
Make test module return dynamic value
Make test module return dynamic value
Python
mit
zaibacu/wutu,zaibacu/wutu,zaibacu/wutu
f8a592301aa44e79e504f15e8c0b37a566c3e4cb
daybed/__init__.py
daybed/__init__.py
"""Main entry point """ import couchdb from pyramid.config import Configurator from pyramid.events import NewRequest from daybed.db import DatabaseConnection, sync_couchdb_views def add_db_to_request(event): request = event.request settings = request.registry.settings con_info = settings['db_server'][set...
"""Main entry point """ import couchdb from pyramid.config import Configurator from pyramid.events import NewRequest from daybed.db import DatabaseConnection, sync_couchdb_views def add_db_to_request(event): request = event.request settings = request.registry.settings con_info = settings['db_server'][set...
Add test at init to create couchdb database if not already exists
Add test at init to create couchdb database if not already exists
Python
bsd-3-clause
spiral-project/daybed,spiral-project/daybed
c613b59861d24a7627844114933c318423d18866
alpha_helix_generator/geometry.py
alpha_helix_generator/geometry.py
import numpy as np
import numpy as np def normalize(v): '''Normalize a vector based on its 2 norm.''' if 0 == np.linalg.norm(v): return v return v / np.linalg.norm(v) def create_frame_from_three_points(p1, p2, p3): '''Create a left-handed coordinate frame from 3 points. The p2 is the origin; the y-axis is ...
Add some basic geometric functions.
Add some basic geometric functions.
Python
bsd-3-clause
xingjiepan/ss_generator
e3828ae72ae778461eee9b93ccc87167505f91f8
validate.py
validate.py
"""Check for inconsistancies in the database.""" from server.db import BuildingBuilder, BuildingType, load, UnitType def main(): load() for name in UnitType.resource_names(): if UnitType.count(getattr(UnitType, name) == 1): continue else: print(f'There is no unit that ...
"""Check for inconsistancies in the database.""" from server.db import ( BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType ) def main(): load() for name in UnitType.resource_names(): if UnitType.count(getattr(UnitType, name) >= 1): continue else: print...
Make sure all unit types can be recruited.
Make sure all unit types can be recruited.
Python
mpl-2.0
chrisnorman7/pyrts,chrisnorman7/pyrts,chrisnorman7/pyrts
99412f8b3394abdab900755095c788604669853d
ankieta/ankieta/petition/views.py
ankieta/ankieta/petition/views.py
# from django.shortcuts import render from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import SetHeadlineMixin from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class ...
# from django.shortcuts import render from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView...
Remove headline from create view
Remove headline from create view
Python
bsd-3-clause
watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl
72216757991a2120bb81e0003496eee908373b0c
keystone/common/policies/ec2_credential.py
keystone/common/policies/ec2_credential.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Set the correct in-code policy for ec2 operations
Set the correct in-code policy for ec2 operations In I8bd0fa342cdfee00acd3c7a33f7232fe0a87e23f we moved some of the policy defaults into code. Some of the policy were accidentally changed. Change-Id: Ib744317025d928c7397ab00dc706172592a9abaf Closes-Bug: #1675377
Python
apache-2.0
ilay09/keystone,rajalokan/keystone,openstack/keystone,ilay09/keystone,mahak/keystone,ilay09/keystone,mahak/keystone,openstack/keystone,rajalokan/keystone,rajalokan/keystone,mahak/keystone,openstack/keystone
1090b8b4e17b29b69eb205ac0c7fea65f597807f
ffdnispdb/__init__.py
ffdnispdb/__init__.py
# -*- coding: utf-8 -*- from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db...
# -*- coding: utf-8 -*- from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) ...
Enable NullCache so we can start implementing cache
Enable NullCache so we can start implementing cache
Python
bsd-3-clause
Psycojoker/ffdn-db,Psycojoker/ffdn-db
b16d634ee9390864da8de6f8d4e7f9e546c8f772
ifs/source/jenkins.py
ifs/source/jenkins.py
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update...
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update...
Update Jenkins source to only update the Jenkins repository
Update Jenkins source to only update the Jenkins repository
Python
isc
cbednarski/ifs-python,cbednarski/ifs-python
77fac3732f1baae9f3c3be7b38f8837459fee163
src/markdown/makrdown.py
src/markdown/makrdown.py
from markdown import markdown from markdown.extensions.tables import TableExtension from .my_codehilite import CodeHiliteExtension from .my_fenced_code import FencedCodeExtension from .my_headerid import HeaderIdExtension def customized_markdown(text): return markdown(text, extensions=[FencedCodeExtension(), ...
import subprocess from xml.etree import ElementTree import pygments from bs4 import BeautifulSoup from pygments.formatters import get_formatter_by_name from pygments.lexers import get_lexer_by_name def customized_markdown(text): kramdown = subprocess.Popen( ["kramdown", "--input", "GFM", ...
Use kramdown for markdown convertion.
Use kramdown for markdown convertion.
Python
apache-2.0
belovrv/kotlin-web-site,meilalina/kotlin-web-site,hltj/kotlin-web-site-cn,madvirus/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,meilalina/kotlin-web-site,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-...
58ce11d293d19247e2765176983edc5e552bdfd5
celery/loaders/__init__.py
celery/loaders/__init__.py
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loa...
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loa...
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Python
bsd-3-clause
frac/celery,cbrepo/celery,cbrepo/celery,mitsuhiko/celery,ask/celery,frac/celery,ask/celery,WoLpH/celery,mitsuhiko/celery,WoLpH/celery
786e98f3c37e1c3bdedc424ed6eaec86e900ec83
test/test_testplugin.py
test/test_testplugin.py
"""Tests of the test-runner plugins.""" import py import unittest from nose.plugins import PluginTester from coverage.runners.noseplugin import Coverage class TestCoverage(PluginTester, unittest.TestCase): """Test the nose plugin.""" activate = '--with-coverage' # enables the plugin plugins = [Coverage()...
"""Tests of the test-runner plugins.""" import py import unittest from nose.plugins import PluginTester from coverage.runners.noseplugin import Coverage class TestCoverage(PluginTester, unittest.TestCase): """Test the nose plugin.""" activate = '--with-coverage' # enables the plugin plugins = [Coverage()...
Mark the py.test test as not to be run in nose.
Mark the py.test test as not to be run in nose.
Python
apache-2.0
jayhetee/coveragepy,nedbat/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,blueyed/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,hugovk/coveragepy,hugovk/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,jayh...
8ce509a2a3df1fcc38442e35e8733bf00bd788ad
harvest/decorators.py
harvest/decorators.py
import os from functools import wraps from argparse import ArgumentParser from fabric.context_managers import prefix def cached_property(func): cach_attr = '_{0}'.format(func.__name__) @property def wrap(self): if not hasattr(self, cach_attr): value = func(self) if value i...
import os from functools import wraps from argparse import ArgumentParser from fabric.context_managers import prefix def cached_property(func): cach_attr = '_{0}'.format(func.__name__) @property def wrap(self): if not hasattr(self, cach_attr): value = func(self) if value i...
Return resulting object from decorated function if any
Return resulting object from decorated function if any
Python
bsd-2-clause
chop-dbhi/harvest,tjrivera/harvest
27aad0e3ed95cb43b28eb3c02fa96b3a9b74de5b
tests/test_container.py
tests/test_container.py
# coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
# coding: utf8 import os import sys import unittest from .common import * # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. # Starting with Python 3.6 the situation is saner thanks to PEP 529: # # https://www.python.org/dev/peps/pep-0529/ broken_unicode = ( os.name == 'nt' and sys.versi...
Disable unicode filename test on Windows with Python 3.0 - 3.5
Disable unicode filename test on Windows with Python 3.0 - 3.5 Before PEP 529 landed in Python 3.6, unicode filename handling on Windows is hit-and-miss, so don't break CI.
Python
bsd-3-clause
PyAV-Org/PyAV,mikeboers/PyAV,PyAV-Org/PyAV,mikeboers/PyAV
6b83217f422b46ef9cc4ef5aa124350eee825fe1
satchless/contrib/tax/flatgroups/models.py
satchless/contrib/tax/flatgroups/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class TaxGroup(models.Model): name = models.CharField(_("group name"), max_length=100) rate = models.DecimalField(_("rate"), max_digits=4, decimal_places=2, help_text=_("Percentile rate of the t...
from django.db import models from django.utils.translation import ugettext_lazy as _ class TaxGroup(models.Model): name = models.CharField(_("group name"), max_length=100) rate = models.DecimalField(_("rate"), max_digits=4, decimal_places=2, help_text=_("Percentile rate of the t...
Fix - TaxedProductMixin is abstract model
Fix - TaxedProductMixin is abstract model
Python
bsd-3-clause
taedori81/satchless
0bc7ad27ec36832f7309af476efdabd25a677328
grako/rendering.py
grako/rendering.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**f...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**f...
Allow render_fields to override the default template.
Allow render_fields to override the default template.
Python
bsd-2-clause
vmuriart/grako,frnknglrt/grako
08b998d63808b99cf96635bd50b7d33238cda633
Recorders.py
Recorders.py
from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.form...
import os from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') ...
Create folder if not exist
Create folder if not exist
Python
mit
hectortosa/py-temperature-recorder
156093f3b4872d68663897b8525f4706ec5a555c
pyfr/template.py
pyfr/template.py
# -*- coding: utf-8 -*- import os import pkgutil from mako.lookup import TemplateLookup from mako.template import Template class DottedTemplateLookup(TemplateLookup): def __init__(self, pkg): self.dfltpkg = pkg def adjust_uri(self, uri, relto): return uri def get_template(self, name):...
# -*- coding: utf-8 -*- import os import pkgutil from mako.lookup import TemplateLookup from mako.template import Template class DottedTemplateLookup(TemplateLookup): def __init__(self, pkg): self.dfltpkg = pkg def adjust_uri(self, uri, relto): return uri def get_template(self, name):...
Enhance the dotted name lookup functionality.
Enhance the dotted name lookup functionality.
Python
bsd-3-clause
tjcorona/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,iyer-arvind/PyFR,Aerojspark/PyFR
1a74d34d358940175c9e5ac50a11ac3f0f40729b
app/sense.py
app/sense.py
import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread =...
import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread =...
Work without the Gyro sensor for retail set compatibility.
Work without the Gyro sensor for retail set compatibility.
Python
bsd-2-clause
legorovers/legoflask,legorovers/legoflask,legorovers/legoflask
b3cbd97738c03975f89cc0264cfd47ea44b9728e
annoycode.py
annoycode.py
# == Requires python 3.4! == # Changes Unicode symbols with other symbols that looks the same. from data import Data if __name__ == "__main__": data = Data() if not data.load() or not data.hasMatches(): print("Use trainer.py to generate data for use.") exit(-1) string = "A B C ! -" (ne...
# == Requires python 3.4! == # Changes Unicode symbols with other symbols that looks the same. from data import Data if __name__ == "__main__": data = Data() if not data.load() or not data.hasMatches(): print("Use trainer.py to generate data for use.") exit(-1) string = "ABC!-" stringE...
Print stats on in/out byte count and increase in percent.
ac: Print stats on in/out byte count and increase in percent.
Python
mit
netromdk/annoycode
b529bc715ff133147576aa9026fd281226b7f3b7
app/views.py
app/views.py
from app import app from app.models import Post from flask import render_template @app.route('/') @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" posts = Post.query.filter_by_latest() if posts: pagination = posts.paginate(page=page, per_page=Post.PER_PAGE) return render_t...
from app import app from app.models import Post from flask import render_template @app.route('/') @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" posts = Post.query.filter_by(visible=True) \ .order_by(Post.published.desc()) if posts: pagination = posts.p...
Fix queries and path to templates
Fix queries and path to templates
Python
mit
thebitstick/Flask-Blog,thebitstick/Flask-Blog
009a9f401fd0c1dba6702c1114a73b77f38b9ce3
bin/parse.py
bin/parse.py
#!/usr/bin/env python # -*- encoding: utf8 -*- import json import sys result = {} INDEX = { "AREA": 5 + 3 * 3 + 3 * 3, "CITY": 5 + 3 * 3, "CODE": 5 } for line in open("ORIGIN.txt"): code = line[:INDEX["CODE"]] city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {...
#!/usr/bin/env python # -*- encoding: utf8 -*- import json import sys result = {} INDEX = { "AREA": 5 + 3 * 3 + 3 * 3, "CITY": 5 + 3 * 3, "CODE": 5 } for line in open("ORIGIN.txt"): code = line[:INDEX["CODE"]] city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {...
Fix name parsing for roads
Fix name parsing for roads
Python
mit
lihengl/dizu-api,lihengl/dizu-api
dfa3a3c120b2555706c37da19496557a55f743db
reports/views.py
reports/views.py
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.core.paginator import Paginator from .forms import ReportForm from .models import Report def can_add_reports(user): return user.is_authenticated() and user.has_perm('reports.add_report') @user_passes_tes...
from django.contrib.auth.decorators import permission_required from django.core.paginator import Paginator from django.shortcuts import render from .forms import ReportForm, CopyFormSet from .models import Report @permission_required('reports.add_report', login_url='members:login') def add_report(request): data ...
Add add report with copies functionality and permission
Add add report with copies functionality and permission
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
2e5bcbea0b6adbc947e62c31726734c081500d14
scripts/generate_dump_for_offline_apps_off.py
scripts/generate_dump_for_offline_apps_off.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function import csv from itertools import imap from operator import itemgetter def main(): import pandas df = pandas.read_csv('/srv/off/html/data/en.openfoodfacts.org.products.csv', sep='\t', low_memory=False) colnames = ['code','pr...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import csv from itertools import imap from operator import itemgetter def main(): import pandas df = pandas.read_csv('/srv/off/html/data/en.openfoodfacts.org.products.csv', sep='\t', low_memory=False) colnames = ['code','pr...
Add support for the Eco-Score for Offline-Scan
Add support for the Eco-Score for Offline-Scan Add support for the Eco-Score for Offline-Scan
Python
agpl-3.0
openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server
9530f7a65b5381fbb178dab120454dfc40a8d604
djangopypi2/apps/pypi_users/views.py
djangopypi2/apps/pypi_users/views.py
from django.contrib.auth import logout as auth_logout from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.generic.detail import SingleObjectMixin from django.views.generic.list import MultipleObjectMixin from django.views.generic.list import ListView f...
from django.contrib.auth import logout as auth_logout from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.generic.detail import SingleObjectMixin from django.views.generic.list import MultipleObjectMixin from django.views.generic.list import ListView f...
Fix bad super calls causing infinite recursion
Fix bad super calls causing infinite recursion
Python
bsd-3-clause
popen2/djangopypi2,popen2/djangopypi2,pitrho/djangopypi2,hsmade/djangopypi2,pitrho/djangopypi2,hsmade/djangopypi2
dca70886d2535dd843ea995b8d193958997de41b
slack_sdk/oauth/state_store/state_store.py
slack_sdk/oauth/state_store/state_store.py
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self, *args, **kwargs) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
Enable additional data on state creation
Enable additional data on state creation This should allow for the creation of custom states where the additional data can be used to associate external accounts.
Python
mit
slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient
f0017fc656bc3ee0cfbe1bafe73efe9abc27bc32
mqueue/apps.py
mqueue/apps.py
import importlib from typing import List, Tuple, Union from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" verbose_name = _(u"Events queue") def ready(self): # models registration from settings from djang...
import importlib from typing import List, Tuple, Union from django.utils.translation import gettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" default_auto_field = "django.db.models.BigAutoField" verbose_name = _("Events queue") def ready(self): ...
Add bigautofield default in app conf
Add bigautofield default in app conf
Python
mit
synw/django-mqueue,synw/django-mqueue,synw/django-mqueue
1813413b33170f87cc9fb721c7b5a8cdecfab722
ckanext/googleanalytics/tests/conftest.py
ckanext/googleanalytics/tests/conftest.py
import pytest import factory from factory.alchemy import SQLAlchemyModelFactory from pytest_factoryboy import register import ckan.model as model from ckanext.googleanalytics.model import PackageStats, ResourceStats @pytest.fixture() def clean_db(reset_db, migrate_db_for): reset_db() migrate_db_for("google...
import pytest import factory from factory.alchemy import SQLAlchemyModelFactory from pytest_factoryboy import register from ckan.plugins import toolkit import ckan.model as model from ckanext.googleanalytics.model import PackageStats, ResourceStats if toolkit.requires_ckan_version("2.9"): @pytest.fixture() ...
Fix fixture for older versions
Fix fixture for older versions
Python
agpl-3.0
ckan/ckanext-googleanalytics,ckan/ckanext-googleanalytics,ckan/ckanext-googleanalytics
cca432708ec6220c8d3b7f23ff8c7c5f29d6737a
app/tools/application.py
app/tools/application.py
# -*- coding:utf-8 -*- import os,time,asyncio,json import logging logging.basicConfig(level=logging.ERROR) try: from aiohttp import web except ImportError: logging.error("Can't import module aiohttp") from tools.log import Log from tools.httptools import Middleware,Route from tools.template import Template from tool...
# -*- coding:utf-8 -*- import os,time,asyncio,json import logging logging.basicConfig(level=logging.ERROR) try: from aiohttp import web except ImportError: logging.error("Can't import module aiohttp") from tools.log import Log from tools.httptools import Middleware,Route from tools.template import Template from tool...
Change the way of creating database's connection pool
Change the way of creating database's connection pool
Python
mit
free-free/pyblog,free-free/pyblog,free-free/pyblog,free-free/pyblog
23bf1380d20e0782025ba997f3d33be6d873ae04
piwik/indico_piwik/views.py
piwik/indico_piwik/views.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
Mark sidemenu entry as active
Piwik: Mark sidemenu entry as active
Python
mit
ThiefMaster/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins
bc9012c887065e503a5ac231df8ed4e47a2175ad
apps/challenges/forms.py
apps/challenges/forms.py
from django import forms from tower import ugettext_lazy as _ from challenges.models import Submission class EntryForm(forms.ModelForm): class Meta: model = Submission fields = ( 'title', 'brief_description', 'description', 'created_by' ...
from django import forms from challenges.models import Submission class EntryForm(forms.ModelForm): class Meta: model = Submission fields = ( 'title', 'brief_description', 'description', 'created_by' )
Clear up an unused import.
Clear up an unused import.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
a8e87b389c8b61e986ffb3c9c25af71c09796b52
collector.py
collector.py
import yaml import newspaper from newspaper import news_pool def get_config(): with open('/options/config.yml') as file: config = yaml.safe_load(file) keys = config.keys() if not 'threads' in keys: config['threads'] = 2 if not 'source' in keys: raise Exception('"source" not def...
import yaml import newspaper from rabbit.publisher import Publisher def main(): with open('/options/config.yml') as file: config = yaml.safe_load(file) paper = newspaper.build(config['source']) publisher = Publisher( rabbit_url=config['rabbit_url'], publish_interval=1, arti...
Build paper and hand articles to queue
Build paper and hand articles to queue
Python
mit
projectweekend/Article-Collector
26e43b23a72a85c23184c2f5551885d65cc17831
conda_verify/errors.py
conda_verify/errors.py
from collections import namedtuple class PackageError(Exception): """Exception to be raised when user wants to exit on error.""" class RecipeError(Exception): """Exception to be raised when user wants to exit on error.""" class Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])): ""...
from collections import namedtuple class PackageError(Exception): """Exception to be raised when user wants to exit on error.""" class RecipeError(Exception): """Exception to be raised when user wants to exit on error.""" class Error(namedtuple('Error', ['code', 'message'])): """Error class creates er...
Remove file and line_number from Error class (may add at a later date)
Remove file and line_number from Error class (may add at a later date)
Python
bsd-3-clause
mandeep/conda-verify
6ae9da5ddf987873abb6f54992907542eaf80237
movieman2/tests.py
movieman2/tests.py
import datetime from django.contrib.auth.models import User from django.test import TestCase import tmdbsimple as tmdb from .models import Movie class MovieTestCase(TestCase): def setUp(self): User.objects.create(username="test_user", password="pass", email="test@user.tld", first_name="Test", ...
import datetime import tmdbsimple as tmdb from django.contrib.auth.models import User from django.test import TestCase from .models import Movie class MovieTestCase(TestCase): def setUp(self): User.objects.create(username="movie_test_case", password="pass", email="movie@test_case.tld", ...
Change test case user info
Change test case user info
Python
mit
simon-andrews/movieman2,simon-andrews/movieman2
732a49045d0e5f2dabc6c3d4b89e9be41633b1d8
contacts/views/__init__.py
contacts/views/__init__.py
from braces.views import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import ( get_object_or_404, redirect ) from contacts.models import ( Book, BookOwner, ) class BookOwnerMixin(LoginRequiredMixin): def get_queryset(self): if self.kwargs.g...
from braces.views import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import ( get_object_or_404, redirect ) from contacts.models import ( Book, BookOwner, ) class BookOwnerMixin(LoginRequiredMixin): def get_queryset(self): if self.kwargs.g...
Create book if one doesn't exist during tag creation
Create book if one doesn't exist during tag creation
Python
mit
phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts
3484610b0c711b000da8dc37ab76649aa4abfc58
ptt_preproc_filter.py
ptt_preproc_filter.py
#!/usr/bin/env python import json import sys from os import scandir, remove from datetime import datetime START_DT = datetime(2016, 7, 1, 0, 0, 0) END_DT = datetime(2016, 12, 1, 0, 0, 0) DRY_RUN = True for dir_entry in scandir('preprocessed'): path = dir_entry.path with open(path) as f: # read t...
#!/usr/bin/env python import json import sys from pathlib import Path from os import remove from datetime import datetime START_DT = datetime(2016, 7, 1, 0, 0, 0) END_DT = datetime(2016, 12, 1, 0, 0, 0) DRY_RUN = True for path in Path('preprocessed/').iterdir(): with path.open() as f: # read the jso...
Use pathlib in the filter
Use pathlib in the filter
Python
mit
moskytw/mining-news
71cf0ce2348b46841f2f37c2c8934726832e5094
takeyourmeds/groups/groups_admin/tests.py
takeyourmeds/groups/groups_admin/tests.py
from takeyourmeds.utils.test import SuperuserTestCase class SmokeTest(SuperuserTestCase): def test_index(self): self.assertGET(200, 'groups:admin:index', login=True) def test_view(self): self.assertGET( 200, 'groups:admin:view', self.user.profile.group_id, ...
from takeyourmeds.utils.test import SuperuserTestCase class SmokeTest(SuperuserTestCase): def test_index(self): self.assertGET(200, 'groups:admin:index', login=True) def test_view(self): self.assertGET( 200, 'groups:admin:view', self.user.profile.group_id, ...
Test access token csv download
Test access token csv download Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
808b248d71785e44f764b7724e0d2812a750c9b4
Memoir/urls.py
Memoir/urls.py
"""Memoir URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
"""Memoir URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
Configure a simple index page
Configure a simple index page For now, this is a place-holder.
Python
mit
nivbend/memoir,nivbend/memoir,nivbend/memoir
bd4b4af4596120d1deee6db4e420829c0d40e377
boris/settings/config.py
boris/settings/config.py
import os import boris from .base import STATIC_URL # helper for building absolute paths PROJECT_ROOT = os.path.abspath(os.path.dirname(boris.__file__)) p = lambda x: os.path.join(PROJECT_ROOT, x) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'boris.db', 'USER...
import os import boris from .base import STATIC_URL # helper for building absolute paths PROJECT_ROOT = os.path.abspath(os.path.dirname(boris.__file__)) p = lambda x: os.path.join(PROJECT_ROOT, x) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'boris', 'USER': ''...
Change default database from sqlite to mysql.
Change default database from sqlite to mysql.
Python
mit
fragaria/BorIS,fragaria/BorIS,fragaria/BorIS
a2d4381de5dc50110a0e57d7e56a668edbee2ccf
bot/utils.py
bot/utils.py
from discord import Embed def build_embed(ctx, desc: str, title: str = ''): name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12 def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ...
Add support for colored output in embeds
Add support for colored output in embeds
Python
apache-2.0
HellPie/discord-reply-bot
81189460862be9d03c951c318df6ada2ffefb02f
functest/tests/unit/utils/test_utils.py
functest/tests/unit/utils/test_utils.py
#!/usr/bin/env python # Copyright (c) 2016 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 import logg...
#!/usr/bin/env python # Copyright (c) 2016 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 import logg...
Allow unit testing w/o internet connectivity
Allow unit testing w/o internet connectivity urllib2.urlopen() is now patched when testing the internet connectivity helper. Change-Id: I4ddf1dd8f494fe282735e1051986a0b5dd1a040f Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
Python
apache-2.0
mywulin/functest,opnfv/functest,mywulin/functest,opnfv/functest
23d5d0e0e77dc0b0816df51a8a1e42bc4069112b
rst2pdf/style2yaml.py
rst2pdf/style2yaml.py
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Convert older RSON stylesheets to YAML format Run the script with the filename to convert, it outputs to stdout """ import argparse import json import yaml from rst2pdf.dumpstyle import fixstyle from rst2pdf.rson import loads as rloads def main(): pars...
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Convert older RSON stylesheets to YAML format Run the script with this list of filenames to convert. It outputs to stdout, or use the --save3 flag to have it create .yaml files """ import argparse import json import os import yaml from rst2pdf.dumpstyle impo...
Add save functionality to the conversion script
Add save functionality to the conversion script
Python
mit
rst2pdf/rst2pdf,rst2pdf/rst2pdf
e380ef8d890db4cd21ab9ceb943a38758526976f
numba/tests/issues/test_issue_184.py
numba/tests/issues/test_issue_184.py
import sys from numba import * import numpy as np @jit(object_(double[:, :])) def func2(A): L = [] n = A.shape[0] for i in range(10): for j in range(10): temp = A[i-n : i+n+1, j-2 : j+n+1] L.append(temp) return L A = np.empty(1000000, dtype=np.double).reshape(1000, 100...
import sys from numba import * import numpy as np @jit(object_(double[:, :])) def func2(A): L = [] n = A.shape[0] for i in range(10): for j in range(10): temp = A[i-n : i+n+1, j-2 : j+n+1] L.append(temp) return L A = np.empty(1000000, dtype=np.double).reshape(1000, 100...
Fix test 184 for python 3
Fix test 184 for python 3
Python
bsd-2-clause
gdementen/numba,seibert/numba,numba/numba,ssarangi/numba,pombredanne/numba,pitrou/numba,cpcloud/numba,gmarkall/numba,ssarangi/numba,stefanseefeld/numba,gmarkall/numba,seibert/numba,stuartarchibald/numba,IntelLabs/numba,GaZ3ll3/numba,stefanseefeld/numba,gdementen/numba,stefanseefeld/numba,gmarkall/numba,pombredanne/numb...
5439f17fb2ebea7f8c5695c79324c29c483bfb78
wger/nutrition/migrations/0004_auto_20200819_2310.py
wger/nutrition/migrations/0004_auto_20200819_2310.py
# Generated by Django 3.1 on 2020-08-19 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0003_auto_20170118_2308'), ] operations = [ migrations.AlterField( model_name='nutritionplan', name='desc...
# flake8: noqa # Generated by Django 3.1 on 2020-08-19 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0003_auto_20170118_2308'), ] operations = [ migrations.AlterField( model_name='nutritionplan', ...
Add noqa flag to migration file
Add noqa flag to migration file
Python
agpl-3.0
rolandgeider/wger,petervanderdoes/wger,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,wger-project/wger,petervanderdoes/wger,petervanderdoes/wger,rolandgeider/wger,rolandgeider/wger,wger-project/wger,wger-project/wger
2dfe6e78088f974310c1e7fc309f008310be0080
dask_ndmeasure/_utils.py
dask_ndmeasure/_utils.py
# -*- coding: utf-8 -*- import operator import numpy import dask.array from . import _compat def _norm_input_labels_index(input, labels=None, index=None): """ Normalize arguments to a standard form. """ input = _compat._asarray(input) if labels is None: labels = (input != 0).astype(...
# -*- coding: utf-8 -*- import operator import numpy import dask.array from . import _compat def _norm_input_labels_index(input, labels=None, index=None): """ Normalize arguments to a standard form. """ input = _compat._asarray(input) if labels is None: labels = (input != 0).astype(...
Simplify the label matches function
Simplify the label matches function Focus only creating a mask of selected labels and none of the other products that this function was creating before.
Python
bsd-3-clause
dask-image/dask-ndmeasure
c790e1dd756495f0e34ff3c2cdadb02b4d6ee320
protocols/admin.py
protocols/admin.py
from django.contrib import admin from .models import Protocol, Topic, Institution class ProtocolAdmin(admin.ModelAdmin): list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'get_absent'] list_display_links = ['number'] list_filter = ['topics'] search...
from django.contrib import admin from .models import Protocol, Topic, Institution class ProtocolAdmin(admin.ModelAdmin): list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution'] list_display_links = ['number'] list_filter = ['institution__name',...
Change search and list fields
Change search and list fields
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
299fed5e4531b9cf3bc6043f69b4c7c4db62b6dc
proxy/data/clients.py
proxy/data/clients.py
import blocks connectedClients = {} class ClientData(object): """docstring for ClientData""" def __init__(self, ipAddress, segaId, handle): self.ipAddress = ipAddress self.segaId = segaId self.handle = handle def getHandle(self): return self.handle def setHandle(self, handle): self.handle = handle def ...
import blocks connectedClients = {} class ClientData(object): """docstring for ClientData""" def __init__(self, ipAddress, segaId, handle): self.ipAddress = ipAddress self.segaId = segaId self.handle = handle def getHandle(self): return self.handle def setHandle(self, handle): self.handle = handle def ...
Update SEGA Id in server side too
Update SEGA Id in server side too
Python
agpl-3.0
alama/PSO2Proxy,cyberkitsune/PSO2Proxy,alama/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy,flyergo/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy
c74cb57a8c0186b4186319018a1ed6d7f3687882
celery/tests/test_serialization.py
celery/tests/test_serialization.py
import sys import unittest class TestAAPickle(unittest.TestCase): def test_no_cpickle(self): from celery.tests.utils import mask_modules del(sys.modules["celery.serialization"]) with mask_modules("cPickle"): from celery.serialization import pickle import pickle as ...
from __future__ import with_statement import sys import unittest class TestAAPickle(unittest.TestCase): def test_no_cpickle(self): from celery.tests.utils import mask_modules del(sys.modules["celery.serialization"]) with mask_modules("cPickle"): from celery.serialization impor...
Make tests pass in Python 2.5 by importing with_statement from __future__
Make tests pass in Python 2.5 by importing with_statement from __future__
Python
bsd-3-clause
frac/celery,WoLpH/celery,mitsuhiko/celery,frac/celery,ask/celery,cbrepo/celery,WoLpH/celery,cbrepo/celery,ask/celery,mitsuhiko/celery
adb658a874a7d0437607bf828e99adf2dee74438
openassessment/fileupload/backends/__init__.py
openassessment/fileupload/backends/__init__.py
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # Use S3 backend by default (current behaviour) backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backen...
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # .. setting_name: ORA2_FILEUPLOAD_BACKEND # .. setting_default: s3 # .. setting_description: The backend used to upload the ora2 submissions attachments # the s...
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
Python
agpl-3.0
edx/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2
b84dff394f4c9b0b5aeaeb6bdc1d67ef4a9f02e0
neuroimaging/setup.py
neuroimaging/setup.py
import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('neuroimaging', parent_package, top_path) config.add_subpackage('algorithms') config.add_subpackage('core') config.add_subpackage('data_io') config.add_subpa...
import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('neuroimaging', parent_package, top_path) config.add_subpackage('algorithms') config.add_subpackage('core') config.add_subpackage('externals') config.add_sub...
Change neuroimaging package list data_io to io.
Change neuroimaging package list data_io to io.
Python
bsd-3-clause
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
b7f2efe79e5a91ab78850842eafc73d1ee0a52cc
shortuuid/__init__.py
shortuuid/__init__.py
from shortuuid.main import ( encode, decode, uuid, get_alphabet, set_alphabet, ShortUUID, )
from shortuuid.main import ( encode, decode, uuid, random, get_alphabet, set_alphabet, ShortUUID, )
Include `random` in imports from shortuuid.main
Include `random` in imports from shortuuid.main When `random` was added to `main.py` the `__init__.py` file wasn't updated to expose it. Currently, to use, you have to do: `import shortuuid; shortuuid.main.random(24)`. With these changes you can do `import shortuuid; shortuuid.random()`. This better mirrors the behavi...
Python
bsd-3-clause
skorokithakis/shortuuid,stochastic-technologies/shortuuid
2db6e8e294059847251feb9610c42180ae44e05b
fbone/appointment/views.py
fbone/appointment/views.py
# -*- coding: utf-8 -*- from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __n...
# -*- coding: utf-8 -*- from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appo...
Fix some error about session.
Fix some error about session.
Python
bsd-3-clause
wpic/flask-appointment-calendar,wpic/flask-appointment-calendar
f694b582e72412d4022d6ff21a97d32f77484b9b
heap/heap.py
heap/heap.py
# -*- coding:utf-8 -*- import numpy as np class ArrayHeap(object): def __init__(self, sz, data = None): self.sz = sz self.cnt = 0 self.heap = [0 for i in range(sz + 1)] if data is not None: for i, val in enumerate(data): self.heap[i + 1] = val ...
# -*- coding:utf-8 -*- import numpy as np class MaxHeap(object): def __init__(self, sz, data): self.sz = sz self.heap = [0] * (sz + 1) self.cnt = len(data) self.heap[1: self.cnt + 1] = data self.build_heap() def build_heap(self): last_non_leaf = se...
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
Python
apache-2.0
free-free/algorithm,free-free/algorithm
1ade5cef22e162ce07edb6d94859268727da4949
agile.py
agile.py
import requests import xml.etree.ElementTree as ET from credentials import app_key, user_key, corp_id, report_id base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render' date = '&DatePicker=thisweek' report = '&MembershipMultiPicker=130&filename=memberactivity.xml' url = '{}{}{}{}{}{}{}'.format(base...
import requests import xml.etree.ElementTree as ET from credentials import app_key, user_key, corp_id, report_id base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render' date = '&DatePicker=thisweek' report = '&MembershipMultiPicker=130&filename=memberactivity.xml' url = '{}{}{}{}{}{}{}'.format(base...
Create dict out of member info and append to list
Create dict out of member info and append to list append_members() work identically to append_contacts(). A for loop is also needed to loop over every member entry in the XML file.
Python
mit
deadlyraptor/reels
f6b40cbe9da0552b27b7c4c5d1a2d9bb0a75dafd
custom/icds_reports/permissions.py
custom/icds_reports/permissions.py
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a spe...
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a spe...
Remove Feature flag from the location security check for dashboard
Remove Feature flag from the location security check for dashboard
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
62eea0104615b5d75183d5392fe250fa07d2a988
src/bulksms/config.py
src/bulksms/config.py
# BULKSMS Config. CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'http://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' ...
# BULKSMS Config. CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SENDING': { { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'https://...
Add url for getting credits.
Add url for getting credits.
Python
mit
tsotetsi/django-bulksms
d1a96f13204ad7028432096d25718e611d4d3d9d
depot/gpg.py
depot/gpg.py
import getpass import os import gnupg class GPG(object): def __init__(self, keyid): self.gpg = gnupg.GPG(use_agent=False) self.keyid = keyid if not self.keyid: # Compat with how Freight does it. self.keyid = os.environ.get('GPG') self.passphrase = None ...
import getpass import os import gnupg class GPG(object): def __init__(self, keyid, key=None, home=None): self.gpg = gnupg.GPG(use_agent=False, gnupghome=home) if key: if not home: raise ValueError('Cowardly refusing to import key in to default key store') r...
Allow passing in a raw key and homedir.
Allow passing in a raw key and homedir.
Python
apache-2.0
coderanger/depot
11f43c583fb3b7e8ed2aa74f0f58445a6c2fbecf
bot/api/api.py
bot/api/api.py
from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): ...
from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): ...
Fix get_pending_updates not correctly returning all pending updates
Fix get_pending_updates not correctly returning all pending updates It was only returning the first 100 ones returned in the first telegram API call.
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
48b8efabd11a44dfabcd91f6744858535ddfb498
djangosaml2/templatetags/idplist.py
djangosaml2/templatetags/idplist.py
# Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
Python
apache-2.0
GradConnection/djangosaml2,advisory/djangosaml2_tenant,WiserTogether/djangosaml2,kviktor/djangosaml2-py3,advisory/djangosaml2_tenant,Gagnavarslan/djangosaml2,shabda/djangosaml2,GradConnection/djangosaml2,WiserTogether/djangosaml2,shabda/djangosaml2,kviktor/djangosaml2-py3,City-of-Helsinki/djangosaml2,City-of-Helsinki/d...
d636d8e74514bbda29170b18ef3de90dfbd96397
pylisp/application/lispd/address_tree/ddt_container_node.py
pylisp/application/lispd/address_tree/ddt_container_node.py
''' Created on 1 jun. 2013 @author: sander ''' from .container_node import ContainerNode class DDTContainerNode(ContainerNode): pass
''' Created on 1 jun. 2013 @author: sander ''' from .container_node import ContainerNode class DDTContainerNode(ContainerNode): ''' A ContainerNode that indicates that we are responsible for this part of the DDT tree. '''
Add a bit of docs
Add a bit of docs
Python
bsd-3-clause
steffann/pylisp
b6e9215457eba813f91c9eb4a8b96f8652bcd5fc
functional_tests/pages/settings.py
functional_tests/pages/settings.py
# -*- coding: utf-8 -*- from selenium.webdriver.support.ui import Select from page_objects import PageObject, PageElement, MultiPageElement class SettingsPage(PageObject): return_link = PageElement(css='.mui--text-title a.appbar-correct') inlist_delete_confirm = PageElement(name='inlist_delete_confirm') ac...
# -*- coding: utf-8 -*- from selenium.webdriver.support.ui import Select from page_objects import PageObject, PageElement, MultiPageElement class SettingsPage(PageObject): return_link = PageElement(css='#sidebar-brand a') inlist_delete_confirm = PageElement(name='inlist_delete_confirm') action_delete_confi...
Make the return link work again
Make the return link work again
Python
mit
XeryusTC/projman,XeryusTC/projman,XeryusTC/projman
a38e293d76beaa71893a8f5c4be2ea562d6d3fc2
apistar/layouts/standard/project/routes.py
apistar/layouts/standard/project/routes.py
from apistar import Route, Include from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome routes = [ Route('/', 'GET', welcome), Include('/docs', docs_routes), Include('/static', static_routes) ]
from apistar import Include, Route from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome routes = [ Route('/', 'GET', welcome), Include('/docs', docs_routes), Include('/static', static_routes) ]
Fix import ordering in standard layout
Fix import ordering in standard layout
Python
bsd-3-clause
encode/apistar,rsalmaso/apistar,rsalmaso/apistar,encode/apistar,tomchristie/apistar,tomchristie/apistar,tomchristie/apistar,thimslugga/apistar,thimslugga/apistar,rsalmaso/apistar,encode/apistar,rsalmaso/apistar,encode/apistar,thimslugga/apistar,thimslugga/apistar,tomchristie/apistar
e9bd1c56025e380444ba1e92f6631f59dd01a10a
cms/djangoapps/contentstore/views/session_kv_store.py
cms/djangoapps/contentstore/views/session_kv_store.py
from xblock.runtime import KeyValueStore, InvalidScopeError class SessionKeyValueStore(KeyValueStore): def __init__(self, request, descriptor_model_data): self._descriptor_model_data = descriptor_model_data self._session = request.session def get(self, key): try: return se...
from xblock.runtime import KeyValueStore, InvalidScopeError class SessionKeyValueStore(KeyValueStore): def __init__(self, request, descriptor_model_data): self._descriptor_model_data = descriptor_model_data self._session = request.session def get(self, key): try: return se...
Fix SessionKeyValueStore.has to use the correct indexing value when looking up data
Fix SessionKeyValueStore.has to use the correct indexing value when looking up data
Python
agpl-3.0
ampax/edx-platform-backup,ak2703/edx-platform,ferabra/edx-platform,doganov/edx-platform,pdehaye/theming-edx-platform,jelugbo/tundex,jazztpt/edx-platform,shubhdev/edx-platform,J861449197/edx-platform,wwj718/ANALYSE,wwj718/ANALYSE,doismellburning/edx-platform,shabab12/edx-platform,jamiefolsom/edx-platform,abdoosh00/edraa...
4a67ee6df306fa7907ef76647446e46ae1bfea99
erudite/components/knowledge_provider.py
erudite/components/knowledge_provider.py
""" Knowledge provider that will respond to requests made by the rdf publisher or another bot. """ from sleekxmpp.plugins.base import base_plugin from rhobot.components.storage.client import StoragePayload from rdflib.namespace import FOAF import logging logger = logging.getLogger(__name__) class KnowledgeProvider(b...
""" Knowledge provider that will respond to requests made by the rdf publisher or another bot. """ from sleekxmpp.plugins.base import base_plugin from rhobot.components.storage.client import StoragePayload from rdflib.namespace import FOAF from rhobot.namespace import RHO import logging logger = logging.getLogger(__na...
Use string of Rho Namespace
Use string of Rho Namespace Instead of the URI object, need to use the string.
Python
bsd-3-clause
rerobins/rho_erudite
154659f2126cd83e0a52af3d1a84620ca5c52409
examples/generic_lpu/visualize_output.py
examples/generic_lpu/visualize_output.py
import numpy as np import neurokernel.LPU.utils.visualizer as vis import networkx as nx nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False, 'true':True, 'True':True} G = nx.read_gexf('./data/generic_lpu.gexf.gz') neu_out = [k for k,n in G.node.items() if n['na...
import numpy as np import matplotlib as mpl mpl.use('agg') import neurokernel.LPU.utils.visualizer as vis import networkx as nx nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False, 'true':True, 'True':True} G = nx.read_gexf('./data/generic_lpu.gexf.gz') neu_ou...
Use AGG backend for generic visualization to avoid display dependency.
Use AGG backend for generic visualization to avoid display dependency.
Python
bsd-3-clause
cerrno/neurokernel
d38f36e0b783c1a1f72ead46b90a982fcbe34488
tools/conan/conanfile.py
tools/conan/conanfile.py
from conans import ConanFile, CMake, tools class LibWFUTConan(ConanFile): name = "libwfut" version = "0.2.4" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/libwfut" description = "A client side C+...
from conans import ConanFile, CMake, tools class LibWFUTConan(ConanFile): name = "libwfut" version = "0.2.4" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/libwfut" description = "A client side C+...
Use Conan Center provided libcurl.
Use Conan Center provided libcurl.
Python
lgpl-2.1
worldforge/libwfut,worldforge/libwfut,worldforge/libwfut,worldforge/libwfut
68287347cacae6a7836698cfb11523c8819628c9
virustotal/vt.py
virustotal/vt.py
from threading import Semaphore from os.path import basename from rate import ratelimiter import requests class VirusTotal(): def __init__(self, apikey, limit=4, every=60): self.semaphore = Semaphore(limit) self.apikey = apikey self.every = every def scan(self, path): with ra...
from threading import Semaphore from os.path import basename from rate import ratelimiter import requests class VirusTotal(): def __init__(self, apikey, limit=4, every=60): self.semaphore = threading.Semaphore(limit) self.apikey = apikey self.every = every def scan(self, path): ...
Add apikey to get_report api
Add apikey to get_report api
Python
mit
enricobacis/playscraper
b2adc19e5f28c16bc7cfcd38ed35043d7b1fbe29
profile_collection/startup/15-machines.py
profile_collection/startup/15-machines.py
from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO from ophyd import Component as Cpt # Undulator class Undulator(PVPositionerPC): readback = Cpt(EpicsSignalRO, '-LEnc}Gap') setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos') actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go') actuate_value = 1 stop_si...
from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO from ophyd import Component as Cpt # Undulator class Undulator(PVPositionerPC): readback = Cpt(EpicsSignalRO, '-LEnc}Gap') setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos') actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go') actuate_value = 1 stop_si...
ADD readback.name in iuv_gap to fix speck save prob
ADD readback.name in iuv_gap to fix speck save prob
Python
bsd-2-clause
NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd
d5b068b2efc5fca30014ac7b4d58123461bfbdc1
djedi/utils/templates.py
djedi/utils/templates.py
import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") con...
import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") con...
Update rest api url config error message
Update rest api url config error message
Python
bsd-3-clause
5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms
248fda4f499375b24a2f670569259f0904948b7e
troposphere/detective.py
troposphere/detective.py
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean class Graph(AWSObject): resource_type = "AWS::Detective::Graph" props = {} class MemberInvitation(AWSObject): resource_type = "AWS::Dete...
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, Tags from .validators import boolean class Graph(AWSObject): resource_type = "AWS::Detective::Graph" props = { "Tags": (Tags, False), } class MemberInvitation(...
Update Detective per 2021-04-29 changes
Update Detective per 2021-04-29 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
7c0d68b1bce27d026b69e3a069c549ab560b0f3d
spillway/mixins.py
spillway/mixins.py
class FormMixin(object): """Mixin to provide form validation and data cleaning of GET or POST requests. """ form_class = None @property def form(self): """Returns a validated form dict or an empty dict.""" _form = getattr(self, '_form', False) if not _form: s...
class FormMixin(object): """Mixin to provide form validation and data cleaning of GET or POST requests. """ form_class = None @property def form(self): """Returns a validated form dict or an empty dict.""" _form = getattr(self, '_form', False) if not _form: s...
Use DRF query params and data request attrs
Use DRF query params and data request attrs
Python
bsd-3-clause
barseghyanartur/django-spillway,kuzmich/django-spillway,bkg/django-spillway
f62278c420429cfe9a3f2a8903f902ae24bdd95d
remoteappmanager/handlers/home_handler.py
remoteappmanager/handlers/home_handler.py
from tornado import gen, web from remoteappmanager.handlers.base_handler import BaseHandler class HomeHandler(BaseHandler): """Render the user's home page""" @web.authenticated @gen.coroutine def get(self): images_info = yield self._get_images_info() self.render('home.html', images_i...
from tornado import gen, web from remoteappmanager.handlers.base_handler import BaseHandler class HomeHandler(BaseHandler): """Render the user's home page""" @web.authenticated @gen.coroutine def get(self): self.render('home.html')
Remove dead code now part of the REST API.
Remove dead code now part of the REST API.
Python
bsd-3-clause
simphony/simphony-remote,simphony/simphony-remote,simphony/simphony-remote,simphony/simphony-remote
916b86865acf0297293e4a13f1da6838f9b2711f
scripts/lib/errors.py
scripts/lib/errors.py
""" Оповещение администратора о возникших ошибках """ from traceback import format_exception, format_exc from lib.config import emergency_id from lib.commands import vk, api class ErrorManager: """ Упрощенное оповещение об ошибках str name: название скрипта (обычно укороченное) Использование: with ErrorManager...
""" Оповещение администратора о возникших ошибках """ from traceback import format_exception, format_exc from contextlib import contextmanager from lib.config import emergency_id from lib.commands import vk, api @contextmanager def ErrorManager(name): """ Упрощенное оповещение об ошибках str name: название скрипт...
Change error class to function
Change error class to function
Python
mit
Varabe/Guild-Manager
146e35f48774173c2000b8a9790cdbe6925ba94a
opps/contrib/multisite/admin.py
opps/contrib/multisite/admin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from .models import SitePermission admin.site.register(SitePermission)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from django.utils import timezone from .models import SitePermission class AdminViewPermission(admin.ModelAdmin): def queryset(self, request): queryset = super(AdminViewPermission, self).queryset(request) try: ...
Create AdminViewPermission on contrib multisite
Create AdminViewPermission on contrib multisite
Python
mit
opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps
bc92988baee2186fe5b746751fb5d2e3ec6cb8d9
statzlogger.py
statzlogger.py
import logging try: NullHandler = logging.NullHandler except AttributeError: class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger("statzlogger") log.addHandler(NullHandler()) class StatzHandler(logging.Handler): def emit(self, record): pass...
import logging try: NullHandler = logging.NullHandler except AttributeError: class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger("statzlogger") log.addHandler(NullHandler()) class StatzHandler(logging.Handler): def __init__(self, level=logging.NOT...
Index creation should apply across the board.
Index creation should apply across the board.
Python
isc
whilp/statzlogger
dbe5c25e302b4b71603a94a9519e74605714284c
generic_links/migrations/0001_initial.py
generic_links/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
Remove migration dependency from Django 1.8
Remove migration dependency from Django 1.8
Python
bsd-3-clause
matagus/django-generic-links,matagus/django-generic-links
a3eb818fb9201d5fdf520ce87c9da1d11e1c7e75
denim/constants.py
denim/constants.py
# -*- encoding:utf8 -*- from fabric.api import env class RootUser(object): """ Class to define Root user. """ uid=0 @classmethod def sudo_identity(cls): return None class DeployUser(object): """ Class to define Deploy User. """ @classmethod def sudo_identity(cls...
# -*- encoding:utf8 -*- from fabric.api import env class UserBase(object): pass class RootUser(UserBase): """ Class to define Root user. """ uid=0 @classmethod def sudo_identity(cls): return None class DeployUser(UserBase): """ Class to define Deploy User. """ ...
Fix issue running database creation, should be run as the deployment user
Fix issue running database creation, should be run as the deployment user
Python
bsd-2-clause
timsavage/denim
9bdfdc860264aa200d74bcaf813c2f5055307a3b
webapp/tests/__init__.py
webapp/tests/__init__.py
# -*- coding: utf-8 -*- from unittest import TestCase from byceps.application import create_app from byceps.database import db class AbstractAppTestCase(TestCase): def setUp(self): self.app = create_app('test', initialize=False) db.app = self.app db.create_all() def tearDown(self)...
# -*- coding: utf-8 -*- from unittest import TestCase from byceps.application import create_app from byceps.blueprints.brand.models import Brand from byceps.blueprints.party.models import Party from byceps.database import db class AbstractAppTestCase(TestCase): def setUp(self): self.app = create_app('t...
Prepare application test with current brand and party.
Prepare application test with current brand and party.
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
af3a124c8608fc516a0b78b25da0d4c96aef68da
avahi-daemon/dbus-test.py
avahi-daemon/dbus-test.py
#!/usr/bin/python2.4 import dbus import dbus.glib import gtk from time import sleep bus = dbus.SystemBus() server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server') print "Host name: %s" % server.GetHostName() print "Domain name: %s" % server....
#!/usr/bin/python2.4 import dbus import dbus.glib import gtk from time import sleep bus = dbus.SystemBus() server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server') def server_state_changed_callback(t): print "Server::StateChanged: ", t s...
Make use of StateChanged signal of DBUS Server object
Make use of StateChanged signal of DBUS Server object git-svn-id: ff687e355030673c307e7da231f59639d58f56d5@172 941a03a8-eaeb-0310-b9a0-b1bbd8fe43fe
Python
lgpl-2.1
Distrotech/avahi,Kisensum/xmDNS-avahi,Kisensum/xmDNS-avahi,heftig/avahi,catta-x/catta,lathiat/avahi,catta-x/catta,lathiat/avahi,heftig/avahi,sunilghai/avahi-clone,sunilghai/avahi-clone,lathiat/avahi,heftig/avahi-1,catta-x/catta,Distrotech/avahi,Distrotech/avahi,heftig/avahi,heftig/avahi-1,heftig/avahi-1,Kisensum/xmDNS-...
50488976619795621b5eb6dd3e427f6f82188426
peanut/template.py
peanut/template.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" import peanut import jinja2 from os import path from jinja2 import FileSystemLoader from jinja2.exceptions import TemplateNotFound class SmartLoader(FileSystemLoader): """A smart template loader""" available_extension = ['.html', '.xml'] def...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" import peanut import jinja2 from os import path from jinja2 import FileSystemLoader from jinja2.exceptions import TemplateNotFound class SmartLoader(FileSystemLoader): """A smart template loader""" available_extension = ['.html', '.xml'] def...
Add an interface to update global context
Add an interface to update global context
Python
mit
zqqf16/Peanut,zqqf16/Peanut,zqqf16/Peanut
a5387c85a898717a5ae13dafe6f0f2b19f44e749
apps/vacancies/tasks.py
apps/vacancies/tasks.py
# coding: utf-8 import urllib from celery import shared_task from apps.vacancies.parsers import VacancySync, YandexRabotaParser @shared_task(ignore_result=True) def update_vacancies(): fulltime = { 'rid': 213, 'currency': 'RUR', 'text': 'python программист', 'strict': 'false', ...
# coding: utf-8 import urllib from celery import shared_task from apps.vacancies.parsers import VacancySync, YandexRabotaParser @shared_task(ignore_result=True) def update_vacancies(): fulltime = { 'rid': 213, 'currency': 'RUR', 'text': 'python программист', 'strict': 'false', ...
Disable contracts in jobs parser
Disable contracts in jobs parser
Python
bsd-3-clause
moscowdjango/moscowdjango,moscowdjango/moscowdjango,moscowdjango/moscowdjango,VladimirFilonov/moscowdjango,moscowpython/moscowpython,VladimirFilonov/moscowdjango,moscowpython/moscowpython,VladimirFilonov/moscowdjango,moscowpython/moscowpython
0281aaa0868d0bfa6ecb7368cff89b4af6b57129
tests/functions_tests/test_dropout.py
tests/functions_tests/test_dropout.py
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import testing if cuda.available: cuda.init() class TestDropout(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (2, 3)).astype(numpy.float32) def check_ty...
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import testing from chainer.testing import attr if cuda.available: cuda.init() class TestDropout(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (2, 3)).astype...
Add attr.gpu decorator to gpu test of dropout
Add attr.gpu decorator to gpu test of dropout
Python
mit
yanweifu/chainer,hvy/chainer,cupy/cupy,ysekky/chainer,woodshop/complex-chainer,niboshi/chainer,tkerola/chainer,kashif/chainer,kikusu/chainer,jnishi/chainer,okuta/chainer,niboshi/chainer,benob/chainer,chainer/chainer,AlpacaDB/chainer,sou81821/chainer,umitanuki/chainer,tscohen/chainer,cupy/cupy,laysakura/chainer,masia02/...
f9c1393b9773a5df993a98b877ce5178d44c8575
common.py
common.py
import os, os.path base_dir = os.getcwd() script_dir = os.path.realpath(os.path.dirname(__file__)) def get_crawl_dir(): return os.path.join(base_dir, "crawl") def revision_present(version, revision): return os.path.isdir(os.path.join(get_crawl_dir(), version, revision))
import os, os.path script_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = script_dir def get_crawl_dir(): return os.path.join(base_dir, "crawl") def revision_present(version, revision): return os.path.isdir(os.path.join(get_crawl_dir(), version, revision))
Use the script dir as base_dir for now.
Use the script dir as base_dir for now.
Python
mit
flodiebold/crawl-versions
9b4e803f68b33f193f0a41784e2f51672d69c4c2
benchmarks/numpy-bench.py
benchmarks/numpy-bench.py
# Copyright 2019 Google LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd import time import numpy as np import sys n = int(sys.argv[1]) x = np.random.randn(n,n) y = np.random.randn(n,n) t0 = time...
# Copyright 2019 Google LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd import time import numpy as np import sys from __future__ import print_function n = int(sys.argv[1]) x = np.random.randn(n,...
Make bechmark compatible with python3
Make bechmark compatible with python3
Python
bsd-3-clause
google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang
5ef45edb38ed5475351d484b89f0e99e5d50ea92
examples/test-archive.py
examples/test-archive.py
from __future__ import print_function import unittest import modfoo import saliweb.test import os class JobTests(saliweb.test.TestCase): """Check custom ModFoo Job class""" def test_archive(self): """Test the archive method""" # Make a ModFoo Job test job in ARCHIVED state j = self.mak...
from __future__ import print_function import unittest import modfoo import saliweb.test import os class JobTests(saliweb.test.TestCase): """Check custom ModFoo Job class""" def test_archive(self): """Test the archive method""" # Make a ModFoo Job test job in ARCHIVED state j = self.ma...
Use context manager in example
Use context manager in example
Python
lgpl-2.1
salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb
44cec721b7a0a20059c143124a889f8f7a1fe615
config.py
config.py
### # Copyright (c) 2012, spline # All rights reserved. # # ### import os import supybot.conf as conf import supybot.registry as registry from supybot.i18n import PluginInternationalization, internationalizeDocstring _ = PluginInternationalization('MLB') def configure(advanced): # This will be called by supybot...
### # Copyright (c) 2012-2013, spline # All rights reserved. # # ### import os import supybot.conf as conf import supybot.registry as registry from supybot.i18n import PluginInternationalization, internationalizeDocstring _ = PluginInternationalization('MLB') def configure(advanced): # This will be called by su...
Remove the dbLocation as we do this within plugin.py
Remove the dbLocation as we do this within plugin.py
Python
mit
reticulatingspline/MLB
bc05c56c60fa61f045079a4b3ef2dea185b213b4
fortuitus/fcore/tests.py
fortuitus/fcore/tests.py
from django.core.urlresolvers import reverse from django.test import TestCase from fortuitus.fcore.factories import UserF from fortuitus.fcore.models import FortuitusProfile class HomeViewTestCase(TestCase): def test_renders_template(self): """ Tests is home page is rendered properly. """ respons...
from django.core.urlresolvers import reverse from django.test import TestCase from fortuitus.fcore.factories import UserF from fortuitus.fcore.models import FortuitusProfile class HomeViewTestCase(TestCase): def test_renders_template(self): """ Tests is home page is rendered properly. """ respons...
Fix failing user profile test
Fix failing user profile test
Python
mit
elegion/djangodash2012,elegion/djangodash2012
2f44eb65e22672a894cced9c9de8d64f72d0fc39
pyosmo/algorithm/weighted.py
pyosmo/algorithm/weighted.py
from typing import List from pyosmo.algorithm.base import OsmoAlgorithm from pyosmo.history.history import OsmoHistory from pyosmo.model import TestStep class WeightedAlgorithm(OsmoAlgorithm): """ Weighted random algorithm """ def choose(self, history: OsmoHistory, choices: List[TestStep]) -> TestStep: ...
from typing import List from pyosmo.algorithm.base import OsmoAlgorithm from pyosmo.history.history import OsmoHistory from pyosmo.model import TestStep class WeightedAlgorithm(OsmoAlgorithm): """ Weighted random algorithm """ def choose(self, history: OsmoHistory, choices: List[TestStep]) -> TestStep: ...
Fix py3.9 check that total weight need to be more than zero
Fix py3.9 check that total weight need to be more than zero
Python
mit
OPpuolitaival/pyosmo,OPpuolitaival/pyosmo
b438e3858910eee4f24a5f33858fb039240750cd
get_data_from_twitter.py
get_data_from_twitter.py
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_...
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_...
Add support for pulling hash tags
Add support for pulling hash tags
Python
mpl-2.0
aDataAlchemist/election-tweets