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 |
|---|---|---|---|---|---|---|---|---|---|---|
a2ee6106a6c98dae102cf14902c6b82f480e6cbe | python/main.py | python/main.py | import sys
from enum import Enum
class Furniture(Enum):
bed = 1
couce = 2
desk = 3
chair = 4
tv = 5
table = 6
rug = 7
shelf = 8
f = open(sys.argv[1], 'r')
print(f.read())
| import sys
from enum import Enum
from furniture import *
#class Furniture(Enum):
# bed = 1
# couce = 2
# desk = 3
# chair = 4
# tv = 5
# table = 6
# rug = 7
# shelf = 8
f = open(sys.argv[1], 'r')
print(f.read())
placeDesksAndChairs()
placeCouchesTablesAndTv()
placeBeds()
placeShelves()
place... | Add calls to furniture placement functions | Add calls to furniture placement functions
| Python | apache-2.0 | TheZoq2/VRHack,TheZoq2/VRHack,TheZoq2/VRHack,TheZoq2/VRHack | ---
+++
@@ -1,15 +1,23 @@
import sys
from enum import Enum
-class Furniture(Enum):
- bed = 1
- couce = 2
- desk = 3
- chair = 4
- tv = 5
- table = 6
- rug = 7
- shelf = 8
+from furniture import *
+
+#class Furniture(Enum):
+# bed = 1
+# couce = 2
+# desk = 3
+# chair = 4
+# ... |
c7ed3e2a39c7de1120a33cd0253d9ac3bd9e7984 | redcliff/cli.py | redcliff/cli.py | from sys import exit
import argparse
from .commands import dispatch
from .config import get_config
from .utils import merge
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--base-url')
parser.add_argument('-k', '--api-key')
parser.add_argument('-C', '--config-file')
par... | from sys import exit
import argparse
from .commands import dispatch, choices
from .config import get_config
from .utils import merge
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--base-url',
metavar='https://redmine.example.com',
h... | Update main arguments parser config | Update main arguments parser config
| Python | mit | dmedvinsky/redcliff | ---
+++
@@ -2,18 +2,29 @@
import argparse
-from .commands import dispatch
+from .commands import dispatch, choices
from .config import get_config
from .utils import merge
def main():
parser = argparse.ArgumentParser()
- parser.add_argument('-u', '--base-url')
- parser.add_argument('-k', '--api-... |
02ca88129430044f4202991358939d87f8c6da0b | simple-cipher/simple_cipher.py | simple-cipher/simple_cipher.py | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key ... | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key ... | Refactor to reuse the encode method for decoding | Refactor to reuse the encode method for decoding
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -12,15 +12,13 @@
self.key = key
self._key = [ord(k)-97 for k in key]
- def encode(self, s):
+ def encode(self, s, dirn=1):
key = self._key * math.ceil(len(s)/len(self._key))
chars = [c for c in s.lower() if c in ascii_lowercase]
- return "".join(self._shif... |
3a86ea268b7cb9f00968e7dcb228d6821dafda99 | simple-cipher/simple_cipher.py | simple-cipher/simple_cipher.py | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key ... | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key ... | Refactor to reuse the encode method for decoding | Refactor to reuse the encode method for decoding
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -12,15 +12,13 @@
self.key = key
self._key = [ord(k)-97 for k in key]
- def encode(self, s):
+ def encode(self, s, dirn=1):
key = self._key * math.ceil(len(s)/len(self._key))
chars = [c for c in s.lower() if c in ascii_lowercase]
- return "".join(self._shif... |
16c9563a75792aba7ccc0d979f579d64dc0140c1 | common_rg_bar.py | common_rg_bar.py | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x':
col_char = '3'
cols... | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
3. (optional) Text to display (without color)
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x... | Add optional text to display | Add optional text to display
| Python | mit | kwadrat/rgb_tdd | ---
+++
@@ -4,6 +4,7 @@
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
+3. (optional) Text to display (without color)
shows red/green bar to visualize return code of previous command
'''
@@ -27,13 +28,18 @@
else:
col_char = '2'
col... |
ff391fc302b6d4e9fab0653522fa2fe47d8e8faa | beavy_modules/url_extractor/lib.py | beavy_modules/url_extractor/lib.py | import lassie
from pyembed.core import PyEmbed
from beavy.app import cache
pyembed = PyEmbed()
@cache.memoize()
def extract_info(url):
return lassie.fetch(url)
@cache.memoize()
def extract_oembed(url, **kwargs):
return pyembed.embed('http://www.youtube.com/watch?v=_PEdPBEpQfY', **kwargs)
|
from pyembed.core import PyEmbed
from beavy.app import cache
from lassie import Lassie
import re
# lassie by default isn't extensive enough for us
# configure it so that it is.
from lassie.filters import FILTER_MAPS
FILTER_MAPS['meta']['open_graph']['map'].update({
# general
"og:type": "type",
"og:site... | Configure Lassie for more information | Configure Lassie for more information
| Python | mpl-2.0 | beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy | ---
+++
@@ -1,9 +1,57 @@
-import lassie
+
from pyembed.core import PyEmbed
from beavy.app import cache
+from lassie import Lassie
+import re
+
+# lassie by default isn't extensive enough for us
+# configure it so that it is.
+
+from lassie.filters import FILTER_MAPS
+FILTER_MAPS['meta']['open_graph']['map'].upd... |
c58b2dd49ad5c73d49b496025d13116da30b3b9a | examples/qm7_long.py | examples/qm7_long.py | import numpy
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge
from sklearn.metrics import mean_absolute_error as MAE
from molml.features import EncodedBond, Connectivity
from utils import load_qm7
if __name__ == "__main__":
# This is just boiler plate code to load the data
... | from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge
from sklearn.metrics import mean_absolute_error as MAE
from molml.features import EncodedBond, Connectivity, MultiFeature
from utils import load_qm7
if __name__ == "__main__":
# This is just boiler plate code to load the data
... | Change qm7 example to use MultiFeature | Change qm7 example to use MultiFeature
| Python | mit | crcollins/molml | ---
+++
@@ -1,9 +1,8 @@
-import numpy
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge
from sklearn.metrics import mean_absolute_error as MAE
-from molml.features import EncodedBond, Connectivity
+from molml.features import EncodedBond, Connectivity, MultiFeature
from utils ... |
67c444fb3603c234916b790d3dded3625f0512e5 | pivot/test/test_utils.py | pivot/test/test_utils.py | """
Tests utility scripts
"""
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
... | """
Tests utility scripts
"""
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
... | Rename test to something more descriptive. | Rename test to something more descriptive.
| Python | apache-2.0 | uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot | ---
+++
@@ -18,5 +18,5 @@
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
- def test_google_analytics_processor(self):
+ def test_get_latest_term(self):
self.assertEquals(get_latest_term(), 'au12') |
f7c03daa9ce803ec10e1c7cd9319840045f47663 | ddsc_core/management/commands/export_pi_xml.py | ddsc_core/management/commands/export_pi_xml.py | import sys
from django.core.management.base import BaseCommand
import pandas as pd
from tslib.readers import PiXmlReader
from tslib.writers import PiXmlWriter
from ddsc_core.models import Timeseries
class Command(BaseCommand):
args = "<pi.xml>"
help = "help"
def handle(self, *args, **options):
... | from optparse import make_option
from django.core.management.base import BaseCommand
import pandas as pd
from tslib.readers import PiXmlReader
from tslib.writers import PiXmlWriter
from ddsc_core.models import Timeseries
class Command(BaseCommand):
args = "<pi.xml>"
help = (
"Create pi.xml from a t... | Improve management command for exporting pi-xml | Improve management command for exporting pi-xml
| Python | mit | ddsc/ddsc-core,ddsc/ddsc-core | ---
+++
@@ -1,4 +1,4 @@
-import sys
+from optparse import make_option
from django.core.management.base import BaseCommand
import pandas as pd
@@ -11,15 +11,39 @@
class Command(BaseCommand):
args = "<pi.xml>"
- help = "help"
+ help = (
+ "Create pi.xml from a template. A template is a valid pi... |
afb398094e207fdd338a492dbbe9fca3f041e2c7 | tests/test_postgres_processor.py | tests/test_postgres_processor.py | import pytest
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
from . import utils
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
test_db = PostgresProcessor()
NORMALIZED = NormalizedDocument(utils.RE... | import pytest
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
from django.test import TestCase
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
from scrapi.linter.document import RawDocument
test_db = PostgresProcessor()
# NORMALIZED = NormalizedD... | Make this test a django test case | Make this test a django test case
| Python | apache-2.0 | erinspace/scrapi,CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,felliott/scrapi,mehanig/scrapi,fabianvf/scrapi,fabianvf/scrapi,felliott/scrapi,mehanig/scrapi | ---
+++
@@ -3,18 +3,21 @@
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
+from django.test import TestCase
+from scrapi.processing.postgres import PostgresProcessor, Document
+
from . import utils
-from scrapi.linter.document import NormalizedDocument, RawDocument
-from scrapi.proc... |
5d59f800da9fb737cd87d47301793f750ca1cbdd | pysnow/exceptions.py | pysnow/exceptions.py | # -*- coding: utf-8 -*-
class PysnowException(Exception):
pass
class InvalidUsage(PysnowException):
pass
class ResponseError(PysnowException):
message = "<empty>"
detail = "<empty>"
def __init__(self, error):
if "message" in error:
self.message = error["message"] or self.m... | # -*- coding: utf-8 -*-
class PysnowException(Exception):
pass
class InvalidUsage(PysnowException):
pass
class UnexpectedResponseFormat(PysnowException):
pass
class ResponseError(PysnowException):
message = "<empty>"
detail = "<empty>"
def __init__(self, error):
if "message" in ... | Add missing UnexpectedResponseFormat for backward compatability | Add missing UnexpectedResponseFormat for backward compatability
Signed-off-by: Abhijeet Kasurde <6334fd0c217b1f2a15926284df229acde5b4fc3a@redhat.com>
| Python | mit | rbw0/pysnow | ---
+++
@@ -6,6 +6,10 @@
class InvalidUsage(PysnowException):
+ pass
+
+
+class UnexpectedResponseFormat(PysnowException):
pass
|
2e812af6b937091d65a0b83ead936894a2789d02 | rdflib/serializer.py | rdflib/serializer.py | """
Serializer plugin interface.
This module is useful for those wanting to write a serializer that can
plugin to rdflib. If you are wanting to invoke a serializer you likely
want to do so through the Graph class serialize method.
TODO: info for how to write a serializer that can plugin to rdflib.
See also rdflib.plu... | """
Serializer plugin interface.
This module is useful for those wanting to write a serializer that can
plugin to rdflib. If you are wanting to invoke a serializer you likely
want to do so through the Graph class serialize method.
TODO: info for how to write a serializer that can plugin to rdflib.
See also rdflib.plu... | Change to preferred encoding style. | Change to preferred encoding style.
UTF-8 -> utf-8
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib | ---
+++
@@ -22,7 +22,7 @@
class Serializer:
def __init__(self, store: "Graph"):
self.store: "Graph" = store
- self.encoding: str = "UTF-8"
+ self.encoding: str = "utf-8"
self.base: Optional[str] = None
def serialize( |
6e32cfd9b2640b4f119a3a8e4138c883fd4bcef0 | _tests/test_scikit_ci_addons.py | _tests/test_scikit_ci_addons.py |
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
... |
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
... | Fix failing tests on appveyor | ci: Fix failing tests on appveyor
| Python | apache-2.0 | scikit-build/scikit-ci-addons,scikit-build/scikit-ci-addons | ---
+++
@@ -14,7 +14,7 @@
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
- expected_path = ci_addons.home() + '/' + addon
+ expected_path = os.path.join(ci_addons.home(), addon)
if not addon.endswith('.py'):
expected_path += '.py'
assert ci_addons... |
43ab1500719665b44e3b4eca4def9002711c2ee8 | githublist/parser.py | githublist/parser.py | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
fo... | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos?per_page=100'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
retur... | Update api url for recent 100 instead of default 30 | Update api url for recent 100 instead of default 30
| Python | mit | kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list | ---
+++
@@ -1,7 +1,7 @@
import requests
import collections
-API_URL = 'https://api.github.com/users/{}/repos'
+API_URL = 'https://api.github.com/users/{}/repos?per_page=100'
def main(user): |
fdf0daefac50de71a8c4f80a9ef877669ebea48b | byceps/services/tourney/transfer/models.py | byceps/services/tourney/transfer/models.py | """
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import NewType
from uuid import UUID
from attr import attrs
TourneyCategoryID = NewType('TourneyCategoryID', UUID)
Tourne... | """
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from dataclasses import dataclass
from typing import NewType
from uuid import UUID
TourneyCategoryID = NewType('TourneyCategoryID', UUID... | Change tourney match transfer model from `attrs` to `dataclass` | Change tourney match transfer model from `attrs` to `dataclass`
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | ---
+++
@@ -6,10 +6,9 @@
:License: Modified BSD, see LICENSE for details.
"""
+from dataclasses import dataclass
from typing import NewType
from uuid import UUID
-
-from attr import attrs
TourneyCategoryID = NewType('TourneyCategoryID', UUID)
@@ -27,6 +26,6 @@
ParticipantID = NewType('ParticipantID', UUID... |
50519406ac64766874ce9edf5cea69233461ffb2 | tests/test_config.py | tests/test_config.py | # -*- coding: utf-8 -*-
import pytest
import uuid
from s3keyring.s3 import S3Keyring
@pytest.fixture
def config(scope='module'):
return S3Keyring(profile_name='test').config
@pytest.yield_fixture
def dummyparam(config, scope='module'):
yield 'dummyparam'
config.config.remove_option('default', 'dummypa... | # -*- coding: utf-8 -*-
import pytest
import uuid
import tempfile
import os
from s3keyring.s3 import S3Keyring
@pytest.fixture
def config(scope='module'):
return S3Keyring(profile_name='test').config
@pytest.yield_fixture
def dummyparam(config, scope='module'):
yield 'dummyparam'
config.config.remove_... | Test custom configuration file feature | Test custom configuration file feature
| Python | mit | InnovativeTravel/s3-keyring | ---
+++
@@ -3,6 +3,8 @@
import pytest
import uuid
+import tempfile
+import os
from s3keyring.s3 import S3Keyring
@@ -17,9 +19,17 @@
config.config.remove_option('default', 'dummyparam')
+@pytest.yield_fixture
+def dummy_config_file():
+ filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4... |
025927fa19bb96095a2ea1c53524945f1f9590ce | spur/results.py | spur/results.py | def result(return_code, output, stderr_output, allow_error=False):
if allow_error or return_code == 0:
return ExecutionResult(return_code, output, stderr_output)
else:
raise RunProcessError(return_code, output, stderr_output)
class RunProcessError(RuntimeError):
def __init__(self, return_c... | def result(return_code, output, stderr_output, allow_error=False):
result = ExecutionResult(return_code, output, stderr_output)
if allow_error or return_code == 0:
return result
else:
raise result.to_error()
class RunProcessError(RuntimeError):
def __init__(self, return_code, output, s... | Move logic for creating RunProcessError to ExecutionResult.to_error | Move logic for creating RunProcessError to ExecutionResult.to_error
| Python | bsd-2-clause | mwilliamson/spur.py | ---
+++
@@ -1,8 +1,9 @@
def result(return_code, output, stderr_output, allow_error=False):
+ result = ExecutionResult(return_code, output, stderr_output)
if allow_error or return_code == 0:
- return ExecutionResult(return_code, output, stderr_output)
+ return result
else:
- raise Ru... |
936db17eed36284917395a6a8272351dabbc8168 | numpy/_array_api/_dtypes.py | numpy/_array_api/_dtypes.py | from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64
# Note: This name is changed
from .. import bool_ as bool
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float... | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype... | Use dtype objects instead of classes in the array API | Use dtype objects instead of classes in the array API
The array API does not require any methods or behaviors on dtype objects,
other than that they be literals that can be compared for equality and passed
to dtype keywords in functions. Since dtype objects are already used by the
dtype attribute of ndarray, this make... | Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -1,6 +1,19 @@
-from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64
+import numpy as np
+
+# Note: we use dtype objects instead of dtype classes. The spec does not
+# require any behavior on dtypes other than equality.
+int8 = np.dtype('int8')
+int16 = np.dtype('int16')... |
ffd4c52155acd7d04939e766ebe63171b580a2fa | src/__init__.py | src/__init__.py | import os
import logging
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect' ]
# connected client object
_client = None
def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
# get server filename
server = os.path.join(... | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | Add the ability to use inet socket as well. | Add the ability to use inet socket as well.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1236 a8f5125c-1e01-0410-8897-facf34644b8e
| Python | lgpl-2.1 | freevo/kaa-epg | ---
+++
@@ -1,31 +1,45 @@
import os
import logging
+from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
-__all__ = [ 'connect' ]
+__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None... |
9d960bfa74a09382839f9b671004bebaffe46611 | reui/Screen.py | reui/Screen.py | """
A screen object contains a collection of boxes to be displayed on a
physical display device.
"""
from pydispatch import dispatcher
from reui import SGL_BOX_UPDATE
from gaugette import bitmap
class Screen:
_boxes = []
_boxMap = {}
_bitmap = None
def __init__(self, width, height, display):
... | """
A screen object contains a collection of boxes to be displayed on a
physical display device.
"""
from pydispatch import dispatcher
from reui import SGL_BOX_UPDATE
from gaugette import bitmap
class Screen:
_boxes = []
_boxMap = {}
_bitmap = None
def __init__(self, width, height, display):
... | Support for Box direct drawing to screen bitmap | Support for Box direct drawing to screen bitmap | Python | mit | mharriger/reui | ---
+++
@@ -37,3 +37,11 @@
self._bitmap.replace_rect(x, y, sender._bitmap)
self._display.display()
+ def draw_pixel(self, box, x, y, on=True):
+ bx, by = self._boxMap[box]
+ self._bitmap.draw_pixel(bx + x, by + y, on)
+
+ def draw_text(self, box, x, y, string, font=box.... |
f087ea792b1e093e6ed49e3dd3b647f2f8276f64 | acme/_metadata.py | acme/_metadata.py | # python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... | # python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... | Update Acme version to 0.2.1. | Update Acme version to 0.2.1.
PiperOrigin-RevId: 375471102
Change-Id: I9e134bfa61b07059eac564efd515ab788eb1e4f4
| Python | apache-2.0 | deepmind/acme,deepmind/acme | ---
+++
@@ -22,7 +22,7 @@
# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '2'
-_PATCH_VERSION = '0'
+_PATCH_VERSION = '1'
# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION]) |
0cf0f3de5879795fcd01b8d88bf11efb3362f530 | script/echo.py | script/echo.py | #!/usr/bin/env python3
# -*- coding: ascii -*-
# A small example bot for Instant.
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
b = instabot.CmdlineBotBuilder(defnick=NICKNAME)
b.make_parser(sy... | #!/usr/bin/env python3
# -*- coding: ascii -*-
# A small example bot for Instant.
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
b = instabot.CmdlineBotBuilder(defnick=NICKNAME)
b.make_parser(sy... | Make example bot use keepalive | [Instabot] Make example bot use keepalive
| Python | mit | CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant | ---
+++
@@ -18,7 +18,7 @@
b.make_parser(sys.argv[0],
desc='An Instant bot bouncing back received messages.')
b.parse(sys.argv[1:])
- bot = b(post_cb=post_cb)
+ bot = b(keepalive=True, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt: |
d90d35063f1a79916c20d32d3634842dd59798f1 | api/tests/conftest.py | api/tests/conftest.py | import pytest
@pytest.fixture(scope='module')
def app():
from api import app
return app
| import pytest
@pytest.fixture(scope='module')
def app():
from api import app, db
app.config['TESTING'] = True
db.create_all()
return app
| Fix default fixture to initialize database | Fix default fixture to initialize database
| Python | mit | Demotivated/loadstone | ---
+++
@@ -3,5 +3,9 @@
@pytest.fixture(scope='module')
def app():
- from api import app
+ from api import app, db
+
+ app.config['TESTING'] = True
+ db.create_all()
+
return app |
6decf1f48e56832b1d15d3fc26d92f9813d13353 | coop_cms/moves.py | coop_cms/moves.py | # -*- coding: utf-8 -*-
"""
coop_cms manage compatibilty with django and python versions
"""
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
from HTMLParser import HTMLParser
from StringIO import StringIO
else:
# Python 3
from html.parser import HTMLParser
from i... | # -*- coding: utf-8 -*-
"""
coop_cms manage compatibilty with django and python versions
"""
import sys
from django import VERSION
if sys.version_info[0] < 3:
# Python 2
from StringIO import StringIO
from HTMLParser import HTMLParser
else:
# Python 3
from io import BytesIO as StringIO
... | Fix HTMLParser compatibility in Python 3 | Fix HTMLParser compatibility in Python 3
| Python | bsd-3-clause | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms | ---
+++
@@ -10,12 +10,22 @@
if sys.version_info[0] < 3:
# Python 2
+
+ from StringIO import StringIO
+
from HTMLParser import HTMLParser
- from StringIO import StringIO
+
+
+
else:
# Python 3
- from html.parser import HTMLParser
from io import BytesIO as StringIO
+
+ from html.pars... |
9931bd1d5459a983717fb502826f3cca87225b96 | src/qrl/services/grpcHelper.py | src/qrl/services/grpcHelper.py | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger
class GrpcExceptionWrapper(object):
def __init__(self, response_type, state_code=StatusCode.UNKNOWN):... | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger
class GrpcExceptionWrapper(object):
def __init__(self, response_type, state_code=StatusCode.UNKNOWN):... | Set code to Invalid argument for ValueErrors | Set code to Invalid argument for ValueErrors
| Python | mit | jleni/QRL,cyyber/QRL,jleni/QRL,cyyber/QRL,theQRL/QRL,randomshinichi/QRL,theQRL/QRL,randomshinichi/QRL | ---
+++
@@ -20,6 +20,7 @@
try:
return f(caller_self, request, context)
except ValueError as e:
+ context.set_code(StatusCode.INVALID_ARGUMENT)
self._set_context(context, e)
logger.info(str(e))
return self.resp... |
ce1fb05e825e9be7589fd12ab798cae760b605e6 | sheldon/bot.py | sheldon/bot.py | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.config import *
from sheldon.adapter import *
from sheldon.storage import *
class Sheldon:
"""
Main ... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.config import *
from sheldon.adapter import *
from sheldon.storage import *
class Sheldon:
"""
Main ... | Add basic load config function | Add basic load config function
| Python | mit | lises/sheldon | ---
+++
@@ -21,14 +21,28 @@
Run script creating new instance of this class and run it.
"""
- def __init__(self):
+ def __init__(self, command_line_arguments):
"""
Function for loading bot.
+ :param command_line_arguments: dict, arguments for start script
:return:
... |
74f82029223cc541beab98d7026abb1ec992be40 | createTodoFile.py | createTodoFile.py | """createTodoFile.py: Creates an todo file with title name as current date"""
import time
import os.path
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as my... | """createTodoFile.py: Creates an todo file with title name as current date"""
import os.path
import time
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as my... | Add created file to sublime | feat: Add created file to sublime
| Python | mit | prajesh-ananthan/Tools | ---
+++
@@ -1,7 +1,7 @@
"""createTodoFile.py: Creates an todo file with title name as current date"""
+import os.path
import time
-import os.path
def createfile():
@@ -12,12 +12,13 @@
with open(filename, "a") as myfile:
myfile.write("[RESULTS - {}]".format(date))
print("INFO: "... |
0f114a144268bb611ff00db9917756a8c02f84b9 | project/api/signals.py | project/api/signals.py | # Django
# Third-Party
from django.db.models.signals import pre_delete
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings
# Local
from .models import User
from .tasks import delete_account
@receiver(pre_delete, sender=User)
def user_pre_delete(sender, ... | # Django
# Third-Party
from django.db.models.signals import pre_delete
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings
# Local
from .models import User
from .tasks import activate_user
from .tasks import delete_account
@receiver(pre_delete, sender=U... | Connect person to user account | Connect person to user account
| Python | bsd-2-clause | barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api | ---
+++
@@ -7,12 +7,17 @@
# Local
from .models import User
+from .tasks import activate_user
from .tasks import delete_account
@receiver(pre_delete, sender=User)
def user_pre_delete(sender, instance, **kwargs):
- if settings.DJANGO_SETTINGS_MODULE == 'settings.prod':
+ allowed = any([
+ settin... |
9568efceab48f87ed8302ec4f9bad4b15aac4c5a | tests/test_action.py | tests/test_action.py | 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... | 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 test to check if connection is closed after email is sent. | Add test to check if connection is closed after email is sent.
| Python | mit | bsmukasa/stock_alerter | ---
+++
@@ -21,3 +21,13 @@
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
+
+ def test_connection_closed_after_sending_mail(self, mock_smtp_class):
+ mock... |
5bc4aa60be988abc98ba76ca4b790b259d75af37 | capstone/rl/policies/egreedy.py | capstone/rl/policies/egreedy.py | import random
from .greedy import Greedy
from .random_policy import RandomPolicy
from ..policy import Policy
from ...utils import check_random_state
class EGreedy(Policy):
def __init__(self, e, random_state=None):
self.e = e
self.greedy = Greedy()
self.rand = RandomPolicy()
self.r... | from .greedy import Greedy
from .random_policy import RandomPolicy
from ..policy import Policy
from ...utils import check_random_state
class EGreedy(Policy):
def __init__(self, e, random_state=None):
self.e = e
self.greedy = Greedy()
self.rand = RandomPolicy()
self.random_state = ... | Fix EGreedy policy call order | Fix EGreedy policy call order
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -1,4 +1,3 @@
-import random
from .greedy import Greedy
from .random_policy import RandomPolicy
from ..policy import Policy
@@ -15,4 +14,4 @@
def action(self, state, actions=None, vf=None):
policy = self.rand if self.random_state.rand() < self.e else self.greedy
- return policy.act... |
547787272a6945bfefd086504e4c3dcaf483bc37 | tests/test_logger.py | tests/test_logger.py | """Test the logger module"""
from gobble.logger import log
def test_gobble_logger_exists():
assert log.name == 'Gobble'
| """Test the logger module"""
from gobble.logger import log
def test_gobble_logger_exists():
assert log.name == 'Gobble'
| Remove one blank to be friends with the lama. | Remove one blank to be friends with the lama.
| Python | mit | openspending/gobble | ---
+++
@@ -5,4 +5,3 @@
def test_gobble_logger_exists():
assert log.name == 'Gobble'
- |
7be79e544eecf158a6ff1bde2f9f76f5145e4ae1 | tests/tools_tests.py | tests/tools_tests.py | """Tests for ifcfg.tools."""
import logging
import os
import unittest
import ifcfg
from nose.tools import eq_
class IfcfgToolsTestCase(unittest.TestCase):
def test_minimal_logger(self):
os.environ['IFCFG_DEBUG'] = '1'
log = ifcfg.tools.minimal_logger(__name__)
eq_(log.level, logging.DEB... | """Tests for ifcfg.tools."""
import logging
import os
import unittest
import ifcfg
from ifcfg.tools import exec_cmd
from nose.tools import eq_
class IfcfgToolsTestCase(unittest.TestCase):
def test_minimal_logger(self):
os.environ['IFCFG_DEBUG'] = '1'
log = ifcfg.tools.minimal_logger(__name__)
... | Add a test that calls exec_cmd | Add a test that calls exec_cmd
| Python | bsd-3-clause | ftao/python-ifcfg | ---
+++
@@ -5,6 +5,7 @@
import unittest
import ifcfg
+from ifcfg.tools import exec_cmd
from nose.tools import eq_
@@ -15,3 +16,7 @@
log = ifcfg.tools.minimal_logger(__name__)
eq_(log.level, logging.DEBUG)
os.environ['IFCFG_DEBUG'] = '0'
+
+ def test_command(self):
+ outpu... |
30dbda17bfa3b52dc2aace6eba6b8c1e4b3f7542 | robot-name/robot_name.py | robot-name/robot_name.py | # File: robot_name.py
# Purpose: Write a program that manages robot factory settings.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Friday 30 September 2016, 03:00 PM
import string
import random
class Robot():
"""Robot facory settings"""
def __init__(self):
self.name = "... | # File: robot_name.py
# Purpose: Write a program that manages robot factory settings.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Friday 30 September 2016, 03:00 PM
import string
import random
class Robot():
"""Robot facory settings"""
def __init__(self):
self.name = "... | Add methord to generate unique robot name | Add methord to generate unique robot name
| Python | mit | amalshehu/exercism-python | ---
+++
@@ -13,4 +13,12 @@
def __init__(self):
self.name = ""
-
+ def factory_name(self):
+
+ char = ''.join(random.SystemRandom().choice(string.ascii_uppercase) for _ in range(2))
+ num = ''.join(random.SystemRandom().choice(string.digits) for _ in range(3))
+ self.name = ... |
3134af98d2fcf88752170d628400a7e863d4c959 | was/artists/views.py | was/artists/views.py | from django.shortcuts import render, get_object_or_404
from django.views.generic.edit import CreateView, UpdateView
from .form import CreateArtistForm, UpdateArtistForm, Artists
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout
from django.http import HttpResponseRed... | from django.shortcuts import render, get_object_or_404
from django.views.generic.edit import CreateView, UpdateView
from .form import CreateArtistForm, UpdateArtistForm, Artists, User
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout
from django.http import HttpRespo... | Create update view (extends UpdateView generic view). Define get_initail in order to pre populate two custom fields username and email which are not in the original Artists model. | Create update view (extends UpdateView generic view).
Define get_initail in order to pre populate two custom fields username and email which are not in the original
Artists model.
| Python | mit | KeserOner/where-artists-share,KeserOner/where-artists-share | ---
+++
@@ -1,6 +1,6 @@
from django.shortcuts import render, get_object_or_404
from django.views.generic.edit import CreateView, UpdateView
-from .form import CreateArtistForm, UpdateArtistForm, Artists
+from .form import CreateArtistForm, UpdateArtistForm, Artists, User
from django.contrib.auth.forms import Authe... |
533d1462949ab451674d91dd7730957cb2252dde | susumutakuan.py | susumutakuan.py | import discord
import asyncio
import os
import signal
import sys
from subprocess import run
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
def sigterm_handler(signum, frame):
print('Logging out...', flush=True)
raise Keyboar... | import discord
import asyncio
import os
import signal
import sys
from subprocess import run
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
def sigterm_handler(signum, frame):
print('Logging out...', flush=True)
raise Keyboar... | Add universal_newlines paramter to run call | Add universal_newlines paramter to run call
| Python | mit | gryffon/SusumuTakuan,gryffon/SusumuTakuan | ---
+++
@@ -36,7 +36,7 @@
if message.channel.type == discord.ChannelType.private:
if message.content.startswith('!update'):
tmp = await client.send_message(message.channel, 'Updating my code via git...')
- process = run(["sh", "control.sh", "refresh"])
+ process = run(... |
f9835741804da062f1501b06560a2af75b199645 | scrapeOMDB.py | scrapeOMDB.py | #!/usr/bin/python3
# scrapeOMDB.py - parses a movie and year from arguments and returns JSON
import json, requests
URL_BASE = 'http://www.omdbapi.com/?'
def OMDBmovie(mTitle, mYear):
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
response = ... | #!/usr/bin/python3
# scrapeOMDB.py - parses a movie and year from arguments and returns JSON
import json, requests
URL_BASE = 'http://www.omdbapi.com/?'
def OMDBmovie(mTitle, mYear):
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + str(mYear) + '&plot=full&r=json'
# Try to get the url
respon... | Convert movie year to str | Convert movie year to str
| Python | mit | samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia | ---
+++
@@ -7,7 +7,7 @@
def OMDBmovie(mTitle, mYear):
# Craft the URL
- url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
+ url = URL_BASE + 't=' + mTitle + '&y=' + str(mYear) + '&plot=full&r=json'
# Try to get the url
response = requests.get(url) |
1d14d28d68278330855e585a859484019d8c3e43 | cacivicdata/manage.py | cacivicdata/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cacivicdata.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Change back to django default | Change back to django default
| Python | mit | california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website | ---
+++
@@ -3,7 +3,8 @@
import sys
if __name__ == "__main__":
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
- sys.path.append(os.path.dirname(os.path.dirname(__file__)))
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cacivicdata.settings")
+
from django.core.management import exe... |
5632daecf9c5f271eeba0f9948d88f44d6a070d0 | irclogview/models.py | irclogview/models.py | from django.db import models
from picklefield.fields import PickledObjectField
class Channel(models.Model):
name = models.SlugField(max_length=50, unique=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'#%s' % self.name
class Log(models.Model):
channel = mo... | from django.db import models
from picklefield.fields import PickledObjectField
from . import utils
class Channel(models.Model):
name = models.SlugField(max_length=50, unique=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'#%s' % self.name
class Log(models.Mod... | Add function to get content in list of dicts format | Add function to get content in list of dicts format
| Python | agpl-3.0 | BlankOn/irclogview,fajran/irclogview,fajran/irclogview,BlankOn/irclogview | ---
+++
@@ -1,6 +1,8 @@
from django.db import models
from picklefield.fields import PickledObjectField
+
+from . import utils
class Channel(models.Model):
name = models.SlugField(max_length=50, unique=True)
@@ -19,3 +21,10 @@
class Meta:
unique_together = ('channel', 'date')
+ def conte... |
4228082c9c94b3e17e6b00fc1e380841d5389dc5 | crawler/models.py | crawler/models.py | from django.db import models
# Create your models here.
class Data_Ingredient(models.Model):
""""Class used to Store Ingredients of the recipes found in the crawling process"""
Ingredient = models.CharField(max_length=1000)
Recipe = models.CharField(max_length=500)
Group = models.CharField(max_len... | from django.db import models
class Data_Ingredient(models.Model):
""""Class used to Store Ingredients of the recipes found in the crawling process"""
Ingredient = models.CharField(max_length=1000)
Recipe = models.CharField(max_length=500)
Group = models.CharField(max_length=500, default='Ingredientes... | Remove not needed comment line | Remove not needed comment line
| Python | mit | lucasgr7/silverplate,lucasgr7/silverplate,lucasgr7/silverplate | ---
+++
@@ -1,8 +1,4 @@
from django.db import models
-
-
-# Create your models here.
-
class Data_Ingredient(models.Model): |
1d77647efdb26b8282fc0624852d211fa9339539 | db/TableConfig.py | db/TableConfig.py | {
PDBConst.Name: "config",
PDBConst.Columns: [
{
PDBConst.Name: "Name",
PDBConst.Attributes: ["varchar(128)", "not null", "primary key"]
},
{
PDBConst.Name: "Value",
PDBConst.Attributes: ["varchar(128)"]
}],
PDBConst.Initials: [
{"Name": "'version'", "... | {
PDBConst.Name: "config",
PDBConst.Columns: [
{
PDBConst.Name: "Name",
PDBConst.Attributes: ["varchar(128)", "not null", "primary key"]
},
{
PDBConst.Name: "Value",
PDBConst.Attributes: ["varchar(128)"]
}],
PDBConst.Initials: [
{"Name": "'version'", "... | Introduce family id for all | Introduce family id for all
| Python | mit | eddiedb6/ej,eddiedb6/ej,eddiedb6/ej | ---
+++
@@ -10,6 +10,6 @@
PDBConst.Attributes: ["varchar(128)"]
}],
PDBConst.Initials: [
- {"Name": "'version'", "Value": "'1.0'"}
+ {"Name": "'version'", "Value": "'4.0'"}
]
} |
22b6785695967a43ab9d187db60c201c3dc4a8e1 | peerinst/admin.py | peerinst/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['title']}),
(_('Mai... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['title']}),
(_('Mai... | Use radio buttons for the style and number of answers. | Use radio buttons for the style and number of answers.
| Python | agpl-3.0 | open-craft/dalite-ng,open-craft/dalite-ng,open-craft/dalite-ng | ---
+++
@@ -26,6 +26,7 @@
]}),
(None, {'fields': ['example_rationale']}),
]
+ radio_fields = {'answer_style': admin.HORIZONTAL, 'answer_num_choices': admin.HORIZONTAL}
@admin.register(models.Assignment)
class AssignmentAdmin(admin.ModelAdmin): |
b35ee625143fd57f5571f807d0cd4331be4e0947 | caprice/models.py | caprice/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String
from .db import Base, Session
__all__ = ['Schema']
class Schema(Base):
__tablename__ = 'schemas'
# TODO: allow Only UUID? or user defined ID too?
id = Column(String, primary_key=True)
# TODO: JSON uniqueness is nee... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String
from .db import Base, Session
__all__ = ['Schema']
class Schema(Base):
__tablename__ = 'schemas'
# TODO: allow Only UUID? or user defined ID too?
id = Column(String, primary_key=True)
# TODO: JSON uniqueness is nee... | Use compatible(for Python2.6) format string. | Use compatible(for Python2.6) format string.
| Python | mit | FGtatsuro/Caprice,FGtatsuro/Caprice,FGtatsuro/Caprice | ---
+++
@@ -22,7 +22,7 @@
self.body = body
def __repr__(self):
- return '<{!s}: {!r}>'.format(self.__class__.__name__, self.body)
+ return "<{0}: '{1}'>".format(self.__class__.__name__, self.body)
# TODO: Use contextmanager. Ref. http://docs.sqlalchemy.org/en/rel_1_0/orm/session_b... |
8222bf717b92ab57b60b834b4496afb654b8a80b | krisk/connections.py | krisk/connections.py |
from collections import OrderedDict
from IPython.display import Javascript
import json
from krisk.util import join_current_dir
ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/'
ECHARTS_FILE = 'echarts.min'
d_paths = OrderedDict({})
THEMES = ['dark','vintage','roma','shine','infographic','macarons'... |
from collections import OrderedDict
from IPython.display import Javascript
import json
from krisk.util import join_current_dir
ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/'
ECHARTS_FILE = 'echarts.min'
d_paths = OrderedDict({})
THEMES = ['dark','vintage','roma','shine','infographic','macarons'... | Change all js to point to krisk repo | Change all js to point to krisk repo
| Python | bsd-3-clause | napjon/krisk,napjon/krisk,napjon/krisk | ---
+++
@@ -33,9 +33,6 @@
return Javascript("""
require.config({
baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static",
- paths: {
- echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min"
- },
waitSeco... |
e299c07034e0ad1135bda999ad0c63f4b5a7fa40 | chaco/__init__.py | chaco/__init__.py | # Copyright (c) 2005-2013 by Enthought, Inc.
# All rights reserved.
""" Two-dimensional plotting application toolkit.
Part of the Chaco project of the Enthought Tool Suite.
"""
__version__ = '4.5.0dev'
__requires__ = [
'enable',
]
| # Copyright (c) 2005-2013 by Enthought, Inc.
# All rights reserved.
""" Two-dimensional plotting application toolkit.
Part of the Chaco project of the Enthought Tool Suite.
"""
__version__ = '4.5.0.dev'
__requires__ = [
'enable',
]
| Tweak the version number to match other ETS projects. | Tweak the version number to match other ETS projects.
| Python | bsd-3-clause | burnpanck/chaco,tommy-u/chaco,tommy-u/chaco,tommy-u/chaco,burnpanck/chaco,burnpanck/chaco | ---
+++
@@ -3,7 +3,7 @@
""" Two-dimensional plotting application toolkit.
Part of the Chaco project of the Enthought Tool Suite.
"""
-__version__ = '4.5.0dev'
+__version__ = '4.5.0.dev'
__requires__ = [
'enable', |
0f53ec6ddeb236bee78794e8d1ed156ad182bc07 | projects/forms.py | projects/forms.py | from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ProjectForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
instance = super(ProjectForm, self).save(co... | from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ProjectForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
instance = super(ProjectForm, self).save(co... | Add status to project form | Add status to project form
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -29,7 +29,8 @@
'schedule',
'resources',
'finance_description',
- 'partners',)
+ 'partners',
+ 'status')
class RestrictedProjectForm(forms.ModelForm): |
84e9532487615f684abbed17d6821ae7bc84c9be | virtualfish/loader/__init__.py | virtualfish/loader/__init__.py | from __future__ import print_function
import os
import sys
import pkg_resources
def load(plugins=()):
try:
version = pkg_resources.get_distribution("virtualfish").version
commands = ["set -g VIRTUALFISH_VERSION {}".format(version)]
except pkg_resources.DistributionNotFound:
commands = ... | from __future__ import print_function
import os
import sys
import pkg_resources
def load(plugins=(), full_install=True):
try:
version = pkg_resources.get_distribution("virtualfish").version
commands = ["set -g VIRTUALFISH_VERSION {}".format(version)]
except pkg_resources.DistributionNotFound:
... | Add kwarg to load function to distinguish from full install | Add kwarg to load function to distinguish from full install
The load function is used for a full install and thus always adds
general configuration lines to the loader file, but we don't want that
for plugin installation.
| Python | mit | adambrenecki/virtualfish,adambrenecki/virtualfish | ---
+++
@@ -4,18 +4,21 @@
import pkg_resources
-def load(plugins=()):
+def load(plugins=(), full_install=True):
try:
version = pkg_resources.get_distribution("virtualfish").version
commands = ["set -g VIRTUALFISH_VERSION {}".format(version)]
except pkg_resources.DistributionNotFound:
... |
5b652fc1af9c72c195446aaaf3ff35a501766676 | tests/tests.py | tests/tests.py | # coding=UTF-8
import unittest
import treetojson
class TreeToJsonTests(unittest.TestCase):
def test_list(self):
result = "{\"SENTENCE\":[{\"NN\":\"Everyone\"},{\"VBZ\":\"knows\"},{\"DT\":\"an\"},{\"NN\":\"Elephant\"}," \
"{\"VBZ\":\"is\"},{\"JJR\":\"larger\"},{\"IN\":\"than\"},{\"DT\":\"... | Add test case for list containing words with tags | Add test case for list containing words with tags
| Python | mit | saadsahibjan/treetojson | ---
+++
@@ -0,0 +1,21 @@
+# coding=UTF-8
+
+import unittest
+import treetojson
+
+
+class TreeToJsonTests(unittest.TestCase):
+ def test_list(self):
+ result = "{\"SENTENCE\":[{\"NN\":\"Everyone\"},{\"VBZ\":\"knows\"},{\"DT\":\"an\"},{\"NN\":\"Elephant\"}," \
+ "{\"VBZ\":\"is\"},{\"JJR\":\"l... | |
0db1575341ae37644f2ce43c0a89e4baf83f8d87 | filebrowser/urls.py | filebrowser/urls.py | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1', 'permanent': True}, name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb... | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.view... | Remove redirect again, it's somehow causing the JS issue and it won't work for other media types | Remove redirect again, it's somehow causing the JS issue and it won't work for other media types
| Python | bsd-3-clause | django-wodnas/django-filebrowser-no-grappelli,django-wodnas/django-filebrowser-no-grappelli,sandow-digital/django-filebrowser-no-grappelli-sandow,sandow-digital/django-filebrowser-no-grappelli-sandow,sandow-digital/django-filebrowser-no-grappelli-sandow,django-wodnas/django-filebrowser-no-grappelli | ---
+++
@@ -4,7 +4,7 @@
urlpatterns = patterns('',
# filebrowser urls
- url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1', 'permanent': True}, name="fb_browse"),
+ url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', ... |
3039fec89f74618657db0509765dda48a090f0be | hetzner/__init__.py | hetzner/__init__.py | class RobotError(Exception):
def __init__(self, message, status=None):
self.message = message
self.status = status
def __repr__(self):
if self.status is None:
return self.message
else:
return "{0} ({1})".format(self.message, self.status)
class ManualReb... | class RobotError(Exception):
def __init__(self, message, status=None):
self.message = message
self.status = status
def __str__(self):
if self.status is None:
return self.message
else:
return "{0} ({1})".format(self.message, self.status)
class ManualRebo... | Use __str__ for formatting the error. | RobotError: Use __str__ for formatting the error.
On a traceback, the __str__ value will be read instead of __repr__ so we
get the name of the exception class, but not the actual exception.
This is now no longer the case :-)
Signed-off-by: aszlig <ee1aa092358634f9c53f01b5a783726c9e21b35a@redmoonstudios.org>
| Python | bsd-3-clause | RedMoonStudios/hetzner | ---
+++
@@ -3,7 +3,7 @@
self.message = message
self.status = status
- def __repr__(self):
+ def __str__(self):
if self.status is None:
return self.message
else: |
353098b81b0e281d5d78e820dd91c3f360d6e585 | ibmcnx/test/test.py | ibmcnx/test/test.py | import loadFunction.py
loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
| import ibmcnx.test.loadFunction
loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
| Customize scripts to work with menu | Customize scripts to work with menu
| Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -1,4 +1,4 @@
-import loadFunction.py
+import ibmcnx.test.loadFunction
loadFilesService()
|
e1721a515520a85fbbfae112eb63f877de33e7c9 | caffe2/python/test_util.py | caffe2/python/test_util.py | ## @package test_util
# Module caffe2.python.test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import workspace
import unittest
def rand_array(*dims):
# np.random.ran... | ## @package test_util
# Module caffe2.python.test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace
import unittest
def rand_array(*dims):
# np.rand... | Clear the operator default engines before running operator tests | Clear the operator default engines before running operator tests
Reviewed By: akyrola
Differential Revision: D5729024
fbshipit-source-id: f2850d5cf53537b22298b39a07f64dfcc2753c75
| Python | apache-2.0 | sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,davinwang/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,Yangqing/caffe2,sf-wind/caffe2,Yangqing/caffe2,davinwang/caffe2,xzturn/caffe2,sf-wind/caffe2,sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,pietern/caffe2,xzturn/caffe2,Yangqing/caffe2,Yangqing/caffe2,caffe2/caffe2,... | ---
+++
@@ -5,7 +5,7 @@
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
-from caffe2.python import workspace
+from caffe2.python import core, workspace
import unittest
@@ -23,6 +23,9 @@
'caffe2',
'--caffe2_log_level=0',
])
+ ... |
bb24f9d650cc1e8ae4f7f3ffa53a662ff1788c89 | zuora/client.py | zuora/client.py | """
Client for Zuora SOAP API
"""
# TODO:
# - Handle debug
# - Handle error
# - Session policy
import os
from suds.client import Client
from suds.sax.element import Element
from zuora.transport import HttpTransportWithKeepAlive
class ZuoraException(Exception):
"""
Base Zuora Exception.
"""
pass
... | """
Client for Zuora SOAP API
"""
# TODO:
# - Handle debug
# - Handle error
# - Session policy
import os
from suds.client import Client
from suds.sax.element import Element
from zuora.transport import HttpTransportWithKeepAlive
class ZuoraException(Exception):
"""
Base Zuora Exception.
"""
pass
... | Add instanciate method + docstring | Add instanciate method + docstring
| Python | bsd-3-clause | liberation/zuora-client | ---
+++
@@ -37,5 +37,14 @@
self.wsdl_path,
transport=HttpTransportWithKeepAlive())
+ def instanciate(self, instance_type_string):
+ """
+ Create object for client.factory.
+ """
+ return self.client.factory.create(instance_type_string)
+
def __str__(self... |
d37a05d305279d9d3bd74ebbdf500b56f83f4768 | salt/grains/extra.py | salt/grains/extra.py | # -*- coding: utf-8 -*-
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.en... | # -*- coding: utf-8 -*-
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.en... | Fix PEP8 E713 - test for membership should be "not in" | Fix PEP8 E713 - test for membership should be "not in"
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -25,7 +25,7 @@
'''
Return the grains set in the grains file
'''
- if not 'conf_file' in __opts__:
+ if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join( |
7ec5786efbdb20b9cbcdf0b4f1b583a7e07e0644 | comrade/core/tests.py | comrade/core/tests.py | from nose.tools import ok_, eq_
import unittest
import models
class SimpleModel(models.ComradeBaseModel):
def __unicode__(self):
return u'This is a unicode string'
class TestBaseModel(unittest.TestCase):
def setUp(self):
super(TestBaseModel, self).setUp()
self.obj = SimpleModel()
... | from nose.tools import ok_, eq_
import unittest
import models
def check_direct_to_template(prefix, pattern):
from django import test
from django.core.urlresolvers import reverse
client = test.Client()
response = client.get(reverse(prefix + ':' + pattern.name))
template_name = pattern.default_args[... | Add test helper method for checking direct_to_template views. | Add test helper method for checking direct_to_template views.
| Python | mit | bueda/django-comrade | ---
+++
@@ -2,6 +2,19 @@
import unittest
import models
+
+def check_direct_to_template(prefix, pattern):
+ from django import test
+ from django.core.urlresolvers import reverse
+ client = test.Client()
+ response = client.get(reverse(prefix + ':' + pattern.name))
+ template_name = pattern.default_... |
f30e441958b8354b189ee5b5ef1e7eb47ebb1b1a | nhs/gunicorn_conf.py | nhs/gunicorn_conf.py | bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
timeout = 60
| bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 6
timeout = 60
| Increase the number of Gunicorn workers | Increase the number of Gunicorn workers
| Python | agpl-3.0 | openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing | ---
+++
@@ -1,4 +1,4 @@
bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
-workers = 3
+workers = 6
timeout = 60 |
4f3cfe6e990c932d7f86dbd0cf8ae762407278b0 | nucleus/base/urls.py | nucleus/base/urls.py | from django.conf.urls import url
from nucleus.base import views
urlpatterns = (
url(r'^/?$', views.home, name='base.home'),
)
| from django.conf.urls import url
from django.views.generic import RedirectView
urlpatterns = (
url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'),
)
| Change root URL to redirect to /rna/ | Change root URL to redirect to /rna/
| Python | mpl-2.0 | mozilla/nucleus,mozilla/nucleus,mozilla/nucleus,mozilla/nucleus | ---
+++
@@ -1,8 +1,7 @@
from django.conf.urls import url
-
-from nucleus.base import views
+from django.views.generic import RedirectView
urlpatterns = (
- url(r'^/?$', views.home, name='base.home'),
+ url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'),
) |
5d8ea747bd5f34b382cc9fef91105f3ed434c0db | pylearn2/datasets/hdf5.py | pylearn2/datasets/hdf5.py | """Objects for datasets serialized in HDF5 format (.h5)."""
import h5py
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs):
"""
... | """Objects for datasets serialized in HDF5 format (.h5)."""
import warnings
try:
import h5py
except ImportError:
warnings.warn("Could not import h5py")
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
... | Fix import issue in h5py.py | Fix import issue in h5py.py
| Python | bsd-3-clause | fulmicoton/pylearn2,caidongyun/pylearn2,ddboline/pylearn2,chrish42/pylearn,CIFASIS/pylearn2,sandeepkbhat/pylearn2,aalmah/pylearn2,goodfeli/pylearn2,junbochen/pylearn2,jamessergeant/pylearn2,nouiz/pylearn2,mclaughlin6464/pylearn2,pombredanne/pylearn2,JesseLivezey/plankton,msingh172/pylearn2,w1kke/pylearn2,shiquanwang/py... | ---
+++
@@ -1,5 +1,9 @@
"""Objects for datasets serialized in HDF5 format (.h5)."""
-import h5py
+import warnings
+try:
+ import h5py
+except ImportError:
+ warnings.warn("Could not import h5py")
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
|
9b8cbfcf33ba644670a42490db7de4249e5ff080 | invocations/docs.py | invocations/docs.py | import os
from invoke.tasks import task
from invoke.runner import run
docs_dir = 'docs'
build = os.path.join(docs_dir, '_build')
@task
def clean_docs():
run("rm -rf %s" % build)
@task
def browse_docs():
run("open %s" % os.path.join(build, 'index.html'))
@task
def docs(clean=False, browse=False):
if... | import os
from invoke.tasks import task
from invoke.runner import run
docs_dir = 'docs'
build = os.path.join(docs_dir, '_build')
@task
def clean_docs():
run("rm -rf %s" % build)
@task
def browse_docs():
run("open %s" % os.path.join(build, 'index.html'))
@task
def docs(clean=False, browse=False):
if... | Leverage __call__ on task downstream | Leverage __call__ on task downstream
| Python | bsd-2-clause | mrjmad/invocations,alex/invocations,pyinvoke/invocations,singingwolfboy/invocations | ---
+++
@@ -21,7 +21,7 @@
@task
def docs(clean=False, browse=False):
if clean:
- clean_docs.body()
+ clean_docs()
run("sphinx-build %s %s" % (docs_dir, build), pty=True)
if browse:
- browse_docs.body()
+ browse_docs() |
153360072096d4a3cef783d371fbfabcd75bcf98 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '432720d4613e3aac939f127fe55b9d44fea349e5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'afb4570ceee2ad10f3caf5a81335a2ee11ec68a5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | Upgrade libchromiumcontent to loose iframe sandbox. | Upgrade libchromiumcontent to loose iframe sandbox.
| Python | mit | rreimann/electron,dongjoon-hyun/electron,brave/muon,trankmichael/electron,kokdemo/electron,robinvandernoord/electron,tonyganch/electron,tylergibson/electron,natgolov/electron,sircharleswatson/electron,matiasinsaurralde/electron,vaginessa/electron,fritx/electron,benweissmann/electron,xiruibing/electron,cos2004/electron,... | ---
+++
@@ -5,7 +5,7 @@
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = '432720d4613e3aac939f127fe55b9d44fea349e5'
+LIBCHROMIUMCONTENT_COMMIT = 'afb4570ceee2ad10f3caf5a81335a2ee11ec68a5'
ARCH = {
'cygwin': '32bit', |
5c0ace537a073f3d851ad4e490a7f2b5a0062c62 | tfr/features.py | tfr/features.py | import numpy as np
def mean_power(x_blocks):
return np.sqrt(np.mean(x_blocks**2, axis=-1))
def power(x_blocks):
return np.sqrt(np.sum(x_blocks**2, axis=-1))
def mean_energy(x_blocks):
return np.mean(x_blocks**2, axis=-1)
def energy(x_blocks):
return np.sum(x_blocks**2, axis=-1)
if __name__ == '__ma... | """
Example usage:
import matplotlib.pyplot as plt
from files import load_wav
from analysis import split_to_blocks
def analyze_mean_energy(file, block_size=1024):
x, fs = load_wav(file)
blocks, t = split_to_blocks(x, block_size)
y = mean_energy(blocks)
plt.semilogy(t, y)
plt.ylim(0, 1)
"""
import... | Put the code into a comment as an example usage. | Put the code into a comment as an example usage.
| Python | mit | bzamecnik/tfr,bzamecnik/tfr | ---
+++
@@ -1,4 +1,20 @@
+"""
+Example usage:
+
+import matplotlib.pyplot as plt
+from files import load_wav
+from analysis import split_to_blocks
+
+def analyze_mean_energy(file, block_size=1024):
+ x, fs = load_wav(file)
+ blocks, t = split_to_blocks(x, block_size)
+ y = mean_energy(blocks)
+ plt.semilo... |
744c91ca30379d6cca7f7f9fc2b014e0f29e55e4 | keepaneyeon/http.py | keepaneyeon/http.py | import requests
class HttpDownloader():
def __init__(self, opts={}):
self.base = opts
def build_request_options(self, opts):
options = {'method': 'get'}
options.update(self.base)
options.update(opts)
options.update({'stream': True})
return options
def downl... | import requests
class HttpDownloader():
def __init__(self, **opts):
self.base = opts
def build_request_options(self, opts):
options = {'method': 'get'}
options.update(self.base)
options.update(opts)
options.update({'stream': True})
return options
def downlo... | Make HTTPDownloader work with YAML config | Make HTTPDownloader work with YAML config
| Python | mit | mmcloughlin/keepaneyeon | ---
+++
@@ -1,7 +1,7 @@
import requests
class HttpDownloader():
- def __init__(self, opts={}):
+ def __init__(self, **opts):
self.base = opts
def build_request_options(self, opts): |
e3c53133b71d7426695fbf24cac5b8e82311c037 | seeker/middleware.py | seeker/middleware.py | from .utils import index, delete
from django.db import models
import logging
logger = logging.getLogger(__name__)
class ModelIndexingMiddleware (object):
"""
Middleware class that automatically indexes any new or deleted model objects.
"""
def __init__(self):
models.signals.post_save.connect(... | from .utils import index, delete
from django.db import models
import logging
logger = logging.getLogger(__name__)
class ModelIndexingMiddleware (object):
"""
Middleware class that automatically indexes any new or deleted model objects.
"""
def __init__(self):
models.signals.post_save.connect(... | Make signal dispatch_uid values more specific | Make signal dispatch_uid values more specific | Python | bsd-2-clause | imsweb/django-seeker,imsweb/django-seeker | ---
+++
@@ -10,8 +10,8 @@
"""
def __init__(self):
- models.signals.post_save.connect(self.handle_save, dispatch_uid='handle_save')
- models.signals.post_delete.connect(self.handle_delete, dispatch_uid='handle_delete')
+ models.signals.post_save.connect(self.handle_save, dispatch_uid='... |
56d92af9ba0a9b81dd0e802d05717ec6e4f511d3 | seven23/api/views.py | seven23/api/views.py | """
Root views of api
"""
import json
import os
import markdown2
from django.http import HttpResponse
from django.db import models
from rest_framework.decorators import api_view
from seven23 import settings
from seven23.models.terms.models import TermsAndConditions
@api_view(["GET"])
def api_init(request):
... | """
Root views of api
"""
import json
import os
import markdown2
from django.http import HttpResponse
from django.db import models
from rest_framework.decorators import api_view
from seven23 import settings
from seven23.models.terms.models import TermsAndConditions
@api_view(["GET"])
def api_init(request):
... | Fix bug on API with date in Terms and Conditions not serializable | Fix bug on API with date in Terms and Conditions not serializable
| Python | mit | sebastienbarbier/723e_server,sebastienbarbier/723e,sebastienbarbier/723e_server,sebastienbarbier/723e | ---
+++
@@ -27,7 +27,7 @@
try:
terms = TermsAndConditions.objects.latest('date')
- result['terms_and_conditions_date'] = terms.date
+ result['terms_and_conditions_date'] = terms.date.strftime("%Y-%m-%d")
result['terms_and_conditions'] = markdown2.markdown(terms.markdown)
ex... |
fecf53c0c4414f50a9c3937b05d27de8c1387c45 | src/hireme/tasks/task2.py | src/hireme/tasks/task2.py | # -*- coding: utf-8 -*-
from . import render_task
@render_task
def solve():
return dict(
solution='42',
title='task2'
) | # -*- coding: utf-8 -*-
import re
from flask import request
from werkzeug import exceptions
import numpy as np
from . import render_task
@render_task
def solve():
input_data = request.form.get('input')
method = request.method
title = 'task2'
if method == 'GET':
return dict(
titl... | Implement rudimentary task 2 solution | Implement rudimentary task 2 solution
| Python | bsd-2-clause | cutoffthetop/hireme | ---
+++
@@ -1,10 +1,76 @@
# -*- coding: utf-8 -*-
+
+import re
+
+from flask import request
+from werkzeug import exceptions
+import numpy as np
from . import render_task
+
@render_task
def solve():
+ input_data = request.form.get('input')
+ method = request.method
+ title = 'task2'
+ if method ==... |
84041a2bb517841d725781bdd72b1daf4f8e603d | spacy/ja/__init__.py | spacy/ja/__init__.py | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class Japanese(Language):
lang = 'ja'
def make_doc(self, text):
try:
from janome.t... | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language, BaseDefaults
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class JapaneseTokenizer(object):
def __init__(self, cls, nlp... | Make create_tokenizer work with Japanese | Make create_tokenizer work with Japanese
| Python | mit | spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,raphael0202/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,raphael0202/spaCy,raphael0202/spaCy,raphael0202/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,raphael0202/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaC... | ---
+++
@@ -3,21 +3,39 @@
from os import path
-from ..language import Language
+from ..language import Language, BaseDefaults
+from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
-
-class Japanese(Language):
- lang = 'ja'
-
- def make_doc(... |
cec423c4a1e633193ef3e639a1cb202bddc27e18 | api/base/content_negotiation.py | api/base/content_negotiation.py |
from rest_framework.negotiation import DefaultContentNegotiation
class JSONAPIContentNegotiation(DefaultContentNegotiation):
def select_renderer(self, request, renderers, format_suffix=None):
"""
If 'application/json' in acceptable media types, use the first renderer in
DEFAULT_RENDERER_... |
from rest_framework.negotiation import DefaultContentNegotiation
class JSONAPIContentNegotiation(DefaultContentNegotiation):
def select_renderer(self, request, renderers, format_suffix=None):
"""
Returns appropriate tuple (renderer, media type).
If 'application/json' in acceptable media... | Add one-line summary to docstring. | Add one-line summary to docstring.
| Python | apache-2.0 | hmoco/osf.io,doublebits/osf.io,leb2dg/osf.io,doublebits/osf.io,erinspace/osf.io,billyhunt/osf.io,jnayak1/osf.io,felliott/osf.io,sbt9uc/osf.io,MerlinZhang/osf.io,caneruguz/osf.io,ZobairAlijan/osf.io,RomanZWang/osf.io,pattisdr/osf.io,RomanZWang/osf.io,zachjanicki/osf.io,kwierman/osf.io,ticklemepierce/osf.io,icereval/osf.... | ---
+++
@@ -6,10 +6,11 @@
def select_renderer(self, request, renderers, format_suffix=None):
"""
+ Returns appropriate tuple (renderer, media type).
+
If 'application/json' in acceptable media types, use the first renderer in
DEFAULT_RENDERER_CLASSES which should be 'api.base.... |
2604d759bfd9a18e5e594cfa5b50e83c73fbc2d8 | devito/interfaces.py | devito/interfaces.py | import numpy as np
from sympy import IndexedBase
class MatrixData(IndexedBase):
def __init__(self, name, shape, dtype):
self.name = name
self.shape = shape
self.dtype = dtype
self.pointer = None
self.initializer = None
def set_initializer(self, lambda_initializer):
... | import numpy as np
from sympy import IndexedBase
class DenseData(IndexedBase):
def __init__(self, name, shape, dtype):
self.name = name
self.shape = shape
self.dtype = dtype
self.pointer = None
self.initializer = None
def set_initializer(self, lambda_initializer):
... | Change name from MatrixData to DenseData | Change name from MatrixData to DenseData
| Python | mit | opesci/devito,opesci/devito | ---
+++
@@ -2,7 +2,7 @@
from sympy import IndexedBase
-class MatrixData(IndexedBase):
+class DenseData(IndexedBase):
def __init__(self, name, shape, dtype):
self.name = name
self.shape = shape
@@ -28,7 +28,7 @@
return self.pointer
-class TimeData(MatrixData):
+class TimeData(D... |
840d80c543c4688ebd1bda41b8689cf404bf755c | edit_spectide.py | edit_spectide.py | """
Edits the spectide amplitude values to some factor of their original value.
WARNING: When using this on FVCOM input files, it will change the format of
the variables. changeNC presumes each variable has a value and unit associated
with it, whereas some of the variables in the FVCOM inputs are in fact not
that so... | """
Edits the spectide amplitude values to some factor of their original value.
WARNING: When using this on FVCOM input files, it will change the format of
the variables. changeNC presumes each variable has a value and unit associated
with it, whereas some of the variables in the FVCOM inputs are in fact not
that so... | Update help to indicate where the necessary script lives | Update help to indicate where the necessary script lives
| Python | mit | pwcazenave/PyFVCOM | ---
+++
@@ -7,6 +7,8 @@
that sort of data, and so have different structures. Probably best to use the
combination of ncdump and ncgen to edit the values as text and generate a new
NetCDF file from that edited text.
+
+Lee's changeNC file should live in the SVN repository.
"""
|
127b90c88d1362e7b10e7bf36dff56b96a5c4f0b | simpegEM/FDEM/__init__.py | simpegEM/FDEM/__init__.py | from SurveyFDEM import *
from FDEM import ProblemFDEM_e, ProblemFDEM_b, ProblemFDEM_j, ProblemFDEM_h
| from SurveyFDEM import *
from FDEM import BaseFDEMProblem, ProblemFDEM_e, ProblemFDEM_b, ProblemFDEM_j, ProblemFDEM_h, omega
| Add more files to export on the init. | Add more files to export on the init.
| Python | mit | simpeg/discretize,lheagy/simpegem,simpeg/discretize,simpeg/discretize,simpeg/simpeg,simpeg/simpegem | ---
+++
@@ -1,2 +1,2 @@
from SurveyFDEM import *
-from FDEM import ProblemFDEM_e, ProblemFDEM_b, ProblemFDEM_j, ProblemFDEM_h
+from FDEM import BaseFDEMProblem, ProblemFDEM_e, ProblemFDEM_b, ProblemFDEM_j, ProblemFDEM_h, omega |
8ef4ca2166167f6370dd8c2f724e752210adf067 | sirius/SI_V07/__init__.py | sirius/SI_V07/__init__.py | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import family_data as _family_data
from . import record_names
create_accelerator = _accelerator.create_accelerator
get_family_data = _family_data.get_family_data
# -- default accelerator values for SI_V07 --
energy = _la... | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = _accelerator.create_accelerator
# -- default accelerator values for SI_V07 --
energy = _lattice._energy
harmonic_number = _lattice._harmonic_number
default_cavity_on = _ac... | Fix bug when family_data.py was deleted | Fix bug when family_data.py was deleted
| Python | mit | lnls-fac/sirius | ---
+++
@@ -1,10 +1,8 @@
from . import lattice as _lattice
from . import accelerator as _accelerator
-from . import family_data as _family_data
from . import record_names
create_accelerator = _accelerator.create_accelerator
-get_family_data = _family_data.get_family_data
# -- default accelerator values for S... |
55072134b8053ac126213e580fcc59977cfb7a02 | scikits/image/setup.py | scikits/image/setup.py | import os
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('image', parent_package, top_path)
config.add_subpackage('opencv')
config.add_subpackage('graph')
config.add_subpackage('io')
config.add_subpackage('morpho... | import os
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('image', parent_package, top_path)
config.add_subpackage('opencv')
config.add_subpackage('graph')
config.add_subpackage('io')
config.add_subpackage('morpho... | Add 'draw' and 'feature' sub-modules. | BUG: Add 'draw' and 'feature' sub-modules.
| Python | bsd-3-clause | paalge/scikit-image,michaelaye/scikit-image,bennlich/scikit-image,chintak/scikit-image,paalge/scikit-image,ClinicalGraphics/scikit-image,warmspringwinds/scikit-image,michaelaye/scikit-image,chriscrosscutler/scikit-image,ClinicalGraphics/scikit-image,WarrenWeckesser/scikits-image,emmanuelle/scikits.image,Midafi/scikit-i... | ---
+++
@@ -14,6 +14,8 @@
config.add_subpackage('data')
config.add_subpackage('util')
config.add_subpackage('color')
+ config.add_subpackage('draw')
+ config.add_subpackage('feature')
def add_test_directories(arg, dirname, fnames):
if dirname.split(os.path.sep)[-1] == 'tests': |
7eadc9e514b1311409356f4c6c40ef8cdb2de809 | manager/__init__.py | manager/__init__.py | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_o... | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_o... | Add new stuff to the css bundle | Add new stuff to the css bundle
| Python | mit | hreeder/ignition,hreeder/ignition,hreeder/ignition | ---
+++
@@ -47,6 +47,9 @@
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
+ 'fontawesome/css/font-awesome.min.css',
+ 'admin-lte/dist/css/AdminLTE.css',
+ 'admin-lte/dist/css/skins/skin-black.min.css',
output='css_all.css'
)
) |
29ac3073b747d5bafaec240df25844d6d27c049a | marshmallow/base.py | marshmallow/base.py | # -*- coding: utf-8 -*-
"""Abstract base classes.
These are necessary to avoid circular imports between core.py and fields.py.
"""
import copy
class FieldABC(object):
"""Abstract base class from which all Field classes inherit.
"""
parent = None
name = None
def serialize(self, attr, obj, accesso... | # -*- coding: utf-8 -*-
"""Abstract base classes.
These are necessary to avoid circular imports between core.py and fields.py.
"""
import copy
class FieldABC(object):
"""Abstract base class from which all Field classes inherit.
"""
parent = None
name = None
def serialize(self, attr, obj, accesso... | Update signatures of FieldABC methods | Update signatures of FieldABC methods
| Python | mit | marshmallow-code/marshmallow,mwstobo/marshmallow | ---
+++
@@ -18,10 +18,10 @@
def deserialize(self, value):
raise NotImplementedError
- def _serialize(self, value, attr, obj):
+ def _serialize(self, value, attr, obj, **kwargs):
raise NotImplementedError
- def _deserialize(self, value, attr, data):
+ def _deserialize(self, value... |
9da01f39c8d9b73025d85be72b71399b6930b6fb | src/encoded/cache.py | src/encoded/cache.py | from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold ... | from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold ... | Use LRUCache correctly (minimal improvement) | Use LRUCache correctly (minimal improvement)
| Python | mit | ENCODE-DCC/encoded,kidaa/encoded,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,4dn-dcic/fourfront,ClinGen/clincoded,ClinGen/clincoded,4dn-dcic/fourfront,ENCODE-DCC/snovault,4dn-dcic/fourfront,ENCODE-DCC/encoded,T2DREAM/t2dream... | ---
+++
@@ -24,11 +24,11 @@
def get(self, key, default=None):
cache = self.cache
if cache is None:
- return
- cached = cache.get(key)
- if cached is not None:
- return cached[1]
- return default
+ return default
+ try:
+ re... |
a6b39dde09777ff162fbf83976934cbf2ec14056 | app.py | app.py | from flask import Flask
from flask import render_template
app = Flask(__name__)
app.config['DEBUG'] = True
repo_path = '../ames-py'
@app.route("/")
def main():
return render_template("index.html")
@app.route("/data")
def data():
import json
import git
import networkx as nx
G = nx.DiGraph()
... | from flask import Flask
from flask import render_template
app = Flask(__name__)
app.config['DEBUG'] = True
repo_path = '../ames-py'
@app.route("/")
def main():
return render_template("index.html")
@app.route("/data")
def data():
import json
import git
import networkx as nx
G = nx.DiGraph()
... | Add commit message for commits and for parents | Add commit message for commits and for parents
| Python | bsd-3-clause | kdheepak89/c3.py,kdheepak89/c3.py | ---
+++
@@ -30,11 +30,12 @@
commits = loginfo.split("\n\ncommit ")
commits[0] = commits[0].replace("commit ", '')
- for item in commits[:15]:
+ for item in commits[:20]:
node = "{}".format(get_hash(item))
- G.add_node(node)
commit = repo.commit(get_hash(item))
+ G.add... |
169ca5581c6c35d07dd772baf3119f45ba1c1e2e | app.py | app.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import secure_filename
import os
import logging
import stripe
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join('static/uploads')
MODELS_FOLDER = os.path.join('models')
ALLOWED_EXTENSIONS = set(['stl']... | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import secure_filename
import os
import logging
import stripe
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join('static/uploads')
MODELS_FOLDER = os.path.join('models')
ALLOWED_EXTENSIONS = set(['stl']... | Make all log messages show by default | Make all log messages show by default
| Python | mit | karlalopez/Authentise-Store,addendumauto/Authentise-Store,addendumauto/Authentise-Store,addendumauto/Authentise-Store | ---
+++
@@ -39,4 +39,5 @@
from views import *
del session
logging.basicConfig()
+ logging.getLogger().setLevel(logging.DEBUG)
app.run(debug=True) |
d560a809c4d0fd78e1ce0454ea5406e81f356906 | server_app/__main__.py | server_app/__main__.py | import sys
import os
import logging
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
sys.stderr.close()
sys.stdout.close()
sys.stdin.close()
from app import ... | import sys
import os
import logging
import time
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat-"+time.strftime("%d-%m-%Y.log"), level=logging.DEBUG)
sys.stderr.close()
sys.stdout.close... | Make logger sort by date | Make logger sort by date
| Python | bsd-3-clause | jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat | ---
+++
@@ -1,10 +1,11 @@
import sys
import os
import logging
+import time
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
-logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
+logging.basicConfig(filen... |
0438825672a407eb30bff49e03dac89a0534f28a | minimax.py | minimax.py | class Heuristic:
def __init__(self, color):
self.color = color
def heuristic(self, board, color):
raise NotImplementedError('Dont override this class')
def eval(self, vector):
pass
class Minimax:
def __init__(self, me, challenger):
self.me = me
self.challenger = challenger
def heurist... | class Heuristic:
def __init__(self, color):
self.color = color
def heuristic(self, board, color):
raise NotImplementedError('Dont override this class')
def eval(self, vector):
raise NotImplementedError('Dont override this class')
class Minimax:
def __init__(self, me, challenger):
self.m... | Create in MinMax the calculate_min_max | Create in MinMax the calculate_min_max
| Python | apache-2.0 | frila/agente-minimax | ---
+++
@@ -7,7 +7,8 @@
raise NotImplementedError('Dont override this class')
def eval(self, vector):
- pass
+ raise NotImplementedError('Dont override this class')
+
class Minimax:
def __init__(self, me, challenger):
@@ -19,3 +20,9 @@
return self.me.heuristic(board, color)
else
... |
3b3a8dc6aa0b38cfbb68105eb5ef31e8e73ff3a4 | gcm_flask/application/models.py | gcm_flask/application/models.py | """
models.py
App Engine datastore models
"""
from google.appengine.ext import db
class ExampleModel(db.Model):
"""Example Model"""
example_name = db.StringProperty(required=True)
example_description = db.TextProperty(required=True)
added_by = db.UserProperty()
timestamp = db.DateTimeProperty(... | """
models.py
App Engine datastore models
"""
from google.appengine.ext import db
class ExampleModel(db.Model):
"""Example Model"""
example_name = db.StringProperty(required=True)
example_description = db.TextProperty(required=True)
added_by = db.UserProperty()
timestamp = db.DateTimeProperty(... | Update user who sent the message | Update user who sent the message
| Python | apache-2.0 | BarcampBangalore/Barcamp-Bangalore-Android-App,BarcampBangalore/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App,BarcampBangalore/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App,BarcampBangalore/Barcamp-Bangalore-Android-App,rajeefmk/Barcam... | ---
+++
@@ -24,5 +24,5 @@
"""Model for storing messages sent"""
message = db.StringProperty(required=True)
messagetype = db.StringProperty(required=True)
- added_by = db.UserProperty()
+ added_by = db.UserProperty(auto_current_user=True)
sent_at = db.DateTimeProperty(auto_now_add=True) |
c04b8932ec65480ba90dd4578d5f6bb8c3baa690 | demosys/project/default.py | demosys/project/default.py | from demosys.project.base import BaseProject
from demosys.effects.registry import effects, parse_package_string
class Project(BaseProject):
"""
The project what will be assigned when no project are specified.
This is mainly used when the ``runeffect`` command is used
"""
def __init__(self... | from demosys.project.base import BaseProject
from demosys.effects.registry import effects, parse_package_string
class Project(BaseProject):
"""
The project what will be assigned when no project are specified.
This is mainly used when the ``runeffect`` command is used
"""
def __init__(self... | Improve errors when effect packages or effects are not found | Improve errors when effect packages or effects are not found
| Python | isc | Contraz/demosys-py | ---
+++
@@ -21,9 +21,17 @@
pass
def create_effect_instances(self):
- cls = effects.find_effect_class(self.path)
+ if self.effect_class_name:
+ cls = effects.find_effect_class(self.path)
+ if not cls.runnable:
+ raise ValueError("Effect doesn't have th... |
891e8afe5deff5fe7d620abfe8189689d47ec4f8 | djangocms_inherit/forms.py | djangocms_inherit/forms.py | from django import forms
from django.forms.models import ModelForm
from django.forms.utils import ErrorList
from django.utils.translation import ugettext_lazy as _
from cms.models import Page
from .models import InheritPagePlaceholder
class InheritForm(ModelForm):
from_page = forms.ModelChoiceField(
lab... | from django import forms
from django.forms.models import ModelForm
try:
from django.forms.utils import ErrorList
except ImportError:
# Django<1.7 (deprecated in Django 1.8, removed in 1.9)
from django.forms.util import ErrorList
from django.utils.translation import ugettext_lazy as _
from cms.models import... | Make import backward compatible (Django<1.7) | Make import backward compatible (Django<1.7)
| Python | bsd-3-clause | bittner/djangocms-inherit,bittner/djangocms-inherit,divio/djangocms-inherit,divio/djangocms-inherit,divio/djangocms-inherit | ---
+++
@@ -1,6 +1,10 @@
from django import forms
from django.forms.models import ModelForm
-from django.forms.utils import ErrorList
+try:
+ from django.forms.utils import ErrorList
+except ImportError:
+ # Django<1.7 (deprecated in Django 1.8, removed in 1.9)
+ from django.forms.util import ErrorList
fr... |
db59332e3d522c68c3eeef77fe4393fe137e5059 | inspectors/registration/util.py | inspectors/registration/util.py | import requests
API_URL = 'https://opendata.miamidade.gov/resource/vvjq-pfmc.json'
def is_valid_permit(id):
# checks if the ID is a valid Miami-Dade Permit or Process Number
API = API_URL + '?$where=permit_number=%27' + id + '%27%20or%20process_number=%27' + id + '%27'
response = requests.get(API)
js... | import requests
API_URL = 'https://opendata.miamidade.gov/resource/vvjq-pfmc.json'
def is_valid_permit(id):
# checks if the ID is a valid Miami-Dade Permit or Process Number
API = API_URL + '?$where=permit_number=%27' + id + '%27%20or%20process_number=%27' + id + '%27'
response = requests.get(API)
js... | Fix logic bug for API result | Fix logic bug for API result
| Python | bsd-3-clause | codeforamerica/mdc-inspectors,codeforamerica/mdc-inspectors,codeforamerica/mdc-inspectors | ---
+++
@@ -9,4 +9,4 @@
response = requests.get(API)
json_result = response.json()
- return json_result is not None
+ return json_result |
09fa23adfb76f052473ee38de94ce4bdfdcc48e1 | src/nodeconductor_assembly_waldur/packages/perms.py | src/nodeconductor_assembly_waldur/packages/perms.py | from nodeconductor.core.permissions import StaffPermissionLogic
PERMISSION_LOGICS = (
('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)),
('packages.PackageComponent', StaffPermissionLogic(any_permission=True)),
('packages.OpenStackPackage', StaffPermissionLogic(any_permission=True)),... | from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic
from nodeconductor.structure import models as structure_models
PERMISSION_LOGICS = (
('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)),
('packages.PackageComponent', StaffPermissionLogic(... | Allow customer owner to create packages | Allow customer owner to create packages
- wal-26
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur | ---
+++
@@ -1,8 +1,16 @@
-from nodeconductor.core.permissions import StaffPermissionLogic
-
+from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic
+from nodeconductor.structure import models as structure_models
PERMISSION_LOGICS = (
('packages.PackageTemplate', ... |
75d1241c5d62def89a7377e506afdacfa83cbdda | js2xml/parser.py | js2xml/parser.py | import ply.yacc
from slimit.parser import Parser
from js2xml.lexer import CustomLexer as Lexer
from js2xml.log import logger
lextab, yacctab = 'lextab', 'yacctab'
class CustomParser(Parser):
def __init__(self, lex_optimize=False, lextab=lextab,
yacc_optimize=True, yacctab=yacctab, yacc_debug=Fa... | import ply.yacc
from slimit.parser import Parser
from js2xml.lexer import CustomLexer as Lexer
from js2xml.log import logger
lextab, yacctab = 'lextab', 'yacctab'
class CustomParser(Parser):
def __init__(self, lex_optimize=True, lextab=lextab,
yacc_optimize=True, yacctab=yacctab, yacc_debug=Fal... | Write tab but don't warn | Write tab but don't warn
| Python | mit | redapple/js2xml,redapple/js2xml,redapple/js2xml,redapple/js2xml | ---
+++
@@ -8,7 +8,7 @@
class CustomParser(Parser):
- def __init__(self, lex_optimize=False, lextab=lextab,
+ def __init__(self, lex_optimize=True, lextab=lextab,
yacc_optimize=True, yacctab=yacctab, yacc_debug=False,
logger=logger):
self.lex_optimize = lex_opti... |
cc2b579377abde262d76e2484a6488e254b315fc | judge/caching.py | judge/caching.py | from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
def update_submission(id):
key = 'version:submission-%d' % id
cache.add(key, 0, None)
cache.incr(key)
def update_stats():
cache.delete('sub_stats_table')
cache.delete('sub_stats_data')
def point_... | from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
def update_submission(id):
key = 'version:submission-%d' % id
cache.add(key, 0, None)
cache.incr(key)
def update_stats():
cache.delete_many(('sub_stats_table', 'sub_stats_data'))
def point_update(pro... | Delete many to reduce round trips to the cache. | Delete many to reduce round trips to the cache.
| Python | agpl-3.0 | Minkov/site,Minkov/site,DMOJ/site,Minkov/site,DMOJ/site,DMOJ/site,Phoenix1369/site,Phoenix1369/site,Minkov/site,monouno/site,Phoenix1369/site,monouno/site,monouno/site,monouno/site,monouno/site,DMOJ/site,Phoenix1369/site | ---
+++
@@ -9,8 +9,7 @@
def update_stats():
- cache.delete('sub_stats_table')
- cache.delete('sub_stats_data')
+ cache.delete_many(('sub_stats_table', 'sub_stats_data'))
def point_update(profile):
@@ -18,10 +17,11 @@
def finished_submission(sub):
- cache.delete('user_complete:%d' % sub.user... |
05adb44cdec74256fa44ce3a3df61c6525ce7fac | dryscrape/xvfb.py | dryscrape/xvfb.py | import atexit
import os
_xvfb = None
def start_xvfb():
from xvfbwrapper import Xvfb
global _xvfb
if "DISPLAY" in os.environ:
del os.environ["DISPLAY"]
_xvfb = Xvfb()
_xvfb.start()
atexit.register(_xvfb.stop)
def stop_xvfb():
global _xvfb
_xvfb.stop()
| import atexit
import os
_xvfb = None
def start_xvfb():
from xvfbwrapper import Xvfb
global _xvfb
_xvfb = Xvfb()
_xvfb.start()
atexit.register(_xvfb.stop)
def stop_xvfb():
global _xvfb
_xvfb.stop()
| Remove removal of DISPLAY environment variable | Remove removal of DISPLAY environment variable
The issue has to do with the two lines:
` if "DISPLAY" in os.environ:
del os.environ["DISPLAY"]`
This seems to remove the DISPLAY environment variable unnecessarily, as on line 50 of xvfbwrapper.py, self.orig_display is set to the value of DISPLAY. self.orig_di... | Python | mit | niklasb/dryscrape | ---
+++
@@ -3,15 +3,15 @@
_xvfb = None
+
def start_xvfb():
- from xvfbwrapper import Xvfb
- global _xvfb
- if "DISPLAY" in os.environ:
- del os.environ["DISPLAY"]
- _xvfb = Xvfb()
- _xvfb.start()
- atexit.register(_xvfb.stop)
+ from xvfbwrapper import Xvfb
+ global _xvfb
+ _xvfb = Xvfb()
+ ... |
382c46366c4ae29456aae35420990ce25b61ce76 | studygroups/tasks.py | studygroups/tasks.py | from __future__ import absolute_import
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_reminder
from... | from __future__ import absolute_import
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_reminder
from... | Add check for failed reminders so that it doesn't case an Exception | Add check for failed reminders so that it doesn't case an Exception
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | ---
+++
@@ -20,7 +20,7 @@
translation.activate(settings.LANGUAGE_CODE)
# TODO - should this be set here or closer to where the language matters?
for reminder in Reminder.objects.filter(sent_at__isnull=True):
- if reminder.study_group_meeting.meeting_time - now < datetime.timedelta(days=2):
+ ... |
4613daea5d9d603b5f092005627fabd805de8a45 | example/app/utils.py | example/app/utils.py | from django.contrib.auth import get_user_model
def disable_admin_login():
"""
Disable admin login, but allow editing.
amended from: https://stackoverflow.com/a/40008282/517560
"""
User = get_user_model()
user, created = User.objects.update_or_create(
id=1,
defaults=dict(
... | from django.contrib.auth import get_user_model
from django.db.utils import ProgrammingError
def disable_admin_login():
"""
Disable admin login, but allow editing.
amended from: https://stackoverflow.com/a/40008282/517560
"""
User = get_user_model()
try:
user, created = User.objects.u... | Make initial ./manage.py migrate work in example | Make initial ./manage.py migrate work in example
| Python | bsd-3-clause | zostera/django-modeltrans,zostera/django-modeltrans | ---
+++
@@ -1,4 +1,5 @@
from django.contrib.auth import get_user_model
+from django.db.utils import ProgrammingError
def disable_admin_login():
@@ -9,16 +10,20 @@
"""
User = get_user_model()
- user, created = User.objects.update_or_create(
- id=1,
- defaults=dict(
- first... |
187447322d74fc3070c9a75415a55a56ba840ef9 | extruct/jsonld.py | extruct/jsonld.py | # -*- coding: utf-8 -*-
"""
JSON-LD extractor
"""
import json
import re
import lxml.etree
import lxml.html
HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)')
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]')
def extract(self, ... | # -*- coding: utf-8 -*-
"""
JSON-LD extractor
"""
import json
import re
import lxml.etree
import lxml.html
HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)')
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]')
def extract(self, ... | Make comment removal a fallback when failed. | Mod: Make comment removal a fallback when failed.
| Python | bsd-3-clause | scrapinghub/extruct | ---
+++
@@ -29,9 +29,12 @@
def _extract_items(self, node):
script = node.xpath('string()')
- # now do remove possible leading HTML/JavaScript comment first, allow control characters to be loaded
- # TODO: `strict=False` can be configurable if needed
- data = json.loads(HTML_OR_JS_... |
118aa612ef088dba90328f1775d8603ee12e5e5b | main.py | main.py | import logging
import numpy as np
import settings
from models import Robby
def evolve():
population = np.array([Robby() for i in range(0, settings.POPULATION)])
for gen in range(0, settings.GENERATIONS):
for individual in population:
individual.live()
new_population = list()
... | import logging
import numpy as np
import settings
from models import Robby
def evolve():
population = np.array([Robby() for i in range(0, settings.POPULATION)])
for gen in range(0, settings.GENERATIONS):
for individual in population:
individual.live()
new_population = list()
... | Set log level to info, fixed bug with map object | Set log level to info, fixed bug with map object
| Python | mit | ray-dino/robby-genetic-algorithm | ---
+++
@@ -29,10 +29,14 @@
pop_fitness = [r.get_fitness() for r in population]
min_fitness = min(pop_fitness)
max_fitness = max(pop_fitness)
- normalized = map(lambda x: normalize(x, min_fitness, max_fitness),
- pop_fitness)
+ normalized = list(
+ map(
+ lam... |
351bfe236f183c069314f5df7d3c4b8f9d8699b4 | final/problem6.py | final/problem6.py | # Problem 6-1
# 10.0 points possible (graded)
class Person(object):
def __init__(self, name):
self.name = name
def say(self, stuff):
return self.name + ' says: ' + stuff
def __str__(self):
return self.name
class Lecturer(Person):
def lecture(self, stuff):
return 'I bel... | # Problem 6-1
# 10.0 points possible (graded)
class Person(object):
def __init__(self, name):
self.name = name
def say(self, stuff):
return self.name + ' says: ' + stuff
def __str__(self):
return self.name
class Lecturer(Person):
def lecture(self, stuff):
return 'I bel... | Modify lecture method in ArrogantProfessor class using inheritance | Modify lecture method in ArrogantProfessor class using inheritance
| Python | mit | Kunal57/MIT_6.00.1x | ---
+++
@@ -20,7 +20,7 @@
class ArrogantProfessor(Professor):
def lecture(self, stuff):
- return 'It is obvious that ' + Person.say(self, stuff)
+ return 'It is obvious that ' + Lecturer.lecture(self, stuff)
def say(self, stuff):
return self.name + ' says: ' + self.lecture(stuff)
|
3fdb40934319d667ae9e8c550a0404cdd6a8cb64 | grum/api/models/message.py | grum/api/models/message.py | from grum import db
class Message(db.Model):
id = db.Column(db.String(128), primary_key=True)
recipient = db.Column(db.String(128))
recipient_nice = db.Column(db.String(128))
sender = db.Column(db.String(128))
sender_nice = db.Column(db.String(128))
sent_at = db.Column(db.Timestamp)
htm... | from grum import db
class Message(db.Model):
id = db.Column(db.String(128), primary_key=True)
recipient = db.Column(db.String(128))
recipient_nice = db.Column(db.String(128))
sender = db.Column(db.String(128))
sender_nice = db.Column(db.String(128))
sent_at = db.Column(db.Integer)
html ... | Change from timestamp to Integer | Change from timestamp to Integer
| Python | mit | Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web | ---
+++
@@ -9,7 +9,7 @@
sender = db.Column(db.String(128))
sender_nice = db.Column(db.String(128))
- sent_at = db.Column(db.Timestamp)
+ sent_at = db.Column(db.Integer)
html = db.Column(db.Text)
html_stripped = db.Column(db.Text) |
ff8aa2725001dbd1281357ccd5e0877257b5975d | hackernews_scrapy/items.py | hackernews_scrapy/items.py | # -*- coding: utf-8 -*-
import scrapy
class HackernewsScrapyItem(scrapy.Item):
title = scrapy.Field()
| # -*- coding: utf-8 -*-
import scrapy
class HackernewsScrapyItem(scrapy.Item):
title = scrapy.Field()
crawled_at = scrapy.Field()
| Add crawled_at field to HackernewsScrapyItem | Add crawled_at field to HackernewsScrapyItem
| Python | mit | mdsrosa/hackernews_scrapy | ---
+++
@@ -3,4 +3,5 @@
class HackernewsScrapyItem(scrapy.Item):
- title = scrapy.Field()
+ title = scrapy.Field()
+ crawled_at = scrapy.Field() |
4c31f637d2b7f75c35debc51498913139b5634c0 | pushhub/__init__.py | pushhub/__init__.py | from pyramid.config import Configurator
from pyramid_zodbconn import get_connection
from .models import appmaker
from .views import publish, subscribe
def root_factory(request):
conn = get_connection(request)
return appmaker(conn.root())
def main(global_config, **settings):
""" This function returns a ... | from pyramid.config import Configurator
from pyramid_zodbconn import get_connection
from .models import appmaker
from .views import publish, subscribe
def root_factory(request):
conn = get_connection(request)
return appmaker(conn.root())
def main(global_config, **settings):
""" This function returns a ... | Fix typo, make routes a little more legible. | Fix typo, make routes a little more legible.
| Python | bsd-3-clause | ucla/PushHubCore | ---
+++
@@ -19,6 +19,8 @@
config.add_route('publish', '/publish')
config.add_view(publish, route_name='publish')
+
config.add_route('subscribe', '/subscribe')
- config.add_view(subscribe, route_name='suscribe')
+ config.add_view(subscribe, route_name='subscribe')
+
return config.make_wsgi_... |
c147629b4a0a5b405f7568b9278f288fa09fd97b | tests/aggregation/models.py | tests/aggregation/models.py | # coding: utf-8
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField('self', blank=True)
def __unicode__(self):
return self.name
class Publisher(models.Model):
name = models.CharField... | # coding: utf-8
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField('self', blank=True)
def __unicode__(self):
return self.name
class Publisher(models.Model):
name = models.CharField... | Add a boolean field to Store model (store.has_coffee) | Add a boolean field to Store model (store.has_coffee)
| Python | mit | henriquebastos/django-aggregate-if | ---
+++
@@ -36,6 +36,7 @@
books = models.ManyToManyField(Book)
original_opening = models.DateTimeField()
friday_night_closing = models.TimeField()
+ has_coffee = models.BooleanField()
def __unicode__(self):
return self.name |
0143e790245d19528af56df5428dc990d0689637 | node/multiply.py | node/multiply.py | #!/usr/bin/env python
from nodes import Node
class Multiply(Node):
char = "*"
args = 2
results = 1
@Node.test_func([4,5], [20])
def func(self, a,b):
"""a*b"""
return a*b | #!/usr/bin/env python
from nodes import Node
class Multiply(Node):
char = "*"
args = 2
results = 1
@Node.test_func([4,5], [20])
def func(self, a,b):
"""a*b"""
return[a*b] | Multiply now handles lists correctly | Multiply now handles lists correctly
| Python | mit | muddyfish/PYKE,muddyfish/PYKE | ---
+++
@@ -10,4 +10,4 @@
@Node.test_func([4,5], [20])
def func(self, a,b):
"""a*b"""
- return a*b
+ return[a*b] |
9f6ade7fab83f15b49e37e28ac2d044a41846809 | tests/test_create.py | tests/test_create.py | import globals as gbl
from matador.commands import CreateTicket, CreatePackage
from dulwich.repo import Repo
def test_add_to_git(project_repo):
pass
def test_create_ticket(project_repo):
CreateTicket(ticket='test-ticket')
def test_create_package(project_repo):
CreatePackage(package='test-package')
| from matador.commands import CreateTicket, CreatePackage
from dulwich.repo import Repo
from pathlib import Path
def test_add_to_git(project_repo):
pass
def test_create_ticket(session, project_repo):
test_ticket = 'test-ticket'
CreateTicket(ticket=test_ticket)
ticket_folder = Path(project_repo, 'depl... | Add test for git commit | Add test for git commit
| Python | mit | Empiria/matador | ---
+++
@@ -1,15 +1,35 @@
-import globals as gbl
from matador.commands import CreateTicket, CreatePackage
from dulwich.repo import Repo
+from pathlib import Path
def test_add_to_git(project_repo):
pass
-def test_create_ticket(project_repo):
- CreateTicket(ticket='test-ticket')
+def test_create_tick... |
179df740725c0d3c9e256629e4718afcfa3b0cec | terminal_notifier.py | terminal_notifier.py | # This weechat plugin sends OS X notifications for weechat messages
#
# Install terminal-notifier, no other configuration needed.
#
# History:
# 10-04-2015
# Version 1.0.0: initial release
import distutils.spawn
import os
import pipes
import weechat
def notify(data, signal, signal_data):
command = ("terminal-not... | # This weechat plugin sends OS X notifications for weechat messages
#
# Install terminal-notifier, no other configuration needed.
#
# History:
#
# Version 1.0.0: initial release
# Version 1.0.1: fix escape characters which broke terminal-notifier
import distutils.spawn
import os
import pipes
import weechat
def notif... | Fix characters which break terminal-notifier | Fix characters which break terminal-notifier
If your message starts with either a [ or - (and probably more I haven't
found yet) terminal-notifier blows up because of the way it parses its
arguments
| Python | mit | keith/terminal-notifier-weechat | ---
+++
@@ -3,8 +3,9 @@
# Install terminal-notifier, no other configuration needed.
#
# History:
-# 10-04-2015
+#
# Version 1.0.0: initial release
+# Version 1.0.1: fix escape characters which broke terminal-notifier
import distutils.spawn
import os
@@ -13,8 +14,14 @@
def notify(data, signal, signal_data... |
b2d9234ff6353191afc434556f9cfdea2448f726 | test/test_regexes.py | test/test_regexes.py | from findspam import FindSpam
import pytest
@pytest.mark.parametrize("text, match", [
('18669786819 gmail customer service number 1866978-6819 gmail support number', True),
('Is there any http://www.hindawi.com/ template for Cloud-Oriented Data Center Networking?', True),
('bagprada', True),
... | from findspam import FindSpam
import pytest
@pytest.mark.parametrize("title, username, match", [
('18669786819 gmail customer service number 1866978-6819 gmail support number', '', True),
('Is there any http://www.hindawi.com/ template for Cloud-Oriented Data Center Networking?', '', True),
('', '... | Update tests + add username field | Update tests + add username field
| Python | apache-2.0 | Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector,ArtOfCode-/SmokeDetector,ArtOfCode-/SmokeDetector,Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector | ---
+++
@@ -1,18 +1,27 @@
from findspam import FindSpam
import pytest
-@pytest.mark.parametrize("text, match", [
- ('18669786819 gmail customer service number 1866978-6819 gmail support number', True),
- ('Is there any http://www.hindawi.com/ template for Cloud-Oriented Data Center Networking?', True),
- ... |
23c3b63e9f336ad70d481c0355d2f7f1544b9d54 | lattice_length.py | lattice_length.py | # Load the machine
import pkg_resources
pkg_resources.require('aphla')
import aphla as ap
# Load the machine
ap.machines.load('SRI21')
myLattice = ap.machines.getLattice()
length = 0
for key in range(myLattice.size()):
length += myLattice[key].length
print "The length of the lattice is {}.".format(length)
| # Load the machine
import pkg_resources
pkg_resources.require('aphla')
import aphla as ap
# Load the machine
ap.machines.load('SRI21')
my_lattice = ap.machines.getLattice()
length = 0
for key in range(my_lattice.size()):
length += my_lattice[key].length
print "The length of the lattice is {}.".format(length)
| Change variable name to more suitable ones | Change variable name to more suitable ones
| Python | apache-2.0 | razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects | ---
+++
@@ -6,10 +6,10 @@
# Load the machine
ap.machines.load('SRI21')
-myLattice = ap.machines.getLattice()
+my_lattice = ap.machines.getLattice()
length = 0
-for key in range(myLattice.size()):
- length += myLattice[key].length
+for key in range(my_lattice.size()):
+ length += my_lattice[key].length
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.