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
b4f4226d153e993888f6e7429dcc9aca480e680e
owners_client.py
owners_client.py
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both...
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import owners class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a ...
Implement ListOwnersForFile for Depot Tools
[owners] Implement ListOwnersForFile for Depot Tools Add DepotToolsClient to implement the OwnersClient API for Depot Tools, and implement the ListOwnersForFile method. Change-Id: I933a262898439d879c919d695aa62d7702b4c9a4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2530509 Aut...
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
98988373899da3541f084e4c893628f028200d8c
PunchCard.py
PunchCard.py
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - ho...
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + ...
Fix type casts and incorrect numbers
Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.
Python
mit
NLSteveO/PunchCard,NLSteveO/PunchCard
70245be1a4fbb22d20459383136887f0a9cc2ad4
passwd_change.py
passwd_change.py
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.s...
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.s...
Add log file for deleted lines.
Add log file for deleted lines.
Python
mit
maxsocl/oldmailer
68a40f909294c5e2ad6c6bce9f6b7a970d133d21
conanfile.py
conanfile.py
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake...
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake...
Copy find modules to root of module path
conan: Copy find modules to root of module path
Python
mit
polysquare/iwyu-target-cmake,polysquare/include-what-you-use-target-cmake
52aeb0d37aa903c0189416bbafc2a75ea41f3201
slave/skia_slave_scripts/do_skps_capture.py
slave/skia_slave_scripts/do_skps_capture.py
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shel...
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shel...
Clean up any left over browser processes in the RecreateSKPs buildstep.
Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 R=borenet@google.com Review URL: https://codereview.chromium.org/140003003
Python
bsd-3-clause
google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Ti...
5adc4a0637b31de518b30bbc662c3d50bc523a5a
airtravel.py
airtravel.py
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (numb...
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (numb...
Add seating plan to aircraft
Add seating plan to aircraft
Python
mit
kentoj/python-fundamentals
36f59422fdf9d7dc76c31b096c3b7f909762109a
Lib/compiler/syntax.py
Lib/compiler/syntax.py
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ ...
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ ...
Stop looping to do nothing, just pass.
Stop looping to do nothing, just pass.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
6d6e83734d0cb034f8fc198df94bc64cf412d8d6
ceam/framework/components.py
ceam/framework/components.py
from importlib import import_module import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) ...
from importlib import import_module from collections import Iterable import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components config...
Add support for component initialization that returns lists
Add support for component initialization that returns lists
Python
bsd-3-clause
ihmeuw/vivarium
cf822ee4994915cf178c6e603e3cc8726cf7fb82
api/locations/views.py
api/locations/views.py
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requ...
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requ...
Send whole location object over websocket
Send whole location object over websocket
Python
mit
Proj-P/project-p-api,Proj-P/project-p-api
836fd354037a6aca6898b41a9d62ada31f1ee6ba
rasterio/tool.py
rasterio/tool.py
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in th...
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in th...
Print the banner in IPython
Print the banner in IPython
Python
bsd-3-clause
clembou/rasterio,brendan-ward/rasterio,kapadia/rasterio,clembou/rasterio,njwilson23/rasterio,perrygeo/rasterio,brendan-ward/rasterio,perrygeo/rasterio,youngpm/rasterio,johanvdw/rasterio,clembou/rasterio,kapadia/rasterio,njwilson23/rasterio,perrygeo/rasterio,youngpm/rasterio,brendan-ward/rasterio,njwilson23/rasterio,joh...
c4803aca65f05d30285c6b7cad0571cd4baa599b
generator/test/runner.py
generator/test/runner.py
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) ...
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) ...
Add a line that was removed by mistake
Add a line that was removed by mistake
Python
bsd-3-clause
smartdevicelink/sdl_android
5a6b19f956dfde65a1d8316fd4bebe4697846e45
connman_dispatcher/detect.py
connman_dispatcher/detect.py
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() ...
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() ...
Use .state instead of .is_online to keep internal state
Use .state instead of .is_online to keep internal state
Python
isc
a-sk/connman-dispatcher
cc92850fd6ebe5adc4064df1956377bb4f9aa30c
pyslicer/url_resources.py
pyslicer/url_resources.py
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATIO...
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATIO...
Correct endpoint for result and score
Correct endpoint for result and score
Python
mit
SlicingDice/slicingdice-python
7b9ba8634c0a02cb4c82313d9bef3197640c3187
pyqtgraph/graphicsItems/tests/test_PlotDataItem.py
pyqtgraph/graphicsItems/tests/test_PlotDataItem.py
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y ...
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y ...
Add test_setData() for PlotDataItem class
Add test_setData() for PlotDataItem class
Python
mit
campagnola/acq4,pbmanis/acq4,meganbkratz/acq4,acq4/acq4,meganbkratz/acq4,acq4/acq4,pbmanis/acq4,acq4/acq4,pbmanis/acq4,meganbkratz/acq4,acq4/acq4,meganbkratz/acq4,campagnola/acq4,campagnola/acq4,pbmanis/acq4,campagnola/acq4
5e7d73215d17aa52b6aae4dbb1d8e369d785b31d
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_fr...
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_fr...
Use list comprehensions to format all errors where message is not a dict
Use list comprehensions to format all errors where message is not a dict
Python
apache-2.0
SSJohns/osf.io,haoyuchen1992/osf.io,felliott/osf.io,danielneis/osf.io,icereval/osf.io,samchrisinger/osf.io,sloria/osf.io,ZobairAlijan/osf.io,mluke93/osf.io,alexschiller/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,doublebits/osf.io,njantrania/osf.io,kch8...
53aecfed27a01ea3ae44f87e9223260c735c82c6
apps/reviews/models.py
apps/reviews/models.py
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('s...
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('s...
Update reviews model for new added field in 5.5
Update reviews model for new added field in 5.5
Python
bsd-3-clause
Prashant-Surya/addons-server,andymckay/zamboni,elysium001/zamboni,eviljeff/zamboni,eviljeff/zamboni,lavish205/olympia,psiinon/addons-server,mozilla/olympia,andymckay/olympia,wagnerand/addons-server,tsl143/zamboni,kumar303/olympia,andymckay/addons-server,jbalogh/zamboni,wagnerand/zamboni,crdoconnor/olympia,Revanth47/add...
b30be4ee2a9e7c656e78fd34c9b59a1653bed1a2
argonauts/testutils.py
argonauts/testutils.py
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient,...
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient,...
Test requests don't have a charset attribute
Test requests don't have a charset attribute
Python
bsd-2-clause
fusionbox/django-argonauts
347681637c7c9d28ba1c787bb77da1296a02d13f
ckanext/archiver/default_settings.py
ckanext/archiver/default_settings.py
# path to ckan config file CKAN_CONFIG = '/home/okfn/pyenv/src/ckan/ckan.ini' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Use this user name when requesting data from ckan ARCHIVE_USER = u'okfn_maintenance' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LE...
# URL to the CKAN instance CKAN_URL = 'http://127.0.0.1:5000' # API key for the CKAN user that the archiver will authenticate as. # This user must be a system administrator API_KEY = '' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Max content-length of archived files, larger files will be i...
Change settings to use API key and CKAN URL
Change settings to use API key and CKAN URL
Python
mit
ckan/ckanext-archiver,ckan/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,ckan/ckanext-archiver,datagovuk/ckanext-archiver,datagovuk/ckanext-archiver,datagovuk/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver
8da134823a56567e09a09aefc44837a837644912
ddcz/urls.py
ddcz/urls.py
from django.urls import path from . import views app_name='ddcz' urlpatterns = [ path('', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail,...
from django.urls import path from django.views.generic.base import RedirectView from . import views app_name='ddcz' urlpatterns = [ path('', RedirectView.as_view(url='aktuality/', permanent=True)), path('aktuality/', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, ...
Put news on non-root path for clarity
Put news on non-root path for clarity
Python
mit
dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard
a103968558963c032db7294ed15560429861550d
django_filepicker/widgets.py
django_filepicker/widgets.py
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYP...
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dr...
Allow Filepicker JS version to be configured
Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.
Python
mit
filepicker/filepicker-django,filepicker/filepicker-django,FundedByMe/filepicker-django,FundedByMe/filepicker-django
7a3a1ffc6c153e4ea867988d12725f92d133ffc4
js2py/internals/seval.py
js2py/internals/seval.py
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def eval_js_vm(js): a = By...
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def get_js_bytecode(js): a ...
Add a function returning js bytecode.
Add a function returning js bytecode.
Python
mit
PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py
2ceb4f7195220d52ce92156da9332b50369fb746
bluesnap/exceptions.py
bluesnap/exceptions.py
class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
Return formatted messages in APIError
Return formatted messages in APIError
Python
mit
justyoyo/bluesnap-python,kowito/bluesnap-python,justyoyo/bluesnap-python,kowito/bluesnap-python
ee93f680c911f6879e12f7ce7ee3a6c1cfda8379
app/taskqueue/tasks/stats.py
app/taskqueue/tasks/stats.py
# 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 distributed in the hope that it will be usefu...
# 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 distributed in the hope that it will be usefu...
Add missing function doc string.
Add missing function doc string.
Python
lgpl-2.1
kernelci/kernelci-backend,kernelci/kernelci-backend
4be85164344defc9d348594a26c4dab147a8de4a
dvol/test_plugin.py
dvol/test_plugin.py
""" log of integration tests to write: write test_switch_branches_restarts_containers command: docker-compose up -d (in a directory with appropriate docker-compose.yml file) expected behaviour: docker containers are started with dvol accordingly XXX this doesn't seem to work at the moment command: do...
""" log of integration tests to write: write test_switch_branches_restarts_containers command: docker-compose up -d (in a directory with appropriate docker-compose.yml file) expected behaviour: docker containers are started with dvol accordingly command: docker run -ti --volume-driver dvol -v hello:/data...
Tidy up list of tests to write.
Tidy up list of tests to write.
Python
apache-2.0
ClusterHQ/dvol,ClusterHQ/dvol,ClusterHQ/dvol
a7311b1cd9a184af2a98130ba288157f62220da1
src/formatter.py
src/formatter.py
import json from collections import OrderedDict from .command import ShellCommand from .settings import FormatterSettings class Formatter(): def __init__(self, name, command=None, args=None, formatter=None): self.__name = name self.__format = formatter self.__settings = FormatterSettings(n...
import json from collections import OrderedDict from .command import ShellCommand from .settings import FormatterSettings class Formatter(): def __init__(self, name, command='', args='', formatter=None): self.__name = name self.__settings = FormatterSettings(name.lower()) if formatter: ...
Set default values for command and args
Set default values for command and args
Python
mit
Rypac/sublime-format
e8a0e7c3714445577851c5a84ecf7a036937725a
clang_corpus/__init__.py
clang_corpus/__init__.py
from os import listdir from os.path import abspath, isfile, join, splitext # C, C++, Obj-C, & Obj-C++ SOURCE_EXTENSIONS = ('.h', '.hh', '.hpp', '.c', '.cpp', '.cxx', '.m', '.mm') class SourceFile(object): """ A simple object which wraps a text file. """ def __init__(self, path): self._path = absp...
from os import listdir from os.path import abspath, isfile, join, split, splitext # C, C++, Obj-C, & Obj-C++ SOURCE_EXTENSIONS = ('.h', '.hh', '.hpp', '.c', '.cpp', '.cxx', '.m', '.mm') class SourceFile(object): """ A simple object which wraps a text file. """ def __init__(self, path): self._path...
Add an include_paths property to the SourceFile class.
Add an include_paths property to the SourceFile class.
Python
unlicense
jwiggins/clang-corpus,jwiggins/clang-corpus,jwiggins/clang-corpus
2402afe296191d3fddc98212564fb0158cfdcb51
upload_redirects.py
upload_redirects.py
import json from backend.app import app, db from backend.models import * from flask import url_for # read in json redirect dump with open('data/prod_url_alias.json', 'r') as f: redirects = json.loads(f.read()) print len(redirects) old_urls = [] error_count = 0 for i in range(len(redirects)): nid = None ...
import json from backend.app import app, db from backend.models import * from flask import url_for # read in json redirect dump with open('data/nid_url.json', 'r') as f: redirects = json.loads(f.read()) print len(redirects) old_urls = [] existing_redirects = Redirect.query.all() for redirect in existing_redirec...
Check for duplicates in existing dataset. Fix reference to dump file.
Check for duplicates in existing dataset. Fix reference to dump file.
Python
apache-2.0
Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2
1a761c9360f185d6bd07be9f16ea2cfa239f4bdd
groupy/api/base.py
groupy/api/base.py
from groupy import utils class Manager: """Class for interacting with the endpoint for a resource. :param session: the requests session :type session: :class:`~groupy.session.Session` :param str path: path relative to the base URL """ #: the base URL base_url = 'https://api.groupme.com/v...
from groupy import utils class Manager: """Class for interacting with the endpoint for a resource. :param session: the requests session :type session: :class:`~groupy.session.Session` :param str path: path relative to the base URL """ #: the base URL base_url = 'https://api.groupme.com/v...
Fix pickling/unpickling of Resource objects
Fix pickling/unpickling of Resource objects Add __getstate__ and __setstate__ methods to the Resource class to avoid hitting the recursion limit when trying to pickle/unpickle Resource objects. A similar issue/solution can be found here: https://stackoverflow.com/a/12102691
Python
apache-2.0
rhgrant10/Groupy
8626733d3a4960013189ffa90fe8e496dd8cc90a
calexicon/constants.py
calexicon/constants.py
from datetime import date as vanilla_date from dates.base import BasicBCEDate first_julian_date = BasicBCEDate(-45, 1, 1) first_vanilla_date = vanilla_date(1, 1, 1) last_vanilla_date = vanilla_date(9999, 12, 31) julian_day_number_of_first_vanilla_date = 1721423 julian_day_number_of_last_vanilla_date = ( julian_d...
from datetime import date as vanilla_date from dates.base import BasicBCEDate first_julian_date = BasicBCEDate(-45, 1, 1) first_vanilla_date = vanilla_date(1, 1, 1) last_vanilla_date = vanilla_date(9999, 12, 31) julian_day_number_of_first_vanilla_date = 1721423 julian_day_number_of_last_vanilla_date = ( julian_d...
Add another constant for the number of vanilla dates.
Add another constant for the number of vanilla dates.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
67717116a2585975e0e773956d6a102be9dc11d6
ggplot/geoms/geom_boxplot.py
ggplot/geoms/geom_boxplot.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cbook as cbook from .geom import geom from ggplot.utils import is_string from ggplot.utils import is_categorical class g...
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cbook as cbook from .geom import geom from ggplot.utils import is_string from ggplot.utils import is_categorical class g...
Fix y axis tick labels for boxplot
Fix y axis tick labels for boxplot
Python
bsd-2-clause
xguse/ggplot,benslice/ggplot,smblance/ggplot,Cophy08/ggplot,mizzao/ggplot,xguse/ggplot,ricket1978/ggplot,mizzao/ggplot,andnovar/ggplot,bitemyapp/ggplot,kmather73/ggplot,udacity/ggplot,ricket1978/ggplot,benslice/ggplot,wllmtrng/ggplot,assad2012/ggplot
468e2369a2b1af203d8a00abbfb3b01af26ae89a
bot/multithreading/worker.py
bot/multithreading/worker.py
import queue from bot.multithreading.work import Work class Worker: def run(self): raise NotImplementedError() def post(self, work: Work): raise NotImplementedError() def shutdown(self): raise NotImplementedError() class AbstractWorker(Worker): def __init__(self, name: str...
import queue from bot.multithreading.work import Work class Worker: def run(self): raise NotImplementedError() def post(self, work: Work): raise NotImplementedError() def shutdown(self): raise NotImplementedError() class AbstractWorker(Worker): def __init__(self, name: str...
Create a ImmediateWorker that executes the posted jobs on the same thread synchronously
Create a ImmediateWorker that executes the posted jobs on the same thread synchronously
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
423288b4cc8cf1506285913558b3fcff9e7788fa
gitlab/urls.py
gitlab/urls.py
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from gitlab import views urlpatterns = patterns('', url(r'^favicon\.ico$', RedirectView.as_view(url='/static/app/favicon.ico')), url(r'^push_event/hv$', views.push_event_hv), url(r'^push_event/web$', views.push_e...
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from gitlab import views urlpatterns = patterns('', url(r'^favicon\.ico$', RedirectView.as_view(url='/static/app/favicon.ico')), url(r'^push_event/hv$', views.push_event_hv), url(r'^push_event/web$', views.push_e...
Add URL for monitoring hook
Add URL for monitoring hook
Python
apache-2.0
ReanGD/web-work-fitnesse,ReanGD/web-work-fitnesse,ReanGD/web-work-fitnesse
2f9be950c372beb2f555cbe84a22366e0b95e721
hellopy/bot.py
hellopy/bot.py
from wit import Wit from . import text_to_speech as tts from . import config WIT_AI_KEY = config.WIT_AI_KEY session_id = config.USER def say(session_id, context, msg): tts.talk(msg) def error(session_id, context, e): # tts.talk("Algo salió mal.") print(str(e)) def merge(session_id, context, entities...
from wit import Wit import shutil import subprocess import time from . import text_to_speech as tts from . import config WIT_AI_KEY = config.WIT_AI_KEY session_id = config.USER def say(session_id, context, msg): print("HelloPy: " + msg) tts.talk(msg) def error(session_id, context, e): # tts.talk("Algo...
Add functions: mute & open
Add functions: mute & open
Python
mit
stsewd/hellopy
f6bf104cbdcdb909a15c80dafe9ae2e7aebbc2f0
examples/snowball_stemmer_example.py
examples/snowball_stemmer_example.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Szeretnék kérni tőled egy óriási szívességet az édesanyám számára." tokenized_sentence = word_tokenize(test_se...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Péter szereti Enikőt és Marit" tokenized_sentence = word_tokenize(test_sentence) print('With SnowballStemmer...
Add more information to SnowballStemmer
Add more information to SnowballStemmer
Python
apache-2.0
davidpgero/hungarian-nltk
3e1b2b5e87f2d0ed8ecb06b07805723101c23636
km3pipe/tests/test_config.py
km3pipe/tests/test_config.py
# coding=utf-8 # Filename: test_config.py """ Test suite for configuration related functions and classes. """ from __future__ import division, absolute_import, print_function from km3pipe.testing import TestCase, BytesIO from km3pipe.config import Config CONFIGURATION = BytesIO("\n".join(( "[DB]", "username...
# coding=utf-8 # Filename: test_config.py """ Test suite for configuration related functions and classes. """ from __future__ import division, absolute_import, print_function from km3pipe.testing import TestCase, StringIO from km3pipe.config import Config CONFIGURATION = StringIO("\n".join(( "[DB]", "userna...
Switch to StringIO for fake config data
Switch to StringIO for fake config data
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
2a8dd80c9769731963fcd75cb24cd8918e48b269
mythril/analysis/security.py
mythril/analysis/security.py
from mythril.analysis.report import Report from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas def fire_lasers(statespace): issues = [] issues += delegatecall_forward.execute(statespace) issues += delegat...
from mythril.analysis.report import Report from mythril.analysis import modules import pkgutil def fire_lasers(statespace): issues = [] _modules = [] for loader, name, is_pkg in pkgutil.walk_packages(modules.__path__): _modules.append(loader.find_module(name).load_module(name)) for modu...
Implement a nicer way of execution modules
Implement a nicer way of execution modules
Python
mit
b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril
dbb27799a92e58cf03a9b60c17e0f3116fbcf687
modish/__init__.py
modish/__init__.py
# -*- coding: utf-8 -*- from .model import ModalityModel from .estimator import ModalityEstimator from .visualize import MODALITY_TO_COLOR, MODALITY_ORDER, MODALITY_PALETTE,\ MODALITY_TO_CMAP, ModalitiesViz, violinplot __author__ = 'Olga Botvinnik' __email__ = 'olga.botvinnik@gmail.com' __version__ = '0.1.0' __a...
# -*- coding: utf-8 -*- from .model import ModalityModel from .estimator import ModalityEstimator from .visualize import MODALITY_TO_COLOR, MODALITY_ORDER, MODALITY_PALETTE,\ MODALITY_TO_CMAP, ModalitiesViz, violinplot, barplot __author__ = 'Olga Botvinnik' __email__ = 'olga.botvinnik@gmail.com' __version__ = '0.1...
Add object for saving modish test results
Add object for saving modish test results
Python
bsd-3-clause
olgabot/anchor,olgabot/modish,YeoLab/anchor
ab4333ad10713b0df25e0ff9bb46da3a0749326f
analyser/tasks.py
analyser/tasks.py
import os import time import requests from krunchr.vendors.celery import celery @celery.task def get_file(url, path): name, ext = os.path.splitext(url) name = str(int(time.time())) path = "%s/%s%s" % (path, name, ext) response = requests.get(url) print path with open(path, 'w') as f: f.write(respo...
import os import time import rethinkdb as r import requests from krunchr.vendors.celery import celery, db @celery.task(bind=True) def get_file(self, url, path): name, ext = os.path.splitext(url) name = str(int(time.time())) path = "%s/%s%s" % (path, name, ext) response = requests.get(url) with open(path...
Update job state when we finish the task
Update job state when we finish the task
Python
apache-2.0
vtemian/kruncher
28c26bf5d220a5a60b807470bbaf339bdf9206a9
pylearn2/testing/skip.py
pylearn2/testing/skip.py
""" Helper functions for determining which tests to skip. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" from nose.plugins.skip import SkipT...
""" Helper functions for determining which tests to skip. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" from nose.plugins.skip import SkipT...
Add SkipTest for when matplotlib and/or pyplot are not present
Add SkipTest for when matplotlib and/or pyplot are not present
Python
bsd-3-clause
CIFASIS/pylearn2,lisa-lab/pylearn2,msingh172/pylearn2,w1kke/pylearn2,lamblin/pylearn2,bartvm/pylearn2,sandeepkbhat/pylearn2,cosmoharrigan/pylearn2,jeremyfix/pylearn2,mkraemer67/pylearn2,jamessergeant/pylearn2,junbochen/pylearn2,TNick/pylearn2,hantek/pylearn2,nouiz/pylearn2,aalmah/pylearn2,skearnes/pylearn2,kose-y/pylea...
1212d33d849155f8c1cdc6a610e893318937e7c5
silk/webdoc/html/v5.py
silk/webdoc/html/v5.py
"""Module containing only html v5 tags. All deprecated tags have been removed. """ from .common import * del ACRONYM del APPLET del BASEFONT del BIG del CENTER del DIR del FONT del FRAME del FRAMESET del NOFRAMES del STRIKE del TT del U
""" Module containing only html v5 tags. All deprecated tags have been removed. """ from .common import ( # flake8: noqa A, ABBR, # ACRONYM, ADDRESS, # APPLET, AREA, B, BASE, # BASEFONT, BDO, # BIG, BLOCKQUOTE, BODY, BR, BUTTON, Body, CAPTION, C...
Replace import * with explicit names
Replace import * with explicit names
Python
bsd-3-clause
orbnauticus/silk
0c8835bb4ab1715ee0de948d9b15a813752b60b5
dthm4kaiako/gunicorn.conf.py
dthm4kaiako/gunicorn.conf.py
"""Configuration file for gunicorn.""" # Details from https://cloud.google.com/appengine/docs/flexible/python/runtime worker_class = "gevent" forwarded_allow_ips = "*" secure_scheme_headers = {"X-APPENGINE-HTTPS": "on"}
"""Configuration file for gunicorn.""" from multiprocessing import cpu_count # Worker count from http://docs.gunicorn.org/en/stable/design.html#how-many-workers workers = cpu_count() * 2 + 1 # Details from https://cloud.google.com/appengine/docs/flexible/python/runtime worker_class = "gevent" forwarded_allow_ips = "*...
Increase number of server workers
Increase number of server workers
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
40e9375f6b35b4a05ad311822705b7a7efe46b56
site_scons/get_libs.py
site_scons/get_libs.py
import os import sys from SCons.Script import File from path_helpers import path def get_lib_paths(): if sys.platform == 'win32': lib_paths = set(os.environ['PATH'].split(';')) else: lib_paths = set() if os.environ.has_key('LIBRARY_PATH'): lib_paths.update(os.environ['LIB...
import os import sys from SCons.Script import File from path_helpers import path def get_lib_paths(): if sys.platform == 'win32': lib_paths = set(os.environ['PATH'].split(';')) else: lib_paths = set() if os.environ.has_key('LIBRARY_PATH'): lib_paths.update(os.environ['LIB...
Add Linux 32-bit search path for Boost libraries
Add Linux 32-bit search path for Boost libraries
Python
bsd-3-clause
wheeler-microfluidics/dmf-control-board-firmware,wheeler-microfluidics/dmf-control-board-firmware,wheeler-microfluidics/dmf-control-board-firmware,wheeler-microfluidics/dmf-control-board-firmware
90d8411412b79513338b014da63b18d0d29396d9
snmpy/log_processor.py
snmpy/log_processor.py
import re, snmpy_plugins class log_processor: def __init__(self, conf): self.data = [{'value':0, 'label': conf['objects'][item]['label'], 'regex': re.compile(conf['objects'][item]['regex'])} for item in sorted(conf['objects'])] self.proc(conf['logfile']) def len(self): return len(self....
import re import snmpy class log_processor(snmpy.plugin): def __init__(self, conf, script=False): snmpy.plugin.__init__(self, conf, script) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] def w...
Convert to use the base class and update for new plugin path.
Convert to use the base class and update for new plugin path.
Python
mit
mk23/snmpy,mk23/snmpy
34330aec6cf0c038d47c43ef926fa615bd568ea3
sqlservice/__init__.py
sqlservice/__init__.py
# -*- coding: utf-8 -*- """The sqlservice package. """ from .__pkg__ import ( __description__, __url__, __version__, __author__, __email__, __license__ ) from .client import SQLClient from .model import ModelBase, declarative_base from .query import Query from .service import SQLService
# -*- coding: utf-8 -*- """The sqlservice package. """ from .__pkg__ import ( __description__, __url__, __version__, __author__, __email__, __license__ ) from .client import SQLClient from .model import ModelBase, declarative_base from .service import SQLService from . import event
Remove Query from import and add explicit event module import.
Remove Query from import and add explicit event module import.
Python
mit
dgilland/sqlservice
b61ded5a1f59eca7838219d9e904941bd04aa064
lib/euedb.py
lib/euedb.py
#!/usr/bin/python # -*- coding: <encoding name> -*- import os import sys import time import re import MySQLdb from MySQLdb import cursors class mysql: cn = None host = None port = None user = None passw = None def __init__(self, host, user, passw, db, port=3306): self.port = port ...
#!/usr/bin/python # -*- coding: <encoding name> -*- import os import sys import time import re import MySQLdb from MySQLdb import cursors class mysql: cn = None host = None port = None user = None passw = None connected = False def __init__(self, host, user, passw, db, port=3306): ...
Add better connection management ...
Add better connection management ...
Python
agpl-3.0
david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng
9c24dfc6a6207c9688332a16ee1600b73aec44d8
narcis/urls.py
narcis/urls.py
from django.conf.urls import patterns, include, url from django.views.generic.base import RedirectView from django.conf import settings from django.contrib import admin admin.autodiscover() from . import views from projects.views import screenshot urlpatterns = patterns('', # Examples: # url(r'^blog/', inclu...
from django.conf.urls import patterns, include, url from django.views.generic.base import RedirectView from django.conf import settings from django.contrib import admin admin.autodiscover() from . import views from projects.views import screenshot urlpatterns = patterns('', # Examples: # url(r'^blog/', inclu...
Add URL for django admin access to screenshots
Add URL for django admin access to screenshots
Python
mit
deckar01/narcis,deckar01/narcis,deckar01/narcis
94c0c60172c1114d6f0938de88af67ae7203ae95
pi_setup/system.py
pi_setup/system.py
#!/usr/bin/env python import subprocess def main(): subprocess.call(["apt-get", "update"]) subprocess.call(["apt-get", "-y", "upgrade"]) subprocess.call(["apt-get", "-y", "install", "python-dev"]) subprocess.call(["apt-get", "-y", "install", "python-pip"]) subprocess.call(["apt-get", "-y", "instal...
#!/usr/bin/env python import subprocess def main(): subprocess.call(["apt-get", "update"]) subprocess.call(["apt-get", "-y", "upgrade"]) subprocess.call(["apt-get", "-y", "install", "python-dev"]) subprocess.call(["apt-get", "-y", "install", "python-pip"]) subprocess.call(["apt-get", "-y", "instal...
Add python to install script
Add python to install script
Python
mit
projectweekend/Pi-Setup,projectweekend/Pi-Setup
9d3750881eaa215f6d06087e6d0f7b6d223c3cd1
feincms3/plugins/richtext.py
feincms3/plugins/richtext.py
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.html import strip_tags from django.utils.text import Truncator from django.utils.translation import ugettext_lazy as _ from content_editor.admin import ContentEditorInli...
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.html import strip_tags from django.utils.text import Truncator from django.utils.translation import ugettext_lazy as _ from content_editor.admin import ContentEditorInli...
Document the rich text plugin
Document the rich text plugin
Python
bsd-3-clause
matthiask/feincms3,matthiask/feincms3,matthiask/feincms3
c6d589859d621ac0eb2b4843a22cfe8e011bbeaf
braid/postgres.py
braid/postgres.py
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query): with hide('running', 'output'): return sudo('psql --no-align --no-readline --no-password --quiet ' ...
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query, database=None): with hide('running', 'output'): database = '--dbname={}'.format(database) if database else '' ...
Allow to specify a database when running a query
Allow to specify a database when running a query
Python
mit
alex/braid,alex/braid
e2f2541d909861e140030d50cc1981697118bf2e
webvtt/parser.py
webvtt/parser.py
from .exceptions import MalformedFileError class WebVTTParser: def _parse(self, content): self.content = content def read(self, file): with open(file, encoding='utf-8') as f: self._parse(f.readlines()) if not self.is_valid(): raise MalformedFileError ...
from .exceptions import MalformedFileError class WebVTTParser: def _parse(self, content): self.content = content def read(self, file): with open(file, encoding='utf-8') as f: self._parse(f.readlines()) if not self.is_valid(): raise MalformedFileError('The file...
Add message to malformed exception
Add message to malformed exception
Python
mit
glut23/webvtt-py,sampattuzzi/webvtt-py
92c70c5f54b6822f0f3815b66852a2771ef5d49c
scheduling/student_invite.py
scheduling/student_invite.py
from aiohttp.web import Application from db_helper import get_most_recent_group from mail import send_user_email from permissions import get_users_with_permission async def student_invite(app: Application) -> None: print("Inviting students") session = app["session"] group = get_most_recent_group(session)...
from aiohttp.web import Application from db_helper import get_most_recent_group from mail import send_user_email from permissions import get_users_with_permission async def student_invite(app: Application) -> None: print("Inviting students") session = app["session"] group = get_most_recent_group(session)...
Set group as read only when inviting students
Set group as read only when inviting students
Python
agpl-3.0
wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp
027ae8b8029d01622e3a9647f3ec6b1fca4c4d9d
chainerrl/wrappers/__init__.py
chainerrl/wrappers/__init__.py
from chainerrl.wrappers.cast_observation import CastObservation # NOQA from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.scale_reward import ScaleReward # NOQA
from chainerrl.wrappers.cast_observation import CastObservation # NOQA from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.render import Render # NOQA from chainerrl.wrappers.scale_reward im...
Make Render available under chainerrl.wrappers
Make Render available under chainerrl.wrappers
Python
mit
toslunar/chainerrl,toslunar/chainerrl
79aa9edde1bba39a433475929970dd519fecfdf3
requests/_oauth.py
requests/_oauth.py
# -*- coding: utf-8 -*- """ requests._oauth ~~~~~~~~~~~~~~~ This module comtains the path hack neccesary for oauthlib to be vendored into requests while allowing upstream changes. """ import os import sys try: from oauthlib.oauth1 import rfc5849 from oauthlib.common import extract_params from oauthlib.o...
# -*- coding: utf-8 -*- """ requests._oauth ~~~~~~~~~~~~~~~ This module comtains the path hack neccesary for oauthlib to be vendored into requests while allowing upstream changes. """ import os import sys try: from oauthlib.oauth1 import rfc5849 from oauthlib.common import extract_params from oauthlib.o...
Make OAuth path hack platform independent.
Make OAuth path hack platform independent.
Python
isc
Bluehorn/requests,revolunet/requests,psf/requests,revolunet/requests
429d840a34c4ec2e3b475e412b53e99ffe2a5677
studygroups/tasks.py
studygroups/tasks.py
from django.utils import timezone from django.conf import settings from studygroups.models import StudyGroup from studygroups.models import Reminder from studygroups.models import generate_reminder from studygroups.models import send_reminder from django.utils import translation import datetime def send_reminders():...
from django.utils import timezone from django.conf import settings from studygroups.models import StudyGroup from studygroups.models import Reminder from studygroups.models import generate_reminder from studygroups.models import send_reminder from django.utils import translation import datetime def send_reminders():...
Fix task and set language code when sending reminders
Fix task and set language code when sending reminders
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
fa19a6ec882727bb96f27993d7ac765797c19556
logger/utilities.py
logger/utilities.py
#!/usr/bin/env python3 """Small utility functions for use in various places.""" __all__ = ["pick", "is_dunder"] def pick(arg, default): """Handler for default versus given argument.""" return default if arg is None else arg def is_dunder(name): """Return True if a __dunder__ name, False otherwise.""" ...
#!/usr/bin/env python3 """Small utility functions for use in various places.""" __all__ = ["pick", "is_dunder", "find_name"] import sys def pick(arg, default): """Handler for default versus given argument.""" return default if arg is None else arg def is_dunder(name): """Return True if a __dunder__ nam...
Add a find_name utility function
Add a find_name utility function
Python
bsd-2-clause
Vgr255/logging
9eb07a5b7d2875cf79bb698864d11ef29576133e
comics/utils/hash.py
comics/utils/hash.py
import hashlib def sha256sum(filename): """Returns sha256sum for file""" f = file(filename, 'rb') m = hashlib.sha256() while True: b = f.read(8096) if not b: break m.update(b) f.close() return m.hexdigest()
import hashlib def sha256sum(filename=None, filehandle=None): """Returns sha256sum for file""" if filename is not None: f = file(filename, 'rb') else: f = filehandle m = hashlib.sha256() while True: b = f.read(8096) if not b: break m.update(b) ...
Make sha256sum work with open filehandles too
Make sha256sum work with open filehandles too
Python
agpl-3.0
datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics
e99976cbee1e43e7112b4759cf5a1a17a1be8170
utils/gyb_syntax_support/protocolsMap.py
utils/gyb_syntax_support/protocolsMap.py
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { 'DeclBuildable': [ 'CodeBlockItem', 'MemberDeclListItem', 'SyntaxBuildable' ], 'ExprList': [ 'ConditionElement', 'SyntaxBuildable' ], 'IdentifierPattern': [ 'PatternBuildable' ], 'SimpleTypeIdent...
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { 'DeclBuildable': [ 'CodeBlockItem', 'MemberDeclListItem', 'SyntaxBuildable' ], 'ExprList': [ 'ConditionElement', 'SyntaxBuildable' ], 'IdentifierPattern': [ 'PatternBuildable' ], 'MemberDeclList'...
Add convenience initializers for `MemberDeclList`
Add convenience initializers for `MemberDeclList`
Python
apache-2.0
glessard/swift,atrick/swift,apple/swift,benlangmuir/swift,rudkx/swift,glessard/swift,atrick/swift,rudkx/swift,gregomni/swift,glessard/swift,apple/swift,atrick/swift,glessard/swift,JGiola/swift,atrick/swift,ahoppen/swift,gregomni/swift,JGiola/swift,glessard/swift,ahoppen/swift,ahoppen/swift,JGiola/swift,rudkx/swift,atri...
46b00107e90df8f34a9cce5c4b010fdfb88f5f52
shovel/code.py
shovel/code.py
# coding: utf-8 from __future__ import absolute_import, division, print_function from pathlib import Path from isort import SortImports from shovel import task # isort multi_line_output modes GRID = 0 VERTICAL = 1 HANGING_INDENT = 2 VERTICAL_HANGING_INDENT = 3 HANGING_GRID = 4 HANGING_GRID_GROUPED = 5 @task def fo...
# coding: utf-8 from __future__ import absolute_import, division, print_function from pathlib import Path from isort import SortImports from shovel import task # isort multi_line_output modes GRID = 0 VERTICAL = 1 HANGING_INDENT = 2 VERTICAL_HANGING_INDENT = 3 HANGING_GRID = 4 HANGING_GRID_GROUPED = 5 @task def fo...
Add 'six' to known_third_party for SortImports
Add 'six' to known_third_party for SortImports six was being sorted incorrectly due to being classed as first party.
Python
mit
python-astrodynamics/astrodynamics,python-astrodynamics/astrodynamics
9b12a9cdab0021fea7e5f2d8fd8ffe11d065f0d0
tests/test_replay.py
tests/test_replay.py
# -*- coding: utf-8 -*- """ test_replay ----------- """ def test_get_user_config(): config_dict = get_user_config() assert 'replay_dir' in config_dict expected_dir = os.path.expanduser('~/.cookiecutter_replay/') assert config_dict['replay_dir'] == expected_dir
# -*- coding: utf-8 -*- """ test_replay ----------- """ import os import pytest from cookiecutter import replay from cookiecutter.config import get_user_config def test_get_user_config(): config_dict = get_user_config() assert 'replay_dir' in config_dict expected_dir = os.path.expanduser('~/.cookiecu...
Implement tests for replay.dump args
Implement tests for replay.dump args
Python
bsd-3-clause
agconti/cookiecutter,luzfcb/cookiecutter,christabor/cookiecutter,terryjbates/cookiecutter,benthomasson/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,benthomasson/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,takeflight/cookiecut...
6b025a122e0b6ac4761f5e821b0f5465f867fe61
crypto-square/crypto_square.py
crypto-square/crypto_square.py
import math def encode(s): s = list(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) s += "." * (size**2 - len(s)) parts = [s[i*size:(i+1)*size] for i in range(size)] return " ".join(map("".join, zip(*parts))).replace(".", "")
import math def encode(s): s = "".join(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) return " ".join(s[i::size] for i in range(size))
Use string slices with a stride
Use string slices with a stride
Python
agpl-3.0
CubicComet/exercism-python-solutions
dfbdf5d55a2c8d243b09828ef05c7c3c3ffc8d50
dags/longitudinal.py
dags/longitudinal.py
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator default_args = { 'owner': 'rvitillo@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 30), 'email': ['telemetry-alerts@mozilla.com', 'rvitillo@mozilla.com'], ...
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator default_args = { 'owner': 'rvitillo@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 30), 'email': ['telemetry-alerts@mozilla.com', 'rvitillo@mozilla.com'], ...
Add update orphaning job to Airflow
Add update orphaning job to Airflow This depends on the longitudinal job running successfully to run.
Python
mpl-2.0
opentrials/opentrials-airflow,opentrials/opentrials-airflow
0c6bf8eca2d4cfd08cc98df3cb0ab706a6fbf7a2
cxfreeze-setup.py
cxfreeze-setup.py
import sys from glob import glob from cx_Freeze import setup, Executable from version import VERSION # Dependencies are automatically detected, but it might need # fine tuning. excludes = ["Tkinter"] includes = ["logview", "colorwidget"] includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"), ...
import sys from glob import glob from cx_Freeze import setup, Executable from version import VERSION # Dependencies are automatically detected, but it might need # fine tuning. excludes = ["Tkinter"] includes = ["logview", "colorwidget", "pickle"] includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"), ...
Fix a TypeError when load mergeTool setting
Fix a TypeError when load mergeTool setting cx-freeze isn't include pickle module on the Windows platform, it cause "TypeError: unable to convert a C++ 'QVariantList' instance to a Python object"
Python
apache-2.0
timxx/gitc,timxx/gitc
64303ae1a02b707ff11231a9e3c46405a8a591e7
host/cgi-bin/liberator.py
host/cgi-bin/liberator.py
#!/usr/bin/env python import cgi, subprocess, json arguments = cgi.FieldStorage() body = arguments.getvalue('body', '') messageTo = arguments.getvalue('messageTo', '') exitCode = subprocess.call(['./SendImessage.applescript', messageTo, body]) print 'Content-Type: application/json' print '' print json.dumps({'ok': ...
#!/usr/bin/env python from os.path import expanduser from time import sleep import subprocess, json, sys, os messagesDbPath = '%s/Library/Messages/chat.db' % expanduser('~') # manually parse the QUERY_STRING because "+" is being weirdly decoded via FieldStorage queryParameters = {} keyValues = os.environ['QUERY_STRI...
Verify message sent via SQL
Verify message sent via SQL
Python
mit
chainsawsalad/imessage-liberator,chainsawsalad/imessage-liberator,chainsawsalad/imessage-liberator
3f3818e4a21ffc4e1b8d4426093fc093396b5a5b
pandas_finance.py
pandas_finance.py
#!/usr/bin/env python import datetime import scraperwiki import numpy import pandas.io.data as web def get_stock(stock, start, end, service): """ Return data frame of finance data for stock. Takes start and end datetimes, and service name of 'google' or 'yahoo'. """ return web.DataReader(stock, ...
#!/usr/bin/env python import datetime import sqlite3 import pandas.io.data as web import pandas.io.sql as sql def get_stock(stock, start, end): """ Return data frame of Yahoo Finance data for stock. Takes start and end datetimes. """ return web.DataReader(stock, 'yahoo', start, end) def scrape_s...
Use pandas native saving by forcing date to not be index, and be string
Use pandas native saving by forcing date to not be index, and be string
Python
agpl-3.0
scraperwiki/stock-tool,scraperwiki/stock-tool
3919d64370825d8931672011af4b99355e52ef63
motobot/core_plugins/help.py
motobot/core_plugins/help.py
from motobot import IRCBot, command, Notice def get_command_help(bot, command, modifier): responses = [] func = lambda x: x.type == IRCBot.command_plugin and x.arg.lower() == command.lower() for plugin in filter(func, bot.plugins): func = plugin.func if func.__doc__ is not None: ...
from motobot import IRCBot, command, Notice def get_command_help(bot, command): responses = [] func = lambda x: x.type == IRCBot.command_plugin and x.arg.lower() == command.lower() for plugin in filter(func, bot.plugins): func = plugin.func if func.__doc__ is not None: respon...
Update to new response handling
Update to new response handling
Python
mit
Motoko11/MotoBot
0eb5966ec3261e6c6101b4c9874321a105fb4426
dj-resume/urls.py
dj-resume/urls.py
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', (r'apply/', 'resume.views.cs_apply_handler'), (r'cs/', 'resume.views.index_handler'), (r'cap/.*', 'belaylibs.dj_be...
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', (r'cs/', 'resume.views.cs_index_handler'), (r'cap/.*', 'belaylibs.dj_belay.proxyHandler'), (r'applicant/', 'resume...
Make /cs/ point to the correct handler, no more apply handlre
Make /cs/ point to the correct handler, no more apply handlre
Python
apache-2.0
brownplt/k3,brownplt/k3,brownplt/k3
9be2846e408699308798b698754634ce7f370710
openedx/stanford/cms/urls.py
openedx/stanford/cms/urls.py
from django.conf import settings from django.conf.urls import url import contentstore.views urlpatterns = [ url( r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN), contentstore.views.send_test_enrollment_email, name='send_test_enrollment_email', ), ur...
from django.conf import settings from django.conf.urls import url import contentstore.views urlpatterns = [ url( r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN), contentstore.views.send_test_enrollment_email, name='send_test_enrollment_email', ), ur...
Add names to stanford view handlers
Add names to stanford view handlers
Python
agpl-3.0
Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform
d74b524cec824e77adbcf9cc23e28a6efba02985
takePicture.py
takePicture.py
import picamera as p import os import time os.chdir('/home/pi/Desktop') cam = p.PiCamera() cam.resolution = (320,240) cam.hflip = True cam.vflip = True x = 0 while x < 15: img = cam.capture('gregTest.jpg') time.sleep(.25) x +=1 exit()
import picamera as p import os import time os.chdir('/home/pi/Desktop') cam = p.PiCamera() cam.resolution = (320,240) cam.hflip = True cam.vflip = True x = 0 while x < 50: img = cam.capture('tempGregTest.jpg') os.unlink('gregTest.jpg') os.rename('tempGregTest.jpg','gregTest.jpg') time.sleep(.25) x +=1 exit()
Add temp pic file sequence to takepicture file
Add temp pic file sequence to takepicture file
Python
mit
jwarshaw/RaspberryDrive
0c5abad8259cccfd1ce50b27a124089d9ea946dd
copr_build.py
copr_build.py
#!/usr/bin/env python3 import json, os, sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] r = requests.get("%s/projects/%s/chroots" % (api_url, os.environ["copr_projectid"])).json() chroots = [] for i in r.get("chroots"): ...
#!/usr/bin/env python3 import os import sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] project_id = int(os.environ["copr_projectid"]) r = requests.get("%s/projects/%s/chroots" % (api_url, project_id)) if not r.ok: pr...
Fix copr build trigger script
Fix copr build trigger script
Python
mit
kyl191/nginx-pagespeed,kyl191/nginx-pagespeed,kyl191/nginx-pagespeed
9f1964f9f83c493f9bc6e08e2058d1e14ace031f
synapse/tests/test_cells.py
synapse/tests/test_cells.py
import synapse.axon as s_axon import synapse.cells as s_cells import synapse.cryotank as s_cryotank from synapse.tests.common import * class CellTest(SynTest): def test_getcells(self): data = s_cells.getCells() data = {k: v for k, v in data} self.isin('cortex', data)
import synapse.axon as s_axon import synapse.cells as s_cells import synapse.cryotank as s_cryotank from synapse.tests.common import * class CellTest(SynTest): def test_getcells(self): data = s_cells.getCells() data = {k: v for k, v in data} self.isin('cortex', data) def test_deploy(s...
Add a test for s_cells.deploy()
Add a test for s_cells.deploy()
Python
apache-2.0
vertexproject/synapse,vertexproject/synapse,vertexproject/synapse
e08b4f1b74f0fcd987299d4786b5374fe86a21bc
Lib/idlelib/macosxSupport.py
Lib/idlelib/macosxSupport.py
""" A number of function that enhance IDLE on MacOSX when it used as a normal GUI application (as opposed to an X11 application). """ import sys def runningAsOSXApp(): """ Returns True iff running from the IDLE.app bundle on OSX """ return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0]) def...
""" A number of function that enhance IDLE on MacOSX when it used as a normal GUI application (as opposed to an X11 application). """ import sys def runningAsOSXApp(): """ Returns True iff running from the IDLE.app bundle on OSX """ return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0]) def addOpenEv...
Add missing svn:eol-style property to text files.
Add missing svn:eol-style property to text files.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
a753841d01eb3e9493e08e20e8a28c9b08fdef53
comics/sets/models.py
comics/sets/models.py
from django.db import models from django.utils import timezone from comics.core.models import Comic class Set(models.Model): name = models.SlugField(max_length=100, unique=True, help_text='The set identifier') add_new_comics = models.BooleanField(default=False, help_text='Automatically add ne...
from django.db import models from django.utils import timezone from comics.core.models import Comic class Set(models.Model): name = models.SlugField( max_length=100, unique=True, help_text='The set identifier') add_new_comics = models.BooleanField( default=False, help_text='Au...
Fix all warnings in sets app
flake8: Fix all warnings in sets app
Python
agpl-3.0
datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics
4410e03df12b99c46467b6fe93f7b8cb206d441c
decorators.py
decorators.py
import time def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :p...
import time from functools import wraps def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonD...
Remove unreachable code. Use functools.wraps.
Remove unreachable code. Use functools.wraps. - Remove code that was unreachable. Thanks Jaskirat (http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/#c24691) - Use functools.wraps to make the retry decorator "well behaved" - Fix typo
Python
bsd-3-clause
saltycrane/retry-decorator
ebd024b4f8ee6e490c183da0bada28a2aaf328d8
comrade/users/urls.py
comrade/users/urls.py
from django.conf.urls.defaults import * from django.core.urlresolvers import reverse from django.utils.functional import lazy reverse_lazy = lazy(reverse, unicode) urlpatterns = patterns('django.contrib.auth.views', url(r'^login/', 'login', name='login'), url(r'^logout/', 'logout', {'next_page':'/'}, name='lo...
from django.conf.urls.defaults import * from django.core.urlresolvers import reverse from django.utils.functional import lazy reverse_lazy = lazy(reverse, unicode) urlpatterns = patterns('django.contrib.auth.views', url(r'^login/', 'login', name='login'), url(r'^logout/', 'logout', {'next_page':'/'}, name='lo...
Rename url namespace users -> account.
Rename url namespace users -> account.
Python
mit
bueda/django-comrade
b471da17f2e7b13d30746481e5db13f4d88de4d6
django/contrib/admin/__init__.py
django/contrib/admin/__init__.py
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. T...
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInli...
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. --HG-- extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%4014359
Python
bsd-3-clause
adieu/django-nonrel,adieu/django-nonrel,adieu/django-nonrel
2d5710dfc8361bb4c383e8fe8a2e2ca267c11875
luhn/luhn.py
luhn/luhn.py
# File: luhn.py # Purpose: Write a program that can take a number and determine whether # or not it is valid per the Luhn formula. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 09:55 PM class Luhn(object): def __init__(self, card_number): ...
# File: luhn.py # Purpose: Write a program that can take a number and determine whether # or not it is valid per the Luhn formula. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 09:55 PM class Luhn(object): def __init__(self, card_number): ...
Convert card number to string for iteration
Convert card number to string for iteration
Python
mit
amalshehu/exercism-python
88d93f580ce2f587ac5fa1b41e7ab3f67a9c6be4
avalonstar/apps/live/urls.py
avalonstar/apps/live/urls.py
# -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import patterns, include, url from .views import AwayView, BumperView, GameView, PrologueView urlpatterns = patterns('', url(r'^away/$', name='live-away', view=AwayView.as_view()), url(r'^bumper/$', name='live-bumper', view=Bumper...
# -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import patterns, include, url from .views import (AwayView, BumperView, DiscussionView, GameView, PrologueView) urlpatterns = patterns('', url(r'^away/$', name='live-away', view=AwayView.as_view()), url(r'^bumper/$', name='liv...
Add DiscussionView to the URLs.
Add DiscussionView to the URLs.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
0fed581409f0dfa4788964d02d066e8e30f1387f
webapp/byceps/blueprints/shop_admin/service.py
webapp/byceps/blueprints/shop_admin/service.py
# -*- coding: utf-8 -*- """ byceps.blueprints.shop_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from collections import Counter from ..shop.models import PaymentState def count_ordered_articles(article): """Count how often the article has been ordered, grou...
# -*- coding: utf-8 -*- """ byceps.blueprints.shop_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from collections import Counter from ..shop.models import PaymentState def count_ordered_articles(article): """Count how often the article has been ordered, grou...
Make sure every payment state is present in the counter.
Make sure every payment state is present in the counter.
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
0cb5447de992389be9587d7706637212bfe3b90b
tests/events/tests.py
tests/events/tests.py
# -*- coding: utf-8 -*- from mock import Mock from unittest2 import TestCase from raven.events import Message class MessageTest(TestCase): def test_to_string(self): unformatted_message = 'My message from %s about %s' client = Mock() message = Message(client) message.logger = Mock...
# -*- coding: utf-8 -*- from mock import Mock from unittest2 import TestCase from raven.events import Message class MessageTest(TestCase): def test_to_string(self): unformatted_message = 'My message from %s about %s' client = Mock() message = Message(client) message.logger = Mock...
Update test to match current behavior
Update test to match current behavior
Python
bsd-3-clause
johansteffner/raven-python,Photonomie/raven-python,jbarbuto/raven-python,nikolas/raven-python,lepture/raven-python,smarkets/raven-python,arthurlogilab/raven-python,lepture/raven-python,hzy/raven-python,recht/raven-python,inspirehep/raven-python,nikolas/raven-python,openlabs/raven,patrys/opbeat_python,ewdurbin/raven-pyt...
f4f5a6ffa1fd60437b83bfc435a180ddf2433ea4
tests/test_confirmation.py
tests/test_confirmation.py
import pytest import linkatos.confirmation as confirmation def test_no_confirmation_with_url(): expecting_confirmation = False parsed_m = {'out': 'http://ex.org', 'channel': 'ch', 'type': 'url'} assert confirmation.update_confirmation_if_url(parsed_m, ex...
import pytest import linkatos.confirmation as confirmation def test_no_confirmation_with_url(): expecting_confirmation = False parsed_m = {'out': 'http://ex.org', 'channel': 'ch', 'type': 'url'} assert confirmation.update_if_url(parsed_m, expecting_confi...
Fix change of function names
test: Fix change of function names
Python
mit
iwi/linkatos,iwi/linkatos
96bb2ba0dc6e58195b598e03d177114becfeba7a
nxpy/util.py
nxpy/util.py
import re from lxml import etree def new_ele(tag, attrs={}, **extra): etree.Element(tag, attrs, **extra) def sub_ele(parent, tag, attrs={}, **extra): etree.SubElement(parent, tag, attrs, **extra) # Globals tag_pattern = re.compile(r'({.*})?(.*)') whitespace_pattern = re.compile(r'[\n\r\s]+')
import re # Globals tag_pattern = re.compile(r'({.*})?(.*)') whitespace_pattern = re.compile(r'[\n\r\s]+')
Remove new_ele() and sub_ele() functions
Remove new_ele() and sub_ele() functions
Python
apache-2.0
Kent1/nxpy
9130a94153b7d9f70883da737fb60d41db73e09a
try_telethon.py
try_telethon.py
#!/usr/bin/env python3 import traceback from telethon_examples.interactive_telegram_client \ import InteractiveTelegramClient def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file...
#!/usr/bin/env python3 import traceback from telethon_examples.interactive_telegram_client \ import InteractiveTelegramClient def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file...
Support configuring SOCKS proxy in the example
Support configuring SOCKS proxy in the example
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,kyasabu/Telethon,andr-04/Telethon,LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon
52b022869b7092fc519accc2132c3f842502aeae
create_input_files.py
create_input_files.py
from utils import write_csv_rows, read_csv_rows class input_table: def __init__(self, filename, content): self.filename = filename self.content = content connect_tbl=input_table('connectivity.csv', [['Connectivity Table'], ['x1','y1','x2','y2','E','...
from utils import write_csv_rows, read_csv_rows class input_table: def __init__(self, filename, name, headers, content=[]): self.filename = filename self.name = name self.headers = headers self.content = content connect_filename = 'connectivity.csv' connect_name = ['Connectivity Ta...
Clean up input tables class and instance declarations
Clean up input tables class and instance declarations
Python
mit
ndebuhr/openfea,ndebuhr/openfea
33620c30a7e79243a9a1f32cdad7e2af8e1fa278
auditlog/admin.py
auditlog/admin.py
from django.contrib import admin from auditlog.filters import ResourceTypeFilter from auditlog.mixins import LogEntryAdminMixin from auditlog.models import LogEntry class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin): list_display = ["created", "resource_url", "action", "msg_short", "user_url"] search_...
from django.contrib import admin from auditlog.filters import ResourceTypeFilter from auditlog.mixins import LogEntryAdminMixin from auditlog.models import LogEntry class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin): list_display = ["created", "resource_url", "action", "msg_short", "user_url"] search_...
Add actor username to search fields
Add actor username to search fields
Python
mit
jjkester/django-auditlog
f25c0074a013255141371b46cff0a506ad0b2ab5
axiom/__init__.py
axiom/__init__.py
# -*- test-case-name: axiom.test -*- from axiom._version import __version__ from epsilon import asTwistedVersion version = asTwistedVersion("axiom", __version__)
# -*- test-case-name: axiom.test -*- from axiom._version import __version__ from twisted.python import versions def asTwistedVersion(packageName, versionString): return versions.Version(packageName, *map(int, versionString.split("."))) version = asTwistedVersion("axiom", __version__)
Add a local asTwistedVersion implementation to Axiom, so as to not add another setup-time dependency on Epsilon
Add a local asTwistedVersion implementation to Axiom, so as to not add another setup-time dependency on Epsilon
Python
mit
hawkowl/axiom,twisted/axiom
0c3a0fd8eee8ca4ced29dbb69570aa1605ea0d5d
PEATSA/Database/Scripts/JobMailer.py
PEATSA/Database/Scripts/JobMailer.py
#! /usr/bin/python import sys, time, optparse, os import PEATSA.Core as Core import PEATSA.WebApp as WebApp import ConstructJob import MySQLdb usage = "usage: %prog [options]" parser = optparse.OptionParser(usage=usage, version="% 0.1", description=__doc__) parser.add_option("-c", "--configurationFile", dest="configu...
#! /usr/bin/python import sys, time, optparse, os import PEATSA.Core as Core import PEATSA.WebApp as WebApp import ConstructJob import MySQLdb usage = "usage: %prog [options]" parser = optparse.OptionParser(usage=usage, version="% 0.1", description=__doc__) parser.add_option("-c", "--configurationFile", dest="configu...
Print error on mailing a failed job note
Print error on mailing a failed job note
Python
mit
dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat
ddcb5b11a2f050e1eb8ae185888dde2ef1c66d72
dedupe/convenience.py
dedupe/convenience.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPair...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPair...
Index of the list should be an int
Index of the list should be an int
Python
mit
dedupeio/dedupe-examples,dedupeio/dedupe,neozhangthe1/dedupe,tfmorris/dedupe,datamade/dedupe,pombredanne/dedupe,datamade/dedupe,nmiranda/dedupe,pombredanne/dedupe,neozhangthe1/dedupe,dedupeio/dedupe,davidkunio/dedupe,01-/dedupe,01-/dedupe,nmiranda/dedupe,tfmorris/dedupe,davidkunio/dedupe
c8b28cc0afc45c2e7b7ca83a41bc67804c7e9506
src/samples/showvideo.py
src/samples/showvideo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import avg, app import sys class VideoPlayer(app.MainDiv): def init(self): self.videoNode = avg.VideoNode( href=sys.argv[1], parent=self) self.videoNode.play() app.App().run(VideoPlayer(), app_resolu...
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import avg, app import sys class VideoPlayer(app.MainDiv): def onArgvParserCreated(self, parser): parser.set_usage("%prog <video>") def onArgvParsed(self, options, args, parser): if len(args) != 1: parser.print_help() ...
Add checks for script parameters and correct onInit name
Add checks for script parameters and correct onInit name
Python
lgpl-2.1
libavg/libavg,libavg/libavg,libavg/libavg,libavg/libavg
97919d06b252af37e7c955ff800b309599e2debc
usingnamespace/forms/user.py
usingnamespace/forms/user.py
import colander import deform from csrf import CSRFSchema class LoginForm(CSRFSchema): """The user login form.""" username = colander.SchemaNode(colander.String(), title="Username", widget=deform.widget.TextInputWidget(css_class='form-control'), ) password = colander.Sc...
import colander import deform from schemaform import SchemaFormMixin from csrf import CSRFSchema class LoginForm(CSRFSchema, SchemaFormMixin): """The user login form.""" username = colander.SchemaNode(colander.String(), title="Username", __buttons__ = (deform.form.Button(name=_("Submit"), css...
Add SchemaFormMixin to the LoginForm
Add SchemaFormMixin to the LoginForm
Python
isc
usingnamespace/usingnamespace
85458434391144aa40101ba9f97c4ec47c975438
zsh/scripts/pyjson_helper.py
zsh/scripts/pyjson_helper.py
import argparse import json parser = argparse.ArgumentParser() parser.add_argument('json_file') args = parser.parse_args() if __name__ == '__main__': with open(args.json_file) as f: data = json.load(f) print '\n###' print 'Loaded JSON in variable `data`.' print '###'
import argparse import json import inspect parser = argparse.ArgumentParser() parser.add_argument('json_file') args = parser.parse_args() def load_json(json_file): with open(json_file) as f: return json.load(f) if __name__ == '__main__': data = load_json(args.json_file) print '\n' print inspe...
Print code used to load json in python helper
zsh: Print code used to load json in python helper
Python
mit
achalddave/dotfiles,achalddave/dotfiles
4102320e908dfa6e2fc320d73f118670ad5b1501
tests/basics/fun_name.py
tests/basics/fun_name.py
def Fun(): pass class A: def __init__(self): pass def Fun(self): pass try: print(Fun.__name__) print(A.__init__.__name__) print(A.Fun.__name__) print(A().Fun.__name__) except AttributeError: print('SKIP') raise SystemExit # __name__ of a bound native method is not ...
def Fun(): pass class A: def __init__(self): pass def Fun(self): pass try: print(Fun.__name__) print(A.__init__.__name__) print(A.Fun.__name__) print(A().Fun.__name__) except AttributeError: print('SKIP') raise SystemExit # __name__ of a bound native method is not ...
Add test for getting name of func with closed over locals.
tests/basics: Add test for getting name of func with closed over locals. Tests correct decoding of the prelude to get the function name.
Python
mit
pozetroninc/micropython,adafruit/circuitpython,MrSurly/micropython,henriknelson/micropython,selste/micropython,kerneltask/micropython,trezor/micropython,pozetroninc/micropython,selste/micropython,pozetroninc/micropython,pramasoul/micropython,kerneltask/micropython,henriknelson/micropython,henriknelson/micropython,tobba...
8fa89c8642721896b7b97ff928bc66e65470691a
pinax/stripe/tests/test_utils.py
pinax/stripe/tests/test_utils.py
import datetime from django.test import TestCase from django.utils import timezone from ..utils import convert_tstamp, plan_from_stripe_id class TestTimestampConversion(TestCase): def test_conversion_without_field_name(self): stamp = convert_tstamp(1365567407) self.assertEquals( sta...
import datetime from django.test import TestCase from django.utils import timezone from ..utils import convert_tstamp class TestTimestampConversion(TestCase): def test_conversion_without_field_name(self): stamp = convert_tstamp(1365567407) self.assertEquals( stamp, datet...
Remove test for function that no longer exists
Remove test for function that no longer exists
Python
mit
pinax/django-stripe-payments
27b1d403540503f6e9d0ccd679918e3efe63ecf7
tests/test_navigation.py
tests/test_navigation.py
def get_menu_titles(page) -> list: page.wait_for_load_state() menu_list = page.query_selector_all("//*[@class='toctree-wrapper compound']/ul/li/a") return [title.as_element().inner_text() for title in menu_list] flag = True def test_check_titles(page): global flag if(flag): page.goto("i...
def get_menu_titles(page) -> list: page.wait_for_load_state() menu_list = page.query_selector_all("//*[@class='toctree-wrapper compound']/ul/li/a") return [title.as_element().inner_text() for title in menu_list] flag = True def test_check_titles(page): global flag if(flag): page.goto("i...
Delete debug comments and tool
Delete debug comments and tool
Python
agpl-3.0
PyAr/PyZombis,PyAr/PyZombis,PyAr/PyZombis
508c9ef5f7dfd974fdad650cf1a211dad9d41db5
skipper/config.py
skipper/config.py
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('c...
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('c...
Handle env vars in volumes
Handle env vars in volumes
Python
apache-2.0
Stratoscale/skipper,Stratoscale/skipper
1e150c4d5797f17ba8bea53d328cb613adc6bc0f
self_play.py
self_play.py
import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game....
import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game self.log = [] def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.t...
Add log to self play
Add log to self play
Python
mit
misterwilliam/connect-four
4dabc48455ebb8f22d37cd964ceb16373f784362
mothermayi/colors.py
mothermayi/colors.py
BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def green(text): return GREEN + text + ENDC def red(text): return RED + text + ENDC
BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def green(text): return GREEN + text + ENDC def red(text): return RED + text + ENDC def yellow(text): return YELLOW + text + ENDC
Add a function for getting yellow
Add a function for getting yellow
Python
mit
EliRibble/mothermayi
70cc77a9146f9d4afd78df9a2f8da8673f0320de
extractor.py
extractor.py
import extractor.ui.mainapplication as ui import Tkinter as tk def main(): ## root = tk.Tk() ## root.title('SNES Wolfenstein 3D Extractor') ## root.minsize(400, 100) ## ui.MainApplication(root).pack(side="top", fill="both", expand=True) ## root.mainloop() ui.MainApplication().mainloop() main()
import extractor.ui.mainapplication as ui import Tkinter as tk def main(): ## root = tk.Tk() ## root.title('SNES Wolfenstein 3D Extractor') ## root.minsize(400, 100) ## ui.MainApplication(root).pack(side="top", fill="both", expand=True) root = ui.MainApplication() root.mainloop() main()
Split program call into two lines.
Split program call into two lines.
Python
mit
adambiser/snes-wolf3d-extractor
316a6583036ca18cfdf1a95a122aa2367237fa2c
get/views.py
get/views.py
from django.shortcuts import render_to_response from django.shortcuts import redirect from models import DownloadLink def index(request): links = DownloadLink.objects.all() context = {'links': list(links)} return render_to_response('get/listing.tpl', context)
from django.shortcuts import render_to_response from django.shortcuts import redirect from models import DownloadLink def index(request): links = DownloadLink.objects.order_by('-pk') context = {'links': list(links)} return render_to_response('get/listing.tpl', context)
Order download links by pk.
get: Order download links by pk.
Python
bsd-3-clause
ProgVal/Supybot-website
1e50bdf90756a79d45b0c35353d007c5dad2abfc
hand_data.py
hand_data.py
import time from lib import Leap from lib.Leap import Bone ''' gets the current frame from controller for each finger, stores the topmost end of each bone (4 points) adjusts bone location relativity by subtracting the center of the palm returns the adjusted bone locations in the form: [(finger1bone1x, finger1bone1y, f...
import time from lib import Leap from lib.Leap import Bone ''' gets the current frame from controller for each finger, stores the topmost end of each bone (4 points) adjusts bone location relativity by subtracting the center of the palm returns the adjusted bone locations in the form: {feat0=some_float, feat1=some_flo...
Return hand data as dictionary
Return hand data as dictionary
Python
mit
ssaamm/sign-language-tutor,ssaamm/sign-language-translator,ssaamm/sign-language-translator,ssaamm/sign-language-tutor
33f94c28500c96841b1bf5ce507e418364ea556f
StarWebTkeDesenv.py
StarWebTkeDesenv.py
import urllib.parse import urllib.request import http.cookiejar url = 'http://stwebdv.thyssenkruppelevadores.com.br/scripts/gisdesenv.pl/swfw3.r' values = {'usuario' : 'admin', 'senha' : 'tke'} cj = http.cookiejar.CookieJar() data = urllib.parse.urlencode(values).encode('utf-8') opener = urllib.request.buil...
import urllib.parse import urllib.request import http.cookiejar cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) loginUrl = 'http://stwebdv.thyssenkruppelevadores.com.br/scripts/gisdesenv.pl/swfw3.r' loginData = {'usuario' : 'admin', 'senha' : 'tke'} postDa...
Add files to be compiled.
Add files to be compiled.
Python
mit
taschetto/sublimeSettings,taschetto/sublimeSettings