commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
f5bbdea74c0f8a0cc8ac4331ea8adc45c3f266c8 | converter.py | converter.py | #
# MIT License
# Copyright (c) 2017 Hampus Tågerud
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, m... | #
# MIT License
# Copyright (c) 2017 Hampus Tågerud
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, m... | Read files defined as argument | Read files defined as argument
| Python | mit | hampustagerud/colorconverter | ---
+++
@@ -23,11 +23,23 @@
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
+import sys
+
def main():
+ if len(sys.argv) > 1:
+ for i in range(1, len(sys.argv)):
+ with open(sys.argv[i]) as f:
+ lines = f.read().splitlines()
+ for line in lines:
+ ... |
33e88c063fedb11211e3786a9d722a9d12f72ce8 | contrib/dn42_whoisd.py | contrib/dn42_whoisd.py | #!/bin/python
# coding: utf-8
import argparse
import asyncio
import lglass.dn42
import lglass.whois.engine
import lglass.whois.server
def create_database(db_path):
return lglass.dn42.DN42Database(db_path)
if __name__ == "__main__":
argparser = argparse.ArgumentParser(description="DN42 Whois server")
arg... | #!/bin/python
# coding: utf-8
import argparse
import asyncio
import lglass.dn42
import lglass.whois.engine
import lglass.whois.server
def create_database(db_path):
return lglass.dn42.DN42Database(db_path)
if __name__ == "__main__":
argparser = argparse.ArgumentParser(description="DN42 Whois server")
arg... | Add type hint for -DN42 | Add type hint for -DN42
| Python | mit | fritz0705/lglass | ---
+++
@@ -21,6 +21,7 @@
db = create_database(args.database)
engine = lglass.whois.engine.WhoisEngine(db)
+ engine.type_hints[r"[0-9A-Za-z]+-DN42$"] = {"role", "person"}
server = lglass.whois.server.SimpleWhoisServer(engine)
loop = asyncio.get_event_loop() |
fdb3801a513357c4f5ba655a6216ba59ee1e3df9 | overlay/Chart.py | overlay/Chart.py | from SVGGenerator import SVGGenerator
from Label import Label
class Chart(SVGGenerator):
def __init__(self, name, title, data):
SVGGenerator.__init__(self, './chart.svg.mustache')
self.name = name
self.title = title
self.x = 10
self.y = 10
self.width = 110
s... | from SVGGenerator import SVGGenerator
from Label import Label
class Chart(SVGGenerator):
def __init__(self, name, title, data):
SVGGenerator.__init__(self, './chart.svg.mustache')
self.name = name
self.title = title
self.x = 10
self.y = 10
self.width = 110
s... | Increase opacity on chart backgrounds | Increase opacity on chart backgrounds
| Python | mit | gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,thelonious/g2x,gizmo-cda/g2x | ---
+++
@@ -13,7 +13,7 @@
self.height = 110
self.padding = 5
self.background_color = "white"
- self.background_opacity = 0.4
+ self.background_opacity = 0.6
self.path_data = data
self.path_color = "rgb(0,192,0)"
|
56327baa67d5f05551bc52a1c0466e8d8b905797 | metrics.py | metrics.py | """The metrics module implements functions assessing prediction error for specific purposes."""
import numpy as np
def trapz(x, y):
"""Trapezoidal rule for integrating
the curve defined by x-y pairs.
Assume x and y are in the range [0,1]
"""
assert len(x) == len(y), 'x and y need to be of same len... | """The metrics module implements functions assessing prediction error for specific purposes."""
import numpy as np
def trapz(x, y):
"""Trapezoidal rule for integrating
the curve defined by x-y pairs.
Assume x and y are in the range [0,1]
"""
assert len(x) == len(y), 'x and y need to be of same le... | Add the missing 'np.' before 'array' | Add the missing 'np.' before 'array'
| Python | mit | ceshine/isml15-wed | ---
+++
@@ -1,6 +1,7 @@
"""The metrics module implements functions assessing prediction error for specific purposes."""
import numpy as np
+
def trapz(x, y):
"""Trapezoidal rule for integrating
@@ -8,13 +9,12 @@
Assume x and y are in the range [0,1]
"""
assert len(x) == len(y), 'x and y nee... |
222628c6747bdc3574bcb7cf6257c785ffa6451d | inventory_control/database/sql.py | inventory_control/database/sql.py | """
So this is where all the SQL commands live
"""
CREATE_SQL = """
CREATE TABLE component_type (
id INT PRIMARY KEY AUTO_INCREMENT,
type VARCHAR(255) UNIQUE
);
CREATE TABLE components (
id INT PRIMARY KEY AUTO_INCREMENT,
sku TEXT,
type INT,
status INT,
FOREIGN KEY (type) REFERENCES compo... | """
So this is where all the SQL commands live
"""
CREATE_SQL = """
CREATE TABLE component_type (
id INT PRIMARY KEY AUTO_INCREMENT,
type VARCHAR(255) UNIQUE
);
CREATE TABLE components (
id INT PRIMARY KEY AUTO_INCREMENT,
serial_number VARCHAR(255),
sku TEXT,
type INT,
status INT,
FOR... | Add product_number and serial_number identifiers | Add product_number and serial_number identifiers
| Python | mit | worldcomputerxchange/inventory-control,codeforsanjose/inventory-control | ---
+++
@@ -11,6 +11,7 @@
CREATE TABLE components (
id INT PRIMARY KEY AUTO_INCREMENT,
+ serial_number VARCHAR(255),
sku TEXT,
type INT,
status INT,
@@ -19,6 +20,7 @@
CREATE TABLE projects (
id INT PRIMARY KEY AUTO_INCREMENT,
+ product_number INT,
motherboard INT,
power_... |
4a4a3eed7b959e342e3ff00dfc28f116158839d6 | tests/test_result.py | tests/test_result.py | import unittest
from performance_testing.result import Result, File
import os
import shutil
class ResultTestCase(unittest.TestCase):
def setUp(self):
self.current_directory = os.path.dirname(os.path.abspath(__file__))
self.result_directory = os.path.join(self.current_directory, 'assets/test_result... | import unittest
from performance_testing.result import Result, File
import os
import shutil
class ResultTestCase(unittest.TestCase):
def setUp(self):
self.current_directory = os.path.dirname(os.path.abspath(__file__))
self.result_directory = os.path.join(self.current_directory, 'assets/test_result... | Split up tests for Result and File | Split up tests for Result and File
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | ---
+++
@@ -9,10 +9,23 @@
self.current_directory = os.path.dirname(os.path.abspath(__file__))
self.result_directory = os.path.join(self.current_directory, 'assets/test_result')
- def test_result_init(self):
+ def clear_result_dir(self):
if os.path.exists(self.result_directory):
... |
a2997b5f76c658ba8ddd933275aa6f37c1bedc50 | promgen/util.py | promgen/util.py | # Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE
import requests.sessions
from promgen.version import __version__
def post(url, **kwargs):
with requests.sessions.Session() as session:
session.headers['User-Agent'] = 'promgen/{}'.format(__... | # Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE
import requests.sessions
from promgen.version import __version__
def post(url, *args, **kwargs):
with requests.sessions.Session() as session:
session.headers['User-Agent'] = 'promgen/{}'.fo... | Make sure we pass *args to the requests session object | Make sure we pass *args to the requests session object
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen | ---
+++
@@ -6,18 +6,19 @@
from promgen.version import __version__
-def post(url, **kwargs):
+def post(url, *args, **kwargs):
with requests.sessions.Session() as session:
session.headers['User-Agent'] = 'promgen/{}'.format(__version__)
- return session.post(url, **kwargs)
+ return sess... |
aaf0d25cae834222f14303f33ab126be7ae29142 | pambox/intelligibility_models/__init__.py | pambox/intelligibility_models/__init__.py | import sepsm
import sii
| """
The :mod:`pambox.intelligibility_modesl` module gather speech intelligibility
models.
"""
from .mrsepsm import MrSepsm
from .sepsm import Sepsm
from .sii import Sii
__all__ = ['Sepsm',
'MrSepsm',
'Sii']
| Define __all__ in intelligibility_models package | Define __all__ in intelligibility_models package
Define to import all intelligibility models available if one imports
with *. Also, allows to import the models directly from
intelligibility_models, rather than having to import the modules.
| Python | bsd-3-clause | achabotl/pambox | ---
+++
@@ -1,2 +1,13 @@
-import sepsm
-import sii
+"""
+The :mod:`pambox.intelligibility_modesl` module gather speech intelligibility
+models.
+"""
+from .mrsepsm import MrSepsm
+from .sepsm import Sepsm
+from .sii import Sii
+
+__all__ = ['Sepsm',
+ 'MrSepsm',
+ 'Sii']
+
+ |
e90cc22226189b8950957cbf8637e49ee7798c4b | django_token/middleware.py | django_token/middleware.py | from django.http import HttpResponseBadRequest
from django.contrib import auth
class TokenMiddleware(object):
"""
Middleware that authenticates against a token in the http authorization header.
"""
def process_request(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATIO... | from django.http import HttpResponseBadRequest
from django.contrib import auth
class TokenMiddleware(object):
"""
Middleware that authenticates against a token in the http authorization header.
"""
def process_request(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATIO... | Use partition instead of split. | Use partition instead of split.
| Python | mit | jasonbeverage/django-token | ---
+++
@@ -8,15 +8,15 @@
"""
def process_request(self, request):
- auth_header = request.META.get('HTTP_AUTHORIZATION', b'').split()
+ auth_header = request.META.get('HTTP_AUTHORIZATION', b'').partition(' ')
- if not auth_header or auth_header[0].lower() != b'token':
+ if au... |
721be562a175227fa496789e9ce642416c5993b7 | enactiveagents/controller/controller.py | enactiveagents/controller/controller.py | """
Main world controller.
"""
from appstate import AppState
import pygame
import events
class Controller(events.EventListener):
"""
Controller class.
"""
def __init__(self):
pass
def _quit(self):
"""
Gracefully quit the simulator.
"""
quitEvent = events... | """
Main world controller.
"""
from appstate import AppState
import pygame
import events
class Controller(events.EventListener):
"""
Controller class.
"""
def __init__(self):
pass
def _quit(self):
"""
Gracefully quit the simulator.
"""
quitEvent = events... | Fix bug crashing the experiment on a non-recognized keypress. | Fix bug crashing the experiment on a non-recognized keypress.
| Python | mit | Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents | ---
+++
@@ -36,8 +36,6 @@
self._quit()
return
- pygame.M
-
def notify(self, event):
if isinstance(event, events.TickEvent):
self.process_input() |
53acdb65defa43db67f11a5c5a41c1353e9498f7 | tests/test__utils.py | tests/test__utils.py | # -*- coding: utf-8 -*-
| # -*- coding: utf-8 -*-
import pytest
import numpy as np
import dask.array as da
import dask.array.utils as dau
import dask_ndfourier._utils
@pytest.mark.parametrize(
"a, s, n, axis", [
(da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1),
]
)
def test_norm_args(a, s, n, axis):
... | Test that `s` as a Dask Array is preserved | Test that `s` as a Dask Array is preserved
Ensure that if `s` is a Dask Array, it will still be a Dask Array after
type normalization is done on the input arguments of the Fourier
filters. This allows Fourier filters to construct a computation around
an unknown `s` in addition to an unknown input array.
| Python | bsd-3-clause | dask-image/dask-ndfourier | ---
+++
@@ -1 +1,22 @@
# -*- coding: utf-8 -*-
+
+
+import pytest
+
+import numpy as np
+
+import dask.array as da
+import dask.array.utils as dau
+
+import dask_ndfourier._utils
+
+
+@pytest.mark.parametrize(
+ "a, s, n, axis", [
+ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1),
+ ... |
a13829a0c2b95773832e68e6f0a1dc661a288ec4 | tests/test_action.py | tests/test_action.py | import unittest
from unittest import mock
from action import PrintAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("G... | import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock... | Add EmailActionTest class and as well as a test to check if email is sent to the right server. | Add EmailActionTest class and as well as a test to check if email is sent to the right server.
| Python | mit | bsmukasa/stock_alerter | ---
+++
@@ -1,7 +1,8 @@
+import smtplib
import unittest
from unittest import mock
-from action import PrintAction
+from action import PrintAction, EmailAction
@mock.patch("builtins.print")
@@ -10,3 +11,13 @@
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_call... |
ef27b615702d9ce84db9087898c1f66286e66cf2 | PRESUBMIT.py | PRESUBMIT.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.
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit... | # Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built... | Fix the license header regex. | Fix the license header regex.
Most of the files are attributed to Google Inc so I used this instead of
Chromium Authors.
R=mark@chromium.org
BUG=
TEST=
Review URL: http://codereview.chromium.org/7108074
| Python | bsd-3-clause | csulmone/gyp,csulmone/gyp,csulmone/gyp,csulmone/gyp | ---
+++
@@ -1,4 +1,4 @@
-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -19,8 +19,17 @@
def CheckChangeOnCommit(input_api, output_api)... |
0819957eda318205e17591dccd81482701eab25c | tests/test_sqlite.py | tests/test_sqlite.py | # This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more informatio... | # This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more informatio... | Use faster password hasher in sqlite tests | Use faster password hasher in sqlite tests
Fixed #18163
| Python | bsd-3-clause | dbaxa/django,gunchleoc/django,varunnaganathan/django,yamila-moreno/django,dracos/django,savoirfairelinux/django,crazy-canux/django,mattseymour/django,charettes/django,MatthewWilkes/django,dsanders11/django,ccn-2m/django,beck/django,dgladkov/django,litchfield/django,MounirMesselmeni/django,jyotsna1820/django,ojake/djang... | ---
+++
@@ -22,3 +22,9 @@
}
SECRET_KEY = "django_tests_secret_key"
+# To speed up tests under SQLite we use the MD5 hasher as the default one.
+# This should not be needed under other databases, as the relative speedup
+# is only marginal there.
+PASSWORD_HASHERS = (
+ 'django.contrib.auth.hashers.MD5Password... |
43b8e4de31d0659561ffedfeb0ab4a42f035eade | dev/test_all.py | dev/test_all.py | # Copyright 2021 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2021 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Exclude chamber workflow from targets tested by j2 testall | Exclude chamber workflow from targets tested by j2 testall
PiperOrigin-RevId: 384424406
| Python | apache-2.0 | google/j2cl,google/j2cl,google/j2cl,google/j2cl,google/j2cl | ---
+++
@@ -20,7 +20,7 @@
def main(argv):
root = "//third_party/java_src/j2cl/"
- cmd = ["blaze", "test", "--keep_going"]
+ cmd = ["blaze", "test", "--test_tag_filters=-chamber", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(a... |
a3c3c5f4cbbea80aada1358ca52c698cf13136cc | unittests/test_xmp.py | unittests/test_xmp.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.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to
from blister.xmp import XMP
class XMPTest (unittest.TestCase):
... | # 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.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to
from blister.xmp import XMP
class XMPTest (unittest.TestCase):
... | Move XMP init into setUp() | Move XMP init into setUp()
| Python | bsd-3-clause | daaang/blister | ---
+++
@@ -9,19 +9,20 @@
class XMPTest (unittest.TestCase):
+ def setUp (self):
+ self.xmp = XMP()
+
def test_degenerate (self):
- xmp = XMP()
- assert_that(xmp, evaluates_to(False))
- assert_that(xmp, has_length(0))
- assert_that(list(xmp), is_(equal_to([])))
+ ... |
c5cf8df78106e15a81f976f99d26d361b036318a | indra/tools/reading/run_drum_reading.py | indra/tools/reading/run_drum_reading.py | import sys
import json
from indra.sources.trips.drum_reader import DrumReader
from indra.sources.trips import process_xml
def read_content(content):
sentences = []
for k, v in content.items():
sentences += v
dr = DrumReader(to_read=sentences)
try:
dr.start()
except SystemExit:
... | import sys
import json
import time
import pickle
from indra.sources.trips import process_xml
from indra.sources.trips.drum_reader import DrumReader
def set_pmid(statements, pmid):
for stmt in statements:
for evidence in stmt.evidence:
evidence.pmid = pmid
def read_content(content, host):
... | Improve batch Drum reading implementation | Improve batch Drum reading implementation
| Python | bsd-2-clause | bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra | ---
+++
@@ -1,25 +1,49 @@
import sys
import json
+import time
+import pickle
+from indra.sources.trips import process_xml
from indra.sources.trips.drum_reader import DrumReader
-from indra.sources.trips import process_xml
-def read_content(content):
- sentences = []
- for k, v in content.items():
- ... |
b3f516b91d118824bb90f834184aa25a5a5f1c68 | train.py | train.py | # -*- coding: utf-8 -*-
import logging
from gensim.models import word2vec
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.LineSentence("wiki_seg.txt")
model = word2vec.Word2Vec(sentences, size=250)
#保存模型,供日後使用
model.sa... | # -*- coding: utf-8 -*-
import logging
from gensim.models import word2vec
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.LineSentence("wiki_seg.txt")
model = word2vec.Word2Vec(sentences, vector_size=250)
#保存模型,供日後使用
m... | Fix the argument name to adapt gensim 4.0. | [U] Fix the argument name to adapt gensim 4.0. | Python | mit | zake7749/word2vec-tutorial | ---
+++
@@ -8,7 +8,7 @@
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.LineSentence("wiki_seg.txt")
- model = word2vec.Word2Vec(sentences, size=250)
+ model = word2vec.Word2Vec(sentences, vector_size=250)
#保存模型,供日後使用
model... |
afd496ccdde07502e6f42ae1b4127d130aed050c | docs/conf.py | docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... | Reset docs theme, RTD should override | Reset docs theme, RTD should override
| Python | mit | galaxyproject/gravity | ---
+++
@@ -31,5 +31,5 @@
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
-html_theme = 'alabaster'
+html_theme = 'default'
html_static_path = ['_static'] |
9942b7b6e550ec6f76def44a7470f747c47b13a8 | utils/00-cinspect.py | utils/00-cinspect.py | """ A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat ... | """ A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat ... | Patch the colorized formatter to not break for C modules. | Patch the colorized formatter to not break for C modules.
| Python | bsd-3-clause | punchagan/cinspect,punchagan/cinspect | ---
+++
@@ -25,3 +25,19 @@
return fname
OI.find_file = patch_find_file
+
+ipy = get_ipython()
+
+old_format = ipy.inspector.format
+
+def c_format(raw, *args, **kwargs):
+ return raw
+
+def my_format(raw, out = None, scheme = ''):
+ try:
+ output = old_format(raw, out, scheme)
+ except:
+ ... |
886539f4bd3d67938f90b6500ee625db470284a2 | UM/View/CompositePass.py | UM/View/CompositePass.py | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Resources import Resources
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
def __init__(self, name, width, height):
super().__init__(name... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Resources import Resources
from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
... | Make basic composite pass work | Make basic composite pass work
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -1,17 +1,21 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
+from UM.Application import Application
from UM.Resources import Resources
+
+from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import Ope... |
a2e4e8593ec4c09d504b74544b134d27d1428ce3 | emma2/msm/flux/__init__.py | emma2/msm/flux/__init__.py | from .api import *
| r"""
===================================================================
flux - Reactive flux an transition pathways (:mod:`emma2.msm.flux`)
===================================================================
.. currentmodule:: emma2.msm.flux
This module contains functions to compute reactive flux networks and
find ... | Include flux package in doc | [msm/flux] Include flux package in doc
| Python | bsd-2-clause | arokem/PyEMMA,trendelkampschroer/PyEMMA,trendelkampschroer/PyEMMA,arokem/PyEMMA | ---
+++
@@ -1 +1,54 @@
+r"""
+
+===================================================================
+flux - Reactive flux an transition pathways (:mod:`emma2.msm.flux`)
+===================================================================
+
+.. currentmodule:: emma2.msm.flux
+
+This module contains functions to comput... |
5ae5c27f69cdfb1c53ada0a2aa90d76c4d3ce421 | memcached.py | memcached.py | #!/usr/bin/env python
#
# igcollect - Memcached
#
# Copyright (c) 2016, InnoGames GmbH
#
import telnetlib
import sys
import socket
import time
def main(host='127.0.0.1', port='11211'):
hostname = socket.gethostname().replace('.', '_')
ts = str(int(time.time()))
template = 'servers.' + hostname + '.softwa... | #!/usr/bin/env python
#
# igcollect - Memcached
#
# Copyright (c) 2016, InnoGames GmbH
#
import telnetlib
import sys
import socket
import time
import re
def main(host='127.0.0.1', port='11211'):
hostname = socket.gethostname().replace('.', '_')
ts = str(int(time.time()))
template = 'servers.' + hostname ... | Use regexp for checking the line | Use regexp for checking the line
| Python | mit | innogames/igcollect | ---
+++
@@ -9,18 +9,19 @@
import sys
import socket
import time
+import re
def main(host='127.0.0.1', port='11211'):
hostname = socket.gethostname().replace('.', '_')
ts = str(int(time.time()))
template = 'servers.' + hostname + '.software.memcached.{1} {2} ' + ts
+ pattern = re.compile('STAT... |
3863bda6af40f62e49f4883468f4947d46f0cccc | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# 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 a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# 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 a... | Update dsub version to 0.3.6 | Update dsub version to 0.3.6
PiperOrigin-RevId: 281980915
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.3.6.dev0'
+DSUB_VERSION = '0.3.6' |
9a791b9c5e79011edaa2a9d2f25bf92e0bf17543 | client/libsinan/version_check_handler.py | client/libsinan/version_check_handler.py | import libsinan
from libsinan import handler, output, jsax
class VersionCheckTaskHandler(output.SimpleTaskHandler):
def object_end(self):
""" We only get one object per right now so
lets print it out when we get it """
if self.task == "version":
if self.event_type == 'info':... | import libsinan
from libsinan import handler, output, jsax
class VersionCheckTaskHandler(output.SimpleTaskHandler):
def __init__(self):
output.SimpleTaskHandler.__init__(self)
self.version = None
def object_end(self):
""" We only get one object per right now so
lets print it ... | Make sure version is initialized | Make sure version is initialized
| Python | mit | erlware-deprecated/sinan,erlware-deprecated/sinan,ericbmerritt/sinan,ericbmerritt/sinan,erlware-deprecated/sinan,ericbmerritt/sinan | ---
+++
@@ -4,6 +4,9 @@
class VersionCheckTaskHandler(output.SimpleTaskHandler):
+ def __init__(self):
+ output.SimpleTaskHandler.__init__(self)
+ self.version = None
def object_end(self):
""" We only get one object per right now so |
5abe9a29ae586907304649fe6682e3e8997da310 | app/views.py | app/views.py | from index import app
from flask import render_template, request
from config import BASE_URL
from query import get_callout, get_billboard
SHEET_ID = 'tzE2PsqJoWRpENlMr-ZlS8A'
#SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet
#@app.route('/')
#def index():
# page_url = BASE_URL + request.path
# page_title = '... | from index import app
from flask import render_template, request
from config import BASE_URL
from query import get_callout, get_billboard
SHEET_ID = 'tzE2PsqJoWRpENlMr-ZlS8A'
#SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet
@app.route('/')
def index():
page_url = BASE_URL + request.path
page_title = 'Audi... | Update stream name to Replay | Update stream name to Replay
| Python | apache-2.0 | vprnet/audio-player,vprnet/audio-player,vprnet/audio-player | ---
+++
@@ -7,27 +7,27 @@
#SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet
-#@app.route('/')
-#def index():
-# page_url = BASE_URL + request.path
-# page_title = 'Audio Player'
-# stream_name = "My Place"
-#
-# social = {
-# 'title': "VPR Audio Player",
-# 'subtitle': "",
-# '... |
738b0e1344572d000f51e862000fb719c7035c2c | st2reactor/st2reactor/cmd/rulesengine.py | st2reactor/st2reactor/cmd/rulesengine.py | import os
from oslo.config import cfg
from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2common.constants.logging import DEFAULT_LOGGING_CONF_PATH
from st2reactor.rules import config
from st2reactor.rules import worker
LOG = logging.getLo... | import os
import sys
from oslo.config import cfg
from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2common.constants.logging import DEFAULT_LOGGING_CONF_PATH
from st2reactor.rules import config
from st2reactor.rules import worker
LOG = lo... | Fix rules engine version reporting. | Fix rules engine version reporting.
| Python | apache-2.0 | Itxaka/st2,punalpatel/st2,grengojbo/st2,grengojbo/st2,jtopjian/st2,nzlosh/st2,lakshmi-kannan/st2,peak6/st2,jtopjian/st2,peak6/st2,alfasin/st2,jtopjian/st2,Itxaka/st2,Itxaka/st2,pinterb/st2,StackStorm/st2,punalpatel/st2,tonybaloney/st2,punalpatel/st2,pixelrebel/st2,StackStorm/st2,pixelrebel/st2,lakshmi-kannan/st2,StackS... | ---
+++
@@ -1,4 +1,5 @@
import os
+import sys
from oslo.config import cfg
@@ -39,6 +40,8 @@
try:
_setup()
return worker.work()
+ except SystemExit as exit_code:
+ sys.exit(exit_code)
except:
LOG.exception('(PID:%s) RulesEngine quit due to exception.', os.getpid())
... |
77b5680794a7a60dedf687f4a199e48121f96955 | tests/performance/benchmark_aggregator.py | tests/performance/benchmark_aggregator.py | """
Performance tests for the agent/dogstatsd metrics aggregator.
"""
from aggregator import MetricsAggregator
class TestAggregatorPerf(object):
def test_aggregation_performance(self):
ma = MetricsAggregator('my.host')
flush_count = 10
loops_per_flush = 10000
metric_count = 5... | """
Performance tests for the agent/dogstatsd metrics aggregator.
"""
from aggregator import MetricsAggregator
class TestAggregatorPerf(object):
def test_aggregation_performance(self):
ma = MetricsAggregator('my.host')
flush_count = 10
loops_per_flush = 10000
metric_count = 5... | Add sets + a float value to the benchmark. | Add sets + a float value to the benchmark.
| Python | bsd-3-clause | yuecong/dd-agent,darron/dd-agent,oneandoneis2/dd-agent,AniruddhaSAtre/dd-agent,packetloop/dd-agent,remh/dd-agent,guruxu/dd-agent,jyogi/purvar-agent,relateiq/dd-agent,JohnLZeller/dd-agent,citrusleaf/dd-agent,lookout/dd-agent,citrusleaf/dd-agent,zendesk/dd-agent,zendesk/dd-agent,JohnLZeller/dd-agent,oneandoneis2/dd-agent... | ---
+++
@@ -24,6 +24,8 @@
ma.submit_packets('counter.%s:%s|c' % (j, i))
ma.submit_packets('gauge.%s:%s|g' % (j, i))
ma.submit_packets('histogram.%s:%s|h' % (j, i))
+ ma.submit_packets('set.%s:%s|s' % (j, 1.0))
+
ma.flush()
... |
c9d1a3ad2c3c64f49ec83cf8d09cc6d35915990c | airtravel.py | airtravel.py | """Model for aircraft flights"""
class Flight:
def __init__(self, number):
if not number[:4].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:4].isupper():
raise ValueError("Invalid airline code'{}'".format(number))
if not (numb... | """Model for aircraft flights"""
class Flight:
"""A flight with a specific passenger aircraft."""
def __init__(self, number, aircraft):
if not number[:4].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:4].isupper():
raise ValueErro... | Add aircraft and seating arrangement to Flight | Add aircraft and seating arrangement to Flight
| Python | mit | kentoj/python-fundamentals | ---
+++
@@ -2,7 +2,9 @@
class Flight:
- def __init__(self, number):
+ """A flight with a specific passenger aircraft."""
+
+ def __init__(self, number, aircraft):
if not number[:4].isalpha():
raise ValueError("No airline code in '{}'".format(number))
@@ -13,12 +15,18 @@
... |
adcb7af597c77d85eb9234d91e2c0bd8575630e1 | fcm_django/api/__init__.py | fcm_django/api/__init__.py | from django.conf import settings
if "tastypie" in settings.INSTALLED_APPS:
# Tastypie resources are importable from the api package level (backwards compatibility)
from .tastypie import APNSDeviceResource, GCMDeviceResource, WNSDeviceResource, APNSDeviceAuthenticatedResource, \
GCMDeviceAuthenticatedResource, WNSD... | from django.conf import settings
if "tastypie" in settings.INSTALLED_APPS:
# Tastypie resources are importable from the api package level (backwards compatibility)
from .tastypie import APNSDeviceAuthenticatedResource, FCMDeviceResource
__all__ = [
"APNSDeviceAuthenticatedResource",
"FCMDeviceResource",
]
| Remove references to old resources | Remove references to old resources
| Python | mit | xtrinch/fcm-django | ---
+++
@@ -2,14 +2,9 @@
if "tastypie" in settings.INSTALLED_APPS:
# Tastypie resources are importable from the api package level (backwards compatibility)
- from .tastypie import APNSDeviceResource, GCMDeviceResource, WNSDeviceResource, APNSDeviceAuthenticatedResource, \
- GCMDeviceAuthenticatedResource, WNSDe... |
0e5b2af3fe04bd12b95b15215db0416b79c25df6 | fake_useragent/fake.py | fake_useragent/fake.py | import os
import random
try:
import json
except ImportError:
import simplejson as json
from fake_useragent import settings
from fake_useragent.build import build_db
class UserAgent(object):
def __init__(self):
super(UserAgent, self).__init__()
# check db json file exists
if not os... | import os
import random
try:
import json
except ImportError:
import simplejson as json
from fake_useragent import settings
from fake_useragent.build import build_db
class UserAgent(object):
def __init__(self):
super(UserAgent, self).__init__()
# check db json file exists
if not os... | Fix non existing useragents shortcut | Fix non existing useragents shortcut
| Python | apache-2.0 | sebalas/fake-useragent,hellysmile/fake-useragent,hellysmile/fake-useragent,hellysmile/fake-useragent,mochawich/fake-useragent | ---
+++
@@ -37,6 +37,9 @@
elif attr == 'ff':
attr = 'firefox'
- return self.data['browsers'][attr][
- random.randint(0, settings.BROWSERS_COUNT_LIMIT - 1)
- ]
+ try:
+ return self.data['browsers'][attr][
+ random.randint(0, settings.BRO... |
13dc6443500d09432c6410b766c5c6eda05fdf7a | froide/publicbody/forms.py | froide/publicbody/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from froide.helper.form_utils import JSONMixin
from .models import PublicBody
from .widgets import PublicBodySelect
class PublicBodyForm(JSONMixin, forms.Form):
publicbody = forms.ModelChoiceField(
queryset=PublicBody.o... | from django import forms
from django.utils.translation import ugettext_lazy as _
from froide.helper.form_utils import JSONMixin
from .models import PublicBody
from .widgets import PublicBodySelect
class PublicBodyForm(JSONMixin, forms.Form):
publicbody = forms.ModelChoiceField(
queryset=PublicBody.o... | Add as_data to multiple publicbody form | Add as_data to multiple publicbody form | Python | mit | stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide | ---
+++
@@ -28,7 +28,7 @@
return []
-class MultiplePublicBodyForm(JSONMixin, forms.Form):
+class MultiplePublicBodyForm(PublicBodyForm):
publicbody = forms.ModelMultipleChoiceField(
queryset=PublicBody.objects.all(),
label=_("Search for a topic or a public body:")
@@ -40,3 ... |
96cbe6cd5b1d86663fe44c7fb4351fdb9bf7b2eb | metafunctions/map.py | metafunctions/map.py | import typing as tp
import itertools
from metafunctions.concurrent import FunctionMerge
from metafunctions.operators import concat
class MergeMap(FunctionMerge):
def __init__(self, function:tp.Callable, merge_function:tp.Callable=concat):
super().__init__(merge_function, (function, ))
def _get_call_... | import typing as tp
import itertools
from metafunctions.concurrent import FunctionMerge
from metafunctions.operators import concat
class MergeMap(FunctionMerge):
def __init__(self, function:tp.Callable, merge_function:tp.Callable=concat):
'''
MergeMap is a FunctionMerge with only one function. Wh... | Add a docstring for MergeMap | Add a docstring for MergeMap
| Python | mit | ForeverWintr/metafunctions | ---
+++
@@ -7,6 +7,10 @@
class MergeMap(FunctionMerge):
def __init__(self, function:tp.Callable, merge_function:tp.Callable=concat):
+ '''
+ MergeMap is a FunctionMerge with only one function. When called, it behaves like the
+ builtin `map` function and calls its function once per item i... |
c465b1f0c995ac2cb7c6c8b4ad5f721f800e2864 | argparams.py | argparams.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ARG parameters class
"""
from __future__ import print_function, division
class ARGparams(object):
"""Class for ARG model parameters.
Attributes
----------
scale : float
rho : float
delta : float
Methods
-------
convert_to_theta
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ARG parameters class
"""
from __future__ import print_function, division
class ARGparams(object):
"""Class for ARG model parameters.
Attributes
----------
scale : float
rho : float
delta : float
beta : float
theta : list
Raises
... | Fix incorrect attributes in ARGparams class | Fix incorrect attributes in ARGparams class
| Python | mit | khrapovs/argamma | ---
+++
@@ -14,11 +14,12 @@
scale : float
rho : float
delta : float
+ beta : float
+ theta : list
- Methods
- -------
- convert_to_theta
- Convert parameters to the vector
+ Raises
+ ------
+ AssertionError
"""
def __init__(self, scale=.001, rho=.9, delta=1.... |
037c2bc9857fc1feb59f7d4ad3cb81575177e675 | src/smsfly/versiontools.py | src/smsfly/versiontools.py | """Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
) -> str:
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
ro... | """Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root... | Drop func annotations for the sake of Python 3.5 | Drop func annotations for the sake of Python 3.5
| Python | mit | wk-tech/python-smsfly | ---
+++
@@ -10,7 +10,7 @@
root='.',
relative_to=None,
local_scheme='node-and-date',
-) -> str:
+):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version( |
c2598058722531662aab8831640fc367689d2a43 | tests/utils/test_process_word_vectors.py | tests/utils/test_process_word_vectors.py | import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.current... | import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.current... | Update Fasttext pretrained vectors location | Update Fasttext pretrained vectors location
| Python | mit | lvapeab/nmt-keras,lvapeab/nmt-keras | ---
+++
@@ -11,7 +11,7 @@
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
- call(["wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/" + vectors_name + " -O " +
+ call(["wget https:/... |
760447a190b2908d47b14adaa6b1ad1a9369524c | app/cron_tasks.py | app/cron_tasks.py | import logging
import os
import sys
# Tweak import path so that httplib2 (which lives in datasources) can be
# imported as httplib2 while the app is running.
# TODO(mihaip): move httplib2 (and oauth2 and python-twitter) into a third_party
# directory.
APP_DIR = os.path.abspath(os.path.dirname(__file__))
DATASOURCES_DI... | import logging
import os
import sys
from google.appengine.dist import use_library
use_library('django', '1.2')
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_settings'
# Tweak import path so that httplib2 (which lives in datasources) can be
# imported as httplib2 while the app is running.
# TODO(mihaip): move httpli... | Use Django 1.2 for the cron/tasks instance too. | Use Django 1.2 for the cron/tasks instance too.
| Python | apache-2.0 | mihaip/streamspigot,mihaip/streamspigot,mihaip/streamspigot,mihaip/streamspigot | ---
+++
@@ -1,6 +1,11 @@
import logging
import os
import sys
+
+from google.appengine.dist import use_library
+use_library('django', '1.2')
+
+os.environ['DJANGO_SETTINGS_MODULE'] = 'django_settings'
# Tweak import path so that httplib2 (which lives in datasources) can be
# imported as httplib2 while the app i... |
3962b88d764c7179f7b051153b337d180a3ba8f4 | oneflow/settings/snippets/djdt.py | oneflow/settings/snippets/djdt.py | # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# leto.licorn.org
'82.236.133.193',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug... | # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# gurney.licorn.org
'109.190.93.141',
# my LAN
'192.168.111.23',
'192.168.111.111',
)
DEBUG_TOOLBAR_PANELS = (
'debug_to... | Fix the django debug toolbar not appearing and the user echo thing slowing my loadings in development. | Fix the django debug toolbar not appearing and the user echo thing slowing my loadings in development.
| Python | agpl-3.0 | WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow | ---
+++
@@ -6,8 +6,11 @@
INTERNAL_IPS = (
'127.0.0.1',
- # leto.licorn.org
- '82.236.133.193',
+ # gurney.licorn.org
+ '109.190.93.141',
+ # my LAN
+ '192.168.111.23',
+ '192.168.111.111',
)
DEBUG_TOOLBAR_PANELS = ( |
bca338a0f945e74c97b4d7dd044090ed3b3f5b11 | aspen/tests/test_restarter.py | aspen/tests/test_restarter.py | from aspen import restarter
from aspen.tests.fsfix import attach_teardown
class Foo:
pass
def test_startup_basically_works():
website = Foo()
website.changes_kill = True
website.dotaspen = 'bar'
website.root = 'foo'
restarter.startup(website)
expected = []
actual = restarter.extras
... | from aspen.cli import restarter
from aspen.tests.fsfix import attach_teardown
class Foo:
pass
def test_startup_basically_works():
website = Foo()
website.changes_kill = True
website.dotaspen = 'bar'
website.root = 'foo'
restarter.install(website)
expected = []
actual = restarter.extras... | Fix up test for recent changes to restarter. | Fix up test for recent changes to restarter.
| Python | mit | gratipay/aspen.py,gratipay/aspen.py | ---
+++
@@ -1,4 +1,4 @@
-from aspen import restarter
+from aspen.cli import restarter
from aspen.tests.fsfix import attach_teardown
class Foo:
@@ -9,7 +9,7 @@
website.changes_kill = True
website.dotaspen = 'bar'
website.root = 'foo'
- restarter.startup(website)
+ restarter.install(website)
... |
dd39c73f9044815e82fa950f605b4b929d4f17f5 | assistscraper/lxml_helpers.py | assistscraper/lxml_helpers.py | from lxml import html
def document(resource_name):
return html.parse("http://www.assist.org/web-assist/" + resource_name)
# TODO: catch IndexErrors in callers
def find_by_name(tag, name, *, parent):
return parent.xpath('//{tag}[@name="{name}"]'.format(tag=tag,
... | from lxml import html
def document(resource_name):
return html.parse("http://www.assist.org/web-assist/" + resource_name)
def find_by_name(tag, name, *, parent):
return parent.find('.//{tag}[@name="{name}"]'.format(tag=tag, name=name))
def find_select(name, *, parent):
return find_by_name("select", na... | Return None instead of IndexError when there is no match! | Return None instead of IndexError when there is no match!
| Python | mit | karinassuni/assistscraper | ---
+++
@@ -5,10 +5,8 @@
return html.parse("http://www.assist.org/web-assist/" + resource_name)
-# TODO: catch IndexErrors in callers
def find_by_name(tag, name, *, parent):
- return parent.xpath('//{tag}[@name="{name}"]'.format(tag=tag,
- name=name... |
68f68a7c29dd49a9306445d02f5a7050aa84259e | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | from openerp import models, fields, api
'''
This module create model of Course
'''
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string ='Title', required=True) # Field reserved to identified name rec
... | from openerp import models, fields, api
'''
This module create model of Course
'''
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string ='Title', required=True) # Field reserved to identified name rec
... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | KarenKawaii/openacademy-project | ---
+++
@@ -29,3 +29,18 @@
'UNIQUE(name)',
"The course title must be unique"),
]
+
+ @api.one # api.one send defaults params: cr, uid, id, context
+ def copy(self, default=None):
+ print "estoy pasando por la funcion heredada de copy en cursos"
+ # default['name'] = sel... |
6b5e0249374f1adc7e6eafb2e050cd6a2f03d1c9 | examples/create_repository.py | examples/create_repository.py | from pyolite import Pyolite
# initial olite object
admin_repository = '~/presslabs/ansible-playbooks/gitolite-admin'
olite = Pyolite(admin_repository=admin_repository)
# create a repo
repo = olite.repos.get_or_create('awesome_name')
repo = olite.repos.get('awesome_name')
repo = olite.repos.create('awesome_name')
# a... | from pyolite import Pyolite
# initial olite object
admin_repository = '~/presslabs/ansible-playbooks/gitolite-admin'
olite = Pyolite(admin_repository=admin_repository)
# create a repo
repo = olite.repos.get_or_create('awesome_name')
repo = olite.repos.get('awesome_name')
repo = olite.repos.create('awesome_name')
# a... | Change the api a little bit | Change the api a little bit
| Python | bsd-2-clause | shawkinsl/pyolite,PressLabs/pyolite | ---
+++
@@ -10,13 +10,20 @@
repo = olite.repos.create('awesome_name')
# add a new user to repo
-repo.users.add('bob', permissions='RW+', path_key='~/.ssh/id_rsa.pub',
- raw_key='my-awesome-key')
+bob = repo.users.add('bob', permissions='RW+', key_path='~/.ssh/id_rsa.pub',
+ key='... |
840dce03718947498e72e561e7ddca22c4174915 | django_olcc/olcc/context_processors.py | django_olcc/olcc/context_processors.py | from olcc.models import ImportRecord
"""
Inject the last import date into the request context.
"""
def last_updated(request):
record = ImportRecord.objects.latest()
if record:
return {
'last_updated': record.created_at
}
| from olcc.models import ImportRecord
"""
Inject the last import date into the request context.
"""
def last_updated(request):
try:
return {
'last_updated': ImportRecord.objects.latest().created_at
}
except ImportRecord.DoesNotExist:
pass
| Fix a DoesNotExist bug in the olcc context processor. | Fix a DoesNotExist bug in the olcc context processor.
| Python | mit | twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc | ---
+++
@@ -4,8 +4,9 @@
Inject the last import date into the request context.
"""
def last_updated(request):
- record = ImportRecord.objects.latest()
- if record:
+ try:
return {
- 'last_updated': record.created_at
+ 'last_updated': ImportRecord.objects.latest().created_at
... |
7c4e372ec901e88ed0c6193a5c06f94a4bbc418b | EC2/create_instance.py | EC2/create_instance.py | import boto3
import botocore
import time
ec2 = boto3.resource('ec2', region_name='us-east-1')
client = boto3.client('ec2')
# Create a security group
try:
sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook')
response = client.authorize_security_group_ingress(GroupName='ju... | import boto3
import botocore
import time
ec2 = boto3.resource('ec2', region_name='us-east-1')
client = boto3.client('ec2')
# Create a security group
try:
sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook')
response = client.authorize_security_group_ingress(GroupName='ju... | Update the script to create EC2 instance. | Update the script to create EC2 instance.
This creates an EC2 i3.8xlarge.
| Python | apache-2.0 | flashxio/FlashX,icoming/FlashX,flashxio/FlashX,icoming/FlashX,flashxio/FlashX,flashxio/FlashX,icoming/FlashX,flashxio/FlashX,icoming/FlashX,icoming/FlashX,flashxio/FlashX | ---
+++
@@ -14,7 +14,7 @@
sg = client.describe_security_groups(GroupNames=['jupyter'])
print("the security group exist")
-o = ec2.create_instances(ImageId='ami-e36637f5', MinCount=1, MaxCount=1, InstanceType='i3.xlarge', SecurityGroups=['jupyter'])
+o = ec2.create_instances(ImageId='ami-622a0119', MinCoun... |
dba918008892214e56bebc8684839f16ae7d7325 | src/engine/request_handler.py | src/engine/request_handler.py | import Queue
import json
import EBQP
from . import world
from . import types
from . import consts
from . import loc
class GameRequestHandler:
def __init__(self):
self.world = None
self.responses = {
EBQP.new: self.respond_new,
}
def process(self, request):
reques... | import Queue
import json
import EBQP
from . import world
from . import types
from . import consts
from . import loc
class GameRequestHandler:
def __init__(self):
self.world = None
self.responses = {
EBQP.new: self.respond_new,
}
def process(self, request):
reques... | Debug flag to insert tank into game board | Debug flag to insert tank into game board
| Python | mit | Tactique/game_engine,Tactique/game_engine | ---
+++
@@ -33,7 +33,8 @@
def respond_new(self, args):
uids = args['uids']
self.world = world.World(uids)
- self.world.add_unit(uids[0], types.new_unit('Tank', consts.RED, loc.Loc(3, 3)))
+ if 'debug' in args:
+ self.world.add_unit(uids[0], types.new_unit('Tank', consts... |
c958a314dc8ceb72e34ed969d3cff3751d513a49 | grab/tools/progress.py | grab/tools/progress.py | import sys
import logging
logger = logging.getLogger('grab.tools.progress')
class Progress(object):
def __init__(self, step=None, total=None, stop=None, name='items', level=logging.DEBUG):
if not total and not step:
raise Exception('Both step and total arguments are None')
if total an... | import sys
import logging
logger = logging.getLogger('grab.tools.progress')
class Progress(object):
def __init__(self, step=None, total=None, stop=None, name='items', level=logging.DEBUG):
if total is None and step is None:
raise Exception('Both step and total arguments are None')
if ... | Fix bug in Progress object | Fix bug in Progress object
| Python | mit | codevlabs/grab,liorvh/grab,giserh/grab,alihalabyah/grab,SpaceAppsXploration/grab,istinspring/grab,DDShadoww/grab,subeax/grab,subeax/grab,istinspring/grab,pombredanne/grab-1,codevlabs/grab,giserh/grab,lorien/grab,huiyi1990/grab,maurobaraldi/grab,subeax/grab,lorien/grab,kevinlondon/grab,alihalabyah/grab,pombredanne/grab-... | ---
+++
@@ -5,10 +5,12 @@
class Progress(object):
def __init__(self, step=None, total=None, stop=None, name='items', level=logging.DEBUG):
- if not total and not step:
+ if total is None and step is None:
raise Exception('Both step and total arguments are None')
if total an... |
6a63fc4abd524da96ee09bfa94f7eae534a9834e | tests/managers/object_storage_tests.py | tests/managers/object_storage_tests.py | """
SoftLayer.tests.managers.object_storage_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import fixtures
from SoftLayer import testing
class ObjectStorageTests(testing.TestCase):
def set_up(self):
self.ob... | """
SoftLayer.tests.managers.object_storage_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import fixtures
from SoftLayer import testing
class ObjectStorageTests(testing.TestCase):
def set_up(self):
self.ob... | Fix small style issue w/ assertEqual vs assertEquals | Fix small style issue w/ assertEqual vs assertEquals
| Python | mit | softlayer/softlayer-python,nanjj/softlayer-python,allmightyspiff/softlayer-python,kyubifire/softlayer-python,Neetuj/softlayer-python,skraghu/softlayer-python | ---
+++
@@ -16,8 +16,8 @@
def test_list_accounts(self):
accounts = self.object_storage.list_accounts()
- self.assertEquals(accounts,
- fixtures.SoftLayer_Account.getHubNetworkStorage)
+ self.assertEqual(accounts,
+ fixtures.SoftLayer_Accou... |
dfce2472c81c84a6e73315f288c41683ede92363 | pydarkstar/auction/auctionbase.py | pydarkstar/auction/auctionbase.py | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import pydarkstar.darkobject
import pydarkstar.database
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
Base class for Auction House objects.
:param db: database object
"""
def __init__(self, db, rollback=True, fail=False, *a... | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import pydarkstar.darkobject
import pydarkstar.database
import contextlib
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
Base class for Auction House objects.
:param db: database object
"""
def __init__(self, db, rollback=Tr... | Add session and scoped session to AuctionBase. | Add session and scoped session to AuctionBase.
| Python | mit | AdamGagorik/pydarkstar,LegionXI/pydarkstar | ---
+++
@@ -3,6 +3,7 @@
"""
import pydarkstar.darkobject
import pydarkstar.database
+import contextlib
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
@@ -16,6 +17,25 @@
self._rollback = bool(rollback)
self._fail = bool(fail)
self._db = db
+
+ def session(self, *args,... |
510117cb0f487232d1cd0c5392a4514e1dc1b46e | scripts/produce_data.py | scripts/produce_data.py | #!/usr/bin/python
import time
import sys
import random
import rospy
import cv_bridge
import cv
import rospkg
from geometry_msgs.msg import Vector3
class DataTester(object):
def __init__(self, myo_number, mode="zero"):
self.mode = mode
self._myo_name = "myo_" + str(myo_number)
rospy.init... | Add testing publisher script for dummy myo data | Add testing publisher script for dummy myo data
| Python | mit | ipab-rad/myo_baxter_pc,ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo,ipab-rad/baxter_myo | ---
+++
@@ -0,0 +1,73 @@
+#!/usr/bin/python
+import time
+import sys
+import random
+
+import rospy
+import cv_bridge
+import cv
+import rospkg
+
+from geometry_msgs.msg import Vector3
+
+
+class DataTester(object):
+
+ def __init__(self, myo_number, mode="zero"):
+ self.mode = mode
+ self._myo_name ... | |
1cdc38742e6fc09595a45c28d179125d3771521c | euler010.py | euler010.py | #!/usr/bin/python
from math import sqrt, ceil, floor
LIMIT = 2000000
"""
This is the first, brute force method, we search for primes,
and put them into an array, so we can use as test later.
This is not fast, and do millons mod test
"""
def isPrime(x):
i = 0
while primeList[i] <= sqrt(x):
if x % pr... | Add solutions for problem 10 | Add solutions for problem 10
| Python | mit | cifvts/PyEuler | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/bin/python
+
+from math import sqrt, ceil, floor
+
+LIMIT = 2000000
+
+"""
+This is the first, brute force method, we search for primes,
+and put them into an array, so we can use as test later.
+This is not fast, and do millons mod test
+"""
+
+
+def isPrime(x):
+ i = 0
+ while... | |
cbf9b7605a31cd67b1c94b8157cb6ae55fd36c69 | zerver/test_urls.py | zerver/test_urls.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import django.core.urlresolvers
from django.test import TestCase
import importlib
from zproject import urls
class URLResolutionTest(TestCase):
def check_function_exists(self, module_name, view):
module = i... | Add test that all functions defined in urls.py actually exist. | Add test that all functions defined in urls.py actually exist.
This would have caught the create_user_backend issue introduced recently.
| Python | apache-2.0 | sharmaeklavya2/zulip,AZtheAsian/zulip,rishig/zulip,shubhamdhama/zulip,sup95/zulip,shubhamdhama/zulip,jphilipsen05/zulip,samatdav/zulip,Jianchun1/zulip,zulip/zulip,blaze225/zulip,PhilSk/zulip,vaidap/zulip,dattatreya303/zulip,eeshangarg/zulip,shubhamdhama/zulip,TigorC/zulip,verma-varsha/zulip,mahim97/zulip,hackerkid/zuli... | ---
+++
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import
+from __future__ import print_function
+
+import django.core.urlresolvers
+from django.test import TestCase
+import importlib
+from zproject import urls
+
+class URLResolutionTest(TestCase):
+ def check_function_exists(self, ... | |
fc35730074f5af647579012b706e531e84da5ab6 | src/main/python/json_to_csv.py | src/main/python/json_to_csv.py | # Adapted from http://stackoverflow.com/questions/1871524/convert-from-json-to-csv-using-python
import csv
import json
with open("comments.txt") as file:
data = json.load(file)
with open("comments.csv", "wb") as file:
csv_file = csv.writer(file)
csv_file.writerow(['user:login', 'path', 'commit_id', 'url', 'line',
... | Add tool for converting in-line notes metadata to .csv | Add tool for converting in-line notes metadata to .csv
| Python | mit | PovertyAction/github-download | ---
+++
@@ -0,0 +1,15 @@
+# Adapted from http://stackoverflow.com/questions/1871524/convert-from-json-to-csv-using-python
+import csv
+import json
+
+with open("comments.txt") as file:
+ data = json.load(file)
+
+with open("comments.csv", "wb") as file:
+ csv_file = csv.writer(file)
+ csv_file.writerow(['user:login',... | |
3bd35228c61d73d8a43ffcda70386b194c9123b2 | benchmark/TSP/TSPLIB/compare_to_BKS.py | benchmark/TSP/TSPLIB/compare_to_BKS.py | # -*- coding: utf-8 -*-
import json, sys, os
import numpy as np
# Compare a set of computed solutions to best known solutions on the
# same problems.
def s_round(v, d):
return str(round(v, d))
def log_comparisons(BKS, files):
print ','.join(["Instance", "Jobs", "Vehicles", "Optimal cost", "Solution cost", "Gap (... | Automate comparison to best known solutions. | Automate comparison to best known solutions.
| Python | bsd-2-clause | VROOM-Project/vroom-scripts,VROOM-Project/vroom-scripts | ---
+++
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+import json, sys, os
+import numpy as np
+
+# Compare a set of computed solutions to best known solutions on the
+# same problems.
+
+def s_round(v, d):
+ return str(round(v, d))
+
+def log_comparisons(BKS, files):
+ print ','.join(["Instance", "Jobs", "Vehicles", ... | |
f6f022a4eb6af051becd5564c1b0de6943918968 | sudoku_example.py | sudoku_example.py | #!/usr/bin/env python
import sys
sys.path.append("./src")
from sat import SAT_solver
from sudoku import sudoku, printSudoku, processResult
print "================================================="
print "SUDOKU"
print "================================================="
solver = SAT_solver()
# define bord as follows... | Add example of solving sudoku puzzle. | Add example of solving sudoku puzzle.
| Python | bsd-3-clause | urska19/LVR-sat | ---
+++
@@ -0,0 +1,41 @@
+#!/usr/bin/env python
+import sys
+sys.path.append("./src")
+from sat import SAT_solver
+from sudoku import sudoku, printSudoku, processResult
+
+
+print "================================================="
+print "SUDOKU"
+print "================================================="
+
+solver =... | |
4e223603a0216a667acc888268f845b41d16ab03 | numpy/distutils/tests/test_npy_pkg_config.py | numpy/distutils/tests/test_npy_pkg_config.py | import os
from tempfile import mkstemp
from numpy.testing import *
from numpy.distutils.npy_pkg_config import read_config
simple = """\
[meta]
Name = foo
Description = foo lib
Version = 0.1
[default]
cflags = -I/usr/include
libs = -L/usr/lib
"""
simple_d = {'cflags': '-I/usr/include', 'libflags': '-L/usr/lib',
... | Add two unit-tests for LibraryInfo. | Add two unit-tests for LibraryInfo.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7223 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | illume/numpy3k,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GS... | ---
+++
@@ -0,0 +1,72 @@
+import os
+from tempfile import mkstemp
+
+from numpy.testing import *
+from numpy.distutils.npy_pkg_config import read_config
+
+simple = """\
+[meta]
+Name = foo
+Description = foo lib
+Version = 0.1
+
+[default]
+cflags = -I/usr/include
+libs = -L/usr/lib
+"""
+simple_d = {'cflags': '-I/u... | |
fc9798c22f56a50233a40cff30ddd60fbecf471b | timeside/server/management/commands/timeside-items-post-save.py | timeside/server/management/commands/timeside-items-post-save.py | from django.core.management.base import BaseCommand
from timeside.server.models import Item
class Command(BaseCommand):
help = "This command will generate all post_save callback and will thus create audio_duration, mime_type and sha1 field if missing"
def handle(self, *args, **options):
for item in ... | Add management command to update Item fields that gets updated after save() | Server: Add management command to update Item fields that gets updated after save()
| Python | agpl-3.0 | Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide | ---
+++
@@ -0,0 +1,11 @@
+from django.core.management.base import BaseCommand
+
+from timeside.server.models import Item
+
+
+class Command(BaseCommand):
+ help = "This command will generate all post_save callback and will thus create audio_duration, mime_type and sha1 field if missing"
+
+ def handle(self, *ar... | |
2b4ed8cc91ef4f5cd56dae7fbfa9e1a8f5dabcb8 | backend/tests/api/test_commands.py | backend/tests/api/test_commands.py | import io
from unittest.mock import Mock, mock_open, patch
import strawberry
from django.core.management import call_command
def test_generate_graphql_schema():
out = io.StringIO()
m_open = mock_open()
@strawberry.type
class TestSchema:
a: int
with patch("api.management.commands.graphq... | Add tests for the graphql_schema command | Add tests for the graphql_schema command
| Python | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -0,0 +1,29 @@
+import io
+from unittest.mock import Mock, mock_open, patch
+
+import strawberry
+from django.core.management import call_command
+
+
+def test_generate_graphql_schema():
+ out = io.StringIO()
+
+ m_open = mock_open()
+
+ @strawberry.type
+ class TestSchema:
+ a: int
+
+ ... | |
31c7ed89e66c32c46650ee93bfa8c8b2b8fbfad1 | cisco_olt_client/tests/test_command.py | cisco_olt_client/tests/test_command.py | from cisco_olt_client.command import Command
def test_simple_compile():
cmd_str = 'cmd --arg1=val1 --arg2=val2'
cmd = Command('cmd', (('arg1', 'val1'), ('arg2', 'val2')))
assert cmd.compile() == cmd_str
cmd = Command('cmd', {'arg1': 'val1', 'arg2': 'val2'})
# order is not guaranteed
assert '-... | Add test for command compilation | Add test for command compilation
| Python | mit | Vnet-as/cisco-olt-client | ---
+++
@@ -0,0 +1,16 @@
+from cisco_olt_client.command import Command
+
+
+def test_simple_compile():
+ cmd_str = 'cmd --arg1=val1 --arg2=val2'
+ cmd = Command('cmd', (('arg1', 'val1'), ('arg2', 'val2')))
+ assert cmd.compile() == cmd_str
+
+ cmd = Command('cmd', {'arg1': 'val1', 'arg2': 'val2'})
+ # ... | |
2f450c0cb3d4c440b695696f88b72202c2f7d788 | tests/emukit/core/test_optimization.py | tests/emukit/core/test_optimization.py | import numpy as np
from emukit.core import ParameterSpace
from emukit.core import ContinuousParameter, InformationSourceParameter
from emukit.core.acquisition import Acquisition
from emukit.core.optimization import AcquisitionOptimizer
from emukit.core.optimization import MultiSourceAcquisitionOptimizer
class Simple... | Test acquisition optimizer and multi source acquisition optimizer | Test acquisition optimizer and multi source acquisition optimizer
| Python | apache-2.0 | EmuKit/emukit | ---
+++
@@ -0,0 +1,42 @@
+import numpy as np
+
+from emukit.core import ParameterSpace
+from emukit.core import ContinuousParameter, InformationSourceParameter
+from emukit.core.acquisition import Acquisition
+from emukit.core.optimization import AcquisitionOptimizer
+from emukit.core.optimization import MultiSourceA... | |
f574a74f99d1b8aa0fa107ba2416699104d1f36d | inspector/cbv/templatetags/cbv_tags.py | inspector/cbv/templatetags/cbv_tags.py | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def called_same(qs, name):
return [item for item in qs if item.name==name]
| Add filter that gets items with the same .name from a list. | Add filter that gets items with the same .name from a list.
| Python | bsd-2-clause | abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector | ---
+++
@@ -0,0 +1,9 @@
+from django import template
+from django.conf import settings
+
+register = template.Library()
+
+
+@register.filter
+def called_same(qs, name):
+ return [item for item in qs if item.name==name] | |
1a65b417129e0a32a079509c3e3868ced275b4b6 | utils/validate.py | utils/validate.py | #!/usr/bin/env python
import sys
import json
import fileinput
import dateutil.parser
line_number = 0
for line in fileinput.input():
... | Add a little validation utility. | Add a little validation utility.
| Python | mit | DocNow/twarc,miku/twarc,kevinbgunn/twarc,edsu/twarc,remagio/twarc,hugovk/twarc,ericscartier/twarc,kevinbgunn/twarc,ericscartier/twarc,miku/twarc,remagio/twarc | ---
+++
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+import sys
+import json
+import fileinput
+import dateutil.parser
+
+line_number = 0 ... | |
e872f249590244814e67894fc48b97d63ccad2c2 | tools/data/window_file_select_vid_classes.py | tools/data/window_file_select_vid_classes.py | #!/usr/bin/env python
import argparse
import scipy.io as sio
import os
import os.path as osp
import numpy as np
from vdetlib.vdet.dataset import index_det_to_vdet
if __name__ == '__main__':
parser = argparse.ArgumentParser('Convert a window file for DET for VID.')
parser.add_argument('window_file')
parser.... | Add script to convert DET window file to VID window file. | Add script to convert DET window file to VID window file.
| Python | mit | myfavouritekk/TPN | ---
+++
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+import argparse
+import scipy.io as sio
+import os
+import os.path as osp
+import numpy as np
+from vdetlib.vdet.dataset import index_det_to_vdet
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser('Convert a window file for DET for VID.')
+ parser.a... | |
268d67b3b6e81ba3b01a3e106dbabd5f03f42a50 | glitter/block_admin.py | glitter/block_admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import warnings
from glitter.blockadmin.blocks import BlockAdmin, site
from .models import BaseBlock # noqa
BlockModelAdmin = BlockAdmin
__all__ = ['site', 'BlockModelAdmin']
warnings.warn(
"BlockModelAdmin has been moved to blockadmin.blocks... | Add deprecation warning and backward compatibility | Add deprecation warning and backward compatibility
| Python | bsd-3-clause | developersociety/django-glitter,developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter | ---
+++
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+
+import warnings
+
+from glitter.blockadmin.blocks import BlockAdmin, site
+
+from .models import BaseBlock # noqa
+
+
+BlockModelAdmin = BlockAdmin
+
+__all__ = ['site', 'BlockModelAdmin']
+
+
+warnings.warn(
+ "BlockM... | |
81771f60b00d605dfe1bc07f1af6660cd3c1e0f2 | magnum/tests/unit/cmd/test_conductor.py | magnum/tests/unit/cmd/test_conductor.py | # Copyright 2016 - Fujitsu, Ltd.
#
# 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 agr... | Improve unit test coverage for cmd/conductor.py | Improve unit test coverage for cmd/conductor.py
Add new unit tests for cmd/conductor.py.
Increase the coverage for cmd/conductor.py from 0 to 100%.
Change-Id: I0c65ee9bc161046bcbd2b0ef5a8faf2f50a0f43e
Partial-Bug: #1511667
| Python | apache-2.0 | ArchiFleKs/magnum,ArchiFleKs/magnum,openstack/magnum,openstack/magnum | ---
+++
@@ -0,0 +1,36 @@
+# Copyright 2016 - Fujitsu, Ltd.
+#
+# 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
+#
+# Unle... | |
232aef0417fc10ecc73820b73d4b104498ff3bd3 | parse.py | parse.py | # KlupuNG
# Copyright (C) 2013 Koodilehto Osk <http://koodilehto.fi>.
#
# 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 ve... | Add simple script for parsing meeting doc dirs | Add simple script for parsing meeting doc dirs
| Python | agpl-3.0 | tuomasjjrasanen/klupu,tuomasjjrasanen/klupu | ---
+++
@@ -0,0 +1,28 @@
+# KlupuNG
+# Copyright (C) 2013 Koodilehto Osk <http://koodilehto.fi>.
+#
+# 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... | |
5f4580cdc2f46ef9294057372609e1b9a48f7041 | tests/test_cardxml.py | tests/test_cardxml.py | from hearthstone import cardxml
def test_cardxml_load():
cardid_db, _ = cardxml.load()
dbf_db, _ = cardxml.load_dbf()
assert cardid_db
assert dbf_db
for card_id, card in cardid_db.items():
assert dbf_db[card.dbf_id].id == card_id
for dbf_id, card in dbf_db.items():
assert cardid_db[card.id].dbf_id == dbf... | Add a test for the cardxml databases | tests: Add a test for the cardxml databases
| Python | mit | HearthSim/python-hearthstone | ---
+++
@@ -0,0 +1,15 @@
+from hearthstone import cardxml
+
+
+def test_cardxml_load():
+ cardid_db, _ = cardxml.load()
+ dbf_db, _ = cardxml.load_dbf()
+
+ assert cardid_db
+ assert dbf_db
+
+ for card_id, card in cardid_db.items():
+ assert dbf_db[card.dbf_id].id == card_id
+
+ for dbf_id, card in dbf_db.items():
... | |
24ba638d16433ce298fca9dfd4e12cad01c86728 | scripts/one_hot_encoding.py | scripts/one_hot_encoding.py | import sys
import pandas as pd
sys.path.append('..')
from utils.preprocessing import one_hot_encoding
path = '../datasets/processed/'
train_users = pd.read_csv(path + 'semi_processed_train_users.csv')
test_users = pd.read_csv(path + 'semi_processed_test_users.csv')
# Join users
users = pd.concat((train_users, test_us... | Add scrit to finish preprocessing | Add scrit to finish preprocessing
| Python | mit | davidgasquez/kaggle-airbnb | ---
+++
@@ -0,0 +1,41 @@
+import sys
+import pandas as pd
+sys.path.append('..')
+from utils.preprocessing import one_hot_encoding
+
+path = '../datasets/processed/'
+train_users = pd.read_csv(path + 'semi_processed_train_users.csv')
+test_users = pd.read_csv(path + 'semi_processed_test_users.csv')
+
+# Join users
+u... | |
8e7ac2d9b4c281520c2a5d65d6d10cc39f64181d | controller/single_instance_task.py | controller/single_instance_task.py | import functools
from django.core.cache import cache
def single_instance_task(timeout):
def task_exc(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock_id = "celery-single-instance-" + func.__name__
acquire_lock = lambda: cache.add(lock_id, "true", timeout)
... | Add in single instance task file | Add in single instance task file
| Python | agpl-3.0 | edx/edx-ora,edx/edx-ora,edx/edx-ora,edx/edx-ora | ---
+++
@@ -0,0 +1,17 @@
+import functools
+from django.core.cache import cache
+
+def single_instance_task(timeout):
+ def task_exc(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ lock_id = "celery-single-instance-" + func.__name__
+ acquire_lock = lambda: cac... | |
17f14574a35d985571e71023587ddb858a8b3ba2 | tests/test_engines.py | tests/test_engines.py | #!/usr/bin/env python
from __future__ import print_function
import unittest
try:
from unittest import mock
except ImportError:
import mock
import imp
import os.path
import engines
class TestInit(unittest.TestCase):
def test_init(self):
mock_engines = {}
mock_listdir = mock.Mock(ret... | Add tests for engines package. | Add tests for engines package.
| Python | mit | blubberdiblub/eztemplate | ---
+++
@@ -0,0 +1,102 @@
+#!/usr/bin/env python
+
+from __future__ import print_function
+
+import unittest
+
+try:
+ from unittest import mock
+except ImportError:
+ import mock
+
+import imp
+import os.path
+
+
+import engines
+
+
+class TestInit(unittest.TestCase):
+
+ def test_init(self):
+ mock_... | |
41ebf7cbb3c23ddbd47ef0259490d6669538faa1 | rockit/core/tests/test_task_settings.py | rockit/core/tests/test_task_settings.py | from django.test import TestCase
from rockit.core import holders
from rockit.core import tasks
class TaskSettingsTestCase(TestCase):
def test_it_should_be_able_to_call_task(self):
holder = holders.SettingsHolder()
holder = tasks.settings(holder)
self.assertNotEqual(0, len(holder.get_cont... | Add unit test for task settings | Add unit test for task settings
| Python | mit | acreations/rockit-server,acreations/rockit-server,acreations/rockit-server,acreations/rockit-server | ---
+++
@@ -0,0 +1,12 @@
+from django.test import TestCase
+
+from rockit.core import holders
+from rockit.core import tasks
+
+class TaskSettingsTestCase(TestCase):
+
+ def test_it_should_be_able_to_call_task(self):
+ holder = holders.SettingsHolder()
+ holder = tasks.settings(holder)
+
+ sel... | |
d50b67c5e16775861f251e794f75daecab64223b | tests/test_assigned_labels.py | tests/test_assigned_labels.py | from ghi_assist.hooks.assigned_label_hook import AssignedLabelHook
def test_assign():
"""Test successful assignment."""
hook = AssignedLabelHook()
payload = {"action": "assigned",
"issue": {"labels": [{"name": "alpha"},
{"name": "beta"},
... | Add tests for (un)claiming issues | Add tests for (un)claiming issues
Test that labels are added and removed correctly to note when an issue
is assigned or unassigned.
| Python | agpl-3.0 | afuna/ghi-assist | ---
+++
@@ -0,0 +1,47 @@
+from ghi_assist.hooks.assigned_label_hook import AssignedLabelHook
+
+def test_assign():
+ """Test successful assignment."""
+ hook = AssignedLabelHook()
+ payload = {"action": "assigned",
+ "issue": {"labels": [{"name": "alpha"},
+ {... | |
d9a522df5827867897e4a2bbaf680db563fb983e | scripts/tile_images.py | scripts/tile_images.py | """Tile images."""
import os
import random
import argparse
from collections import defaultdict
import dtoolcore
import numpy as np
from jicbioimage.core.image import Image
from skimage.transform import downscale_local_mean
from dtoolutils import (
temp_working_dir,
stage_outputs
)
from image_utils impor... | Add script to tile images | Add script to tile images
| Python | mit | JIC-Image-Analysis/senescence-in-field,JIC-Image-Analysis/senescence-in-field,JIC-Image-Analysis/senescence-in-field | ---
+++
@@ -0,0 +1,112 @@
+"""Tile images."""
+
+import os
+import random
+import argparse
+
+from collections import defaultdict
+
+import dtoolcore
+
+import numpy as np
+
+from jicbioimage.core.image import Image
+
+from skimage.transform import downscale_local_mean
+
+from dtoolutils import (
+ temp_working_di... | |
7af557a6c40508e758c020539647e6578c779018 | example_crm/dev_malcolm.py | example_crm/dev_malcolm.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'temp.db', # Or path to databas... | Add dev env for malcolm | Add dev env for malcolm
| Python | apache-2.0 | pkimber/crm,pkimber/crm,pkimber/crm | ---
+++
@@ -0,0 +1,15 @@
+# -*- encoding: utf-8 -*-
+
+from __future__ import unicode_literals
+from .base import *
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+ 'NAME': 'temp.db', ... | |
56583a6e15bc4dbfb1c80739e3942eed733b91e3 | get-version-from-git.py | get-version-from-git.py | #!/usr/bin/env python
from __future__ import print_function
# Edit these constants if desired. NOTE that if you change DEFAULT_TAG_FORMAT,
# you'll need to change the .lstrip('v") part of parse_tag() as well.
DEFAULT_TAG_FORMAT="v[0-9]*" # Shell glob format, not regex
DEFAULT_VERSION_IF_NO_TAGS="0.0.0"
import subpr... | Add the script for people to download | Add the script for people to download
| Python | mit | rmunn/version-numbers-from-git,rmunn/version-numbers-from-git,rmunn/version-numbers-from-git | ---
+++
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+
+from __future__ import print_function
+
+# Edit these constants if desired. NOTE that if you change DEFAULT_TAG_FORMAT,
+# you'll need to change the .lstrip('v") part of parse_tag() as well.
+DEFAULT_TAG_FORMAT="v[0-9]*" # Shell glob format, not regex
+DEFAULT_VERSI... | |
7b18fd4e2f4b975e891d31994f15e30d7fd50d1b | ply_speed.py | ply_speed.py | import cProfile
import time
from res import types
from src import ai
from src import coordinate
from src import historynode
plyNum = 5
aiObject = ai.AI()
game = historynode.HistoryNode()
game.setState(coordinate.Coordinate(3, 7), types.GOOSE)
game.setState(coordinate.Coordinate(4, 7), types.GOOSE)
game.setState(coor... | Add script to test search speed | Add script to test search speed
| Python | mit | blairck/jaeger | ---
+++
@@ -0,0 +1,59 @@
+import cProfile
+
+import time
+
+from res import types
+from src import ai
+from src import coordinate
+from src import historynode
+
+plyNum = 5
+aiObject = ai.AI()
+game = historynode.HistoryNode()
+game.setState(coordinate.Coordinate(3, 7), types.GOOSE)
+game.setState(coordinate.Coordina... | |
153fd9e9c0b9e251c423b811f3d67522d469d9bc | all-domains/tutorials/cracking-the-coding-interview/arrays-left-rotation/solution.py | all-domains/tutorials/cracking-the-coding-interview/arrays-left-rotation/solution.py | # https://www.hackerrank.com/challenges/ctci-array-left-rotation
# Python 3
def array_left_rotation(a, n, k):
# Convert generator to a list
arr = list(a)
for _ in range(k):
temp = arr.pop(0)
arr.append(temp)
# Return a generator from the list
return (x for x in arr)
n, k = map(int... | Solve first problem for Cracking the coding interview | Solve first problem for Cracking the coding interview
| Python | mit | arvinsim/hackerrank-solutions | ---
+++
@@ -0,0 +1,17 @@
+# https://www.hackerrank.com/challenges/ctci-array-left-rotation
+# Python 3
+
+def array_left_rotation(a, n, k):
+ # Convert generator to a list
+ arr = list(a)
+ for _ in range(k):
+ temp = arr.pop(0)
+ arr.append(temp)
+ # Return a generator from the list
+ r... | |
ea74801222231145421187a005756db752e9a2f8 | tests/test_flask_get.py | tests/test_flask_get.py | import unittest
from flask import Flask
from flask.ext.autodoc import Autodoc
class TestAutodocWithFlask(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.autodoc = Autodoc(self.app)
@self.app.route('/')
@self.autodoc.doc()
def index():
"""R... | Add a test for HTML retrieval. | Add a test for HTML retrieval.
| Python | mit | jwg4/flask-autodoc,jwg4/flask-autodoc | ---
+++
@@ -0,0 +1,26 @@
+import unittest
+
+from flask import Flask
+from flask.ext.autodoc import Autodoc
+
+
+class TestAutodocWithFlask(unittest.TestCase):
+ def setUp(self):
+ self.app = Flask(__name__)
+ self.autodoc = Autodoc(self.app)
+
+ @self.app.route('/')
+ @self.autodoc.doc... | |
f9733f0fcbf94aabda179e50a4eb694f117c208d | cdf/renderers.py | cdf/renderers.py | from cdf.config import DJANGO_VERSIONS, VERSION
from cdf.jinja_utils import template_env
class BasePageRenderer(object):
def __init__(self, klasses):
self.klasses = klasses
def render(self, filename):
template = template_env.get_template(self.template_name)
context = self.get_context... | Add base renderer and an index page renderer | Add base renderer and an index page renderer
| Python | mit | ana-balica/classy-django-forms,ana-balica/classy-django-forms,ana-balica/classy-django-forms | ---
+++
@@ -0,0 +1,30 @@
+from cdf.config import DJANGO_VERSIONS, VERSION
+from cdf.jinja_utils import template_env
+
+
+class BasePageRenderer(object):
+
+ def __init__(self, klasses):
+ self.klasses = klasses
+
+ def render(self, filename):
+ template = template_env.get_template(self.template_na... | |
32de58c3a36bf9f9f8ec98e904aee989ebe3428e | install_deps.py | install_deps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Installs dependencies appropriate for the Python version."""
import subprocess
import sys
subprocess.call("pip", "install --use-mirrors -r requirements.txt")
if sys.version_info[0] >= 3: # Python 3
# No Python 3-specific dependencies right now
pass
else: # Pyth... | Install different deps for Python 3 vs. Python 2. | Install different deps for Python 3 vs. Python 2.
| Python | mit | gthank/pto,gthank/pto | ---
+++
@@ -0,0 +1,12 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Installs dependencies appropriate for the Python version."""
+import subprocess
+import sys
+
+subprocess.call("pip", "install --use-mirrors -r requirements.txt")
+if sys.version_info[0] >= 3: # Python 3
+ # No Python 3-specific dependenc... | |
1394800c7c7bd62e0191cdb85612fa3066789424 | weekday_greeting_slackbot.py | weekday_greeting_slackbot.py | #!/usr/bin/env python3
from slackclient import SlackClient
import json
import time
slack_token = ""
channel = ""
message = ""
report_slack_token = ""
report_channel = ""
report_slackbot_name = ""
report_alert_list = ""
def report_result(result):
if result.get("ok"):
report_message = ... | Add basic Slackbot script with reporting enabled | Add basic Slackbot script with reporting enabled
| Python | mit | jleung51/scripts,jleung51/scripts,jleung51/scripts | ---
+++
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+
+from slackclient import SlackClient
+
+import json
+import time
+
+slack_token = ""
+channel = ""
+message = ""
+
+report_slack_token = ""
+report_channel = ""
+report_slackbot_name = ""
+report_alert_list = ""
+
+def report_result(result):
+ i... | |
e65641c7a2d944a39cf0cf4988d6b03e74a9712b | examples/sqlite_fts_compression.py | examples/sqlite_fts_compression.py | #
# Small example demonstrating the use of zlib compression with the Sqlite
# full-text search extension.
#
import zlib
from peewee import *
from playhouse.sqlite_ext import *
db = SqliteExtDatabase(':memory:')
class SearchIndex(FTSModel):
content = SearchField()
class Meta:
database = db
@db.fun... | Add small example of sqlite FTS with compression. | Add small example of sqlite FTS with compression.
| Python | mit | coleifer/peewee,coleifer/peewee,coleifer/peewee | ---
+++
@@ -0,0 +1,64 @@
+#
+# Small example demonstrating the use of zlib compression with the Sqlite
+# full-text search extension.
+#
+import zlib
+
+from peewee import *
+from playhouse.sqlite_ext import *
+
+
+db = SqliteExtDatabase(':memory:')
+
+class SearchIndex(FTSModel):
+ content = SearchField()
+
+ ... | |
df6fba6742e4fddfebd305a1ed624927f26e0f45 | endpoints/__init__.py | endpoints/__init__.py | #!/usr/bin/python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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... | #!/usr/bin/python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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... | Bump minor version (2.3.1 -> 2.4.0) | Bump minor version (2.3.1 -> 2.4.0)
Rationale:
* Discovery docs now properly contain the OAuth2 scopes
* Improved security definition generation in OpenAPI specs
| Python | apache-2.0 | cloudendpoints/endpoints-python,inklesspen/endpoints-python,inklesspen/endpoints-python,cloudendpoints/endpoints-python | ---
+++
@@ -34,4 +34,4 @@
from users_id_token import InvalidGetUserCall
from users_id_token import SKIP_CLIENT_ID_CHECK
-__version__ = '2.3.1'
+__version__ = '2.4.0' |
ebc88a28e2f8018b2887970bddb0423243ee8292 | src/core/templatetags/nose_tools.py | src/core/templatetags/nose_tools.py | from nose import tools
from django import template
register = template.Library()
class NoseNode(template.Node):
def render(self, context):
tools.set_trace() # Debugger will stop here
return ''
@register.tag
def set_trace(parser, token):
return NoseNode()
| Add template tag for debugging | Add template tag for debugging
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | ---
+++
@@ -0,0 +1,14 @@
+from nose import tools
+from django import template
+
+register = template.Library()
+
+class NoseNode(template.Node):
+
+ def render(self, context):
+ tools.set_trace() # Debugger will stop here
+ return ''
+
+@register.tag
+def set_trace(parser, token):
+ return... | |
56319a8562d10b43189ffa968b5ecc477f50a6c9 | src/python/BasicAvg.py | src/python/BasicAvg.py | """
>>> from pyspark.context import SparkContext
>>> sc = SparkContext('local', 'test')
>>> b = sc.parallelize([1, 2, 3, 4])
>>> basicAvg(b)
2.5
"""
import sys
from pyspark import SparkContext
def basicAvg(nums):
"""Compute the avg"""
sumCount = nums.map(lambda x: (x,1)).fold((0, 0), (lambda x, y: (x[0] + y[... | Add a basic avg example | Add a basic avg example
| Python | mit | kpraveen420/learning-spark,mmirolim/learning-spark,shimizust/learning-spark,jindalcastle/learning-spark,JerryTseng/learning-spark,GatsbyNewton/learning-spark,tengteng/learning-spark,tengteng/learning-spark,feynman0825/learning-spark,SunGuo/learning-spark,bhagatsingh/learning-spark,baokunguo/learning-spark-examples,diog... | ---
+++
@@ -0,0 +1,26 @@
+"""
+>>> from pyspark.context import SparkContext
+>>> sc = SparkContext('local', 'test')
+>>> b = sc.parallelize([1, 2, 3, 4])
+>>> basicAvg(b)
+2.5
+"""
+
+import sys
+
+from pyspark import SparkContext
+
+def basicAvg(nums):
+ """Compute the avg"""
+ sumCount = nums.map(lambda x: (x... | |
8003a4b4b2aaaaba54570f670c7a5df93fe8434d | tests/pykafka/utils/test_compression.py | tests/pykafka/utils/test_compression.py | import unittest2
from pykafka.utils import compression
class CompressionTests(unittest2.TestCase):
"""Keeping these simple by verifying what goes in is what comes out."""
text = "The man in black fled across the desert, and the gunslinger followed."
def test_gzip(self):
encoded = compression.enco... | Add specific tests for compression. | Add specific tests for compression.
| Python | apache-2.0 | vortec/pykafka,benauthor/pykafka,yungchin/pykafka,aeroevan/pykafka,sammerry/pykafka,thedrow/samsa,wikimedia/operations-debs-python-pykafka,tempbottle/pykafka,yungchin/pykafka,thedrow/samsa,wikimedia/operations-debs-python-pykafka,jofusa/pykafka,thedrow/samsa,jofusa/pykafka,appsoma/pykafka,vortec/pykafka,appsoma/pykafka... | ---
+++
@@ -0,0 +1,32 @@
+import unittest2
+
+from pykafka.utils import compression
+
+class CompressionTests(unittest2.TestCase):
+ """Keeping these simple by verifying what goes in is what comes out."""
+ text = "The man in black fled across the desert, and the gunslinger followed."
+
+ def test_gzip(self)... | |
6eca5cd06da3a195f226d2b864b8af41b62bda45 | kargtom/twodim/LongestChain/longestChain_002.py | kargtom/twodim/LongestChain/longestChain_002.py | def longestChain(words):
lendict = {}
lenlist = []
# build the dictory where
# the key is the length of a word,
# and the value is the set of words with the length
for word in words:
l = len(word)
if len(word) in lendict:
lendict[l][word] = -1
else:
... | Create the top-down longestPath with optimization | Create the top-down longestPath with optimization
horizontal optimization and vertical optimization | Python | mit | Chasego/codi,Chasego/cod,Chasego/codirit,Chasego/codirit,Chasego/codirit,Chasego/codirit,cc13ny/algo,Chasego/codi,cc13ny/Allin,cc13ny/algo,cc13ny/algo,Chasego/cod,Chasego/cod,cc13ny/algo,cc13ny/Allin,cc13ny/algo,cc13ny/Allin,Chasego/codi,Chasego/codi,cc13ny/Allin,Chasego/codirit,Chasego/cod,Chasego/codi,Chasego/cod,cc1... | ---
+++
@@ -0,0 +1,66 @@
+def longestChain(words):
+ lendict = {}
+ lenlist = []
+
+ # build the dictory where
+ # the key is the length of a word,
+ # and the value is the set of words with the length
+ for word in words:
+ l = len(word)
+ if len(word) in lendict:
+ lendict... | |
a906d3523bb9d6a1ca233a9d5e0e33c477c96e60 | test/test_retriever.py | test/test_retriever.py | """Tests for the EcoData Retriever"""
from StringIO import StringIO
from engine import Engine
def test_escape_single_quotes():
"""Test escaping of single quotes"""
test_engine = Engine()
assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'"
def test_escape_double_quotes():
"""Test e... | Add some basic unit tests for functions with no dependencies | Add some basic unit tests for functions with no dependencies
| Python | mit | embaldridge/retriever,bendmorris/retriever,goelakash/retriever,embaldridge/retriever,henrykironde/deletedret,davharris/retriever,henrykironde/deletedret,goelakash/retriever,bendmorris/retriever,davharris/retriever,davharris/retriever,bendmorris/retriever,embaldridge/retriever | ---
+++
@@ -0,0 +1,19 @@
+"""Tests for the EcoData Retriever"""
+
+from StringIO import StringIO
+from engine import Engine
+
+def test_escape_single_quotes():
+ """Test escaping of single quotes"""
+ test_engine = Engine()
+ assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'"
+
+def test... | |
e966e0774ad1474335a654cbe8f594d61ee97c3d | proselint/checks/misc/creditcard.py | proselint/checks/misc/creditcard.py | # -*- coding: utf-8 -*-
"""MSC: Credit card number printed.
---
layout: post
error_code: MSC
source: ???
source_url: ???
title: credit card number printed
date: 2014-06-10 12:31:19
categories: writing
---
Credit card number printed.
"""
from proselint.tools import blacklist
err = "MSC102"
msg = u... | Add a credit card number checker | Add a credit card number checker
| Python | bsd-3-clause | jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint | ---
+++
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+"""MSC: Credit card number printed.
+
+---
+layout: post
+error_code: MSC
+source: ???
+source_url: ???
+title: credit card number printed
+date: 2014-06-10 12:31:19
+categories: writing
+---
+
+Credit card number printed.
+
+"""
+from proselint.to... | |
6f2f857528d5d1df227f56422222c8de72c2e012 | tests/functional/test_service_alias.py | tests/functional/test_service_alias.py | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | Add functional test for service name aliases | Add functional test for service name aliases
| Python | apache-2.0 | pplu/botocore,boto/botocore | ---
+++
@@ -0,0 +1,37 @@
+# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"). You
+# may not use this file except in compliance with the License. A copy of
+# the License is located at
+#
+# http://aws.amazon.com/apache2.0/
+#... | |
e96a8dd7854809e64e27f1b06cd380586a628da0 | tests/functional/test_six_threading.py | tests/functional/test_six_threading.py | """
Regression test for six issue #98 (https://github.com/benjaminp/six/issues/98)
"""
from mock import patch
import sys
import threading
import time
from botocore.vendored import six
_original_setattr = six.moves.__class__.__setattr__
def _wrapped_setattr(key, value):
# Monkey patch six.moves.__setattr__ to s... | Add test for six.moves thread safety | Add test for six.moves thread safety
| Python | apache-2.0 | pplu/botocore,boto/botocore | ---
+++
@@ -0,0 +1,65 @@
+"""
+Regression test for six issue #98 (https://github.com/benjaminp/six/issues/98)
+"""
+from mock import patch
+import sys
+import threading
+import time
+
+from botocore.vendored import six
+
+
+_original_setattr = six.moves.__class__.__setattr__
+
+
+def _wrapped_setattr(key, value):
+ ... | |
0400dce44abca87cc0c0069b062f1f6942640125 | tests/test_cli_info.py | tests/test_cli_info.py | # -*- coding: utf-8 -*-
import pytest
COOKIECUTTER_DJANGO_INFO = """Name: cookiecutter-django
Author: pydanny
Repository: https://github.com/pydanny/cookiecutter-django
Context: {
"author_name": "Your Name",
"description": "A short description of the project.",
"domain_name": "example.com",
"email": "... | Implement an integration test for cibopath info | Implement an integration test for cibopath info
| Python | bsd-3-clause | hackebrot/cibopath | ---
+++
@@ -0,0 +1,48 @@
+# -*- coding: utf-8 -*-
+
+import pytest
+
+COOKIECUTTER_DJANGO_INFO = """Name: cookiecutter-django
+Author: pydanny
+Repository: https://github.com/pydanny/cookiecutter-django
+Context: {
+ "author_name": "Your Name",
+ "description": "A short description of the project.",
+ "domai... | |
a98c80247b5ec978e811cd6444596010d67c6a45 | tests/test_randvars.py | tests/test_randvars.py | """Tests of randvars module"""
import numpy as np
from dapper.tools.randvars import GaussRV
def test_gauss_rv():
M = 4
nsamples = 5
grv = GaussRV(mu=0, C=0, M=M)
assert (grv.sample(nsamples) == np.zeros((nsamples, M))).all()
test_gauss_rv()
| Add simple test of GaussRV class | Add simple test of GaussRV class
| Python | mit | nansencenter/DAPPER,nansencenter/DAPPER | ---
+++
@@ -0,0 +1,15 @@
+"""Tests of randvars module"""
+
+import numpy as np
+
+from dapper.tools.randvars import GaussRV
+
+
+def test_gauss_rv():
+ M = 4
+ nsamples = 5
+ grv = GaussRV(mu=0, C=0, M=M)
+ assert (grv.sample(nsamples) == np.zeros((nsamples, M))).all()
+
+
+test_gauss_rv() | |
6ab93cfc86f1fdf714a9921fcefd8f0dc36d55d1 | test/test_i18n_keys.py | test/test_i18n_keys.py | # -*- coding: utf-8 -*-
import re
import glob
import json
###############################################################################
# Find used keys in python code #
###############################################################################
def find_expected... | Add a test for i18n keys | Add a test for i18n keys
| Python | agpl-3.0 | YunoHost/moulinette | ---
+++
@@ -0,0 +1,83 @@
+# -*- coding: utf-8 -*-
+
+import re
+import glob
+import json
+
+
+###############################################################################
+# Find used keys in python code #
+##############################################################... | |
d616adf1ec2a2326f15607cbb30fee14c8023af2 | dojo/db_migrations/0021_auto_20191102_0956.py | dojo/db_migrations/0021_auto_20191102_0956.py | # Generated by Django 2.2.4 on 2019-11-02 09:56
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dojo', '0020_system_settings_allow_anonymous_survey_repsonse'),
]
operations = [
migrations.AlterField(
... | Add fix for CVE regex | Add fix for CVE regex
Signed-off-by: Kirill Gotsman <f479563306f23e4f1078487c7a864fa75778a9d5@cloudbees.com>
| Python | bsd-3-clause | rackerlabs/django-DefectDojo,rackerlabs/django-DefectDojo,rackerlabs/django-DefectDojo,rackerlabs/django-DefectDojo | ---
+++
@@ -0,0 +1,24 @@
+# Generated by Django 2.2.4 on 2019-11-02 09:56
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('dojo', '0020_system_settings_allow_anonymous_survey_repsonse'),
+ ]
+
+ operations =... | |
21420f6c730fb7e4063cddd28de3e7580c6efb36 | bin/versionbuild.py | bin/versionbuild.py | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 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/licen... | Add script to ensure semantic versions work with continuous build. | Add script to ensure semantic versions work with continuous build.
This module generates and inserts a patch component of the semantic version
stamp for Barbican, intended to ensure that a strictly monotonically increasing
version is produced for consecutive development releases. Some repositories
such as yum use this... | Python | apache-2.0 | cneill/barbican,cneill/barbican,cloudkeep/barbican,openstack/barbican,jmvrbanac/barbican,cloudkeep/barbican,jmvrbanac/barbican,openstack/barbican,MCDong/barbican,MCDong/barbican | ---
+++
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright (c) 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... | |
ab142f01ec932faaed05441b74c4be760a963374 | tests/rules_tests/RulesTest.py | tests/rules_tests/RulesTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 15.08.2017 15:31
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import *
class RulesTest(TestCase):
pass
if __name__ == '__main__':
main()
| Add file for test of behaviour when rules are pass | Add file for test of behaviour when rules are pass
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+"""
+:Author Patrik Valkovic
+:Created 15.08.2017 15:31
+:Licence GNUv3
+Part of grammpy
+
+"""
+
+from unittest import main, TestCase
+from grammpy import *
+
+
+class RulesTest(TestCase):
+ pass
+
+
+if __name__ == '__main__':
+ main() | |
7e97663eb29452769103684fce9166a0db17ab5a | speedtest.py | speedtest.py | #!/usr/bin/env python
from fastcomp import compare
import random
import string
def randomstr(minlen=5, maxlen=7):
charset = '01'
length = random.randint(minlen, maxlen)
return ''.join(random.choice(charset) for i in range(length))
if __name__ == "__main__":
import timeit
# Set up conditions
... | Add a script for speed measurement. | Add a script for speed measurement.
| Python | mit | fujimotos/fastcomp | ---
+++
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+
+from fastcomp import compare
+import random
+import string
+
+def randomstr(minlen=5, maxlen=7):
+ charset = '01'
+ length = random.randint(minlen, maxlen)
+ return ''.join(random.choice(charset) for i in range(length))
+
+if __name__ == "__main__":
+ imp... | |
f2396baa459c61fbbcd3c4889868f813a373d7e8 | tests/providers/conftest.py | tests/providers/conftest.py | import pytest
from web3.web3.ipcprovider import IPCProvider
from web3.web3.rpcprovider import TestRPCProvider, RPCProvider
@pytest.fixture(params=['tester', 'rpc', 'ipc'])
def disconnected_provider(request):
"""
Supply a Provider that's not connected to a node.
(See also the web3 fixture.)
"""
i... | Add fixture for disconnected providers | Add fixture for disconnected providers
| Python | mit | pipermerriam/web3.py,shravan-shandilya/web3.py | ---
+++
@@ -0,0 +1,24 @@
+import pytest
+
+from web3.web3.ipcprovider import IPCProvider
+from web3.web3.rpcprovider import TestRPCProvider, RPCProvider
+
+
+@pytest.fixture(params=['tester', 'rpc', 'ipc'])
+def disconnected_provider(request):
+ """
+ Supply a Provider that's not connected to a node.
+
+ (Se... | |
824c591204c7939a854d1d618cf32358387dbff0 | tests/test_location.py | tests/test_location.py | from SUASSystem import *
import math
import numpy
import unittest
from dronekit import LocationGlobalRelative
class locationTestCase(unittest.TestCase):
def setUp(self):
self.position = Location(5, 12, 20)
def test_get_lat(self):
self.assertEquals(5, self.position.get_lat())
| Add initial location unit tests | Add initial location unit tests
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | ---
+++
@@ -0,0 +1,13 @@
+from SUASSystem import *
+import math
+import numpy
+import unittest
+from dronekit import LocationGlobalRelative
+
+class locationTestCase(unittest.TestCase):
+
+ def setUp(self):
+ self.position = Location(5, 12, 20)
+
+ def test_get_lat(self):
+ self.assertEquals(5, se... | |
a7d8442482b7862b96adf3c8f40015072221f600 | pygments/styles/igor.py | pygments/styles/igor.py | from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: ... | Add custom style which imitates the offical coloring | Add custom style which imitates the offical coloring
| Python | bsd-2-clause | dscorbett/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,dscorbett/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,dscorbett/pygments,ds... | ---
+++
@@ -0,0 +1,13 @@
+from pygments.style import Style
+from pygments.token import Keyword, Name, Comment, String, Error, \
+ Number, Operator, Generic
+
+class IgorStyle(Style):
+ default_style = ""
+ styles = {
+ Comment: 'italic #FF0000',
+ Keyword: '#0000F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.