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
3fe6d183b3c168da73f9fb65a9b52ffe1d79e6e1
txkazoo/test/test_version.py
txkazoo/test/test_version.py
import txkazoo from twisted.trial.unittest import SynchronousTestCase class VersionTests(SynchronousTestCase): """ Tests for programmatically acquiring the version of txkazoo. """ def test_both_names(self): """ The version is programmatically avaialble on the ``txkazoo`` modul...
# Copyright 2013-2014 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Add copyright header to test
Add copyright header to test
Python
apache-2.0
rackerlabs/txkazoo
5d93d1fb887d76d6fbe0a2f699e973ed9f6e7556
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
0a09dbb6cc0104c9e1d3e504f84a70f729d14af1
tests/unit/test_utils.py
tests/unit/test_utils.py
# -*- coding: utf-8 -*- """ radish ~~~~~~ Behavior Driven Development tool for Python - the root from red to green Copyright: MIT, Timo Furrer <tuxtimo@gmail.com> """ import pytest import radish.utils as utils @pytest.mark.parametrize('basedirs, expected_basedirs', [ (['foo', 'bar'], ['foo', ...
# -*- coding: utf-8 -*- """ radish ~~~~~~ Behavior Driven Development tool for Python - the root from red to green Copyright: MIT, Timo Furrer <tuxtimo@gmail.com> """ import pytest import radish.utils as utils @pytest.mark.parametrize('basedirs, expected_basedirs', [ (['foo', 'bar'], ['foo', ...
Add a test for utils.make_unique_obj_list
Add a test for utils.make_unique_obj_list
Python
mit
radish-bdd/radish,radish-bdd/radish
f693f09bfedc4981557741a8ac445c160faab65d
assisstant/main.py
assisstant/main.py
#!/usr/bin/env python3 import sys from PyQt5.QtWidgets import QApplication from keyboard.ui.widgets import KeyboardWindow if __name__ == '__main__': app = QApplication([]) window = KeyboardWindow() window.showMaximized() sys.exit(app.exec())
#!/usr/bin/env python3 import sys import signal from PyQt5.QtWidgets import QApplication from keyboard.ui.widgets import KeyboardWindow if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) window = KeyboardWindow() window.showMaximized() sys.exit(app.exec())
Add signal handler to quit the application
Add signal handler to quit the application
Python
apache-2.0
brainbots/assistant
015ba19ceefacd82e68aa7a023e33140e868f5a6
cybox/common/defined_object.py
cybox/common/defined_object.py
class DefinedObject(object): pass
from StringIO import StringIO class DefinedObject(object): def to_xml(self): """Export an object as an XML String""" s = StringIO() self.to_obj().export(s, 0) return s.getvalue()
Add utility method to DefinedObject base class
Add utility method to DefinedObject base class
Python
bsd-3-clause
CybOXProject/python-cybox
b9671e96e40b38d0662dbe0e32dca0ca0c5fe62e
tensor2tensor/rl/trainer_model_based_test.py
tensor2tensor/rl/trainer_model_based_test.py
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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...
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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...
Add a test for the AE experiment
Add a test for the AE experiment
Python
apache-2.0
tensorflow/tensor2tensor,tensorflow/tensor2tensor,vthorsteinsson/tensor2tensor,tensorflow/tensor2tensor,vthorsteinsson/tensor2tensor,tensorflow/tensor2tensor,vthorsteinsson/tensor2tensor,tensorflow/tensor2tensor,vthorsteinsson/tensor2tensor
fff3e2ed2ef1bb3f87f31178ef03d6752f2dc152
salt/modules/cmd.py
salt/modules/cmd.py
''' Module for shelling out commands, inclusion of this module should be configurable for security reasons ''' def echo(text): ''' Return a string - used for testing the connection ''' return text
''' Module for shelling out commands, inclusion of this module should be configurable for security reasons ''' def echo(text): ''' Return a string - used for testing the connection ''' print 'Echo got called!' return text
Add a debugging line to the echo command
Add a debugging line to the echo command
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
a5338e46ffd0684b2d4f21708176cf6c8bbdcc92
tests/changes/api/test_author_build_index.py
tests/changes/api/test_author_build_index.py
from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.fo...
from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.fo...
Test self request without authentication
Test self request without authentication
Python
apache-2.0
wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes
b4aae8d7f87bd3f1bb27610440c20ab1110d2b3a
dbaas/util/update_instances_with_offering.py
dbaas/util/update_instances_with_offering.py
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: ...
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: ...
Fix script to update offering on instances
Fix script to update offering on instances
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
a18ae589f8217bc26bf1d4a8841c637354aedbaa
ispmgr/wwwdomain.py
ispmgr/wwwdomain.py
import json import api class WWWDomain(api.API): def __init__(self, auth_handler): self.url = auth_handler.url self.sessid = auth_handler.sessid self.func = 'wwwdomain.edit' self.out = 'json' self.params = { 'auth' : self.sessid, 'out' : self.out, ...
import json import api class WWWDomain(api.API): def __init__(self, auth_handler): self.url = auth_handler.url self.sessid = auth_handler.sessid self.func = 'wwwdomain.edit' self.out = 'json' self._clear_params() def _clear_params(self): try: self.p...
Clear parameters before editing/adding. Before it was been unpossible to call two functions in sequence.
Clear parameters before editing/adding. Before it was been unpossible to call two functions in sequence.
Python
mit
jakubjedelsky/python-ispmgr
c0a341bb285e9906747c1f872e3b022a3a491044
falmer/events/filters.py
falmer/events/filters.py
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter, BooleanFilter, ModelChoiceFilter from falmer.events.models import Curator from . import models class EventFilterSet(FilterSet): class Meta: model = models.Event fields = ( 'title', 'venue', 't...
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter, BooleanFilter, ModelChoiceFilter from falmer.events.models import Curator from . import models class EventFilterSet(FilterSet): class Meta: model = models.Event fields = ( 'title', 'venue', 't...
Add type filter by slug
Add type filter by slug
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
a7f761d662b98dea2b16f711e7d17ad826f491af
onestop/test_gtfs.py
onestop/test_gtfs.py
"""geohash unit tests.""" import unittest import os import json import gtfs class TestGTFSReader(unittest.TestCase): test_gtfs = os.path.join('examples', 'sample-feed.zip') def test_readcsv(self): expect = { 'stop_lat': '36.425288', 'zone_id': '', 'stop_lon': '-117.133162', 'stop...
"""geohash unit tests.""" import unittest import os import json import gtfs class TestGTFSReader(unittest.TestCase): test_gtfs = os.path.join('examples', 'sample-feed.zip') def test_readcsv(self): expect = { 'stop_lat': '36.425288', 'zone_id': '', 'stop_lon': '-117.133162', 'stop...
Remove this test for now
Remove this test for now
Python
mit
srthurman/transitland-python-client,transitland/transitland-python-client
dd58dbbbdb9b3a9479fa5db38a4e4038a6514fef
configReader.py
configReader.py
class ConfigReader(): def __init__(self): self.keys={} #Read Keys from file def readKeys(self): keysFile=open("config.txt","r") fileLines=keysFile.readlines() keysFile.close() self.keys.clear() for item in fileLines: #If last char is \n if (item[-1]=='\n'): item=item[:-1] #If a commented l...
class ConfigReader(): def __init__(self): self.keys={} #Read Keys from file def readKeys(self): keysFile=open("config.txt","r") fileLines=keysFile.readlines() keysFile.close() self.keys.clear() for item in fileLines: #If last char is \n if (item[-1]=='\n'): item=item[:-1] #If a commented l...
Change 'pass' statements to 'continue' statements.
Change 'pass' statements to 'continue' statements.
Python
mit
ollien/PyConfigReader
a8966a4d3f9a160af3865b8cadb26e58eb36fd64
src/database/__init__.py
src/database/__init__.py
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker session = None def init_session(connection_string=None, drop=False): if connection_string is None: connection_string = 'sqlite://' from database.model import Base global session if drop: t...
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import StaticPool session = None def init_session(connection_string=None, drop=False): if connection_string is None: engine = create_engine('sqlite://', echo...
Fix the database session init to work with the flask debug server.
Fix the database session init to work with the flask debug server. The debug webserver consists of two parts: the watcher that watches the files for changes and the worker that is forked and will be restarted after each modification. Sqlachemy uses a SingletonPool that will not work with this if the database was initi...
Python
bsd-3-clause
janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system
0dc3e4ffe86f25697799b8092822a8d77a22493b
pi_mqtt_gpio/__init__.py
pi_mqtt_gpio/__init__.py
import sys print("FATAL ERROR: The file at pi_mqtt_gpio/__init__.py should be replaced us" "ing 'make schema' before packaging.") sys.exit(1)
import yaml CONFIG_SCHEMA = yaml.load(""" mqtt: type: dict required: yes schema: host: type: string empty: no required: no default: localhost port: type: integer min: 1 max: 65535 required: no default: 1883 user: type: string required:...
Add schema to repo for now
Add schema to repo for now
Python
mit
flyte/pi-mqtt-gpio
d0c284139fe475a62fa53cde7e3e20cf2cc2d977
plugins/FileHandlers/STLWriter/__init__.py
plugins/FileHandlers/STLWriter/__init__.py
from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" } } def register(app): return STLWriter.STLWriter()
from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" }, 'mesh_writer': { 'extension': 'stl', 'description': 'STL File' } } def register(app): return STLWriter.STLWriter()
Add writer metadata to the STL writer plugin so it can be used in Cura
Add writer metadata to the STL writer plugin so it can be used in Cura
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
6f0a35372d625f923b9093194540cf0b0e9f054d
platformio_api/__init__.py
platformio_api/__init__.py
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import json import logging.config import os from time import tzset VERSION = (0, 3, 0) __version__ = ".".join([str(s) for s in VERSION]) __title__ = "platformio-api" __description__ = ("An API for PlatformIO") __url__ = "https://github.com/iv...
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import json import logging.config import os from time import tzset VERSION = (0, 3, 0) __version__ = ".".join([str(s) for s in VERSION]) __title__ = "platformio-api" __description__ = ("An API for PlatformIO") __url__ = "https://github.com/iv...
Increase repo size to 20Mb
Increase repo size to 20Mb
Python
apache-2.0
orgkhnargh/platformio-api,platformio/platformio-api
72b899fd0ae8bd07edf454d410e65ff00a9ca772
generic_links/models.py
generic_links/models.py
# -*- coding: UTF-8 -*- from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ c...
# -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get us...
Update for custom user model support
Update for custom user model support
Python
bsd-3-clause
matagus/django-generic-links,matagus/django-generic-links
56d1416a486f48fcbcf425d535268dec19715f2e
blueplayer/__main__.py
blueplayer/__main__.py
import sys import serial import threading from blueplayer import blueplayer def main(): args = sys.argv[1:] # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyAMA0" else: port = args[0] player = None with serial.Serial(port) as serial_port:...
import sys import serial import threading from blueplayer import blueplayer def main(): args = sys.argv[1:] # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyS0" else: port = args[0] player = None with serial.Serial(port, 19200) as serial_...
Update serial port and baud rate
Update serial port and baud rate
Python
mit
dylwhich/rpi-ipod-emulator
851e515379a5da66b4171f5340b910a2db84d0f0
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ilya Akhmadullin # Copyright (c) 2013 Ilya Akhmadullin # # License: MIT # """This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ilya Akhmadullin # Copyright (c) 2013 Ilya Akhmadullin # # License: MIT # """This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to...
Use the config_file attribute to find .jscs.json
Use the config_file attribute to find .jscs.json
Python
mit
roberthoog/SublimeLinter-jscs,SublimeLinter/SublimeLinter-jscs
c3ada10657efa7435564a1d6f8ff7afbfb585f54
pombola/nigeria/tests.py
pombola/nigeria/tests.py
import unittest import doctest from . import views from django.test import TestCase from nose.plugins.attrib import attr # Needed to run the doc tests in views.py def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(views)) return suite @attr(country='nigeria') class HomeViewTes...
import unittest import doctest from . import views from django.test import TestCase from nose.plugins.attrib import attr from pombola.info.models import InfoPage # Needed to run the doc tests in views.py def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(views)) return suite ...
Add a regression test for displaying escaped HTML in the blog
NG: Add a regression test for displaying escaped HTML in the blog A fixed version of the test that Chris Mytton suggested in: https://github.com/mysociety/pombola/pull/1587
Python
agpl-3.0
patricmutwiri/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,ken-muturi/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,mysociety/pombol...
6ef289403b4d88bc5e1a70568133924de54c2b9f
pyang/plugins/bbf.py
pyang/plugins/bbf.py
"""BBF usage guidelines plugin See BBF Assigned Names and Numbers at https://wiki.broadband-forum.org/display/BBF/Assigned+Names+and+Numbers#AssignedNamesandNumbers-URNNamespaces """ import optparse from pyang import plugin from pyang.plugins import lint def pyang_plugin_init(): plugin.register_plugin(BBFPlugin(...
"""BBF usage guidelines plugin See BBF Assigned Names and Numbers at https://wiki.broadband-forum.org/display/BBF/Assigned+Names+and+Numbers#AssignedNamesandNumbers-URNNamespaces """ import optparse from pyang import plugin from pyang.plugins import lint def pyang_plugin_init(): plugin.register_plugin(BBFPlugin(...
Set the parent class 'ensure_hyphenated_names' and set 'ctx.max_line_len' to 70
Set the parent class 'ensure_hyphenated_names' and set 'ctx.max_line_len' to 70 This is to match the settings that BBF uses when validating its modules. The max_line_len setting won't override an explicit --max-line-len from the command line.
Python
isc
mbj4668/pyang,mbj4668/pyang
dc6af73616163463bf2c5feac97ac1473ea76e07
proj/proj/models/user.py
proj/proj/models/user.py
# coding: utf-8 import datetime from ._base import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True) email = db.Column(db.String(50)) avatar = db.Column(db.String(200)) created_at = db.Column(db.DateTime, default=datetime.datetime.no...
# coding: utf-8 import datetime from ._base import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True) email = db.Column(db.String(50)) avatar = db.Column(db.String(200)) password = db.Column(db.String(200)) created_at = db.Column(...
Add password to User model.
Add password to User model.
Python
mit
1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost
1a0339b85d852526c184eeace73021fc7d68b2c6
python_dispatcher.py
python_dispatcher.py
import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', a...
import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas import ppp_spell_checker #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.co...
Fix name of spell checker.
Fix name of spell checker.
Python
cc0-1.0
ProjetPP/Deployment,ProjetPP/Deployment,ProjetPP/Deployment
89b54d9c7fec213465446148e39612a2ac659ca2
test/common/test_openstack.py
test/common/test_openstack.py
import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) self.connection = OpenStackBaseCo...
import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection from libcloud.utils.py3 import PY25 class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) ...
Fix test so it works with python 2.5.
Fix test so it works with python 2.5. git-svn-id: 9ad005ce451fa0ce30ad6352b03eb45b36893355@1342997 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
Jc2k/libcloud,marcinzaremba/libcloud,Scalr/libcloud,mathspace/libcloud,Verizon/libcloud,DimensionDataCBUSydney/libcloud,Cloud-Elasticity-Services/as-libcloud,lochiiconnectivity/libcloud,MrBasset/libcloud,sfriesel/libcloud,wrigri/libcloud,Itxaka/libcloud,erjohnso/libcloud,jerryblakley/libcloud,Scalr/libcloud,marcinzarem...
f8d90e92ce791650dc89944fca009fc36d9e3a90
crawler/wikitravel-optimize-articles.py
crawler/wikitravel-optimize-articles.py
#!/opt/local/bin/python import json import os import re import string import sys myPath = os.path.dirname(os.path.realpath(__file__)) for i, line in enumerate(sys.stdin): (url, title, fileBase) = json.loads(line) fileName = fileBase + '.article' outFileName = fileName + '.opt' if os.path.exists(outFileName): ...
#!/opt/local/bin/python import json import os import re import string import sys myPath = os.path.dirname(os.path.realpath(__file__)) def formatPath(s): return s.replace('(', '\\(').replace(')', '\\)') for i, line in enumerate(sys.stdin): (url, title, fileBase) = json.loads(line) fileName = fileBase + '.articl...
Handle correctly paths with symbols '(' and ')'.
[crawler] Handle correctly paths with symbols '(' and ')'.
Python
apache-2.0
VladiMihaylenko/omim,edl00k/omim,dobriy-eeh/omim,65apps/omim,65apps/omim,Zverik/omim,vasilenkomike/omim,UdjinM6/omim,syershov/omim,milchakov/omim,yunikkk/omim,ygorshenin/omim,alexzatsepin/omim,mapsme/omim,kw217/omim,dobriy-eeh/omim,AlexanderMatveenko/omim,vasilenkomike/omim,rokuz/omim,mpimenov/omim,andrewshadura/omim,g...
5389fb8575251e2bd8ed18d96f4aa615e9a37bfa
deploy.py
deploy.py
#!/usr/bin/env python import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() pri...
#!/usr/bin/env python import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() pri...
Fix virtualenv path on PythonAnywhere
Fix virtualenv path on PythonAnywhere
Python
apache-2.0
ajdavis/twitter-gender-ratio,ajdavis/twitter-gender-distribution,ajdavis/twitter-gender-distribution,ajdavis/twitter-gender-ratio
81ca235178a742e0041f2483d1f80d367d77264d
markov.py
markov.py
import random class Markov: def __init__(self, source, k=5): self.source = source self.k = k self._init_source() def _init_source(self): self.seeds = {} for i in range(len(self.source) - self.k - 1): seed = tuple(self.source[i:i+self.k]) if seed ...
import random class Markov: def __init__(self, source, k=5): self.source = source self.k = k self._init_source() def _init_source(self): self.seeds = {} for i in range(len(self.source) - self.k - 1): seed = tuple(self.source[i:i+self.k]) if seed ...
Fix find_seed behavior when the word is not present
Fix find_seed behavior when the word is not present
Python
mit
calzoneman/MarkovBot,calzoneman/MarkovBot
09a395526dadac36f295674e01121818278ac91f
kobold/hash_functions.py
kobold/hash_functions.py
def merge(default, to_mutate): for key, value in default.items(): to_mutate.setdefault(key, value) return to_mutate def combine(default, extra): new = {} for key, value in default.items(): new[key] = value for key, value in extra.items(): new[key] = value return new ...
def project(hash_in, attributes): return {key: value for (key, value) in hash_in.iteritems() if key in attributes} def merge(default, to_mutate): for key, value in default.items(): to_mutate.setdefault(key, value) return to_mutate def combine(default, extra): new = {} for key, value in...
Add a "project" hash function, for projecting certain keys out of a dict
Add a "project" hash function, for projecting certain keys out of a dict
Python
mit
krieghan/kobold_python,krieghan/kobold_python
f3d3750986a8710c54c110c43c00fa152dbbd383
src/hades/bin/su.py
src/hades/bin/su.py
import grp import logging import os import pwd import sys from hades.common.cli import ( ArgumentParser, parser as common_parser, setup_cli_logging, ) logger = logging.getLogger(__name__) def drop_privileges(passwd, group): if os.geteuid() != 0: logger.error("Can't drop privileges (EUID != 0)") ...
import grp import logging import os import pwd import sys from hades.common.cli import ( ArgumentParser, parser as common_parser, setup_cli_logging, ) logger = logging.getLogger(__name__) def drop_privileges(passwd, group): os.setgid(group.gr_gid) os.initgroups(passwd.pw_name, group.gr_gid) os.setui...
Abort if privileges can't be dropped
Abort if privileges can't be dropped
Python
mit
agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades
258c24c86ebbcc4a4a347e916d520c0f98f82f90
reboot_router_claro3G.py
reboot_router_claro3G.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import urllib2 as http # URL with GET to reboot router or status main page to tests #url_get_reboot = 'http://10.11.12.254/log/in?un=admin&pw=admin12&rd=%2Fuir%2Frebo.htm?rc=&Nrd=0&Nsm=1' url_get_status = 'http://10.11.12.254/log/in?un=admin&pw=admin12&rd=%2Fuir%2Fstatus...
#! /usr/bin/env python # -*- coding: utf-8 -*- import urllib2 as http # Data Router user_router = "user_here" pass_router = "password_here" ip_router = "IP_here" port_router = "80" # URL with filling the fields above, URL with GET to reboot router or status main page to tests url_get_reboot = "http://" + ip_rout...
Add variables with info access router
Add variables with info access router
Python
apache-2.0
cleitonbueno/reboot_router
5e42ab2aa7e5537a995e8d3ca81a29299a077116
examples/01-web/13-wikia.py
examples/01-web/13-wikia.py
# -*- coding: utf-8 *-* import os, sys, pprint; sys.path.insert(0, os.path.join("..", "..")) from pattern.web import Wikia, WikiaArticleSet, URLTimeout # This example retrieves an article from Wikipedia (http://en.wikipedia.org). # A query requests the article's HTML source from the server, which can be quite slow. #...
# -*- coding: utf-8 *-* import os, sys, pprint; sys.path.insert(0, os.path.join("..", "..")) from pattern.web import Wikia, WikiaArticleSet, URLTimeout # This example retrieves an article from Wikipedia (http://en.wikipedia.org). # A query requests the article's HTML source from the server, which can be quite slow. #...
Increment counter in wikia example per @satoru
Increment counter in wikia example per @satoru
Python
bsd-3-clause
z0by/pattern,abcht/pattern,bijandhakal/pattern,NTesla/pattern,loretoparisi/pattern,Sri0405/pattern,pombredanne/pattern,shuangsong/pattern,jatinmistry13/pattern,sfprime/pattern,z0by/pattern,arne-cl/pattern,rebeling/pattern,clips/pattern,jatinmistry13/pattern,bijandhakal/pattern,codeaudit/pattern-1,aoom/pattern,ashhher3/...
4af368b3d3a4f5cfb8b78e19827c99078fb5ccab
client.py
client.py
#!/usr/bin/env python3 import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected def test_Close(self): ...
#!/usr/bin/env python3 import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected def test_RequstIndex(self...
Add request index page test.
Add request index page test.
Python
bsd-3-clause
starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer
00a29c535dc699b5bbbc7b6eb9d439d289c8de18
common.py
common.py
import datetime import hashlib import os # hack to override sqlite database filename # see: https://help.morph.io/t/using-python-3-with-morph-scraperwiki-fork/148 os.environ['SCRAPERWIKI_DATABASE_NAME'] = 'sqlite:///data.sqlite' import scraperwiki def store_history(data, table): """ store a hash of the conte...
import datetime import hashlib import os # hack to override sqlite database filename # see: https://help.morph.io/t/using-python-3-with-morph-scraperwiki-fork/148 os.environ['SCRAPERWIKI_DATABASE_NAME'] = 'sqlite:///data.sqlite' import scraperwiki def store_history(data, table): """ store a hash of the conte...
Store raw data as well as content hash
Store raw data as well as content hash ..for now. Trying to work out why the content hashes are changing when I am not expecting them to.
Python
mit
wdiv-scrapers/dc-base-scrapers
62da8b8a2774db2ccb725bc0c5a1598252ebf4a7
fuzzer/tasks.py
fuzzer/tasks.py
import redis from celery import Celery from .Fuzzer import Fuzzer import os import time import driller.config as config import logging l = logging.getLogger("fuzzer.tasks") backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT) app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url) @...
import redis from celery import Celery from .Fuzzer import Fuzzer import os import time import driller.config as config import logging l = logging.getLogger("fuzzer.tasks") backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT) app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url) @...
Kill fuzzers when we've found a crash or timed out
Kill fuzzers when we've found a crash or timed out
Python
bsd-2-clause
shellphish/driller
c95dc576153f60c8c56b7b2c5bfac467ccd9dd97
gin/__init__.py
gin/__init__.py
# coding=utf-8 # Copyright 2018 The Gin-Config Authors. # # 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 la...
# coding=utf-8 # Copyright 2018 The Gin-Config Authors. # # 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 la...
Add import for constants_from_enum to be able to use @gin.constants_from_enum
Add import for constants_from_enum to be able to use @gin.constants_from_enum PiperOrigin-RevId: 198401971
Python
apache-2.0
google/gin-config,google/gin-config
f1359fb6b8117a00afd833765646f03650df6a54
_lib/wordpress_post_processor.py
_lib/wordpress_post_processor.py
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) ...
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) ...
Remove commented line we definitely will never need
Remove commented line we definitely will never need
Python
cc0-1.0
kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh
6d57372c270d980e0f7d662a60195e54f88b9be5
web/gunicorn.conf.py
web/gunicorn.conf.py
import os import multiprocessing proc_name = 'gunicorn: {}'.format(os.environ['WEB_HOSTNAME']) user = 'www-data' group = 'www-data' bind = '0.0.0.0:80' workers = multiprocessing.cpu_count() * 2 + 1 threads = workers
import os import multiprocessing proc_name = 'gunicorn: {}'.format(os.environ['WEB_HOSTNAME']) user = 'www-data' group = 'www-data' bind = '0.0.0.0:80' workers = multiprocessing.cpu_count() * 2 + 1 threads = workers accesslog = '-' errorlog = '-'
Make gunicorn log to stdout
Make gunicorn log to stdout
Python
mit
slava-sh/messenger,slava-sh/messenger,slava-sh/messenger,slava-sh/messenger
61029c887729032c8c832e64dfb63c444a637931
alfred/__main__.py
alfred/__main__.py
#!/usr/bin/env python import os from argh import arg, ArghParser from argh.exceptions import CommandError from functools import wraps CONFIG = os.environ.get('ALFRED_CONFIG') def with_app(func): @wraps(func) @arg('--config', help='path to config') def wrapper(args): from alfred import create_ap...
#!/usr/bin/env python import os from argh import arg, ArghParser from argh.exceptions import CommandError from functools import wraps CONFIG = os.environ.get('ALFRED_CONFIG') def with_app(func): @wraps(func) @arg('--config', help='path to config') def wrapper(args): from alfred import create_ap...
Add an option to disable code reloader to runserver command
Add an option to disable code reloader to runserver command
Python
isc
alfredhq/alfred,alfredhq/alfred
c6e48c224b48e90c57d7731fc88be7703990a02a
app/chess/piece.py
app/chess/piece.py
class ChessPiece(object): def __init__(self): self.column = 0 self.row = 0 self.symbol = '' # Checks piece can attack the specified position def can_attack_position(self, column, row): pass # return the character representation of this chess piece def get_symbol(se...
from math import hypot class ChessPiece(object): def __init__(self): self.x = 0 self.y = 0 self.symbol = '' # Checks piece can attack the specified position def deplace_piece(self, square): self.x = square.x self.y = square.y # return the character representa...
Add attack function to KING class
Add attack function to KING class
Python
mit
aymguesmi/ChessChallenge
e2132caf1c677b34eddd679e23983022ec12b5df
watermarker/conf.py
watermarker/conf.py
# -*- coding: utf-8 -*- import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class WatermarkSettings(AppConf): QUALITY = 85 OBSCURE_ORIGINAL = True RANDOM_POSITION_ONCE = True WATERMARK_PERCENTAGE = 30 class Meta: prefix = 'watermark' ...
# -*- coding: utf-8 -*- import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class WatermarkSettings(AppConf): QUALITY = 85 OBSCURE_ORIGINAL = True RANDOM_POSITION_ONCE = True WATERMARK_PERCENTAGE = getattr(settings, 'WATERMARK_PERCENTAGE', 30) ...
Change AppConf class to use settings defined value or default.
Change AppConf class to use settings defined value or default.
Python
bsd-3-clause
lzanuz/django-watermark,lzanuz/django-watermark
13291e4862ef48a3de3615e8eef5704c6bfff628
importlib_metadata/__init__.py
importlib_metadata/__init__.py
import os import sys import glob class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): for path_item in path: glob_spec = os.p...
import os import sys import glob import email import itertools import contextlib class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): for...
Implement metadata loading and version retrieval
Implement metadata loading and version retrieval
Python
apache-2.0
python/importlib_metadata
48543d559d13bb9446f455d14ec3e8ae1ff4f2d7
angular_flask/__init__.py
angular_flask/__init__.py
import os from flask import Flask from flask_sslify import SSLify app = Flask(__name__, instance_path='/instance') if 'DYNO' in os.environ: sslify = SSLify(app) app.config.from_object('config') app.config.from_pyfile('config.py') import angular_flask.core import angular_flask.models import angular_flask.control...
import os from flask import Flask from flask_sslify import SSLify app = Flask(__name__, instance_relative_config=True) if 'DYNO' in os.environ: sslify = SSLify(app) app.config.from_object('config') app.config.from_pyfile('config.py', True) import angular_flask.core import angular_flask.models import angular_fla...
Set tru to config from pyfile
Set tru to config from pyfile
Python
mit
Clarity-89/blog,Clarity-89/blog,Clarity-89/blog
dcba06dfc3ae1e558c3b7926780b0934b7ac3fda
trackpy/tests/test_misc.py
trackpy/tests/test_misc.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os import unittest import warnings import pims import trackpy import trackpy.diag path, _ = os.path.split(os.path.abspath(__file__)) class DiagTests(unittest.TestCase): def test_performa...
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os import unittest import warnings import pims import trackpy import trackpy.diag path, _ = os.path.split(os.path.abspath(__file__)) class DiagTests(unittest.TestCase): def test_performa...
Fix pims warning test under Py3
TST: Fix pims warning test under Py3
Python
bsd-3-clause
daniorerio/trackpy,daniorerio/trackpy
bebc2a499a4190c8c3090bcab0203b913aa7592d
events/auth.py
events/auth.py
from django.contrib.auth.models import AnonymousUser from rest_framework import authentication from rest_framework import exceptions from events.models import DataSource from django.utils.translation import ugettext_lazy as _ class ApiKeyAuthentication(authentication.BaseAuthentication): def authenticate(self, re...
from django.contrib.auth.models import AnonymousUser from rest_framework import authentication from rest_framework import exceptions from events.models import DataSource from django.utils.translation import ugettext_lazy as _ class ApiKeyAuthentication(authentication.BaseAuthentication): def authenticate(self, re...
Fix checking apikey outside runserver
Fix checking apikey outside runserver
Python
mit
City-of-Helsinki/linkedevents,aapris/linkedevents,aapris/linkedevents,aapris/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents
b0a275e2430a04bf4e47b823f48cade92c407673
apiserver/worker/grab_config.py
apiserver/worker/grab_config.py
""" Grab worker configuration from GCloud instance attributes. """ import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/hal...
""" Grab worker configuration from GCloud instance attributes. """ import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/hal...
Fix typo in GPU worker config setup
Fix typo in GPU worker config setup
Python
mit
HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Hal...
7b520e973ed9a72cc3b68bda0a48c89b6d60558b
examples/connect4_uci_outcomes.py
examples/connect4_uci_outcomes.py
from __future__ import division, print_function from collections import Counter from capstone.util.c4uci import load_instance FILENAME = 'datasets/connect-4.data' outcomes = [] with open(FILENAME) as f: for i, line in enumerate(f, 1): _, outcome = load_instance(line) outcomes.append(outcome) ...
from __future__ import division, print_function import pandas as pd from sklearn.linear_model import LinearRegression from capstone.game import Connect4 as C4 from capstone.util import print_header FILENAME = 'datasets/connect-4.data' def column_name(i): if i == 42: return 'outcome' row = chr(ord('a')...
Use pandas dataframes for UCI C4 dataset
Use pandas dataframes for UCI C4 dataset
Python
mit
davidrobles/mlnd-capstone-code
655e741375b3fad7e3b7657662d33ca8017c0220
test/requests/link_checker.py
test/requests/link_checker.py
import requests def check_links(args_obj, parser): print("") print("Checking links") print("########################") print("Not implemented yet.") print("This is supposed to check all links in the system.") print("########################")
from __future__ import print_function import re import requests from lxml.html import parse from requests.exceptions import ConnectionError def is_root_link(link): pattern = re.compile("^/$") return pattern.match(link) def is_mailto_link(link): pattern = re.compile("^mailto:.*") return pattern.match(l...
Add tests to check links.
Add tests to check links.
Python
agpl-3.0
zsloan/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,DannyArends/gen...
1e8fd33ef4e8b75632d8a4fe4d86944fdfc5a649
beetle/__init__.py
beetle/__init__.py
name = 'beetle' version = '0.4.1-dev' project_url = 'https://github.com/cknv/beetle' class BeetleError(Exception): pass
name = 'beetle' version = '0.4.1-dev' project_url = 'https://github.com/cknv/beetle' class BeetleError(Exception): def __init__(self, page=None): self.page = page
Allow the BeetleError class to take a page object as an argument
Allow the BeetleError class to take a page object as an argument
Python
mit
cknv/beetle
98ebd229819cb108af7746dfdd950019111063ce
http_server.py
http_server.py
import socket class HttpServer(object): """docstring for HttpServer""" def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5): self._ip = ip self._port = port self._backlog = backlog self._socket = None def open_socket(self): self._socket = socket.socket( ...
import socket class HttpServer(object): """docstring for HttpServer""" def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5): self._ip = ip self._port = port self._backlog = backlog self._socket = None def open_socket(self): self._socket = socket.socket( ...
Add HttpServer.close_socket() to the server's socket
Add HttpServer.close_socket() to the server's socket
Python
mit
jefrailey/network_tools
0824bb4025d00d9e435c162a0b1931d448baf7c9
hardware/sense_hat/marble_maze.py
hardware/sense_hat/marble_maze.py
# based on https://www.raspberrypi.org/learning/sense-hat-marble-maze/worksheet/ from sense_hat import SenseHat import time sense = SenseHat() sense.clear() time.sleep(0.5) r = (255, 0, 0 ) b = (0,0,0) w = (255, 255, 255 ) x = 1 y = 1 maze = [[r,r,r,r,r,r,r,r], [r,b,b,b,b,b,b,r], [r,r,r,b,r,b,b,r]...
# based on https://www.raspberrypi.org/learning/sense-hat-marble-maze/worksheet/ from sense_hat import SenseHat import time sense = SenseHat() sense.clear() time.sleep(0.5) r = (255, 0, 0 ) b = (0,0,0) w = (255, 255, 255 ) x = 1 y = 1 maze = [[r,r,r,r,r,r,r,r], [r,b,b,b,b,b,b,r], [r,r,r,b,r,b,b,r]...
Add moving of marble on x axis - currently brokwn
Add moving of marble on x axis - currently brokwn
Python
mit
claremacrae/raspi_code,claremacrae/raspi_code,claremacrae/raspi_code
0d81d93a0c90c8cda2e762255c2d41b99ddc16f3
macdict/cli.py
macdict/cli.py
from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(te...
from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(te...
Fix CJK input in command line arguments
Fix CJK input in command line arguments
Python
mit
tonyseek/macdict
9904e3843b2efca908845d57033b13f35c2e2a4d
st2auth_pam_backend/__init__.py
st2auth_pam_backend/__init__.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Fix code so import works under Python 3.
Fix code so import works under Python 3.
Python
apache-2.0
StackStorm/st2-auth-backend-pam,StackStorm/st2-auth-backend-pam
4b7466e3798dea0b3edf94c1e5cc376ba7615d2f
events/models.py
events/models.py
from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ...
from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ...
Add a description to an event
[add] Add a description to an event
Python
agpl-3.0
UrLab/incubator,UrLab/incubator,UrLab/incubator,UrLab/incubator
b5acf414e9fcbecee8da15e2757a60ce10cc5c10
examples/last.py
examples/last.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.dow...
#!/usr/bin/env python # -*- coding: utf-8 -*- from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.dow...
Fix KeyError when no results in time period
Fix KeyError when no results in time period Fix a KeyError when no results were found for the specified time period.
Python
bsd-2-clause
pombredanne/PyMISP,iglocska/PyMISP
af21288fb4245fc56a0b182331cd4db724e05e62
app/accounts/admin.py
app/accounts/admin.py
from django.contrib import admin from .models import UserProfile admin.site.register(UserProfile)
from django.contrib import admin from .models import UserProfile @admin.register(UserProfile) class UserProfileAdmin(admin.ModelAdmin): fieldsets = [ ('User Profile', { 'fields': ('user', 'custom_auth_id', 'facebook_oauth_id', 'google_oauth_id', 'twitter_oauth_id',), ...
Add description for Userprofile model
Add description for Userprofile model
Python
mit
teamtaverna/core
4d2ef07c64603e99f05f2233382dc2a7c5bff5ba
website/members/tests.py
website/members/tests.py
from django.contrib.auth.models import User from django.test import TestCase from datetime import datetime from members.models import Member class MemberTest(TestCase): def setUp(self): self.user = User.objects.create(username='test') self.member = Member.objects.create(user=self.user) se...
from django.contrib.auth.models import User from django.test import TestCase from datetime import datetime from members.models import Member, StudyProgram class MemberTest(TestCase): def setUp(self): self.user = User.objects.create(username='test') self.member = Member.objects.create(user=self.us...
Add test for StudyProgram deletion
:green_heart: Add test for StudyProgram deletion
Python
agpl-3.0
Dekker1/moore,UTNkar/moore,Dekker1/moore,UTNkar/moore,Dekker1/moore,UTNkar/moore,Dekker1/moore,UTNkar/moore
4257381997e8ac6968713f1bad96019f977bafc9
server.py
server.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import tweepy, time, sys, os from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('secrets.cfg') #enter the corresponding information from your Twitter application: CONSUMER_KEY = parser.get('bug_tracker', 'CONSUMER_KEY') CONSUMER_SECRET = pa...
#!/usr/bin/env python # -*- coding: utf-8 -*- import tweepy, time, sys, os from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('secrets.cfg') #enter the corresponding information from your Twitter application: CONSUMER_KEY = parser.get('Twitter', 'CONSUMER_KEY') CONSUMER_SECRET = parser...
Fix config parsing. Tweeting works
Fix config parsing. Tweeting works
Python
mit
premgane/agolo-twitterbot,premgane/agolo-twitterbot
9f512fd6f3c7d2928c66062002b18b7bb13a5653
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provi...
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): ...
Remove the "3" from SublimeLinter3
Remove the "3" from SublimeLinter3
Python
mit
jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint
5decd7e68c6454e455bc1debe232ea37f7260c58
mixins.py
mixins.py
class DepthSerializerMixin(object): """Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url""" def get_serializer_class(self): serializer_class = self.serializer_class query_params = self.request.QUERY_PARAMS depth = query_params.get('__depth', None) serializer_cla...
class DepthSerializerMixin(object): """Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url""" def get_serializer_class(self, *args, **kwargs): serializer_class = super(DepthSerializerMixin, self).get_serializer_class(*args, **kwargs) query_params = self.request.QUERY_...
Call method 'get_serializer_class' of the Class parent
Call method 'get_serializer_class' of the Class parent
Python
mit
krescruz/depth-serializer-mixin
bed9e520a371a99132e05511f110a141d22d2a7f
tests/integration/test_proxy.py
tests/integration/test_proxy.py
# -*- coding: utf-8 -*- '''Test using a proxy.''' # External imports import multiprocessing import SocketServer import SimpleHTTPServer import pytest requests = pytest.importorskip("requests") from six.moves.urllib.request import urlopen # Internal imports import vcr class Proxy(SimpleHTTPServer.SimpleHTTPRequestH...
# -*- coding: utf-8 -*- '''Test using a proxy.''' # External imports import multiprocessing import pytest requests = pytest.importorskip("requests") from six.moves import socketserver, SimpleHTTPServer from six.moves.urllib.request import urlopen # Internal imports import vcr class Proxy(SimpleHTTPServer.SimpleHTT...
Fix `socketserver` for Python 3
Fix `socketserver` for Python 3
Python
mit
graingert/vcrpy,kevin1024/vcrpy,graingert/vcrpy,kevin1024/vcrpy
ff618ea57b8f3d71772bcef5f7fecf9eceae4e3d
scripts/upsrv_schema.py
scripts/upsrv_schema.py
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore cnrPath = '/srv/conary/repository.cnr' cfg = ServerConfig(...
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore cnrPath = '/srv/conary/repository.cnr' cfg = Ser...
Set log level to 2 when migrating so there is some indication it is running
Set log level to 2 when migrating so there is some indication it is running
Python
apache-2.0
sassoftware/rbm,sassoftware/rbm,sassoftware/rbm
85e77bc7a4706ed1b25d4d53e71ca22beafed411
sidertests/test_sider.py
sidertests/test_sider.py
import doctest import os def test_doctest_types(): from sider import types assert 0 == doctest.testmod(types)[0] def test_doctest_datetime(): from sider import datetime assert 0 == doctest.testmod(datetime)[0] exttest_count = 0 def test_ext(): from sider.ext import _exttest assert _extte...
import os exttest_count = 0 def test_ext(): from sider.ext import _exttest assert _exttest.ext_loaded == 'yes' assert exttest_count == 1 from sider import ext assert ext._exttest is _exttest try: import sider.ext._noexttest except ImportError as e: assert str(e) == "No mo...
Drop useless tests that invoking doctests
Drop useless tests that invoking doctests
Python
mit
longfin/sider,dahlia/sider,longfin/sider
1010cb2c4a4930254e2586949314aa0bb6b89b3d
tests/test_solver_constraint.py
tests/test_solver_constraint.py
import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = ...
import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = ...
Test default case for constraint.solve()
Test default case for constraint.solve()
Python
lgpl-2.1
amolenaar/gaphas
2e040a77b70b4a07227f5aa3cb3aee6b8c84f4e0
src/livedumper/common.py
src/livedumper/common.py
"Common functions that may be used everywhere" from __future__ import print_function import os import sys from distutils.util import strtobool def yes_no_query(question): """Ask the user *question* for 'yes' or 'no'; ask again until user inputs a valid option. Returns: 'True' if user answered 'y', ...
"Common functions that may be used everywhere" from __future__ import print_function import os import sys from distutils.util import strtobool try: input = raw_input except NameError: pass def yes_no_query(question): """Ask the user *question* for 'yes' or 'no'; ask again until user inputs a valid ...
Fix Python 2 compatibility, again
Fix Python 2 compatibility, again
Python
bsd-2-clause
m45t3r/livedumper
a76101c9ad416323b9379d48adb61c804a5454c0
localized_fields/admin.py
localized_fields/admin.py
from . import widgets from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \ LocalizedFileField FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = { LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget}, LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget}, Local...
from django.contrib.admin import ModelAdmin from . import widgets from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \ LocalizedFileField FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = { LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget}, LocalizedCharField: {'widget': widg...
Fix LocalizedFieldsAdminMixin not having a base class
Fix LocalizedFieldsAdminMixin not having a base class This was a breaking change and broke a lot of projects.
Python
mit
SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields
8ccffcf02cd5ba8352bc8182d7be13ea015332ca
plinth/utils.py
plinth/utils.py
# # This file is part of Plinth. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
# # This file is part of Plinth. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
Add utility method to lazy format lazy string
Add utility method to lazy format lazy string This method is useful to format strings that are lazy (such as those in Forms).
Python
agpl-3.0
freedomboxtwh/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,harry-7/Plinth,harry-7/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,kkampardi/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Pl...
3313d611d7cc66bf607a341a5d9a6a5d96dfbec5
clowder_server/emailer.py
clowder_server/emailer.py
import os import requests from django.core.mail import send_mail from clowder_account.models import ClowderUser ADMIN_EMAIL = 'admin@clowder.io' def send_alert(company, name): for user in ClowderUser.objects.filter(company=company, allow_email_notifications=True): subject = 'FAILURE: %s' % (name) ...
import os import requests from django.core.mail import send_mail from clowder_account.models import ClowderUser ADMIN_EMAIL = 'admin@clowder.io' def send_alert(company, name): slack_sent = False for user in ClowderUser.objects.filter(company=company, allow_email_notifications=True): subject = 'FAILUR...
Rename bot and prevent channel spamming
Rename bot and prevent channel spamming
Python
agpl-3.0
keithhackbarth/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server
aafcc59ef14fe5af39a06e87bc44546a9da56fb6
lazy_helpers.py
lazy_helpers.py
# Lazy objects, for the serializer to find them we put them here class LazyDriver(object): _driver = None @classmethod def get(cls): if cls._driver is None: from selenium import webdriver # Configure headless mode options = webdriver.ChromeOptions() #Oops ...
# Lazy objects, for the serializer to find them we put them here class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from selenium import webdriver # Configure headless mode options = webdriver.ChromeOpti...
Add some more arguments for chrome driver
Add some more arguments for chrome driver
Python
apache-2.0
holdenk/diversity-analytics,holdenk/diversity-analytics
92438a5450bc644f066a941efe16ec07cf3c129a
httoop/codecs/codec.py
httoop/codecs/codec.py
# -*- coding: utf-8 -*- from httoop.util import Unicode class Codec(object): @classmethod def decode(cls, data, charset=None, mimetype=None): # pragma: no cover if isinstance(data, bytes): data = data.decode(charset) if charset is not None else data.decode() @classmethod def encode(cls, data, charset=None...
# -*- coding: utf-8 -*- from httoop.util import Unicode class Codec(object): @classmethod def decode(cls, data, charset=None, mimetype=None): # pragma: no cover if isinstance(data, bytes): data = data.decode(charset or 'ascii') return data @classmethod def encode(cls, data, charset=None, mimetype=None):...
Make encoding and decoding strict
Make encoding and decoding strict * programmers must know what kind of data they use * don't guess encodings anymore
Python
mit
spaceone/httoop,spaceone/httoop,spaceone/httoop
c7723ff6d7f43330786e84802ef0bacf70d4ba67
instatrace/commands.py
instatrace/commands.py
# Copyright (C) 2010 Peter Teichman import logging import os import sys import time from .stats import Histogram, Statistics log = logging.getLogger("instatrace") class HistogramsCommand: @classmethod def add_subparser(cls, parser): subparser = parser.add_parser("histograms", help="Stat histograms")...
# Copyright (C) 2010 Peter Teichman import logging import os import sys import time from .stats import Histogram, Statistics log = logging.getLogger("instatrace") class HistogramsCommand: @classmethod def add_subparser(cls, parser): subparser = parser.add_parser("histograms", help="Stat histograms")...
Add a --filter flag to histograms
Add a --filter flag to histograms This ignores any lines in the input that don't contain "INSTATRACE: " and removes anything preceding that string before handling the sample.
Python
mit
pteichman/instatrace
504c7ad1a436af356ca73e2fe8934018e3a7547d
manage.py
manage.py
from vulyk.control import cli if __name__ == '__main__': cli()
#!/usr/bin/env python # -*- coding=utf-8 -*- from vulyk.control import cli if __name__ == '__main__': cli()
Make it more executable than it was
Make it more executable than it was
Python
bsd-3-clause
mrgambal/vulyk,mrgambal/vulyk,mrgambal/vulyk
54a6e1463104b87a51d17f937c286721cf84466a
democracy_club/apps/donations/middleware.py
democracy_club/apps/donations/middleware.py
from django.http import HttpResponseRedirect from .forms import DonationForm from .helpers import GoCardlessHelper class DonationFormMiddleware(object): def get_initial(self): return { 'payment_type': 'subscription', 'amount': 10, } def form_valid(self, request, form)...
from django.http import HttpResponseRedirect from .forms import DonationForm from .helpers import GoCardlessHelper, PAYMENT_UNITS class DonationFormMiddleware(object): def get_initial(self, request): suggested_donation = request.GET.get('suggested_donation', 3) form_initial = { 'payme...
Allow altering the donation amount via a link and default to £3
Allow altering the donation amount via a link and default to £3
Python
bsd-3-clause
DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website
3ca9ae145e70a3339028d9de55544da739a86899
cura/CameraAnimation.py
cura/CameraAnimation.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import QVariantAnimation, QEasingCurve from PyQt5.QtGui import QVector3D from UM.Math.Vector import Vector from UM.Logger import Logger class CameraAnimation(QVariantAnimation): def __init__(self, ...
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import QVariantAnimation, QEasingCurve from PyQt5.QtGui import QVector3D from UM.Math.Vector import Vector from UM.Logger import Logger class CameraAnimation(QVariantAnimation): def __init__(self, ...
Undo logging and splitting up QVector3D. CURA-3334
Undo logging and splitting up QVector3D. CURA-3334
Python
agpl-3.0
hmflash/Cura,fieldOfView/Cura,Curahelper/Cura,ynotstartups/Wanhao,hmflash/Cura,Curahelper/Cura,fieldOfView/Cura,ynotstartups/Wanhao
b870f61d131483dd42b3302057351f2461b2cfc6
tests/test_enrichment_fdr.py
tests/test_enrichment_fdr.py
import os def test(): """Test to find this error below. Traceback (most recent call last): File "../scripts/find_enrichment.py", line 130, in <module> study=study, methods=methods) File "../scripts/../goatools/go_enrichment.py", line 93, in __init__ self.run_study(stu...
import os def test(): """Ensure that a study with only unknown GO Terms will run gracefully.""" os.system("python {SCR} --alpha=0.05 {STUDY} {POP} {ASSN} --fdr --obo={OBO}".format( SCR="../scripts/find_enrichment.py", OBO="../go-basic.obo", STUDY="data/study_unknown", POP="../data/population", ...
Make Test description more elegant.
Make Test description more elegant.
Python
bsd-2-clause
fidelram/goatools,mfiers/goatools,lileiting/goatools,tanghaibao/goatools,mfiers/goatools,tanghaibao/goatools,fidelram/goatools,lileiting/goatools
fda563e9661c0a65256ba6b1a7416a0f4171f18e
sentence_transformers/readers/InputExample.py
sentence_transformers/readers/InputExample.py
from typing import Union, List class InputExample: """ Structure for one input example with texts, the label and a unique id """ def __init__(self, guid: str = '', texts: Union[List[str], List[int]] = [], label: Union[int, float] = None): """ Creates one InputExample with the given tex...
from typing import Union, List class InputExample: """ Structure for one input example with texts, the label and a unique id """ def __init__(self, guid: str = '', texts: List[str] = None, texts_tokenized: List[List[int]] = None, label: Union[int, float] = None): """ Creates one InputE...
Add field for pre-tokenized texts
Add field for pre-tokenized texts
Python
apache-2.0
UKPLab/sentence-transformers
08199327c411663a199ebf36379e88a514935399
chdb.py
chdb.py
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE categories ''') db.execute(''' DROP TABLE articles ''') db.execute(''' ...
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE IF EXISTS categories ''') db.execute(''' DROP TABLE IF EXISTS articles ''') ...
Revert "Remove IF EXISTS from DROP TABLE when resetting the db."
Revert "Remove IF EXISTS from DROP TABLE when resetting the db." This reverts commit a7dce25964cd740b0d0db86b255ede60c913e73d.
Python
mit
jhsoby/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt
3e28adb3b32e1c88e9295c44e79840ebfe67f83f
py/foxgami/db.py
py/foxgami/db.py
import functools from sqlalchemy import create_engine @functools.lru_cache() def engine(): return create_engine('postgresql://foxgami:foxgami@localhost/foxgami') def query(sql, args=()): e = engine() result = e.execute(sql, tuple(args)) if result: return list(result) def query_single(sql,...
import functools from sqlalchemy import create_engine @functools.lru_cache() def engine(): return create_engine('postgresql://foxgami:foxgami@localhost/foxgami') def query(sql, args=()): e = engine() result = e.execute(sql, tuple(args)) if result.returns_rows: return list(result) def quer...
Use .returns_rows to determine if we should return list type
Use .returns_rows to determine if we should return list type
Python
mit
flubstep/foxgami.com,flubstep/foxgami.com
50d8ad485549159d2186df2b6b01aee21e51cbc2
notebooks/machine_learning/track_meta.py
notebooks/machine_learning/track_meta.py
# See also examples/example_track/example_meta.py for a longer, commented example track = dict( author_username='dansbecker', ) lessons = [ dict(topic='How Models Work'), dict(topic='Explore Your Data') ] notebooks = [ dict( filename='tut1.ipynb', lesson_idx=0, type='tu...
# See also examples/example_track/example_meta.py for a longer, commented example track = dict( author_username='dansbecker', ) lessons = [ dict(topic='how models work'), dict(topic='exploring your data'), dict(topic='building your first machine learning model'), ] notebooks = [ dict( ...
Add third lesson and reword lesson topics
Add third lesson and reword lesson topics
Python
apache-2.0
Kaggle/learntools,Kaggle/learntools
d0380db930dbf145108a7ef0330dd19475f7fdee
test_arrange_schedule.py
test_arrange_schedule.py
from arrange_schedule import * def test_read_system_setting(): keys = ['board_py_dir','shutdown','max_db_log','min_db_activity'] system_setting = read_system_setting() for key in keys: assert key in system_setting return system_setting def test_crawler_cwb_img(system_setting): send_msg = ...
from arrange_schedule import * def test_read_system_setting(): keys = ['board_py_dir','shutdown','max_db_log','min_db_activity'] system_setting = read_system_setting() for key in keys: assert key in system_setting return system_setting def test_read_arrange_mode(): keys = ['arrange_sn','a...
Add test case for read_arrange_mode()
Add test case for read_arrange_mode()
Python
apache-2.0
Billy4195/electronic-blackboard,SWLBot/electronic-blackboard,stvreumi/electronic-blackboard,chenyang14/electronic-blackboard,SWLBot/electronic-blackboard,Billy4195/electronic-blackboard,stvreumi/electronic-blackboard,chenyang14/electronic-blackboard,stvreumi/electronic-blackboard,Billy4195/electronic-blackboard,stvreum...
3d46ec43570013bd68135126127c4027e25e3cfa
shapely/geos.py
shapely/geos.py
""" Exports the libgeos_c shared lib, GEOS-specific exceptions, and utilities. """ import atexit from ctypes import CDLL, CFUNCTYPE, c_char_p import os, sys # The GEOS shared lib if os.name == 'nt': dll = 'libgeos_c-1.dll' else: dll = 'libgeos_c.so' lgeos = CDLL(dll) # Exceptions class ReadingError(Except...
""" Exports the libgeos_c shared lib, GEOS-specific exceptions, and utilities. """ import atexit from ctypes import CDLL, CFUNCTYPE, c_char_p import sys # The GEOS shared lib if sys.platform == 'win32': dll = 'libgeos_c-1.dll' elif sys.platform == 'darwin': dll = 'libgeos_c.dylib' else: dll = 'libgeos_c....
Add untested support for the darwin platform
Add untested support for the darwin platform git-svn-id: 30e8e193f18ae0331cc1220771e45549f871ece9@762 b426a367-1105-0410-b9ff-cdf4ab011145
Python
bsd-3-clause
abali96/Shapely,jdmcbr/Shapely,abali96/Shapely,mouadino/Shapely,jdmcbr/Shapely,mouadino/Shapely,mindw/shapely,mindw/shapely
4c3e9723f67448e93da65ff10142a98176cebe9b
publishconf.py
publishconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'https://pappasam.github.io' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_D...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'https://softwarejourneyman.com' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTP...
Change publish site to softwarejourneyman.com
Change publish site to softwarejourneyman.com
Python
mit
pappasam/pappasam.github.io,pappasam/pappasam.github.io
e4427016abdc7ef146cd7550f2ac1dace07be442
plinky.py
plinky.py
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run(debug=True)
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
Remove debug flag from app
Remove debug flag from app
Python
mit
RaspberryPiFoundation/plinky,CodeClub/plinky,codecleaner/plinky,codecleaner/plinky,CodeClub/plinky,martinpeck/plinky,martinpeck/plinky,RaspberryPiFoundation/plinky,RaspberryPiFoundation/plinky
9fd54adcbd1d21232306d15dc7c6a786c867e455
src/som/compiler/sourcecode_compiler.py
src/som/compiler/sourcecode_compiler.py
import os def compile_class_from_file(path, filename, system_class, universe): return _SourcecodeCompiler().compile(path, filename, system_class, universe) def compile_class_from_string(stmt, system_class, universe): return _SourcecodeCompiler().compile_class_string(stmt, system_class, universe) class _Sourc...
import os from StringIO import StringIO def compile_class_from_file(path, filename, system_class, universe): return _SourcecodeCompiler().compile(path, filename, system_class, universe) def compile_class_from_string(stmt, system_class, universe): return _SourcecodeCompiler().compile_class_string(stmt, system_...
Use Python file objects directly as input
Use Python file objects directly as input - fix wrong separator between path and filename Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
SOM-st/PySOM,SOM-st/RPySOM,smarr/RTruffleSOM,smarr/PySOM,SOM-st/RTruffleSOM,smarr/PySOM,SOM-st/RPySOM,SOM-st/PySOM,smarr/RTruffleSOM,SOM-st/RTruffleSOM
9b10bd93191913aaedaa28fc693620a6c2e6d203
pml/load_csv.py
pml/load_csv.py
import os import csv from pml import lattice, element, device def load(directory, name, control_system): lat = lattice.Lattice(name, control_system) with open(os.path.join(directory, 'elements.csv')) as elements: csv_reader = csv.DictReader(elements) for item in csv_reader: e = ele...
import os import csv from pml import lattice, element, device def load(directory, mode, control_system): lat = lattice.Lattice(mode, control_system) with open(os.path.join(directory, mode, 'elements.csv')) as elements: csv_reader = csv.DictReader(elements) for item in csv_reader: e...
Simplify the way modes are loaded into a lattice
Simplify the way modes are loaded into a lattice
Python
apache-2.0
willrogers/pml,willrogers/pml
1619ba48666be69710cd6bcbffe663cd1f7c1066
troposphere/codeguruprofiler.py
troposphere/codeguruprofiler.py
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class ProfilingGroup(AWSObject): resource_type = "AWS::CodeGuruProfiler::ProfilingGroup" props = { 'AgentPermissions': (dict, False), 'ProfilingGroupName': (b...
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 16.1.0 from . import AWSObject class ProfilingGroup(AWSObject): resource_type = "AWS::CodeGuruProfiler::Prof...
Add AWS::CodeGuruProfiler::ProfilingGroup.ComputePlatform per 2020-07-09 update
Add AWS::CodeGuruProfiler::ProfilingGroup.ComputePlatform per 2020-07-09 update
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
227ae986590bf2d5daa5aef028f5f4cd4c1e8917
tests/xtests/base.py
tests/xtests/base.py
from django.test import TestCase from django.contrib.auth.models import User from django.test.client import RequestFactory class BaseTest(TestCase): def setUp(self): self.factory = RequestFactory() def _create_superuser(self, username): return User.objects.create(username=username, is_superus...
from django.test import TestCase from django.contrib.auth.models import User from django.test.client import RequestFactory class BaseTest(TestCase): def setUp(self): self.factory = RequestFactory() def _create_superuser(self, username): return User.objects.create(username=username, is_superus...
Add session in tests Mock HttpRequest
Add session in tests Mock HttpRequest
Python
bsd-3-clause
alexsilva/django-xadmin,jneight/django-xadmin,merlian/django-xadmin,pobear/django-xadmin,cupen/django-xadmin,wbcyclist/django-xadmin,cgcgbcbc/django-xadmin,pobear/django-xadmin,t0nyren/django-xadmin,t0nyren/django-xadmin,marguslaak/django-xadmin,t0nyren/django-xadmin,vincent-fei/django-xadmin,iedparis8/django-xadmin,vi...
58846603f8a5310bb0e6e1eaa9f9f599c315b041
django_webtest/response.py
django_webtest/response.py
# -*- coding: utf-8 -*- from django.test import Client from django.http import SimpleCookie from webtest import TestResponse from django_webtest.compat import urlparse class DjangoWebtestResponse(TestResponse): """ WebOb's Response quacking more like django's HttpResponse. This is here to make more django...
# -*- coding: utf-8 -*- from django.test import Client from django.http import SimpleCookie from webtest import TestResponse from django_webtest.compat import urlparse class DjangoWebtestResponse(TestResponse): """ WebOb's Response quacking more like django's HttpResponse. This is here to make more django...
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
Python
mit
kmike/django-webtest,helenst/django-webtest,vaad2/django-webtest,django-webtest/django-webtest,abbottc/django-webtest,kharandziuk/django-webtest,abbottc/django-webtest,MikeAmy/django-webtest,andrewyoung1991/django-webtest,helenst/django-webtest,yrik/django-webtest,andrewyoung1991/django-webtest,andriisoldatenko/django-...
124487f204c5dedea471bd2c45ad8b929ff7fae0
app/clients/sms/loadtesting.py
app/clients/sms/loadtesting.py
import logging from flask import current_app from app.clients.sms.firetext import ( FiretextClient ) logger = logging.getLogger(__name__) class LoadtestingClient(FiretextClient): ''' Loadtest sms client. ''' def init_app(self, config, statsd_client, *args, **kwargs): super(FiretextClie...
import logging from flask import current_app from app.clients.sms.firetext import ( FiretextClient ) logger = logging.getLogger(__name__) class LoadtestingClient(FiretextClient): ''' Loadtest sms client. ''' def init_app(self, config, statsd_client, *args, **kwargs): super(FiretextClie...
Fix from number on Load testing client
Fix from number on Load testing client
Python
mit
alphagov/notifications-api,alphagov/notifications-api
b394f79132d952be20baf15725715691ace69ced
web/slas-web/web/urls.py
web/slas-web/web/urls.py
"""web URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
"""web URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
Change web admin page title
Change web admin page title
Python
mit
chyla/slas,chyla/pat-lms,chyla/slas,chyla/pat-lms,chyla/slas,chyla/pat-lms,chyla/slas,chyla/slas,chyla/pat-lms,chyla/pat-lms,chyla/slas,chyla/pat-lms,chyla/slas,chyla/pat-lms
e836f3c558085aa0a1275546ac45b8146254ee6b
test/default.py
test/default.py
from mock import MagicMock import pbclient class TestDefault(object): """Test class for pbs.helpers.""" error = {"action": "GET", "exception_cls": "NotFound", "exception_msg": "(NotFound)", "status": "failed", "status_code": 404, "target": "/api...
"""Test module for pbs client.""" from mock import MagicMock import pbclient class TestDefault(object): """Test class for pbs.helpers.""" config = MagicMock() config.server = 'http://server' config.api_key = 'apikey' config.pbclient = pbclient config.project = {'name': 'name', ...
Refactor error as a property.
Refactor error as a property.
Python
agpl-3.0
PyBossa/pbs,PyBossa/pbs,PyBossa/pbs
fc561301c3a3aea79043348a01e6a468a5693d3e
tests/test_importable.py
tests/test_importable.py
"""Basic set of tests to ensure entire code base is importable""" import pytest def test_importable(): """Simple smoketest to ensure all isort modules are importable""" import isort import isort._future import isort._future._dataclasses import isort._version import isort.api import isort.c...
"""Basic set of tests to ensure entire code base is importable""" import pytest def test_importable(): """Simple smoketest to ensure all isort modules are importable""" import isort import isort._future import isort._future._dataclasses import isort._version import isort.api import isort.c...
Remove no longer needed import check
Remove no longer needed import check
Python
mit
PyCQA/isort,PyCQA/isort
e3aa12af05003222b295a4cea39a1c05c911024a
main.py
main.py
from connect_four import ConnectFour def main(): """ Play a game! """ connect_four = ConnectFour() # start the game connect_four.start() if __name__ == "__main__": # Default "main method" idiom. main()
from connect_four import ConnectFour def main(): """ Play a game! """ connect_four = ConnectFour() menu_choice = 1 while menu_choice == 1: # start the game connect_four.start_new() # menu print("Menu") print("1 - Play again") print("2 - Quit") ...
Add menu to start new game and quit
Add menu to start new game and quit
Python
mit
LouisBarranqueiro/ia-connect-four-game
08c2e9144e605063ac3c6313efe639eb7139ba75
main.py
main.py
# Fox, rewritten in Python for literally no reason at all. import discord import asyncio print("Just a moment, Fox is initializing...") fox = discord.Client() @fox.event async def on_ready(): print('Fox is ready!') print('Fox username: ' + fox.user.name) print('Fox user ID: ' + fox.user.id) print('--...
# Fox, rewritten in Python for literally no reason at all. import discord import asyncio import plugins import plugins.core print("Just a moment, Fox is initializing...") fox = discord.Client() @fox.event async def on_ready(): print('Fox is ready!') print('Fox username: ' + fox.user.name) print('Fox u...
Add import statements for plugin system
Add import statements for plugin system Signed-off-by: Reed <f5cabf8735907151a446812c9875d6c0c712d847@plusreed.com>
Python
mit
plusreed/foxpy
c5f75072707dbe9a723ffbff71ab01d0519b6baa
tools/generateDataset.py
tools/generateDataset.py
import numpy as np import os import sys import time from unrealcv import client class Dataset(object): def __init__(self,folder,nberOfImages): self.folder=folder self.nberOfImages=nberOfImages self.client.connect() def scan(): try: p=self.client.request('vget /c...
import numpy as np import os import sys import time from unrealcv import client class Dataset(object): def __init__(self,folder,nberOfImages): self.folder=folder self.nberOfImages=nberOfImages self.client.connect() def scan(): try: p=self.client.request('vget /c...
Structure of data generator iimproved
:muscle: Structure of data generator iimproved Structure of dataset generator improved
Python
bsd-2-clause
fkenghagho/RobotVQA
726beb71b45c7320b4e2e883f246d389709efe19
run_tracker.py
run_tracker.py
import sys from cloudtracker import main def run_tracker(input_dir): print( " Running the cloud-tracking algorithm... " ) print( " Input dir: \"" + input_dir + "\" \n" ) main.main(input_dir) print( "\n Entrainment analysis completed " ) if __name__ == '__main__': if len(sys.argv) == 1: ...
import sys, json from cloudtracker import main as tracker_main def run_tracker(input): print( " Running the cloud-tracking algorithm... " ) print( " Input dir: \"" + input + "\" \n" ) # Read .json configuration file with open('model_config.json', 'r') as json_file: config = json.load(json...
Read .json file from starter
Read .json file from starter
Python
bsd-2-clause
lorenghoh/loh_tracker
116708c5458b68110e75a593a0edaa0298bb5586
cyder/core/fields.py
cyder/core/fields.py
from django.db.models import CharField from django.core.exceptions import ValidationError from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising...
from django.db.models import CharField, NOT_PROVIDED from django.core.exceptions import ValidationError from south.modelsinspector import add_introspection_rules from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC addre...
Add introspection rule; prevent South weirdness
Add introspection rule; prevent South weirdness
Python
bsd-3-clause
drkitty/cyder,murrown/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,drkitty/cyder,zeeman/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,zeeman/cyder,murrown/cyder,zeeman/cyder
f2312d1546eb3f6de75cc03a2dabb427a2174e17
examples/sequencealignment.py
examples/sequencealignment.py
# Create sequences to be aligned. from alignment.sequence import Sequence a = Sequence("what a beautiful day".split()) b = Sequence("what a disappointingly bad day".split()) print "Sequence A:", a print "Sequence B:", b print # Create a vocabulary and encode the sequences. from alignment.vocabulary import Vocabulary v...
from alignment.sequence import Sequence from alignment.vocabulary import Vocabulary from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner # Create sequences to be aligned. a = Sequence("what a beautiful day".split()) b = Sequence("what a disappointingly bad day".split()) print "Sequence A:", a pr...
Update the sequence alignment example.
Update the sequence alignment example.
Python
bsd-3-clause
eseraygun/python-entities,eseraygun/python-alignment
d584ccea9fe985fa230c937ee2e6a03ef6b99967
audio_pipeline/util/__init__.py
audio_pipeline/util/__init__.py
from . import Exceptions from . import MBInfo from . import Tag from . import Util from . import format from . import Discogs import re # unknown artist input pattern: class Utilities: unknown_artist_pattern = re.compile(r'unknown artist|^\s*$', flags=re.I) @classmethod def know_artist_name(cls, artist):...
from . import Exceptions from . import MBInfo from . import Tag from . import Util from . import format from . import Discogs import re # unknown artist input pattern: class Utilities: unknown_artist_pattern = re.compile(r'unknown artist|^\s*$', flags=re.I) @classmethod def know_artist_name(cls, artist):...
Check to make sure artist is not None, or evil will occur...
Check to make sure artist is not None, or evil will occur...
Python
mit
hidat/audio_pipeline
19e9080f06aa2264e77b65a9c1ad6d30e6b7da4c
app/aflafrettir/routes.py
app/aflafrettir/routes.py
from flask import render_template from . import aflafrettir from ..models import User, Category, Post @aflafrettir.route('/') def index(): categories = Category.get_all_active() posts = Post.get_all() return render_template('aflafrettir/index.html', categories=categories, ...
from flask import render_template from . import aflafrettir from ..models import User, Category, Post @aflafrettir.route('/frettir') @aflafrettir.route('/', alias=True) def index(): categories = Category.get_all_active() posts = Post.get_all() return render_template('aflafrettir/index.html', ...
Add a route for displaying posts by categories
Add a route for displaying posts by categories
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is