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
9b0571623a0017f96f9945fe263cd302faa11c2e
sparkback/__init__.py
sparkback/__init__.py
# -*- coding: utf-8 -*- import sys ticks = ('▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ') def scale_data(d): data_range = max(d) - min(d) divider = data_range / (len(ticks) - 1) min_value = min(d) scaled = [int(abs(round((i - min_value) / divider))) for i in d] return scaled def print_ansi_spark(d)...
# -*- coding: utf-8 -*- from __future__ import division import argparse ticks = ('▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ') def scale_data(data): m = min(data) n = (max(data) - m) / (len(ticks) - 1) print m,n return [ ticks[int((t - m) / n)] for t in data ] def print_ansi_spark(d): print ''.join...
Make division float to fix divide by zero issues
Make division float to fix divide by zero issues
Python
mit
mmichie/sparkback
8d8dd559252bc32388e224746f2ae8cdbdceaae4
masters/master.client.syzygy/master_win_official_cfg.py
masters/master.client.syzygy/master_win_official_cfg.py
# Copyright (c) 2011 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. from buildbot.scheduler import Scheduler from buildbot.changes.filter import ChangeFilter from master.factory import syzygy_factory def win(): retur...
# Copyright (c) 2011 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. from buildbot.scheduler import Scheduler # This is due to buildbot 0.7.12 being used for the presubmit check. from buildbot.changes.filter import ChangeF...
Fix pylint presubmit check, related to buildbot 0.8.x vs 0.7.x
Fix pylint presubmit check, related to buildbot 0.8.x vs 0.7.x TBR=nsylvain@chromium.org BUG= TEST= Review URL: http://codereview.chromium.org/7631036 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@97254 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
b14d893c68a6c1117f01b7d5712dacd8d5ca8cf9
prolog/builtin/sourcehelper.py
prolog/builtin/sourcehelper.py
import os import sys import py from prolog.interpreter.error import throw_existence_error path = os.path.dirname(__file__) path = os.path.join(path, "..", "prolog_modules") def get_source(filename): try: fd = os.open(filename, os.O_RDONLY, 0777) except OSError, e: try: fd = os.open...
import os import sys from prolog.interpreter.error import throw_existence_error from prolog.interpreter.term import Callable path = os.path.dirname(__file__) path = os.path.join(path, "..", "prolog_modules") def get_source(filename): try: fd = os.open(filename, os.O_RDONLY, 0777) except OSError, e: ...
Make atom from filename before throwing an error in get_source.
Make atom from filename before throwing an error in get_source.
Python
mit
cosmoharrigan/pyrolog
0dabc858976197459cfe71fe1a4a8a85c181db75
django_localflavor_ie/ie_counties.py
django_localflavor_ie/ie_counties.py
""" Sources: Irish Counties: http://en.wikipedia.org/wiki/Counties_of_Ireland """ from django.utils.translation import ugettext_lazy as _ IE_COUNTY_CHOICES = ( ('antrim', _('Antrim')), ('armagh', _('Armagh')), ('carlow', _('Carlow')), ('cavan', _('Cavan')), ('clare', _('Clare')), ('cork...
""" Sources: Irish Counties: http://en.wikipedia.org/wiki/Counties_of_Ireland """ from django.utils.translation import ugettext_lazy as _ IE_COUNTY_CHOICES = ( ('carlow', _('Carlow')), ('cavan', _('Cavan')), ('clare', _('Clare')), ('cork', _('Cork')), ('donegal', _('Donegal')), ('dublin', _...
Remove Northern Irish counties. These are part of the UK, not Ireland
Remove Northern Irish counties. These are part of the UK, not Ireland
Python
bsd-3-clause
martinogden/django-localflavor-ie
6d6ee78d49663150f3d58855b4ea49ca3fbee62f
changes/api/project_build_index.py
changes/api/project_build_index.py
from __future__ import absolute_import, division, unicode_literals from flask import Response, request from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.models import Project, Build class ProjectBuildIndexAPIView(APIView): def _get_project(self, project_id): project...
from __future__ import absolute_import, division, unicode_literals from flask import Response, request from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.models import Project, Build class ProjectBuildIndexAPIView(APIView): def _get_project(self, project_id): project...
Add source to project build index query
Add source to project build index query
Python
apache-2.0
bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes
231a40a8a8c7d7844475a381638c96ebaf3b288a
osOps.py
osOps.py
import os def createFile(directoryPath, fileName): return None def createDirectory(directoryPath): return None def getFileContents(filePath): return None def deleteFile(filePath): return None def deleteDirectory(directoryPath): return None
import os def createDirectory(directoryPath): return None def createFile(filePath): try: createdFile = open(filePath, 'w+') createdFile.close() except IOError: print "Error: could not create file at location: " + filePath def getFileContents(filePath): return None def deleteF...
Implement logic for file creation
Implement logic for file creation
Python
apache-2.0
AmosGarner/PyInventory
560bbc0a0415b536fd6a49bbce6b2beb3f5f7219
src/balistos/tests/test_views.py
src/balistos/tests/test_views.py
# -*- coding: utf-8 -*- """Tests.""" from pyramid import testing from balistos.testing import createTestDB from pyramid_basemodel import Session import unittest class TestHome(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def ...
# -*- coding: utf-8 -*- """Tests.""" from pyramid import testing from balistos.testing import createTestDB from pyramid_basemodel import Session import unittest class TestHome(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def ...
Fix tests to comply with new home view
Fix tests to comply with new home view
Python
mit
ferewuz/balistos,ferewuz/balistos
f8a7939bab7803a04e28f01852b1323fe9651a31
zaqar_ui/version.py
zaqar_ui/version.py
import pbr.version version_info = pbr.version.VersionInfo('zaqar-ui')
# 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 u...
Add Apache 2.0 license to source file
Add Apache 2.0 license to source file As per OpenStack licensing guide lines [1]: [H102 H103] Newly contributed Source Code should be licensed under the Apache 2.0 license. [1] http://docs.openstack.org/developer/hacking/#openstack-licensing Change-Id: I714355371a6c57f74924efec19f12d48c7fe2d3f
Python
apache-2.0
openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui
b46370e025efc4730fb39c05928ff22744956eda
django_perf_rec/functional.py
django_perf_rec/functional.py
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import inspect from functools import wraps def kwargs_only(func): """ Make a function only accept keyword arguments. This can be dropped in Python 3 in lieu of: def foo(*, bar=default): "...
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import inspect from functools import wraps def kwargs_only(func): """ Make a function only accept keyword arguments. This can be dropped in Python 3 in lieu of: def foo(*, bar=default): "...
Fix warnings on Python 3
Fix warnings on Python 3 Fixes #74. Use `inspect.signature()` on Python 3 instead of the deprecated `inspect.getargspec()`.
Python
mit
YPlan/django-perf-rec
ae5e35aefd5b508fa2a0d1ed7d0ceefd9d24eb27
17B-162/spw_setup.py
17B-162/spw_setup.py
# Line SPW setup for 17B-162 w/ rest frequencies linespw_dict = {0: ["HI", "1.420405752GHz"], 1: ["H166alp", "1.42473GHz"], 2: ["H164alp", "1.47734GHz"], 3: ["OH1612", "1.612231GHz"], 4: ["H158alp", "1.65154GHz"], 5: ["OH1665", "1.6654018...
# Line SPW setup for 17B-162 w/ rest frequencies linespw_dict = {0: ["HI", "1.420405752GHz", 4096], 1: ["H166alp", "1.42473GHz", 128], 2: ["H164alp", "1.47734GHz", 128], 3: ["OH1612", "1.612231GHz", 256], 4: ["H158alp", "1.65154GHz", 128], ...
Add the number of channels in each SPW
Add the number of channels in each SPW
Python
mit
e-koch/VLA_Lband,e-koch/VLA_Lband
b42896e796e6f4d2984547a34978bb34c66ba749
blanc_basic_news/news/views.py
blanc_basic_news/news/views.py
from django.views.generic import ListView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.utils import timezone from django.conf import settings from .models import Category, Post class PostListView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) d...
from django.views.generic import ArchiveIndexView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.conf import settings from .models import Category, Post class PostListView(ArchiveIndexView): queryset = Post.objects.select_related().filter(published=True) date_fiel...
Use ArchiveIndexView to reduce code
Use ArchiveIndexView to reduce code
Python
bsd-3-clause
blancltd/blanc-basic-news
63e7c8782c179be3aa003c70ccf1bb7dcf24a39c
setup.py
setup.py
from distutils.core import setup DESCRIPTION=""" """ setup( name="django-moneyfield", description="Django Money Model Field", long_description=DESCRIPTION, version="0.2", author="Carlos Palol", author_email="carlos.palol@awarepixel.com", url="http://www.awarepixel.com", packages=[ ...
from distutils.core import setup DESCRIPTION=""" """ setup( name="django-moneyfield", description="Django Money Model Field", long_description=DESCRIPTION, version="0.2", author="Carlos Palol", author_email="carlos.palol@awarepixel.com", url="https://github.com/carlospalol/django-moneyfie...
Use github page as homepage
Use github page as homepage
Python
mit
generalov/django-moneyfield,carlospalol/django-moneyfield
7f5186caa6b59df412d62b052406dbe675b9e463
OpenSearchInNewTab.py
OpenSearchInNewTab.py
import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if view.name() == DEFAULT_NAME: view.se...
import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.appl...
Refactor API to a more readable form
Refactor API to a more readable form
Python
mit
everyonesdesign/OpenSearchInNewTab
a759875e123dcbd37f3eb21993409397f818f6c6
src/pudl/metadata/__init__.py
src/pudl/metadata/__init__.py
"""Metadata constants and methods.""" from .classes import Resource from .resources import RESOURCES RESOURCES = {name: Resource.from_id(name) for name in RESOURCES}
"""Metadata constants and methods.""" import pydantic from . import resources from .classes import Resource RESOURCES = {} errors = [] for name in resources.RESOURCES: try: RESOURCES[name] = Resource.from_id(name) except pydantic.ValidationError as error: errors.append("\n" + f"[{name}] {erro...
Print all resource validation errors
Print all resource validation errors
Python
mit
catalyst-cooperative/pudl,catalyst-cooperative/pudl
36307802a45f94cb218ce9bbe4a4abc7704a973a
graphics/savefig.py
graphics/savefig.py
import os import matplotlib.pyplot as plt def savefig(filename,path="figs",fig=None,ext='eps',**kwargs): # try: # os.remove(path) # except OSError as e: # try: # os.mkdir(path) # except: # pass if not os.path.exists(path): os.makedirs(path) filename ...
import os import matplotlib.pyplot as plt def savefig(filename,path="figs",fig=None,ext='eps',**kwargs): # try: # os.remove(path) # except OSError as e: # try: # os.mkdir(path) # except: # pass if not os.path.exists(path): os.makedirs(path) filename ...
Save figures with white space cropped out
Save figures with white space cropped out
Python
mit
joelfrederico/SciSalt
e6a7548546b690118537ae2a52b63d39eea6580f
graphiter/models.py
graphiter/models.py
from django.db import models from django.core.urlresolvers import reverse class Chart(models.Model): title = models.CharField(max_length=50) url = models.CharField(max_length=1024) def __unicode__(self): return self.title class Page(models.Model): title = models.CharField(max_length=50) slug = models.SlugFi...
from django.db import models from django.core.urlresolvers import reverse class Chart(models.Model): title = models.CharField(max_length=50) url = models.CharField(max_length=1024) def __unicode__(self): return self.title class Page(models.Model): title = models.CharField(max_length=50) slug = models.SlugFi...
Add help_text for time_from and time_until
Add help_text for time_from and time_until
Python
bsd-2-clause
jwineinger/django-graphiter
12f63ec4224185fc03176995d2cfc00c46c2ace3
MoveByLinesCommand.py
MoveByLinesCommand.py
import sublime import sublime_plugin class MoveByLinesCommand(sublime_plugin.TextCommand): def run(self, edit, forward=True, extend=False, number_of_lines=1): for _ in range(number_of_lines): self.view.run_command('move', {"by": "lines", "forward": forward, "extend": extend})
import sublime import sublime_plugin class MoveByLinesCommand(sublime_plugin.TextCommand): def is_selection_in_sight(self): sel = self.view.sel()[0] visible_region = self.view.visible_region() in_sight = visible_region.intersects(sel) or visible_region.contains(sel) return in_sigh...
Fix annoying issue with view scrolling
Fix annoying issue with view scrolling
Python
unlicense
rahul-ramadas/BagOfTricks
85e8ddb6d72b7f21b49236ea4084029dec09a6f9
projects/forms.py
projects/forms.py
from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(co...
from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(co...
Exclude fields from the RestrcitedForm (no verification)
Exclude fields from the RestrcitedForm (no verification)
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
840643522e32484b1c44352dc095e7369a44ef7b
header_swap_axis.py
header_swap_axis.py
''' Swap the axes in a header, without losing keys to WCS ''' from astropy.wcs import WCS def header_swapaxes(header, ax1, ax2): ''' ''' mywcs = WCS(header) new_hdr = mywcs.swapaxes(ax1, ax2).to_header() lost_keys = list(set(header.keys()) - set(new_hdr.keys())) for key in lost_keys: ...
''' Swap the axes in a header, without losing keys to WCS ''' from astropy.wcs import WCS def header_swapaxes(header, ax1, ax2): ''' ''' mywcs = WCS(header) new_hdr = mywcs.swapaxes(ax1, ax2).to_header() lost_keys = list(set(header.keys()) - set(new_hdr.keys())) for key in lost_keys: ...
Deal with CASA's empty header keywords
Deal with CASA's empty header keywords
Python
mit
e-koch/ewky_scripts,e-koch/ewky_scripts
1d6fa0521b0fbba48ddbc231614b7074a63488c2
tests/utils.py
tests/utils.py
import os import sys from config import * def addLocalPaths(paths): for path_part in paths: base_path = os.path.join(local_path, path_part) abs_path = os.path.abspath(base_path) print "importing " + abs_path sys.path.insert(0, abs_path)
import os import sys from config import * def addLocalPaths(paths): for path_part in paths: base_path = os.path.join(local_path, path_part) abs_path = os.path.abspath(base_path) sys.path.insert(0, abs_path)
Remove debug messages from import.
Remove debug messages from import.
Python
mpl-2.0
EsriOceans/btm
854fe79574782f812313508bd8b207f6c033352a
event/models.py
event/models.py
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) image_url = models.URLField(blank=True) thumb_url = models.URLField(blank=True) events = models.ManyToManyField( 'event.Event', related_name='artists', blank=True, ) class...
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) image_url = models.URLField(blank=True) thumb_url = models.URLField(blank=True) events = models.ManyToManyField( 'event.Event', related_name='artists', blank=True, ) class...
Add Event ordering by datetime
Add Event ordering by datetime
Python
mit
FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack
aed18a3f9cbaf1eae1d7066b438437446513d912
sphinxcontrib/traceables/__init__.py
sphinxcontrib/traceables/__init__.py
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib impor...
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib impor...
Fix missing call to display.setup()
Fix missing call to display.setup()
Python
apache-2.0
t4ngo/sphinxcontrib-traceables
3af265ab0740378267a3c3e9cc85bb21468bf2e0
engine/cli.py
engine/cli.py
from engine.event import * from engine.action import * from engine.code import * from engine.player import * from engine.round import * from engine.team import * def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in user...
from engine.action import Action, Stats from engine.player import Player def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jail...
Remove a few unnecessary imports
Remove a few unnecessary imports
Python
bsd-2-clause
mahfiaz/spotter_irl,mahfiaz/spotter_irl,mahfiaz/spotter_irl
49b5775f430f9d32638f074661ae877047f6dcb2
api/v2/serializers/summaries/image.py
api/v2/serializers/summaries/image.py
from core.models import Application as Image from rest_framework import serializers from api.v2.serializers.fields.base import UUIDHyperlinkedIdentityField class ImageSummarySerializer(serializers.HyperlinkedModelSerializer): user = serializers.PrimaryKeyRelatedField( source='created_by', read_onl...
from core.models import Application as Image from rest_framework import serializers from api.v2.serializers.fields.base import UUIDHyperlinkedIdentityField class ImageSummarySerializer(serializers.HyperlinkedModelSerializer): user = serializers.PrimaryKeyRelatedField( source='created_by', read_onl...
Include 'tags' in the Image summary (returned by the /v2/instances detail API)
Include 'tags' in the Image summary (returned by the /v2/instances detail API)
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
ac786779916e39d31582ed538635dc0aa7ee9310
karspexet/show/admin.py
karspexet/show/admin.py
from django.contrib import admin from karspexet.show.models import Production, Show @admin.register(Production) class ProductionAdmin(admin.ModelAdmin): list_display = ("name", "alt_name") @admin.register(Show) class ShowAdmin(admin.ModelAdmin): list_display = ("production", "slug", "date_string") list...
from django.contrib import admin from django.utils import timezone from karspexet.show.models import Production, Show @admin.register(Production) class ProductionAdmin(admin.ModelAdmin): list_display = ("name", "alt_name") @admin.register(Show) class ShowAdmin(admin.ModelAdmin): list_display = ("date_strin...
Improve ShowAdmin to give better overview
Improve ShowAdmin to give better overview
Python
mit
Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet
62bbc01940e85e6017b4b5d4e757437b05c81f71
evaluation_system/reports/views.py
evaluation_system/reports/views.py
from django.shortcuts import render from django.views.generic import TemplateView from django.shortcuts import redirect from ..evaluation.models import Evaluation, Group_User class showProfessorReport(TemplateView): template_name= "report/professorReport.html" def get(self, request, *args, **kwargs): if not req...
from django.shortcuts import render from django.views.generic import TemplateView from django.shortcuts import redirect from ..evaluation.models import Evaluation, Group_User class showProfessorReport(TemplateView): template_name= "report/professorReport.html" def get(self, request, *args, **kwargs): if not req...
Fix evaluation query on report
Fix evaluation query on report
Python
mit
carlosa54/evaluation_system,carlosa54/evaluation_system,carlosa54/evaluation_system
44791b285f4c30cbafc93abcce525f52d21e8215
Lib/test/test_dbm.py
Lib/test/test_dbm.py
#! /usr/bin/env python """Test script for the dbm module Roger E. Masse """ import dbm from dbm import error from test_support import verbose filename= '/tmp/delete_me' d = dbm.open(filename, 'c') d['a'] = 'b' d['12345678910'] = '019237410982340912840198242' d.keys() if d.has_key('a'): if verbose: prin...
#! /usr/bin/env python """Test script for the dbm module Roger E. Masse """ import dbm from dbm import error from test_support import verbose filename = '/tmp/delete_me' d = dbm.open(filename, 'c') d['a'] = 'b' d['12345678910'] = '019237410982340912840198242' d.keys() if d.has_key('a'): if verbose: pri...
Fix up the cleanup of the temporary DB so it works for BSD DB's compatibility layer as well as "classic" ndbm.
Fix up the cleanup of the temporary DB so it works for BSD DB's compatibility layer as well as "classic" ndbm.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
24998a6ca73f29c5380d875cf9b8da69b8d1e8f0
erpnext/patches/v4_2/repost_reserved_qty.py
erpnext/patches/v4_2/repost_reserved_qty.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.utilities.repost_stock import update_bin_qty, get_reserved_qty def execute(): repost_for = frappe.db.sql(""" select ...
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.utilities.repost_stock import update_bin_qty, get_reserved_qty def execute(): repost_for = frappe.db.sql(""" select ...
Delete Bin for non-stock item
[fix][patch] Delete Bin for non-stock item
Python
agpl-3.0
hanselke/erpnext-1,mahabuber/erpnext,anandpdoshi/erpnext,fuhongliang/erpnext,geekroot/erpnext,mbauskar/omnitech-demo-erpnext,meisterkleister/erpnext,hatwar/buyback-erpnext,njmube/erpnext,gangadharkadam/v6_erp,SPKian/Testing,meisterkleister/erpnext,shft117/SteckerApp,SPKian/Testing2,gangadhar-kadam/helpdesk-erpnext,Apti...
aaaaac53d996ff5ed1f39cbed583079e26150443
falcom/api/hathi/from_json.py
falcom/api/hathi/from_json.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. import json from .data import HathiData def load_json (json_data): try: return json.loads(json_data) except: return...
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. import json from .data import HathiData EMPTY_JSON_DATA = { } def load_json (json_data): try: return json.loads(json_data) ...
Add named constant to explain why { } default
Add named constant to explain why { } default
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
2cd1df93ec3e93fb5f787be5160a50e9f295211f
examples/plot_estimate_covariance_matrix.py
examples/plot_estimate_covariance_matrix.py
""" ============================================== Estimate covariance matrix from a raw FIF file ============================================== """ # Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # # License: BSD (3-clause) print __doc__ import mne from mne import fiff from mne.datasets import sample d...
""" ============================================== Estimate covariance matrix from a raw FIF file ============================================== """ # Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # # License: BSD (3-clause) print __doc__ import mne from mne import fiff from mne.datasets import sample d...
FIX : fix text in cov estimation example
FIX : fix text in cov estimation example
Python
bsd-3-clause
matthew-tucker/mne-python,cjayb/mne-python,wmvanvliet/mne-python,bloyl/mne-python,dgwakeman/mne-python,lorenzo-desantis/mne-python,drammock/mne-python,andyh616/mne-python,mne-tools/mne-python,aestrivex/mne-python,jaeilepp/mne-python,agramfort/mne-python,teonlamont/mne-python,kingjr/mne-python,yousrabk/mne-python,pravsr...
98ca748996fe462cedf284ad91a74bdd30eb81f3
mopidy/__init__.py
mopidy/__init__.py
from __future__ import absolute_import, unicode_literals import platform import sys import textwrap import warnings if not (2, 7) <= sys.version_info < (3,): sys.exit( 'ERROR: Mopidy requires Python 2.7, but found %s.' % platform.python_version()) try: import gobject # noqa except ImportEr...
from __future__ import absolute_import, print_function, unicode_literals import platform import sys import textwrap import warnings if not (2, 7) <= sys.version_info < (3,): sys.exit( 'ERROR: Mopidy requires Python 2.7, but found %s.' % platform.python_version()) try: import gobject # noqa...
Use print function instead of print statement
py3: Use print function instead of print statement
Python
apache-2.0
jcass77/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,vrs01/mopidy,jcass77/mopidy,diandiankan/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,mokieyue/mopidy,rawdlite/mopidy,jcass77/mopidy,jmarsik/mopidy,mopidy/mopidy,bencevans/mopidy,mopidy/mopidy,diandiankan/mopidy,jmarsik/mopidy,vrs01/mopidy,mokieyue/mopidy,kingosticks/mopidy,Su...
77af150756021ac4027e290b5d538e0525d812b9
mopidy/settings.py
mopidy/settings.py
CONSOLE_LOG_FORMAT = u'%(levelname)-8s %(asctime)s %(name)s\n %(message)s' MPD_LINE_ENCODING = u'utf-8' MPD_LINE_TERMINATOR = u'\n' MPD_SERVER_HOSTNAME = u'localhost' MPD_SERVER_PORT = 6600 SPOTIFY_USERNAME = u'' SPOTIFY_PASSWORD = u'' try: from mopidy.local_settings import * except ImportError: pass
CONSOLE_LOG_FORMAT = u'%(levelname)-8s %(asctime)s [%(threadName)s] %(name)s\n %(message)s' MPD_LINE_ENCODING = u'utf-8' MPD_LINE_TERMINATOR = u'\n' MPD_SERVER_HOSTNAME = u'localhost' MPD_SERVER_PORT = 6600 SPOTIFY_USERNAME = u'' SPOTIFY_PASSWORD = u'' try: from mopidy.local_settings import * except ImportError:...
Add threadName to log format
Add threadName to log format
Python
apache-2.0
bencevans/mopidy,pacificIT/mopidy,quartz55/mopidy,SuperStarPL/mopidy,priestd09/mopidy,mokieyue/mopidy,abarisain/mopidy,hkariti/mopidy,swak/mopidy,adamcik/mopidy,quartz55/mopidy,priestd09/mopidy,pacificIT/mopidy,dbrgn/mopidy,jmarsik/mopidy,bencevans/mopidy,tkem/mopidy,abarisain/mopidy,liamw9534/mopidy,hkariti/mopidy,pac...
e91d81a03d57af1fff1b580b1c276fd02f44f587
places/migrations/0011_auto_20200712_1733.py
places/migrations/0011_auto_20200712_1733.py
# Generated by Django 3.0.8 on 2020-07-12 17:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('places', '0010_auto_20200712_0505'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ['...
# Generated by Django 3.0.8 on 2020-07-12 17:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("places", "0010_auto_20200712_0505"), ] operations = [ migrations.AlterModelOptions( name="category", options={"ordering": ["...
Apply black formatting to migration
Apply black formatting to migration
Python
mit
huangsam/chowist,huangsam/chowist,huangsam/chowist
4b716882b3e8e13e591d629a88e5b102c7f008b4
mapit/management/commands/mapit_generation_deactivate.py
mapit/management/commands/mapit_generation_deactivate.py
# This script deactivates a particular generation from optparse import make_option from django.core.management.base import BaseCommand from mapit.models import Generation class Command(BaseCommand): help = 'Deactivate a generation' args = '<GENERATION-ID>' option_list = BaseCommand.option_list + ( ...
# This script deactivates a particular generation from optparse import make_option from django.core.management.base import BaseCommand, CommandError from mapit.models import Generation class Command(BaseCommand): help = 'Deactivate a generation' args = '<GENERATION-ID>' option_list = BaseCommand.option_li...
Add the import for CommandError
Add the import for CommandError
Python
agpl-3.0
opencorato/mapit,chris48s/mapit,New-Bamboo/mapit,Code4SA/mapit,Code4SA/mapit,chris48s/mapit,New-Bamboo/mapit,Code4SA/mapit,Sinar/mapit,opencorato/mapit,opencorato/mapit,Sinar/mapit,chris48s/mapit
f98b78fcf37e9d3e200c468b5a0bba25abdd13fd
django_lti_tool_provider/tests/urls.py
django_lti_tool_provider/tests/urls.py
from django.conf.urls import url from django.contrib.auth.views import login from django_lti_tool_provider import views as lti_views urlpatterns = [ url(r'', lti_views.LTIView.as_view(), name='home'), url('^accounts/login/$', login), url(r'^lti$', lti_views.LTIView.as_view(), name='lti') ]
from django.conf.urls import url from django.contrib.auth.views import LoginView from django_lti_tool_provider import views as lti_views urlpatterns = [ url(r'', lti_views.LTIView.as_view(), name='home'), url('^accounts/login/$', LoginView.as_view()), url(r'^lti$', lti_views.LTIView.as_view(), name='lti'...
Replace contrib.auth's "login" view with LoginView.
Replace contrib.auth's "login" view with LoginView. Cf. https://docs.djangoproject.com/en/2.1/releases/1.11/#id2 contrib.auth's login() and logout() function-based views are deprecated in favor of new class-based views LoginView and LogoutView.
Python
agpl-3.0
open-craft/django-lti-tool-provider
2b4c4a61b7b4853f93c7ac1272905660fce8c3fd
aurorawatchuk/snapshot.py
aurorawatchuk/snapshot.py
from aurorawatchuk import AuroraWatchUK __author__ = 'Steve Marple' __version__ = '0.1.2' __license__ = 'MIT' class AuroraWatchUK_SS(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated ...
import aurorawatchuk __author__ = 'Steve Marple' __version__ = '0.1.2' __license__ = 'MIT' class AuroraWatchUK_SS(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated just once and cache...
Rewrite import to avoid accidental misuse
Rewrite import to avoid accidental misuse Don't import the AuroraWatchUK class into the snapshot namespace, it enables the original AuroraWatchUK class to be used when it was intended to use the snapshot version, AuroraWatchUK_SS.
Python
mit
stevemarple/python-aurorawatchuk
e1f49afe5d4aeae2306349d52df4295944598dc1
thinglang/parser/tokens/logic.py
thinglang/parser/tokens/logic.py
from thinglang.lexer.symbols.logic import LexicalEquality from thinglang.parser.tokens import BaseToken class Conditional(BaseToken): ADVANCE = False def __init__(self, slice): super(Conditional, self).__init__(slice) _, self.value = slice def describe(self): return 'if {}'.form...
from thinglang.lexer.symbols.logic import LexicalEquality from thinglang.parser.tokens import BaseToken class Conditional(BaseToken): ADVANCE = False def __init__(self, slice): super(Conditional, self).__init__(slice) _, self.value = slice def describe(self): return 'if {}'.form...
Update interface signatures for else branches
Update interface signatures for else branches
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
efdfcccf57b294d529039095c2c71401546b3519
elephas/utils/functional_utils.py
elephas/utils/functional_utils.py
from __future__ import absolute_import import numpy as np def add_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x+y) return res def get_neutral(array): res = [] for x in array: res.append(np.zeros_like(x)) return res def divide_by(array_list, num_workers): fo...
from __future__ import absolute_import import numpy as np def add_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x+y) return res def subtract_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x-y) return res def get_neutral(array): res = [] for x ...
Subtract two sets of parameters
Subtract two sets of parameters
Python
mit
FighterLYL/elephas,maxpumperla/elephas,CheMcCandless/elephas,daishichao/elephas,maxpumperla/elephas,aarzhaev/elephas,darcy0511/elephas
634cfafd7470c40c574f315c3302158ea3232bc9
example/achillesexample/blocks.py
example/achillesexample/blocks.py
from achilles import blocks, tables from time import sleep from models import Person register = blocks.Library('example') COUNTER = 0 @register.block(template_name='blocks/message.html') def counter(): global COUNTER COUNTER += 1 return { 'message': 'Block loaded %s times' % COUNTER, } @reg...
from achilles import blocks, tables from time import sleep from models import Person register = blocks.Library('example') COUNTER = 0 @register.block(template_name='blocks/message.html') def counter(): global COUNTER COUNTER += 1 return { 'message': 'Block loaded %s times' % COUNTER, } @reg...
Use verbose names in example table
Use verbose names in example table
Python
apache-2.0
exekias/django-achilles,exekias/django-achilles
21889635640e0ca5e63fb7351b745e29b8748515
labmanager/utils.py
labmanager/utils.py
import os import sys from werkzeug.urls import url_quote, url_unquote from werkzeug.routing import PathConverter def data_filename(fname): basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if os.path.exists(os.path.join(basedir, 'labmanager_data', fname)): return os.path.join(ba...
import os import sys from werkzeug.urls import url_quote, url_unquote from werkzeug.routing import PathConverter def data_filename(fname): basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if os.path.exists(os.path.join(basedir, 'labmanager_data', fname)): return os.path.join(ba...
Fix issue with URL routes
Fix issue with URL routes
Python
bsd-2-clause
gateway4labs/labmanager,gateway4labs/labmanager,labsland/labmanager,labsland/labmanager,morelab/labmanager,go-lab/labmanager,morelab/labmanager,porduna/labmanager,morelab/labmanager,go-lab/labmanager,go-lab/labmanager,porduna/labmanager,morelab/labmanager,porduna/labmanager,labsland/labmanager,labsland/labmanager,pordu...
48f9b32bfe8a222cbe8afdb1e4f0d63bc2ac9a68
nova/conf/cache.py
nova/conf/cache.py
# needs:fix_opt_description # needs:check_deprecation_status # needs:check_opt_group_and_type # needs:fix_opt_description_indentation # needs:fix_opt_registration_consistency # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyrig...
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2016 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance wi...
Update tags for Cache config option
Update tags for Cache config option Updated tags for config options consistency [1]. [1] https://wiki.openstack.org/wiki/ConfigOptionsConsistency Change-Id: I3f82d2b4d60028221bc861bfe0fe5dff6efd971f Implements: Blueprint centralize-config-options-newton
Python
apache-2.0
vmturbo/nova,cloudbase/nova,hanlind/nova,sebrandon1/nova,Juniper/nova,jianghuaw/nova,rajalokan/nova,rahulunair/nova,alaski/nova,Juniper/nova,mahak/nova,Juniper/nova,mikalstill/nova,jianghuaw/nova,rahulunair/nova,sebrandon1/nova,gooddata/openstack-nova,alaski/nova,klmitch/nova,openstack/nova,Juniper/nova,klmitch/nova,ra...
f5e7751835764a819678f58be0098cd7a62cb691
core/admin/mailu/internal/__init__.py
core/admin/mailu/internal/__init__.py
from mailu import limiter import socket import flask internal = flask.Blueprint('internal', __name__) @limiter.request_filter def whitelist_webmail(): try: return flask.request.headers["Client-Ip"] ==\ socket.gethostbyname("webmail") except: return False from mailu.internal im...
from flask_limiter import RateLimitExceeded from mailu import limiter import socket import flask internal = flask.Blueprint('internal', __name__) @internal.app_errorhandler(RateLimitExceeded) def rate_limit_handler(e): response = flask.Response() response.headers['Auth-Status'] = 'Authentication rate limit...
Return correct status codes from auth rate limiter failure.
Return correct status codes from auth rate limiter failure.
Python
mit
kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io
3c0b2806627347aeda52e19b77d84042deb16824
swfc_lt_stream/net.py
swfc_lt_stream/net.py
import enum import functools import operator import struct class Packet(enum.IntEnum): connect = 0 disconnect = 1 data = 2 ack = 3 end = 4 def build_data_packet(window, blockseed, block): payload = struct.pack('!II', window, blockseed) + block return build_packet(Packet.data, payload) ...
import enum import functools import operator import struct class Packet(enum.IntEnum): connect = 0 disconnect = 1 data = 2 ack = 3 end = 4 def build_data_packet(window, blockseed, block): payload = struct.pack('!II', window, blockseed) + block return build_packet(Packet.data, payload) ...
Remove starred expression for 3.4 compatibility
Remove starred expression for 3.4 compatibility
Python
mit
anikey-m/swfc-lt-stream,anikey-m/swfc-lt-stream
347faf7f550253bb076accbb1c4ecaba9d906324
talks/events/forms.py
talks/events/forms.py
from django import forms from .models import Event, EventGroup class EventForm(forms.ModelForm): class Meta: fields = ('title', 'description', 'speakers', 'location', 'start', 'end') model = Event labels = { 'description': 'Abstract', 'speakers': 'Speaker', ...
from django import forms from .models import Event, EventGroup class EventForm(forms.ModelForm): class Meta: fields = ('title', 'description', 'speakers', 'location', 'start', 'end') model = Event labels = { 'description': 'Abstract', 'speakers': 'Speaker', ...
Validate between the Select and create new EventGroup
Validate between the Select and create new EventGroup Added simple booleans to manage this selection for now
Python
apache-2.0
ox-it/talks.ox,ox-it/talks.ox,ox-it/talks.ox
643ea571b795ed933afac13e38e1aee9f5fec4b6
openminted/Ab3P.py
openminted/Ab3P.py
#!/usr/bin/env python import argparse import pubrunner import pubrunner.command_line import os import sys if __name__ == '__main__': parser = argparse.ArgumentParser(description='Main access point for OpenMinTeD Docker component') parser.add_argument('--input',required=True,type=str,help='Input directory') parser....
#!/usr/bin/env python import argparse import pubrunner import pubrunner.command_line import os import sys if __name__ == '__main__': parser = argparse.ArgumentParser(description='Main access point for OpenMinTeD Docker component') parser.add_argument('--input',required=True,type=str,help='Input directory') parser....
Add unused param:language flag for OpenMinTeD purposes
Add unused param:language flag for OpenMinTeD purposes
Python
mit
jakelever/pubrunner,jakelever/pubrunner
7c97bbe3e25f7cc8953fd286a0736ede09f97dcf
paper/replicate.py
paper/replicate.py
import os # Best Python command on your system my_python = "python" print("This script should download and install DNest4 and \ replicate all the runs presented in the paper.\nNote:\ plots will be generated, which need to be manually\n\ closed for the script to continue. It assumes\n\ everything has been compiled alr...
import os import matplotlib.pyplot # Best Python command on your system my_python = "/home/brendon/local/anaconda3/bin/python" print("This script should\ replicate all the runs presented in the paper.\nNote:\ plots will be generated, which need to be manually\n\ closed for the script to continue. It assumes\n\ everyt...
Use existing code (don't clone again)
Use existing code (don't clone again)
Python
mit
eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4
6a095a8a140b8056c5a17467d3249c1ab9bba8f4
grammpy/IsMethodsRuleExtension.py
grammpy/IsMethodsRuleExtension.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .Rule import Rule class IsMethodsRuleExtension(Rule): @classmethod def is_regular(cls): return False @classmethod def is_contextfree(cls): return False @classmeth...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .Rule import Rule class IsMethodsRuleExtension(Rule): @classmethod def is_regular(cls): return False @classmethod def is_contextfree(cls): return False @classmeth...
Add header of Rule.isValid method
Add header of Rule.isValid method
Python
mit
PatrikValkovic/grammpy
aff606998eccb328a48323f79d26d6c96ad4900a
doc/examples/plot_piecewise_affine.py
doc/examples/plot_piecewise_affine.py
""" =============================== Piecewise Affine Transformation =============================== This example shows how to use the Piecewise Affine Transformation. """ import numpy as np import matplotlib.pyplot as plt from skimage.transform import PiecewiseAffineTransform, warp from skimage import data image = ...
""" =============================== Piecewise Affine Transformation =============================== This example shows how to use the Piecewise Affine Transformation. """ import numpy as np import matplotlib.pyplot as plt from skimage.transform import PiecewiseAffineTransform, warp from skimage import data image = ...
Add mesh points to plot
Add mesh points to plot
Python
bsd-3-clause
almarklein/scikit-image,paalge/scikit-image,chintak/scikit-image,keflavich/scikit-image,emon10005/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image,SamHames/scikit-image,rjeli/scikit-image,pratapvardhan/scikit-image,ajaybhat/scikit-image,almarklein/scikit-image,GaZ3ll3/scikit-image,j...
959d20df781edb9f283f5317f50e8000f83e7ab6
tests/rules/test_no_such_file.py
tests/rules/test_no_such_file.py
import pytest from thefuck.rules.no_such_file import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='mv foo bar/foo', stderr="mv: cannot move 'foo' to 'bar/foo': No such file or directory"), Command(script='mv foo bar/', stderr="mv: cannot move 'foo...
import pytest from thefuck.rules.no_such_file import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='mv foo bar/foo', stderr="mv: cannot move 'foo' to 'bar/foo': No such file or directory"), Command(script='mv foo bar/', stderr="mv: cannot move 'foo...
Add `test_not_match` to `no_such_file` tests
Add `test_not_match` to `no_such_file` tests
Python
mit
manashmndl/thefuck,levythu/thefuck,qingying5810/thefuck,mlk/thefuck,vanita5/thefuck,artiya4u/thefuck,nvbn/thefuck,ostree/thefuck,lawrencebenson/thefuck,sekaiamber/thefuck,manashmndl/thefuck,thinkerchan/thefuck,princeofdarkness76/thefuck,subajat1/thefuck,PLNech/thefuck,lawrencebenson/thefuck,roth1002/thefuck,bigplus/the...
6ec61fc80ea8c3626b507d20d6c95d64ae4216c0
tests/twisted/connect/timeout.py
tests/twisted/connect/timeout.py
""" Test that Gabble times out the connection process after a while if the server stops responding at various points. Real Gabbles time out after a minute; the test suite's Gabble times out after a couple of seconds. """ from servicetest import assertEquals from gabbletest import exec_test, XmppAuthenticator import c...
""" Test that Gabble times out the connection process after a while if the server stops responding at various points. Real Gabbles time out after a minute; the test suite's Gabble times out after a couple of seconds. """ from servicetest import assertEquals from gabbletest import exec_test, XmppAuthenticator import c...
Use 'pass', not 'return', for empty Python methods
Use 'pass', not 'return', for empty Python methods
Python
lgpl-2.1
community-ssu/telepathy-gabble,community-ssu/telepathy-gabble,community-ssu/telepathy-gabble,community-ssu/telepathy-gabble
2807e2c39e54046cb750c290cb7b12b289e1cd9a
test/test_indexing.py
test/test_indexing.py
import pytest import os import shutil import xarray as xr from cosima_cookbook import database from dask.distributed import Client from sqlalchemy import select, func @pytest.fixture(scope='module') def client(): return Client() def test_broken(client, tmp_path): db = tmp_path / 'test.db' database.build_...
import pytest import os import shutil import xarray as xr from cosima_cookbook import database from dask.distributed import Client from sqlalchemy import select, func @pytest.fixture(scope='module') def client(): client = Client() yield client client.close() def test_broken(client, tmp_path): db = tm...
Clean up dask client in indexing test
Clean up dask client in indexing test
Python
apache-2.0
OceansAus/cosima-cookbook
7d3de3aa2441739aa951aa100c057cfa878887d5
nukedb.py
nukedb.py
import sqlite3 if __name__=="__main__": conn = sqlite3.connect('auxgis.db') c = conn.cursor() try: c.execute('''DROP TABLE pos;''') except: pass try: c.execute('''DROP TABLE data;''') except: pass conn.commit()
import sqlite3 if __name__=="__main__": conn = sqlite3.connect('auxgis.db') c = conn.cursor() try: c.execute('''DROP TABLE pos;''') except: pass try: c.execute('''DROP TABLE data;''') except: pass try: c.execute('''DROP TABLE recentchanges;''') except: pass conn.commit()
Drop recent changes on nuke
Drop recent changes on nuke
Python
bsd-3-clause
TimSC/auxgis
d0fb38da0200c1b780e296d6c5767438e2f82dc8
array/sudoku-check.py
array/sudoku-check.py
# Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle def check_rows(grid): i = 0 while i < len(grid): j = 0 ref_check = {} while j < len(grid[i]): if grid[i][j] != '.' and grid[i][j] in ref_check: return False else: ref_check[grid[i][j]] = 1 ...
# Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle def check_rows(grid): i = 0 while i < len(grid): j = 0 ref_check = {} while j < len(grid[i]): if grid[i][j] != '.' and grid[i][j] in ref_check: return False else: ref_check[grid[i][j]] = 1 ...
Add check sub grid method
Add check sub grid method
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
55545a23dc209afc07ebe25c296505af50207340
yelp_kafka_tool/util/__init__.py
yelp_kafka_tool/util/__init__.py
from __future__ import print_function import json import sys from itertools import groupby def groupsortby(data, key): """Sort and group by the same key.""" return groupby(sorted(data, key=key), key) def dict_merge(set1, set2): """Joins two dictionaries.""" return dict(set1.items() + set2.items()) ...
from __future__ import print_function import json import sys from itertools import groupby def groupsortby(data, key): """Sort and group by the same key.""" return groupby(sorted(data, key=key), key) def dict_merge(set1, set2): """Joins two dictionaries.""" return dict(set1.items() + set2.items()) ...
Add brokers information to the output of kafka-info
Add brokers information to the output of kafka-info
Python
apache-2.0
anthonysandrin/kafka-utils,Yelp/kafka-utils,anthonysandrin/kafka-utils,Yelp/kafka-utils
f516749bc41dbebeb5b0ae07078af78f510a592e
lib/markdown_deux/__init__.py
lib/markdown_deux/__init__.py
#!/usr/bin/env python # Copyright (c) 2008-2010 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A small Django app that provides template tags for Markdown using the python-markdown2 library. See <http://github.com/trentm/django-markdown-deux> for more info. """ __version_in...
#!/usr/bin/env python # Copyright (c) 2008-2010 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A small Django app that provides template tags for Markdown using the python-markdown2 library. See <http://github.com/trentm/django-markdown-deux> for more info. """ __version_in...
Fix having ver info written twice (divergence). Makes "mk cut_a_release" ver update work.
Fix having ver info written twice (divergence). Makes "mk cut_a_release" ver update work.
Python
mit
douzepouze/django-markdown-tag,trentm/django-markdown-deux,gogobook/django-markdown-deux,gogobook/django-markdown-deux
c84728b57d1c8923cdadec10f132953de4c1dd21
tests/integration/conftest.py
tests/integration/conftest.py
import pytest @pytest.fixture def coinbase(): return '0xdc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd' @pytest.fixture def private_key(): return '0x58d23b55bc9cdce1f18c2500f40ff4ab7245df9a89505e9b1fa4851f623d241d' KEYFILE = '{"address":"dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd","crypto":{"cipher":"aes-128-ctr"...
import pytest from web3.utils.module_testing.math_contract import ( MATH_BYTECODE, MATH_ABI, ) from web3.utils.module_testing.emitter_contract import ( EMITTER_BYTECODE, EMITTER_ABI, ) @pytest.fixture(scope="session") def math_contract_factory(web3): contract_factory = web3.eth.contract(abi=MATH_...
Add common factory fixtures to be shared across integration tests
Add common factory fixtures to be shared across integration tests
Python
mit
pipermerriam/web3.py
564ae1eb637ec509f37ade93d4079117cc73fd58
lab_assistant/storage/__init__.py
lab_assistant/storage/__init__.py
from copy import deepcopy from simpleflake import simpleflake from lab_assistant import conf, utils __all__ = [ 'get_storage', 'store', 'retrieve', 'retrieve_all', 'clear', ] def get_storage(path=None, name='Experiment', **opts): if not path: path = conf.storage['path'] _op...
from copy import deepcopy from collections import defaultdict from simpleflake import simpleflake from lab_assistant import conf, utils __all__ = [ 'get_storage', 'store', 'retrieve', 'retrieve_all', 'clear', ] def get_storage(path=None, name='Experiment', **opts): if not path: pat...
Fix get_storage cache to hold separate entries for each experiment key
Fix get_storage cache to hold separate entries for each experiment key
Python
mit
joealcorn/lab_assistant
cd4c268b0752f85f8dadac03e28f152767ce9f54
tinycontent/templatetags/tinycontent_tags.py
tinycontent/templatetags/tinycontent_tags.py
from django import template from django.template.base import TemplateSyntaxError from tinycontent.models import TinyContent register = template.Library() class TinyContentNode(template.Node): def __init__(self, content_name, nodelist): self.content_name = content_name self.nodelist = nodelist ...
from django import template from django.template.base import TemplateSyntaxError from tinycontent.models import TinyContent register = template.Library() class TinyContentNode(template.Node): def __init__(self, content_name, nodelist): self.content_name = content_name self.nodelist = nodelist ...
Use parser.compile_filter instead of my half-baked attempt
Use parser.compile_filter instead of my half-baked attempt
Python
bsd-3-clause
dominicrodger/django-tinycontent,ad-m/django-tinycontent,watchdogpolska/django-tinycontent,ad-m/django-tinycontent,watchdogpolska/django-tinycontent,dominicrodger/django-tinycontent
1736883e6635a13aa896209e3649c9b30b87b54d
bin/create_contour.py
bin/create_contour.py
#!/usr/bin/env python3 import sys import os sys.path.append('./climatemaps') import climatemaps DATA_DIR = './website/data' def test(): for month in range(1, 13): latrange, lonrange, Z = climatemaps.data.import_climate_data(month) filepath_out = os.path.join(DATA_DIR, 'contour_cloud_' + str(m...
#!/usr/bin/env python3 import sys import os sys.path.append('./climatemaps') import climatemaps DATA_OUT_DIR = './website/data' TYPES = { 'precipitation': './data/precipitation/cpre6190.dat', 'cloud': './data/cloud/ccld6190.dat', } def main(): for data_type, filepath in TYPES.items(): for mo...
Create contour data for multiple climate data types
Create contour data for multiple climate data types
Python
mit
bartromgens/climatemaps,bartromgens/climatemaps,bartromgens/climatemaps
f7faebbd91b4dc0fcd11e10d215d752badc899d6
aspc/senate/views.py
aspc/senate/views.py
from django.views.generic import ListView from aspc.senate.models import Document, Appointment import datetime class DocumentList(ListView): model = Document context_object_name = 'documents' paginate_by = 20 class AppointmentList(ListView): model = Appointment context_object_name = 'appointments'...
from django.views.generic import ListView from aspc.senate.models import Document, Appointment import datetime class DocumentList(ListView): model = Document context_object_name = 'documents' paginate_by = 20 class AppointmentList(ListView): model = Appointment context_object_name = 'appointments'...
Change queryset filtering for positions view
Change queryset filtering for positions view
Python
mit
theworldbright/mainsite,theworldbright/mainsite,theworldbright/mainsite,aspc/mainsite,aspc/mainsite,theworldbright/mainsite,aspc/mainsite,aspc/mainsite
848d783bd988e0cdf31b690f17837ac02e77b43a
pypodio2/client.py
pypodio2/client.py
# -*- coding: utf-8 -*- from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances...
# -*- coding: utf-8 -*- from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances...
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
Python
mit
podio/podio-py
8e7feb7bc09feeca8d3fa0ea9ce6b76edec61ff1
test/contrib/test_pyopenssl.py
test/contrib/test_pyopenssl.py
from urllib3.packages import six if six.PY3: from nose.plugins.skip import SkipTest raise SkipTest('Testing of PyOpenSSL disabled') from urllib3.contrib.pyopenssl import (inject_into_urllib3, extract_from_urllib3) from ..with_dummyserver.test_https import TestHTTPS, Tes...
from nose.plugins.skip import SkipTest from urllib3.packages import six if six.PY3: raise SkipTest('Testing of PyOpenSSL disabled on PY3') try: from urllib3.contrib.pyopenssl import (inject_into_urllib3, extract_from_urllib3) except ImportError as e: raise SkipTe...
Disable PyOpenSSL tests by default.
Disable PyOpenSSL tests by default.
Python
mit
Lukasa/urllib3,matejcik/urllib3,asmeurer/urllib3,sornars/urllib3,silveringsea/urllib3,denim2x/urllib3,sornars/urllib3,Geoion/urllib3,haikuginger/urllib3,matejcik/urllib3,Geoion/urllib3,boyxuper/urllib3,urllib3/urllib3,haikuginger/urllib3,sileht/urllib3,sigmavirus24/urllib3,gardner/urllib3,silveringsea/urllib3,luca3m/ur...
edd716204f1fc3337d46b74ed5708d5d0533f586
km3pipe/__init__.py
km3pipe/__init__.py
# coding=utf-8 # Filename: __init__.py """ The extemporary KM3NeT analysis framework. """ from __future__ import division, absolute_import, print_function try: __KM3PIPE_SETUP__ except NameError: __KM3PIPE_SETUP__ = False from km3pipe.__version__ import version, version_info # noqa if not __KM3PIPE_SETUP_...
# coding=utf-8 # Filename: __init__.py """ The extemporary KM3NeT analysis framework. """ from __future__ import division, absolute_import, print_function try: __KM3PIPE_SETUP__ except NameError: __KM3PIPE_SETUP__ = False from km3pipe.__version__ import version, version_info # noqa if not __KM3PIPE_SETUP_...
Use better name for matplotlib style
Use better name for matplotlib style
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
6559de6724c5e53bed3599c6ec21c968e3a71b83
openspending/tests/controllers/test_rest.py
openspending/tests/controllers/test_rest.py
from openspending.model.dataset import Dataset from openspending.tests.base import ControllerTestCase from openspending.tests.helpers import load_fixture from pylons import url class TestRestController(ControllerTestCase): def setup(self): super(TestRestController, self).setup() load_fixture('cr...
from openspending.model.dataset import Dataset from openspending.tests.base import ControllerTestCase from openspending.tests.helpers import load_fixture from pylons import url class TestRestController(ControllerTestCase): def setup(self): super(TestRestController, self).setup() load_fixture('cr...
Remove test for rest controller.
Remove test for rest controller.
Python
agpl-3.0
nathanhilbert/FPA_Core,pudo/spendb,nathanhilbert/FPA_Core,openspending/spendb,spendb/spendb,openspending/spendb,CivicVision/datahub,openspending/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,johnjohndoe/spendb,spendb/spendb,spendb/spendb,USStateDept/FPA_Core,pudo/spendb,johnjohndoe/spendb,CivicVision/datahub,USStat...
42584d8504daab56ced4447ccc08723999c5ca5b
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ivan Sobolev # Copyright (c) 2016 Ivan Sobolev # # License: MIT # """This module exports the Bemlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Bemlint(NodeLinter): """Provides an ...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ivan Sobolev # Copyright (c) 2016 Ivan Sobolev # # License: MIT # """This module exports the Bemlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Bemlint(NodeLinter): """Provides an ...
Mark usage of temporary files in `cmd`
Mark usage of temporary files in `cmd` The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.
Python
mit
DesTincT/SublimeLinter-contrib-bemlint
e1fe3acf94e1358155ce67f6b38c02feb75df074
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Dmitry Tsoy # Copyright (c) 2013 Dmitry Tsoy # # License: MIT # """This module exports the Phpcs plugin class.""" from SublimeLinter.lint import Linter class Phpcs(Linter): """Provides an interface to phpcs.""...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Dmitry Tsoy # Copyright (c) 2013 Dmitry Tsoy # # License: MIT # """This module exports the Phpcs plugin class.""" from SublimeLinter.lint import Linter class Phpcs(Linter): """Provides an interface to phpcs.""...
Remove the executable property to allow override.
Remove the executable property to allow override. This problem was discussed here : SublimeLinter/SublimeLinter#455 If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder)...
Python
mit
SublimeLinter/SublimeLinter-phpcs
3a4a67a34359c70ac9f3d0f19db3521f6bea7e48
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Andrew Grim # Copyright (c) 2014 Andrew Grim # # License: MIT # """This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Andrew Grim # Copyright (c) 2014 Andrew Grim # # License: MIT # """This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to...
Support Additional Error Output Formats
Support Additional Error Output Formats Make the 'near' match group more flexible to support multiple error output styles for some syntax errors. Examples: Error: Could not parse for environment production: Syntax error at 'class' at line 27 Error: Could not parse for environment production: Syntax error at ...
Python
mit
travisgroth/SublimeLinter-puppet
e73db09c343d7159c09783c514a406fc2fb3f04f
test_py3/pointfree_test_py3.py
test_py3/pointfree_test_py3.py
from unittest import TestCase from pointfree import * def kwonly_pure_func(a, b, *, c): return a + b + c @partial def kwonly_func(a, b, *, c): return a + b + c class KwOnlyArgsCase(TestCase): def testNormalApplication(self): self.assertEqual(kwonly_func(1,2,c=3), 6) def testPartialApplicatio...
from unittest import TestCase from pointfree import * def kwonly_pure_func(a, b, *, c): return a + b + c @partial def kwonly_func(a, b, *, c): return a + b + c @partial def kwonly_defaults_func(a, b, *, c=3): return a + b + c @partial def kwonly_varkw_func(a, b, *, c, **kwargs): return (a + b + c, k...
Add tests for more keyword-only arguments behavior
Add tests for more keyword-only arguments behavior Test for handling of default keyword-only argument values and mixing keyword-only arguments with variable keyword arguments lists.
Python
apache-2.0
markshroyer/pointfree,markshroyer/pointfree
9294e302e4987531ac61db0a952fad22d8785e82
lowfat/validator.py
lowfat/validator.py
""" Validator functions """ from urllib import request from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" online_resource = request.urlopen(url) # Need to test if website didn't redirect the request to another resource....
""" Validator functions """ from urllib import request from urllib.error import HTTPError from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" try: online_resource = request.urlopen(url) except HTTPError as excepti...
Handle HTTP Error 410 when checking blog post
Handle HTTP Error 410 when checking blog post
Python
bsd-3-clause
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
9ef096bb067d062ece8bf4310c11759c90e60202
triggers/makewaves.py
triggers/makewaves.py
#!/usr/bin/env python wavelist = [] for p in range(48): for s in range(24): wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'} wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1) wave['data'] = {'id': p * 24 + s} wavelist.append(wave) import json import stru...
#!/usr/bin/env python import struct wavelist = [] for s in range(12): wave = {'method': 'POST'} wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1) wave['name'] = 'Scene {0:02}'.format(s + 1) wave['data'] = '' wavelist.append(wave) for wave in wavelist: reqdata = '\n'.joi...
Update format of wave file generator.
Update format of wave file generator.
Python
apache-2.0
lordjabez/light-maestro,lordjabez/light-maestro,lordjabez/light-maestro,lordjabez/light-maestro
cbef288c363c70d6085f7f9390aec126919376bc
bin/isy_showevents.py
bin/isy_showevents.py
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import keyring import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read('isy.cfg') server = ISYEvent() # you can subscribe to multiple devices # server.subscrib...
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import keyring import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/isy.cfg')) server = ISYEvent() # you can subscribe to multiple devices...
Move config file to user home directory
Move config file to user home directory
Python
bsd-2-clause
fxstein/ISYlib-python
35555b568d926caef8a7ad3471e3dd5ba8624c0e
norsourceparser/core/constants.py
norsourceparser/core/constants.py
REDUCED_RULE_VALENCY_TOKEN = 0 REDUCED_RULE_POS = 1 REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2 REDUCED_RULE_GLOSSES = 3
REDUCED_RULE_POS = 1 REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2 REDUCED_RULE_GLOSSES = 3 REDUCED_RULE_VALENCY = 4
Rename VALENCY constant and change index
Rename VALENCY constant and change index
Python
mit
Typecraft/norsourceparser
838063cc08da66a31666f798437b8dcdde0286f0
mpf/config_players/flasher_player.py
mpf/config_players/flasher_player.py
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ =...
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager from mpf.core.utility_functions import Util class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' ...
Allow list of flashers as show token value
Allow list of flashers as show token value
Python
mit
missionpinball/mpf,missionpinball/mpf
67b03b45c338143d0e1496dc0c48046ca000b8e8
tests/integration/aiohttp_utils.py
tests/integration/aiohttp_utils.py
# flake8: noqa import asyncio import aiohttp from aiohttp.test_utils import TestClient async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) response = a...
# flake8: noqa import asyncio import aiohttp from aiohttp.test_utils import TestClient async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) response = a...
Add output option to use response.content stream
Add output option to use response.content stream
Python
mit
kevin1024/vcrpy,kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy
0983986f6fc75b1acf0e76255844f7c96ba9838f
pip_refresh/__init__.py
pip_refresh/__init__.py
from functools import partial import subprocess import requests def get_pkg_info(pkg_name, session): r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,)) if r.status_code == requests.codes.ok: return r.json else: raise ValueError('Package %r not found on PyPI.' % (pkg_name,...
from functools import partial import subprocess import multiprocessing import requests def get_pkg_info(pkg_name, session): r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,)) if r.status_code == requests.codes.ok: return r.json else: raise ValueError('Package %r not found...
Use multiprocessing to get quicker updates from PyPI.
Use multiprocessing to get quicker updates from PyPI.
Python
bsd-2-clause
suutari/prequ,suutari/prequ,suutari-ai/prequ
2994466719ce4f096d68a24c2e20fdd9ffc4232d
project/api/backends.py
project/api/backends.py
# Third-Party from django_filters.rest_framework.backends import DjangoFilterBackend from dry_rest_permissions.generics import DRYPermissionFiltersBase class CoalesceFilterBackend(DjangoFilterBackend): """Support Ember Data coalesceFindRequests.""" def filter_queryset(self, request, queryset, view): ...
# Third-Party from django_filters.rest_framework.backends import DjangoFilterBackend class CoalesceFilterBackend(DjangoFilterBackend): """Support Ember Data coalesceFindRequests.""" def filter_queryset(self, request, queryset, view): raw = request.query_params.get('filter[id]') if raw: ...
Remove unused score filter backend
Remove unused score filter backend
Python
bsd-2-clause
dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api
693ce5f8b1344f072e1f116ebf3ad79ffaad42b6
fungui.py
fungui.py
#!/usr/bin/env python """ fungui is a software to help measuring the shell of a fungi. """ # Import modules from PyQt4 import QtGui, QtCore
#!/usr/bin/env python """ fungui is a software to help measuring the shell of a fungi. """ # Import modules from PyQt4 import QtGui, QtCore import sys # Global variables FRAME_WIDTH = 1020 FRAME_HEIGHT = 480 class MainWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) ...
Create a frame with a menu bar.
Create a frame with a menu bar. The software will have several buttons, but the idea of the menu bar is to have redundancy on the commands and to inform the user of the shortcuts.
Python
bsd-3-clause
leouieda/funghi
38ceb6d04f7b09b3ab29468c2fa9ccc94e1b5dc5
casepro/pods/views.py
casepro/pods/views.py
from __future__ import unicode_literals import json from django.http import JsonResponse from casepro.pods import registry def read_pod_data(request, index): """Delegates to the `read_data` function of the correct pod.""" if request.method != 'GET': return JsonResponse({'reason': 'Method not allowed...
from __future__ import unicode_literals import json from django.http import JsonResponse from casepro.cases.models import Case, CaseAction from casepro.pods import registry def read_pod_data(request, index): """Delegates to the `read_data` function of the correct pod.""" if request.method != 'GET': ...
Change case field to case_id in error message
Change case field to case_id in error message
Python
bsd-3-clause
xkmato/casepro,praekelt/casepro,rapidpro/casepro,rapidpro/casepro,rapidpro/casepro,praekelt/casepro,xkmato/casepro,praekelt/casepro
d3fc9414effb4c49104cc4a0888872d9eb4c20a9
py/garage/garage/sql/utils.py
py/garage/garage/sql/utils.py
__all__ = [ 'ensure_only_one_row', 'insert_or_ignore', ] def ensure_only_one_row(rows): row = rows.fetchone() if row is None or rows.fetchone() is not None: raise KeyError return row def insert_or_ignore(conn, table, values): conn.execute(table.insert().prefix_with('OR IGNORE'), valu...
__all__ = [ 'add_if_not_exists_clause', 'ensure_only_one_row', 'insert_or_ignore', ] from garage import asserts from sqlalchemy.schema import CreateIndex def add_if_not_exists_clause(index, engine): # `sqlalchemy.Index.create()` does not take `checkfirst` for reasons # that I am unaware of, and ...
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"
Python
mit
clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage
04b785a9761e4d49c3f0e3dfc5d3df06cd3209a1
coffer/utils/ccopy.py
coffer/utils/ccopy.py
import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: os.popen("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else:...
import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: os.system("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else...
Copy now waits for files to be copies over
Copy now waits for files to be copies over
Python
mit
Max00355/Coffer
0434baddfc2eb3691180e6fa461be3323852eea9
clubadm/middleware.py
clubadm/middleware.py
from django.http import Http404 from django.utils import timezone from clubadm.models import Member, Season class SeasonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs: year = int(view_kwargs["year"]) try: ...
from django.http import Http404 from django.utils import timezone from clubadm.models import Member, Season class SeasonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs: year = int(view_kwargs["year"]) try: ...
Handle an authentication edge case
Handle an authentication edge case
Python
mit
clubadm/clubadm,clubadm/clubadm,clubadm/clubadm
d6bec06d22eb8337ed22a536389c6f4ca794106a
py/templates.py
py/templates.py
import os.path import jinja2 import configmanager configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs"))) templateConfig = configs["templates"] templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"])) cla...
import os.path import jinja2 import configmanager configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs"))) templateConfig = configs["templates"] templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"])) cla...
Add paramater for template path
Add paramater for template path
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
1339be71399a7fc8efaea4f2bd892f1b54ced011
libcontextsubscriber/multithreading-tests/stress-test/provider.py
libcontextsubscriber/multithreading-tests/stress-test/provider.py
#!/usr/bin/python """A test provider for the stress testing.""" # change registry this often [msec] registryChangeTimeout = 2017 from ContextKit.flexiprovider import * import gobject import time import os def update(): t = time.time() dt = int(1000*(t - round(t))) gobject.timeout_add(1000 - dt, update)...
#!/usr/bin/python """A test provider for the stress testing.""" # change registry this often [msec] registryChangeTimeout = 2017 from ContextKit.flexiprovider import * import gobject import time import os def update(): t = time.time() dt = int(1000*(t - round(t))) gobject.timeout_add(1000 - dt, update)...
Fix stress test to avoid cdb bus error bug ref 125505
Fix stress test to avoid cdb bus error bug ref 125505 Signed-off-by: Marja Hassinen <97dfd0cfe579e2c003b71e95ee20ee035e309879@nokia.com>
Python
lgpl-2.1
rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck
312f6d380ed81b420878bb32ea996fef14ba3f6d
run_doctests.py
run_doctests.py
if __name__ == '__main__': import doctest from lesion import trace doctest.testmod(trace)
if __name__ == '__main__': import doctest from lesion import lifio, stats, trace map(doctest.testmod, [lifio, stats, trace])
Add new modules to doctests
Add new modules to doctests
Python
bsd-3-clause
jni/lesion
ff5da3c3ccb378772e073a1020d3a7fcee72d7e4
scripts/install_devplatforms.py
scripts/install_devplatforms.py
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
Use stable dev/platforms for CI
Use stable dev/platforms for CI
Python
apache-2.0
platformio/platformio-core,platformio/platformio-core,platformio/platformio
59f5007787b87a37b5e5669a75d39d1d7e88e0e9
redfish/__init__.py
redfish/__init__.py
# -*- coding: utf-8 -*- # 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, softw...
# -*- coding: utf-8 -*- # 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, softw...
Fix pbr if running without git or sdist
Fix pbr if running without git or sdist
Python
apache-2.0
uggla/python-redfish,bcornec/python-redfish,bcornec/python-redfish,uggla/python-redfish,uggla/python-redfish,bcornec/python-redfish
91edea41858c1171168b8e2ed77f97ea19c8f684
public/sentry/env_remote_user_middleware.py
public/sentry/env_remote_user_middleware.py
import os from django.contrib.auth.middleware import RemoteUserMiddleware class EnvRemoteUserMiddleware(RemoteUserMiddleware): header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
import os from django.contrib.auth.middleware import RemoteUserMiddleware class EnvRemoteUserMiddleware(RemoteUserMiddleware): header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER') def configure_user(user): if 'REMOTE_USER_EMAIL_SUFFIX' in os.environ: user.email = "{0}{1}".format(u...
Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX
sentry: Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX
Python
mit
3ofcoins/docker-images,3ofcoins/docker-images
43d14f73055643a2e4921a58aa1bf5e14fdf8e74
linter.py
linter.py
import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' ...
import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' ...
Update regex to include filename capture group.
Update regex to include filename capture group.
Python
mit
lavrton/SublimeLinter-contrib-tslint
b7377196cdd05d9d6d481f7b93308189c4524c52
sfm/api/filters.py
sfm/api/filters.py
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter from ui.models import Warc, Seed, Harvest from django_filters import Filter from django_filters.fields import Lookup class ListFilter(Filter): def filter(self, qs, value): return super(ListFilter, self).filter(qs, Lookup(value.split(u",")...
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter from ui.models import Warc, Seed, Harvest from django_filters import Filter from django_filters.fields import Lookup class ListFilter(Filter): def filter(self, qs, value): return super(ListFilter, self).filter(qs, Lookup(value.split(u",")...
Fix to take into account history in API queries.
Fix to take into account history in API queries.
Python
mit
gwu-libraries/sfm,gwu-libraries/sfm-ui,gwu-libraries/sfm,gwu-libraries/sfm,gwu-libraries/sfm-ui,gwu-libraries/sfm-ui,gwu-libraries/sfm-ui
b44345efada2a89423c89ec88a24f1dbe97ef562
viewer.py
viewer.py
# Nessus results viewing tools # # Developed by Felix Ingram, f.ingram@gmail.com, @lllamaboy # http://www.github.com/nccgroup/nessusviewer # # Released under AGPL. See LICENSE for more information if __name__ == '__main__': import wx from controller import ViewerController app = wx.App(0) Vi...
# Nessus results viewing tools # # Developed by Felix Ingram, f.ingram@gmail.com, @lllamaboy # http://www.github.com/nccgroup/nessusviewer # # Released under AGPL. See LICENSE for more information if __name__ == '__main__': import sys try: import wx except ImportError: print("""...
Add simple test for whether WX is installed. Display download link if not.
Add simple test for whether WX is installed. Display download link if not.
Python
agpl-3.0
nccgroup/lapith
3046eaf265d015c2257efa8066a04c26ddd4448e
search.py
search.py
import io import getopt import sys import pickle def usage(): print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results") if __name__ == '__main__': dict_file = postings_file = query_file = output_file = None try: opts, args = getopt.getopt(sys.argv[1:], '...
import io import getopt import sys import pickle def usage(): print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results") if __name__ == '__main__': dict_file = postings_file = query_file = output_file = None try: opts, args = getopt.getopt(sys.argv[1:], '...
Add todo for seeking and reading
Add todo for seeking and reading
Python
mit
ikaruswill/boolean-retrieval,ikaruswill/vector-space-model
592a2c778bf7c87b7aad6f9ba14c1ba83da033e8
scoring_engine/web/views/services.py
scoring_engine/web/views/services.py
from flask import Blueprint, render_template, flash from flask_login import login_required, current_user mod = Blueprint('services', __name__) @mod.route('/services') @login_required def home(): current_team = current_user.team if not current_user.is_blue_team: flash('Only blue teams can access servi...
from flask import Blueprint, render_template, url_for, redirect from flask_login import login_required, current_user from scoring_engine.models.service import Service mod = Blueprint('services', __name__) @mod.route('/services') @login_required def home(): current_team = current_user.team if not current_user...
Add unauthorize to service template
Add unauthorize to service template Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
cdfbd5bab75de151e2e9f3f36eb18741ddb862c1
sifter.py
sifter.py
import os import requests import re import json NUM_REGEX = r'\#([0-9]+)' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers...
import os import requests import re import json NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(a...
Change the Sifter issue number matching
Change the Sifter issue number matching Now it's only 3-5 digits, optionally with the hash, and only as a standalone word.
Python
bsd-2-clause
honza/nigel
74eb842870424a22334fee35881f1b6c877da8e6
scot/backend_mne.py
scot/backend_mne.py
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2016 SCoT Development Team """Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def ...
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2016 SCoT Development Team """Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def ...
Use regularized covariance in CSP by default
Use regularized covariance in CSP by default
Python
mit
scot-dev/scot,cbrnr/scot,mbillingr/SCoT,cbrnr/scot,scot-dev/scot,cle1109/scot,cle1109/scot,mbillingr/SCoT
322ccf3bb4197a466ac5022ae2098a82bbeab6f1
sorting_algorithms/selection_sort.py
sorting_algorithms/selection_sort.py
def selection_sort(L): """ :param L: unsorted list :return: this is a method, there is no return function. The method sorts a list using selection sort algorithm >>> L = [2, 7, 5, 3] >>> selection_sort(L) >>> L [2, 3, 5, 7] """ end = len(L) # Find the index of the smalle...
def selection_sort(L): """ (list) -> NoneType Sort list from smallest to largest using selection sort algorithm :param L: unsorted list >>> L = [2, 7, 5, 3] >>> selection_sort(L) >>> L [2, 3, 5, 7] """ end = len(L) # Find the index of the smallest element in L[i:] and sw...
Improve selection sort algorithm's documentation
Improve selection sort algorithm's documentation
Python
mit
IamGianluca/algorithms_collection,IamGianluca/algorithms
ac30f52aff51dce892e79ce773e84f2458635d1c
digestive/entropy.py
digestive/entropy.py
from collections import Counter from math import log2 from digestive import Sink # TODO: stash intermediate histograms in multiple Counters? # TODO: output as a spark # TODO: output as plot class Entropy(Sink): def __init__(self): super().__init__('entropy') self.length = 0 self.counter =...
from collections import Counter from math import log2 from digestive import Sink class Entropy(Sink): def __init__(self): super().__init__('entropy') self.length = 0 self.counter = Counter() def update(self, data): self.length += len(data) self.counter.update(data) ...
Remove TODO's converted to issues
Remove TODO's converted to issues
Python
isc
akaIDIOT/Digestive
bada6787aa111feac1df32952a8732400632f81d
doc/examples/plot_pyramid.py
doc/examples/plot_pyramid.py
""" ==================== Build image pyramids ==================== The `build_gaussian_pyramid` function takes an image and yields successive images shrunk by a constant scale factor. Image pyramids are often used, e.g., to implement algorithms for denoising, texture discrimination, and scale- invariant detection. """...
""" ==================== Build image pyramids ==================== The `pyramid_gaussian` function takes an image and yields successive images shrunk by a constant scale factor. Image pyramids are often used, e.g., to implement algorithms for denoising, texture discrimination, and scale- invariant detection. """ imp...
Update name of pyramid function in pyramid example description
Update name of pyramid function in pyramid example description
Python
bsd-3-clause
blink1073/scikit-image,warmspringwinds/scikit-image,keflavich/scikit-image,almarklein/scikit-image,blink1073/scikit-image,chintak/scikit-image,robintw/scikit-image,ajaybhat/scikit-image,ClinicalGraphics/scikit-image,SamHames/scikit-image,ofgulban/scikit-image,newville/scikit-image,emon10005/scikit-image,michaelaye/scik...
8f1b473e2dab982e989e9a041aa14e31050d2f4b
scripts/promote_orga.py
scripts/promote_orga.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Promote a user to organizer status. :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.database import db from bootstrap.helpers import promote_orga from bootstrap.util import app_context, get_con...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Promote a user to organizer status. :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.orga import service as orga_service from bootstrap.util import app_context, get_config_name_from_env...
Use service in script to promote a user to organizer
Use service in script to promote a user to organizer
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
499ad0cb7147f705ebf83604b9e0873b5b0edb61
api/rest/scrollingpaginator.py
api/rest/scrollingpaginator.py
from rest_framework import pagination from amcat.tools import amcates from rest_framework.response import Response from django.core.urlresolvers import reverse from rest_framework.utils.urls import replace_query_param class ScrollingPaginator(pagination.BasePagination): def paginate_queryset(self, queryset, requ...
from rest_framework import pagination from amcat.tools import amcates from rest_framework.response import Response from django.core.urlresolvers import reverse from rest_framework.utils.urls import replace_query_param class ScrollingPaginator(pagination.BasePagination): def paginate_queryset(self, queryset, requ...
Allow set scroll timeout param
Allow set scroll timeout param
Python
agpl-3.0
amcat/amcat,amcat/amcat,amcat/amcat,amcat/amcat,amcat/amcat,amcat/amcat
99c00b309e89ceb32528c217e308b91f94a56e2b
cogs/command_log.py
cogs/command_log.py
import logging class CommandLog: """A simple cog to log commands executed.""" def __init__(self): self.log = logging.getLogger('liara.command_log') async def on_command(self, ctx): self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" in {0.guild}'.format(ctx)) def se...
import logging class CommandLog: """A simple cog to log commands executed.""" def __init__(self): self.log = logging.getLogger('liara.command_log') async def on_command(self, ctx): kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()]) args = 'with argumen...
Make the command log more detailed
Make the command log more detailed
Python
mit
Thessia/Liara