commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
c38598f5a6afe6057869dccf65e2950d9fd49fe1
scripts/validate-resources.py
scripts/validate-resources.py
import sys import json from openshift3.resources import load, dumps resources = load(sys.argv[1]) print(repr(resources)) import pprint pprint.pprint(json.loads(dumps(resources)))
import sys import json from openshift3.resources import load, dumps path = len(sys.argv) >= 2 and sys.argv[1] or None resources = load(path) print(repr(resources)) import pprint pprint.pprint(json.loads(dumps(resources)))
Allow resource definitions from standard input.
Allow resource definitions from standard input.
Python
bsd-2-clause
getwarped/powershift
3588f5e30e40f82fb085d01063af64b838528b6a
scripts/fix_merged_user_quickfiles.py
scripts/fix_merged_user_quickfiles.py
import logging import sys from django.db import transaction from django.db.models import F from website.app import setup_django setup_django() from osf.models import QuickFilesNode from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(): dry = '--dry' in sys.argv if not dr...
import logging import sys from django.db import transaction from django.db.models import F, Count from website.app import setup_django setup_django() from osf.models import QuickFilesNode from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(): dry = '--dry' in sys.argv if...
Exclude QuickFilesNodes that don't have contributors
Exclude QuickFilesNodes that don't have contributors
Python
apache-2.0
TomBaxter/osf.io,leb2dg/osf.io,cslzchen/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,aaxelb/osf.io,felliott/osf.io,sloria/osf.io,cslzchen/osf.io,cslzchen/osf.io,baylee-d/osf.io,adlius/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,mattclark/osf.io,leb2dg/osf.io,CenterForOpenScience/o...
6c29d671f95668e5f4a337bfe1df23d3bc6b5b0e
arxiv_vanity/sitemaps.py
arxiv_vanity/sitemaps.py
from django.contrib.sitemaps import Sitemap from .papers.models import Paper class PaperSitemap(Sitemap): changefreq = "monthly" priority = 0.5 limit = 5000 def items(self): return Paper.objects.all() def lastmod(self, obj): return obj.updated
from django.contrib.sitemaps import Sitemap from .papers.models import Paper class PaperSitemap(Sitemap): changefreq = "monthly" priority = 0.5 limit = 1000 def items(self): return Paper.objects.only("arxiv_id", "updated").all() def lastmod(self, obj): return obj.updated
Make sitemap yet more efficient
Make sitemap yet more efficient
Python
apache-2.0
arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity
c99ea848a39d22cb4347606b6cba97b98ce627fd
timesketch/api/v1/resources/information.py
timesketch/api/v1/resources/information.py
# Copyright 2020 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2020 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Fix method docstring (copy paste error)
Fix method docstring (copy paste error) Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47 As the method does not return user info.
Python
apache-2.0
google/timesketch,google/timesketch,google/timesketch,google/timesketch
185d66fa562f931e9910f845e8986620da142c49
tests/test_api_views.py
tests/test_api_views.py
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import pytest import django from django.test import TestCase from rest_framework.test import APIRequestFactory from api.webview.views import DocumentList django.setup() # TODO - make this work without Django. class APIViewTests(TestCase...
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import django from django.test import TestCase from rest_framework.test import APIRequestFactory from api.webview.views import DocumentList django.setup() class APIViewTests(TestCase): def setUp(self): self.factory = APIRequ...
Add some more views tests
Add some more views tests
Python
apache-2.0
mehanig/scrapi,erinspace/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,mehanig/scrapi,erinspace/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi
e830aae894ac2256e70d1bef1d3784dff4cb8bdb
metaci/repository/urls.py
metaci/repository/urls.py
from django.conf.urls import url from metaci.repository import views as repository_views urlpatterns = [ url( r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$', repository_views.branch_detail, name='branch_detail', ), url( r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(...
from django.conf.urls import url from metaci.repository import views as repository_views urlpatterns = [ url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$', repository_views.branch_detail, name='branch_detail', ), url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/co...
Support -'s in github repo and owner name
Support -'s in github repo and owner name
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
8631a61b9b243e5c1724fb2df06f33b1400fb59e
tests/test_koji_sign.py
tests/test_koji_sign.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Tests for koji_sign module. """ import unittest import os import sys DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Tests for koji_sign module. """ import unittest import os import sys # HACK: inject empty koji module to silence failing tests. # We need to add koji to deps (currently not possible) # or create a mock object for testing. import imp sys.modules["koji"] = imp.new_modu...
Fix failing tests by injecting an empty koji module.
Fix failing tests by injecting an empty koji module.
Python
mit
release-engineering/releng-sop,release-engineering/releng-sop
648e2907a5ea5f9157b5aabe4cec10a3d952f5a7
tests/test_scale.py
tests/test_scale.py
from hypothesis import assume, given from ppb_vector import Vector from utils import angle_isclose, floats, isclose, lengths, vectors @given(x=vectors(), length=floats()) def test_scale_to_length(x: Vector, length: float): """Test that the length of x.scale_to(length) is length. Additionally, Vector.scale_t...
from hypothesis import assume, given, strategies as st from pytest import raises # type: ignore from ppb_vector import Vector from utils import angle_isclose, isclose, lengths, vectors @given(v=vectors(), length=st.floats(max_value=0)) def test_scale_negative_length(v: Vector, length: float): """Test that Vecto...
Make a separate test for negative lengths
tests/scale: Make a separate test for negative lengths Previously, we didn't check that negative lengths raise a ValueError, but that *if* a ValueError was raised, then the length was negative.
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
e3fe8c01855e3462ae5e4fd51473a75355fe416d
tests/test_utils.py
tests/test_utils.py
from parsel.utils import shorten from pytest import mark, raises import six @mark.parametrize( 'width,expected', ( (-1, ValueError), (0, u''), (1, u'.'), (2, u'..'), (3, u'...'), (4, u'f...'), (5, u'fo...'), (6, u'foobar'), (7, u'foobar'...
from parsel.utils import shorten, extract_regex from pytest import mark, raises import six @mark.parametrize( 'width,expected', ( (-1, ValueError), (0, u''), (1, u'.'), (2, u'..'), (3, u'...'), (4, u'f...'), (5, u'fo...'), (6, u'foobar'), ...
Add tests for `extract_regex` function.
Add tests for `extract_regex` function.
Python
bsd-3-clause
scrapy/parsel
bea03e81141dcb912e1697fbf22b7ca1d5fd0d4d
tingbot/__init__.py
tingbot/__init__.py
from . import platform_specific, input from .graphics import screen, Surface, Image from .run_loop import main_run_loop, every from .input import touch from .button import press from .web import webhook platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) ...
try: import pygame except ImportError: print 'Failed to import pygame' print '-----------------------' print '' print 'tingbot-python requires pygame. Please download and install pygame 1.9.1' print 'or later from http://www.pygame.org/download.shtml' print '' print "If you're using a vi...
Add import-time check for pygame (since we can't install automatically)
Add import-time check for pygame (since we can't install automatically)
Python
bsd-2-clause
furbrain/tingbot-python
df55e36869789e3b4b94114a339dd2390156fc0b
account/urls.py
account/urls.py
from django.conf.urls import url from django.contrib.auth.views import ( password_change, password_change_done, password_reset, password_reset_done, password_reset_confirm, password_reset_complete, LoginView, LogoutView, ) from .views import AccountView urlpatterns = [ url(r'^$', A...
from django.conf.urls import url from django.contrib.auth.views import ( password_change, password_change_done, password_reset, password_reset_done, password_reset_confirm, password_reset_complete, LoginView, LogoutView, ) from .views import AccountView urlpatterns = [ url(r'^$', A...
Add profile view - default login redirect
Add profile view - default login redirect
Python
mit
uda/djaccount,uda/djaccount
aacb30d2d87cf83c3f09225532c06d81e399cae2
spanky/commands/cmd_roster.py
spanky/commands/cmd_roster.py
import json import click from spanky.cli import pass_context from spanky.lib.enroll import roster @click.command('roster', short_help='Enroll / leave') @click.argument('name') @pass_context def cli(ctx, name): config = ctx.config.load('enroll.yml') click.echo(json.dumps(list(roster(config, name))))
import json import click from spanky.cli import pass_context from spanky.lib.enroll import roster @click.command('roster', short_help='Enroll / leave') @click.argument('name') @pass_context def cli(ctx, name): config = ctx.config.load('enroll.yml') members = list(roster(config, name)) click.echo(json.du...
Return members in roster cmd out.
Return members in roster cmd out.
Python
bsd-3-clause
pglbutt/spanky,pglbutt/spanky,pglbutt/spanky
3da17f4732d0b1987f3a9362eb8dfa70fb21e39b
rabbitpy/utils.py
rabbitpy/utils.py
"""Utilities to make Python 3 support easier, providing wrapper methods which can call the appropriate method for either Python 2 or Python 3 but creating a single API point for rabbitpy to use. """ __since__ = '2013-03-24' from pamqp import PYTHON3 if PYTHON3: from urllib import parse as urlparse else: impo...
"""Utilities to make Python 3 support easier, providing wrapper methods which can call the appropriate method for either Python 2 or Python 3 but creating a single API point for rabbitpy to use. """ from pamqp import PYTHON3 try: from urllib import parse as _urlparse except ImportError: import urlparse as _ur...
Fix urlparse name collision with method
Fix urlparse name collision with method
Python
bsd-3-clause
gmr/rabbitpy,gmr/rabbitpy,jonahbull/rabbitpy
3d399d33302c004122773af52a740da1c736540e
test/functional/test_miscellaneous.py
test/functional/test_miscellaneous.py
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client...
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client...
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs
Python
mit
ipfs/py-ipfs-api,ipfs/py-ipfs-api
6bd8ecf5719e15674ef67100b92822be3cf8e5ec
dataportal/tests/test_replay_persistance.py
dataportal/tests/test_replay_persistance.py
import nose from dataportal.replay.persist import History h = None def setup(): h = History(':memory:') def test_history(): pass
from nose.tools import assert_equal from dataportal.replay.persist import History import dataportal.replay.persist OBJ_ID_LEN = 36 h = None def setup(): global h h = History(':memory:') def test_history(): run_id = ''.join(['a'] * OBJ_ID_LEN) # Simple round-trip: put and get config1 = {'plot_x'...
Add real tests of replay History.
TST: Add real tests of replay History.
Python
bsd-3-clause
tacaswell/dataportal,danielballan/datamuxer,danielballan/datamuxer,NSLS-II/dataportal,ericdill/datamuxer,danielballan/dataportal,NSLS-II/datamuxer,danielballan/dataportal,ericdill/databroker,tacaswell/dataportal,NSLS-II/dataportal,ericdill/datamuxer,ericdill/databroker
334c23e313cef141b6a18e8bf34be0fea662043f
cla_public/libs/call_centre_availability.py
cla_public/libs/call_centre_availability.py
import datetime def time_choice(time): display_format = "%I:%M %p" end = time + datetime.timedelta(minutes=30) display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0") return time.strftime("%H%M"), display_string def suffix(d): if 11 <= d <= 1...
import datetime from flask.ext.babel import lazy_gettext as _ def time_choice(time): display_format = "%I:%M %p" end = time + datetime.timedelta(minutes=30) display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0") return time.strftime("%H%M"), displ...
Allow for Day name and ordinal suffix to be translated
Allow for Day name and ordinal suffix to be translated
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
c5128bb5dd059580f46647cfe881f1b2c154f62f
tests/config_test.py
tests/config_test.py
import os from testfixtures import tempdir import unittest import yaml from i2ssh.config import Config FILENAME = '.i2sshrc' class ConfigTest(unittest.TestCase): @tempdir() def test_cluster(self, tmpdir): cluster_config = {'hosts': ['host1']} full_config = {'mycluster': cluster_config} ...
import os from testfixtures import tempdir import unittest import yaml from i2ssh.config import Config FILENAME = '.i2sshrc' class ConfigTest(unittest.TestCase): @tempdir() def test_cluster(self, tmpdir): cluster_config = {'hosts': ['host1']} full_config = {'mycluster': cluster_config} ...
Fix python3 build: Set byte encoding when writing to file.
Fix python3 build: Set byte encoding when writing to file.
Python
apache-2.0
mbruggmann/i2ssh
da5386234ec66968a1010d073af56ab7f01e4792
openshift/ose_object.py
openshift/ose_object.py
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain ...
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain ...
Use the extracted json for getting data from OSEObject to not extract it every time
Use the extracted json for getting data from OSEObject to not extract it every time
Python
mit
atodorov/python-openshift,atodorov/python-openshift
1af4c1889c55a2ed6e32e8b59ecd2f0be2eb8fea
tests/test_replay.py
tests/test_replay.py
# -*- coding: utf-8 -*- """ test_replay ----------- """ import os import pytest from cookiecutter import replay from cookiecutter.config import get_user_config def test_get_user_config(): config_dict = get_user_config() assert 'replay_dir' in config_dict expected_dir = os.path.expanduser('~/.cookiecu...
# -*- coding: utf-8 -*- """ test_replay ----------- """ import os import pytest from cookiecutter import replay from cookiecutter.config import get_user_config def test_get_user_config(): config_dict = get_user_config() assert 'replay_dir' in config_dict expected_dir = os.path.expanduser('~/.cookiecu...
Implement test to ensure the replay dir existence is verified
Implement test to ensure the replay dir existence is verified
Python
bsd-3-clause
venumech/cookiecutter,agconti/cookiecutter,dajose/cookiecutter,benthomasson/cookiecutter,moi65/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,agconti/cookiecutter,moi65/cookiecutter,stevepiercy/cookiecutter,audreyr/cookiecutter,luzfcb/cookiecutter,cguardia/cookiecutter,dajose/cookiecutter,au...
83c68749910933cdb3a8be1a4fc2c50709f671a1
admin/common_auth/forms.py
admin/common_auth/forms.py
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.Pas...
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.Pas...
Add checkboxselectmultiple widget for admin form
Add checkboxselectmultiple widget for admin form
Python
apache-2.0
felliott/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,erinspace/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,icereval/osf.io,chennan47/osf.io,mfraezz/osf.io,adlius/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,leb...
85c1a9e6dd9e4523d60638027da23fbfce7deff6
stack/cluster.py
stack/cluster.py
from troposphere import ( Parameter, Ref, ) from troposphere.ecs import ( Cluster, ) from .template import template container_instance_type = Ref(template.add_parameter(Parameter( "ContainerInstanceType", Description="The container instance type", Type="String", Default="t2.micro", A...
from troposphere import ( iam, Parameter, Ref, ) from troposphere.ecs import ( Cluster, ) from .template import template container_instance_type = Ref(template.add_parameter(Parameter( "ContainerInstanceType", Description="The container instance type", Type="String", Default="t2.micr...
Add an instance profile for container instances
Add an instance profile for container instances
Python
mit
caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics
b6742ef3f8d1888e46938b2c678bfb093b7a31f2
pymortgage/d3_schedule.py
pymortgage/d3_schedule.py
import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] if by_year: d3_data.insert(0, self.add_year_key("balance")) d3_data.insert(1, self.add_year_key("princi...
import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] keys = ['balance', 'principal', 'interest', 'amount'] if by_year: for i in range(len(keys)): ...
Put some recurring things into a loop to simply code.
Put some recurring things into a loop to simply code.
Python
apache-2.0
csutherl/pymortgage,csutherl/pymortgage,csutherl/pymortgage
cda63e96b042de04b3aa12348a411229e9b9d973
tools/glidein_cat.py
tools/glidein_cat.py
#!/bin/env python # # glidein_cat # # Execute a cat command on the job directory # # Usage: # glidein_ls.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs> # import os import string import stat import sys sys.path.append("lib") sys.path.append("../lib") import glideinMonitor def c...
#!/bin/env python # # glidein_cat.py # # Description: # Execute a cat command on a condor job working directory # # Usage: # glidein_cat.py <cluster>.<process> [<file>] [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>] # # Author: # Igor Sfiligoi (May 2007) # # License: # Fermitools # import sys,os...
Change rel paths into abspaths and use helper module
Change rel paths into abspaths and use helper module
Python
bsd-3-clause
bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS
c8f3b93b763189a3f420b2d91dd9fec3ba96b300
catalog/serializers.py
catalog/serializers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from rest_framework import serializers from catalog.models import Course, Category from documents.serializers import DocumentSerializer from telepathy.serializers import SmallThreadSerializer class CourseSerializer(serializers.HyperlinkedM...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from rest_framework import serializers from catalog.models import Course, Category from documents.serializers import DocumentSerializer from telepathy.serializers import SmallThreadSerializer class CourseSerializer(serializers.HyperlinkedM...
Remove category slug from the API
Remove category slug from the API
Python
agpl-3.0
UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/beta402,UrLab/DocHub,UrLab/DocHub,UrLab/DocHub
5c28e34a795f3dfd8eebdbeb2509525ce4195bba
subversion/bindings/swig/python/tests/core.py
subversion/bindings/swig/python/tests/core.py
import unittest, os import svn.core class SubversionCoreTestCase(unittest.TestCase): """Test cases for the basic SWIG Subversion core""" def test_SubversionException(self): self.assertEqual(svn.core.SubversionException().args, ()) self.assertEqual(svn.core.SubversionException('error message').args, ...
import unittest, os import svn.core class SubversionCoreTestCase(unittest.TestCase): """Test cases for the basic SWIG Subversion core""" def test_SubversionException(self): self.assertEqual(svn.core.SubversionException().args, ()) self.assertEqual(svn.core.SubversionException('error message').args, ...
Add a regression test for the bug fixed in r28485.
Add a regression test for the bug fixed in r28485. * subversion/bindings/swig/python/tests/core.py (SubversionCoreTestCase.test_SubversionException): Test explicit exception fields.
Python
apache-2.0
jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion
e53c1d6b592784cf0d94f31aa798e7a4563a9164
app/soc/views/helper/decorators.py
app/soc/views/helper/decorators.py
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Remove not needed request argument in view decorator.
Remove not needed request argument in view decorator. Patch by: Pawel Solyga Review by: to-be-reviewed --HG-- extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%40826
Python
apache-2.0
SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange
3272a507219b5ca8c3a498acd66db33432458767
app/soc/views/helper/decorators.py
app/soc/views/helper/decorators.py
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Remove not needed request argument in view decorator.
Remove not needed request argument in view decorator. Patch by: Pawel Solyga Review by: to-be-reviewed --HG-- extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%40826
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
2489ac6ce5a0229bbcee6e888f192eeca284106c
thinglang/parser/tokens/arithmetic.py
thinglang/parser/tokens/arithmetic.py
from thinglang.common import ObtainableValue from thinglang.parser.tokens import BaseToken class ArithmeticOperation(BaseToken, ObtainableValue): OPERATIONS = { "+": lambda rhs, lhs: rhs + lhs, "*": lambda rhs, lhs: rhs * lhs, "-": lambda rhs, lhs: rhs - lhs, "/": lambda rhs, lhs: ...
from thinglang.common import ObtainableValue from thinglang.parser.tokens import BaseToken class ArithmeticOperation(BaseToken, ObtainableValue): OPERATIONS = { "+": lambda rhs, lhs: rhs + lhs, "*": lambda rhs, lhs: rhs * lhs, "-": lambda rhs, lhs: rhs - lhs, "/": lambda rhs, lhs: ...
Use argument list instead of lhs/rhs pari in ArithmeticOperation
Use argument list instead of lhs/rhs pari in ArithmeticOperation
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
6a007316bd3c7576e83076bee5d3236a1891a512
messente/api/sms/api/__init__.py
messente/api/sms/api/__init__.py
# -*- coding: utf-8 -*- # Copyright 2016 Messente Communications OÜ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
# -*- coding: utf-8 -*- # Copyright 2016 Messente Communications OÜ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
Declare public interface for api.sms.api module
Declare public interface for api.sms.api module
Python
apache-2.0
messente/messente-python
8b4c8d30e70134a422576178534d41ebc9a92c88
telethon/events/messagedeleted.py
telethon/events/messagedeleted.py
from .common import EventBuilder, EventCommon, name_inner_event from ..tl import types @name_inner_event class MessageDeleted(EventBuilder): """ Event fired when one or more messages are deleted. """ @staticmethod def build(update): if isinstance(update, types.UpdateDeleteMessages): ...
from .common import EventBuilder, EventCommon, name_inner_event from ..tl import types @name_inner_event class MessageDeleted(EventBuilder): """ Event fired when one or more messages are deleted. """ @staticmethod def build(update): if isinstance(update, types.UpdateDeleteMessages): ...
Fix events.MessageDeleted setting readonly properties
Fix events.MessageDeleted setting readonly properties
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,expectocode/Telethon
0d16478f62bfb7c761f70475933772c812f9bdde
app/tests/test_fixtures.py
app/tests/test_fixtures.py
""" Test fixtures. :copyright: (c) 2017 Derek M. Frank :license: MPL-2.0 """ def test_simple_app(app): """Verify basic application.""" assert app def test_simple_config(config): """Verify basic application configuration.""" assert isinstance(config, dict) def test_webdriver_current_url(webdriver...
""" Test fixtures. :copyright: (c) 2017 Derek M. Frank :license: MPL-2.0 """ from flask import Flask # type: ignore def test_simple_app(app): """Verify basic application.""" assert isinstance(app, Flask) def test_simple_config(config): """Verify basic application configuration.""" assert isinstan...
Improve app test and silence pylint
chore(fixture-tests): Improve app test and silence pylint
Python
mpl-2.0
defrank/roshi
dc2900ce180dbcd2b0a0f48e358c38fff67629e0
rwt/tests/test_scripts.py
rwt/tests/test_scripts.py
from __future__ import unicode_literals import textwrap import sys import subprocess def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_file = tmpdir / 'script' sc...
from __future__ import unicode_literals import textwrap import sys import subprocess from rwt import scripts def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_fil...
Add test capturing error when attribute assignment occurs in the top of the script
Add test capturing error when attribute assignment occurs in the top of the script
Python
mit
jaraco/rwt
f7dd16abcab5d5e0134083267f21672de8e3d5e1
hc/front/context_processors.py
hc/front/context_processors.py
from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, "site_root": settings.SITE_ROOT, "site_logo_url": settings.SITE_LOGO_URL, }
from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, "site_logo_url": settings.SITE_LOGO_URL, }
Remove site_root from template context, it's never used
Remove site_root from template context, it's never used
Python
bsd-3-clause
iphoting/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,iphoting/healthchecks
3a3adca2e5462a98c70a8624f880e35e497e5acc
server.py
server.py
import http.server PORT = 8000 HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` server_address = (HOST, PORT) # The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/ # Rather than attempt to display the cgi file itself, which a 'BaseHTTPRequestHandler' or # 'SimpleHT...
import os import http.server PORT = int(os.environ.get("PORT", 8000)) HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` server_address = (HOST, PORT) # The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/ # Rather than attempt to display the cgi file itself, which a ...
Set port depending on environment
Set port depending on environment
Python
mit
Charlotteis/guestbook
7e33e3ed495adc871a49f7217705a7d5710e7ed8
cfgov/v1/templatetags/share.py
cfgov/v1/templatetags/share.py
import os from django import template from wagtail.wagtailcore.models import Page from django.conf import settings register = template.Library() @register.filter def is_shared(page): page = page.specific if isinstance(page, Page): if page.shared: return True else: ret...
import os from django import template from wagtail.wagtailcore.models import Page register = template.Library() @register.filter def is_shared(page): page = page.specific if isinstance(page, Page): if page.shared: return True else: return False @register.assignment_...
Fix one more place where STAGING_HOSTNAME uses settings
Fix one more place where STAGING_HOSTNAME uses settings
Python
cc0-1.0
kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh
fc30efcbea90835314be50e65608102fa538e55c
sri21_vmx_pvs_to_file.py
sri21_vmx_pvs_to_file.py
#!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = '...
#!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = '...
Clear unnecessary code, add comments on sorting
Clear unnecessary code, add comments on sorting
Python
apache-2.0
razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects
23e1efbd24e317e6571d8436fc414dae9a3da767
salt/output/__init__.py
salt/output/__init__.py
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader STATIC = ( 'yaml_out', 'text_out', 'raw_out', 'json_out', ) def display_output(data, out, opts=None): ''' Pri...
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader STATIC = ( 'yaml_out', 'text_out', 'raw_out', 'json_out', ) def display_output(data, out, opts=None): ''' Pri...
Add function to outputter that returns the raw string to print
Add function to outputter that returns the raw string to print
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
2d7974ac4895af5e7d2f5a627656bb3edbfa65a9
config/config.py
config/config.py
def playerIcons(poi): if poi['id'] == 'Player': poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId'] return "Last known location for %s" % poi['EntityId'] def signFilter(poi): if poi['id'] == 'Sign': return "\n".join([poi['Text1'], poi['Text2'], poi['Text3'], poi['Text4']])...
def playerIcons(poi): if poi['id'] == 'Player': poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId'] return "Last known location for %s" % poi['EntityId'] # Only signs with "-- RENDER --" on the last line will be shown # Otherwise, people can't have secret bases and the render is too b...
Add filter text to signs
Add filter text to signs
Python
mit
mide/minecraft-overviewer,StefanBossbaly/minecraft-overviewer,StefanBossbaly/minecraft-overviewer,mide/minecraft-overviewer
fb0eae3a9a760460f664adeef2ff71b2e8daac0f
twelve/env.py
twelve/env.py
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ ...
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ ...
Add a repr for twelve.Environment
Add a repr for twelve.Environment
Python
bsd-3-clause
dstufft/twelve
25bbe2cfc1b3b8f926176d83fbaa5c53bb85651a
tinysrt.py
tinysrt.py
#!/usr/bin/env python import re import datetime from collections import namedtuple SUBTITLE_REGEX = re.compile(r'''\ (\d+) (\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+) (.+) ''') Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content']) def parse_time(time): hours, minutes, seconds, milliseconds = map(...
#!/usr/bin/env python import re import datetime from collections import namedtuple SUBTITLE_PATTERN = '''\ (\d+) (\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+) (.+?) ''' SUBTITLE_REGEX = re.compile(SUBTITLE_PATTERN, re.MULTILINE | re.DOTALL) Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content']) def par...
Split out subtitle pattern from compilation phase
Split out subtitle pattern from compilation phase
Python
mit
cdown/srt
f479db0d829977766607d9131ddc85b1349c6f4a
userApp/tests.py
userApp/tests.py
from django.test import TestCase # Create your tests here. class BasicTestCase(TestCase): """Test getting various urls for user app""" def test_getting_login(self): self.client.get('/user/login') def test_getting_register(self): self.client.get('/user/register') def test_getting_(self...
from django.test import TestCase from django.contrib.auth import get_user_model User = get_user_model() # Create your tests here. class TestUserFunction(TestCase): """Test getting various urls for user app""" def setUp(self): self.test_user = create_user() def test_getting_login(self): se...
Add more thorough testing to user app
Add more thorough testing to user app
Python
mit
SPARLab/BikeMaps,SPARLab/BikeMaps,SPARLab/BikeMaps
28f9f7e85bb8353435db322138d1bd624934110f
london_commute_alert.py
london_commute_alert.py
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines...
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines...
Halt emails for time being
Halt emails for time being
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
3efd847f8569a30b018925b39d1552a4aead6e8f
destroyer/destroyer.py
destroyer/destroyer.py
"""destroyer.py - Main module file for the application. Includes the code for the command line interface.""" import click from .services.twitter import TwitterDestroyer @click.group() def cli(): pass @click.command() @click.option('--unfollow_nonfollowers', default=False, type=click.BOOL) def twitter(unfollo...
"""destroyer.py - Main module file for the application. Includes the code for the command line interface.""" import click from .services.twitter import TwitterDestroyer from .services.facebook import FacebookDestroyer @click.group() def cli(): pass @click.command() @click.option('--unfollow_nonfollowers', de...
Update main module with facebook integration
Update main module with facebook integration
Python
mit
jaredmichaelsmith/destroyer
02da53951e48fd6b164d883cdf5c63c7b7f08049
rmake_plugins/multinode_client/nodetypes.py
rmake_plugins/multinode_client/nodetypes.py
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Cli...
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeType...
Use metaclasses to register node types.
Use metaclasses to register node types.
Python
apache-2.0
fedora-conary/rmake-2,fedora-conary/rmake-2,fedora-conary/rmake-2,fedora-conary/rmake-2
c0c67c14cb9c91c8cd07bfe6d013639121d1c5f7
crm/tests/test_contact_user.py
crm/tests/test_contact_user.py
from django.contrib.auth.models import User from django.db import IntegrityError from django.test import TestCase from crm.tests.model_maker import ( make_contact, make_user_contact, ) from login.tests.model_maker import make_user class TestContactUser(TestCase): def test_link_user_to_contact(self): ...
from django.db import IntegrityError from django.test import TestCase from crm.tests.model_maker import ( make_contact, make_user_contact, ) from crm.tests.scenario import ( contact_contractor, ) from login.tests.scenario import ( get_fred, get_sara, user_contractor, ) class TestContactUser(T...
Update test to use standard scenario
Update test to use standard scenario
Python
apache-2.0
pkimber/crm,pkimber/crm,pkimber/crm
a20c88da5eb0b763072cc7bcba138983fe63ae31
django_fsm_log/apps.py
django_fsm_log/apps.py
from __future__ import unicode_literals from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string from django_fsm.signals import pre_transition, post_transition class DjangoFSMLogAppConfig(AppConfig): name = 'django_fsm_log' verbose_name = "Djang...
from __future__ import unicode_literals from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string from django_fsm.signals import pre_transition, post_transition class DjangoFSMLogAppConfig(AppConfig): name = 'django_fsm_log' verbose_name = "Djang...
Solve warning coming from django 4.0
Solve warning coming from django 4.0
Python
mit
ticosax/django-fsm-log,gizmag/django-fsm-log
28126555aea9a78467dfcadbb2b14f9c640cdc6d
dwitter/templatetags/to_gravatar_url.py
dwitter/templatetags/to_gravatar_url.py
import hashlib from django import template register = template.Library() @register.filter def to_gravatar_url(email): return ('https://gravatar.com/avatar/%s?d=retro' % hashlib.md5((email or '').strip().lower()).hexdigest())
import hashlib from django import template register = template.Library() @register.filter def to_gravatar_url(email): return ('https://gravatar.com/avatar/%s?d=retro' % hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
Fix gravatar hashing error on py3
Fix gravatar hashing error on py3
Python
apache-2.0
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
5a4fc9a89bfdb279ad0cda40f45b35ff3841c970
voteswap/urls.py
voteswap/urls.py
"""voteswap URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
"""voteswap URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
Fix logout view so django stops complaining
Fix logout view so django stops complaining
Python
mit
sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap
bf269c03f93cf26630e67b3e44384eaf1235f808
tests/test_20_message.py
tests/test_20_message.py
from __future__ import absolute_import, division, print_function, unicode_literals import os.path import pytest from eccodes_grib import eccodes from eccodes_grib import message TEST_DATA = os.path.join(os.path.dirname(__file__), 'sample-data', 'ERA5_levels.grib') def test_Message(): codes_id = eccodes.grib...
from __future__ import absolute_import, division, print_function, unicode_literals import os.path import pytest from eccodes_grib import eccodes from eccodes_grib import message TEST_DATA = os.path.join(os.path.dirname(__file__), 'sample-data', 'ERA5_levels.grib') def test_Message(): codes_id = eccodes.grib...
Check more possibilitie for File.
Check more possibilitie for File.
Python
apache-2.0
ecmwf/cfgrib
3e86072667d486cb75e0cefca847bbdd2f032023
charat2/views/guides.py
charat2/views/guides.py
import requests def user_guide(): r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html") r.encoding = r.apparent_encoding return r.text, r.status_code
import requests def user_guide(): r = requests.get("https://karry.terminallycapricio.us/userguide/duplicateguide.html") r.encoding = r.apparent_encoding return r.text, r.status_code
Update the user guide URL.
Update the user guide URL.
Python
agpl-3.0
MSPARP/newparp,MSPARP/newparp,MSPARP/newparp
4b183fb87952404e5a71ffd5c52ea1bba5bfc2b9
csv2ofx/mappings/stripe.py
csv2ofx/mappings/stripe.py
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab # pylint: disable=invalid-name """ csv2ofx.mappings.stripe ~~~~~~~~~~~~~~~~~~~~~~~~ Provides a mapping for transactions obtained via Stripe card processing Note that Stripe provides a Default set of columns or you can download All columns. (as well as custom). The De...
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab # pylint: disable=invalid-name """ csv2ofx.mappings.stripe ~~~~~~~~~~~~~~~~~~~~~~~~ Provides a mapping for transactions obtained via Stripe card processing Note that Stripe provides a Default set of columns or you can download All columns. (as well as custom). The De...
Fix lint line length warnings (blocking manage checks)
Fix lint line length warnings (blocking manage checks)
Python
mit
reubano/csv2ofx,reubano/csv2ofx
3a57dfd7138be531fa265bea282eb7c62a391ac2
bin/debug/load_timeline_for_day_and_user.py
bin/debug/load_timeline_for_day_and_user.py
import json import bson.json_util as bju import emission.core.get_database as edb import argparse import emission.core.wrapper.user as ecwu if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("timeline_filename", help="the name of the file that contains the json representa...
import json import bson.json_util as bju import emission.core.get_database as edb import argparse import emission.core.wrapper.user as ecwu if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("timeline_filename", help="the name of the file that contains the json representa...
Fix the --verbose argument to properly take an int
Fix the --verbose argument to properly take an int Without this, the `i % args.verbose` check would fail since `args.verbose` was a string
Python
bsd-3-clause
e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server
994606d2641115f8af59657204d3d64f540bbfbd
data_structures/linked_list.py
data_structures/linked_list.py
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, values=None, head=None): self.head = head self.length = 0 def __repr__(...
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 ...
Update magic methods, and reorg args.
Update magic methods, and reorg args.
Python
mit
sjschmidt44/python_data_structures
7af339d68d31e402df3a70b6596927439de0f2aa
doc/mkapidoc.py
doc/mkapidoc.py
#!/usr/bin/env python # Generates the API documentation. import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.j...
#!/usr/bin/env python # Generates the API documentation. import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.j...
Hide Exscript.protocols.AbstractMethod from the API docs.
Hide Exscript.protocols.AbstractMethod from the API docs.
Python
mit
maximumG/exscript,knipknap/exscript,maximumG/exscript,knipknap/exscript
23edca2a2a87ca0d96becd92a0bf930cc6c33b6f
alltheitems/world.py
alltheitems/world.py
import alltheitems.__main__ as ati import api.v2 import enum import minecraft class Dimension(enum.Enum): overworld = 0 nether = -1 end = 1 class World: def __init__(self, world=None): if world is None: self.world = minecraft.World() elif isinstance(world, minecraft.World)...
import alltheitems.__main__ as ati import api.v2 import enum import minecraft class Dimension(enum.Enum): overworld = 0 nether = -1 end = 1 class World: def __init__(self, world=None): if world is None: self.world = minecraft.World() elif isinstance(world, minecraft.World)...
Fix API method names called by World.block_at
Fix API method names called by World.block_at
Python
mit
wurstmineberg/alltheitems.wurstmineberg.de,wurstmineberg/alltheitems.wurstmineberg.de
8a10dbe86f6ce02af1884fc9e68aa925003d9ad7
pynder/session.py
pynder/session.py
from time import time from datetime import timedelta from . import api from . import models class Session(object): def __init__(self, facebook_id, facebook_token, proxies=None): self._api = api.TinderAPI(proxies) # perform authentication self._api.auth(facebook_id, facebook_token) ...
from time import time from datetime import timedelta from . import api from . import models class Session(object): def __init__(self, facebook_id, facebook_token, proxies=None): self._api = api.TinderAPI(proxies) # perform authentication self._api.auth(facebook_id, facebook_token) ...
Handle no nearby users gracefully.
Handle no nearby users gracefully.
Python
mit
rforgione/pynder
0383ee9511a4b002fbb3c00b3fc6812e8cc6bf1e
test/integration/fixture_server.py
test/integration/fixture_server.py
""" Tests against the URL Router """ from wsgiref.simple_server import make_server from aragog.routing.decorator import Router router = Router() @router.route("/") def simple_app(environ, start_response): """Simplest possible application object""" status = '200 OK' response_headers = [('Content-type',...
""" Tests against the URL Router """ from wsgiref.simple_server import make_server from aragog import Router router = Router() @router.route('/') def simple_app(environ, start_response): """ Simplest possible application object """ status = '200 OK' response_headers = [('Content-type', 'text/pl...
Update fixture server with environ route.
Update fixture server with environ route. Minor changes to docstrings and change in quotation usage. Router imported from aragog, not routing.decorator.
Python
apache-2.0
bramwelt/aragog
d7ebf5c6db9b73133915aabb3dbd9c5b283f9982
ooni/tests/test_trueheaders.py
ooni/tests/test_trueheaders.py
from twisted.trial import unittest from ooni.utils.txagentwithsocks import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3':...
from twisted.trial import unittest from ooni.utils.trueheaders import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['Va...
Fix unittest for true headers..
Fix unittest for true headers..
Python
bsd-2-clause
kdmurray91/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-prob...
189353e4eb110facbabf9882e0af1ef16ced600f
openstack/tests/functional/network/v2/test_quota.py
openstack/tests/functional/network/v2/test_quota.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Fix network quota test so it works on gate
Fix network quota test so it works on gate The gate does not create quotas by default, but devstack does. This test is not important enough to make work for the gate which would probably require some reconfiguration, but it is nice to have it for devstack. Change-Id: I6618b5ee8c1dde7773b83e8ba97092f30d595e8a Partial-...
Python
apache-2.0
stackforge/python-openstacksdk,openstack/python-openstacksdk,stackforge/python-openstacksdk,openstack/python-openstacksdk,dtroyer/python-openstacksdk,briancurtin/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk
fde67686d2bd685e31cfc0e156314476b057db78
xudd/tests/test_demos.py
xudd/tests/test_demos.py
from xudd.demos import special_hive from xudd.demos import lotsamessages def test_special_hive(): """ This demo tests that demos are actually actors and are in fact subclassable. """ special_hive.main() def test_lotsamessages(): """ Test the lotsamessages demo (but not with too many messages ...
from xudd.demos import special_hive from xudd.demos import lotsamessages def test_special_hive(): """ This demo tests that demos are actually actors and are in fact subclassable. """ special_hive.main() def test_lotsamessages(): """ Test the lotsamessages demo (but not with too many messages ...
Add inter-hive communication lotsamessages test
Add inter-hive communication lotsamessages test
Python
apache-2.0
xudd/xudd
8b9ef7e731a8801535b9348dc0a6869de6c9ecfc
tests/__init__.py
tests/__init__.py
""" tests ~~~~~ Unit tests for the project. :copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors :license: MIT, see the ``LICENSE`` file for more details """
""" tests ~~~~~ Tests for the library and tools. :copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors :license: MIT, see the ``LICENSE`` file for more details """
Make the description of the tests package more precise.
Make the description of the tests package more precise.
Python
mit
s3rvac/retdec-python
1fa2af46d9f1ee05d4e4fd16869803c3dfff23e0
tests/protocol/primitives_tests.py
tests/protocol/primitives_tests.py
import unittest from kiel.protocol import primitives class PrimitivesTests(unittest.TestCase): def test_string_repr(self): s = primitives.String(u"foobar") self.assertEqual(repr(s), '"u\'foobar\'"') def test_array_repr(self): a = primitives.Array.of(primitives.Int32)([1, 3, 6, 9]) ...
import unittest from kiel.protocol import primitives class PrimitivesTests(unittest.TestCase): def test_string_repr(self): s = primitives.String(u"foobar") self.assertEqual(repr(s), '%r' % repr(u"foobar")) def test_array_repr(self): a = primitives.Array.of(primitives.Int32)([1, 3, ...
Fix repr test for py34.
Fix repr test for py34.
Python
apache-2.0
wglass/kiel
6191a5afd390cbd7e892e73af959d8d4cd68f52b
moksha/widgets/iframe.py
moksha/widgets/iframe.py
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ...
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ...
Make our IFrameWidget more configurable
Make our IFrameWidget more configurable
Python
apache-2.0
lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,lmacken/moksha,ralphbean/moksha,lmacken/moksha,ralphbean/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha
2f041e6ed7d07ef8932350b68581e8dfeaef903f
dashboard/dashboard/pinpoint/handlers/job.py
dashboard/dashboard/pinpoint/handlers/job.py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import webapp2 from dashboard.pinpoint.models import job as job_module class JobHandler(webapp2.RequestHandler): def post(self): job_id...
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import webapp2 from dashboard.pinpoint.models import job as job_module class JobHandler(webapp2.RequestHandler): def post(self): job_id...
Move Job handler out of exception block.
[pinpoint] Move Job handler out of exception block. The exception block is solely used for Job loading exceptions. Review-Url: https://codereview.chromium.org/2768293003
Python
bsd-3-clause
catapult-project/catapult,sahiljain/catapult,sahiljain/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapu...
132d160a365580d77c1f5763b1fd1ac044133bb0
NYTimesArticleAPI/__init__.py
NYTimesArticleAPI/__init__.py
from nytapi import * __version__ = "1.0.0" __author__ = "Matt Morrison @MattDMo mattdmo@mattdmo.com" __all__ = ["articleAPI"]
from search_api import * __version__ = "1.0.0" __author__ = "Matt Morrison (@MattDMo)" __all__ = ["articleAPI"] if __name__ == "__main__": print("This module cannot be run on its own. Please use by running ", "\"from NYTimesArticleAPI import articleAPI\"") exit(0)
Print message if module is run on its own
Print message if module is run on its own
Python
mit
MattDMo/NYTimesArticleAPI
bf1cc589147429eb4cc125904c7c0690a6deaf1c
testsuite/N802.py
testsuite/N802.py
#: Okay def ok(): pass #: N802 def __bad(): pass #: N802 def bad__(): pass #: N802 def __bad__(): pass #: Okay def _ok(): pass #: Okay def ok_ok_ok_ok(): pass #: Okay def _somehow_good(): pass #: Okay def go_od_(): pass #: Okay def _go_od_(): pass #: N802 def NotOK(): pass #: Oka...
#: Okay def ok(): pass #: N802 def __bad(): pass #: N802 def bad__(): pass #: N802 def __bad__(): pass #: Okay def _ok(): pass #: Okay def ok_ok_ok_ok(): pass #: Okay def _somehow_good(): pass #: Okay def go_od_(): pass #: Okay def _go_od_(): pass #: N802 def NotOK(): pass #: Oka...
Add more tests around ignored names
Add more tests around ignored names
Python
mit
flintwork/pep8-naming
36663add9f53da925f1d29c8c567ab30a1f33139
tests/api_resources/checkout/test_session.py
tests/api_resources/checkout/test_session.py
from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "loc_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_i...
from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "cs_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id...
Add support for retrieving a Checkout Session
Add support for retrieving a Checkout Session
Python
mit
stripe/stripe-python
ce5b3402d9dc5bf69b96c45a810a987d6d4b4231
tests/functional_tests/test_valid_recipes.py
tests/functional_tests/test_valid_recipes.py
import os import pytest from conda_verify import utilities from conda_verify.errors import RecipeError from conda_verify.verify import Verify @pytest.fixture def recipe_dir(): return os.path.join(os.path.dirname(__file__), 'test_recipes') @pytest.fixture def verifier(): recipe_verifier = Verify() retu...
import os import pytest from conda_verify import utilities from conda_verify.verify import Verify @pytest.fixture def recipe_dir(): return os.path.join(os.path.dirname(__file__), 'test_recipes') @pytest.fixture def verifier(): recipe_verifier = Verify() return recipe_verifier def test_valid_test_fil...
Change exception from RecipeError to SystemExit
Change exception from RecipeError to SystemExit
Python
bsd-3-clause
mandeep/conda-verify
11feab5b49bf818e8dde90497d90dafc7ceb5183
src/locations/models.py
src/locations/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class District(models.Model): name = models.CharField(_('Name'), max_length=255, unique=True) class Meta: verbose_name = _('District') verbose_name_plural = _('Districts') def __unicode__(self): ...
from django.db import models from django.utils.translation import ugettext_lazy as _ class District(models.Model): name = models.CharField(_('Name'), max_length=255, unique=True) class Meta: verbose_name = _('District') verbose_name_plural = _('Districts') ordering = ['name'] def...
Order locations and districts by name
Order locations and districts by name
Python
mit
mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign
45add3b1d96022244b372fe07d6f6dceab23786d
councilmatic_core/management/commands/update_headshots.py
councilmatic_core/management/commands/update_headshots.py
from django.core.management.base import BaseCommand, CommandError from django.core.files import File from django.conf import settings from opencivicdata.core.models import Person as OCDPerson import requests class Command(BaseCommand): help = 'Attach headshots to councilmembers' def handle(self, *args, **o...
from django.core.management.base import BaseCommand, CommandError from django.core.files import File from django.conf import settings from opencivicdata.core.models import Person as OCDPerson import requests class Command(BaseCommand): help = 'Attach headshots to councilmembers' def handle(self, *args, **o...
Add prefix to headshot filenames for easy exclusion from gitignore
Add prefix to headshot filenames for easy exclusion from gitignore
Python
mit
datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic
98307aec0d3182e3e461bd1ed287b75b26ae6e36
migrations/0013_update_counter_options.py
migrations/0013_update_counter_options.py
import json from redash import models if __name__ == '__main__': for vis in models.Visualization.select(): if vis.type == 'COUNTER': options = json.loads(vis.options) print "Before: ", options if 'rowNumber' in options: options['rowNumber'] += 1 ...
import json from redash import models if __name__ == '__main__': for vis in models.Visualization.select(): if vis.type == 'COUNTER': options = json.loads(vis.options) print "Before: ", options if 'rowNumber' in options and options['rowNumber'] is not None: ...
Make the counter migration safer.
Make the counter migration safer.
Python
bsd-2-clause
amino-data/redash,rockwotj/redash,getredash/redash,jmvasquez/redashtest,hudl/redash,pubnative/redash,getredash/redash,vishesh92/redash,stefanseifert/redash,alexanderlz/redash,getredash/redash,stefanseifert/redash,denisov-vlad/redash,ninneko/redash,crowdworks/redash,denisov-vlad/redash,easytaxibr/redash,amino-data/redas...
6bcf987ac927c4cd9829b55ec2521d77fcc2c3ad
examples/test_mfa_login.py
examples/test_mfa_login.py
from seleniumbase import BaseCase class TestMFALogin(BaseCase): def test_mfa_login(self): self.open("https://seleniumbase.io/realworld/login") self.type("#username", "demo_user") self.type("#password", "secret_pass") self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG") ...
from seleniumbase import BaseCase class TestMFALogin(BaseCase): def test_mfa_login(self): self.open("https://seleniumbase.io/realworld/login") self.type("#username", "demo_user") self.type("#password", "secret_pass") self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG") ...
Add a click() call to an example test
Add a click() call to an example test
Python
mit
mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase
f9648e4b48d2affee103ad5f229492254e3e4dc8
web3/web3/jsonrpc.py
web3/web3/jsonrpc.py
class Jsonrpc(object): def __init__(self): self.messageId = 0 @staticmethod def getInstance(): return Jsonrpc() def toPayload(self, method, params): """ Should be called to valid json create payload object """ if not method: raise Exception(...
import json class Jsonrpc(object): def toPayload(self, reqid, method, params): """ Should be called to valid json create payload object """ if not method: raise Exception("jsonrpc method should be specified!") return json.dumps({ "jsonrpc": "2.0", ...
Move message id generation to requestmanager
Move message id generation to requestmanager
Python
mit
pipermerriam/web3.py,shravan-shandilya/web3.py
d9f388d2b486da3bd5e3209db70d3e691aec584d
clowder/clowder/cli/yaml_controller.py
clowder/clowder/cli/yaml_controller.py
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class YAMLController(AbstractBaseController): class Meta: label = 'yaml' stacked_on = 'base' stacked_type = 'nested' description = 'Print clowder.yaml information' ...
from __future__ import print_function import sys from cement.ext.ext_argparse import expose import clowder.util.formatting as fmt from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.util.decorators import ( print_clowder_repo_status, valid_clowder_yaml_required ) from clowder...
Add `clowder yaml` logic to Cement controller
Add `clowder yaml` logic to Cement controller
Python
mit
JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder
5945b27aa6b5ae43470738dd6638ffa4617f7be1
poradnia/users/migrations/0014_auto_20170317_1927.py
poradnia/users/migrations/0014_auto_20170317_1927.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-17 18:27 from __future__ import unicode_literals import django.contrib.auth.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0013_profile_event_reminder_time'), ] ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-17 18:27 from __future__ import unicode_literals from django.db import migrations, models try: import django.contrib.auth.validators extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]} except ImportError: e...
Fix backward compatibility of migrations
Fix backward compatibility of migrations
Python
mit
watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia
444a66b0b0da31ed4febea2dcd82fbf6d12ea107
examples/deploy_local_file_resource.py
examples/deploy_local_file_resource.py
""" This example: 1. Connects to the current model 2. Deploy a local charm with a oci-image resource and waits until it reports itself active 3. Destroys the unit and application """ from juju import jasyncio from juju.model import Model from pathlib import Path async def main(): model = Model() print('C...
""" This example: 1. Connects to the current model 2. Deploy a local charm with a oci-image resource and waits until it reports itself active 3. Destroys the unit and application """ from juju import jasyncio from juju.model import Model from pathlib import Path async def main(): model = Model() print('C...
Make sure we cleanup even if fails in example
Make sure we cleanup even if fails in example
Python
apache-2.0
juju/python-libjuju,juju/python-libjuju
5acee7067df2af2b351bfb4b5757b4d53f023d32
radio/management/commands/export_talkgroups.py
radio/management/commands/export_talkgroups.py
import sys import datetime import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils import timezone from radio.models import * class Command(BaseCommand): help = 'Import talkgroup info' def add_arguments(self, parser): parser.add_...
import sys import datetime import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils import timezone from radio.models import * class Command(BaseCommand): help = 'Import talkgroup info' def add_arguments(self, parser): parser.add_...
Add system support to export talkgroups
Add system support to export talkgroups
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
025bc069e231b58977e7d8ea7c526849f227b9ff
pytest_pipeline/utils.py
pytest_pipeline/utils.py
# -*- coding: utf-8 -*- """ pytest_pipeline.utils ~~~~~~~~~~~~~~~~~~~~~ General utilities. :copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id> :license: BSD """ import gzip import hashlib def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.op...
# -*- coding: utf-8 -*- """ pytest_pipeline.utils ~~~~~~~~~~~~~~~~~~~~~ General utilities. :copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id> :license: BSD """ import gzip import hashlib import os def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener...
Add utility function for executable checking
Add utility function for executable checking
Python
bsd-3-clause
bow/pytest-pipeline
40bc1f50e7b0605522feb4ac86daebb9f785eb88
test/OLItest/globals.py
test/OLItest/globals.py
#Constants, that don't rely on anything else in the module # Copyright (C) 2012- Sebastian Spaeth & contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of th...
#Constants, that don't rely on anything else in the module # Copyright (C) 2012- Sebastian Spaeth & contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of th...
Use only 1 IMAP connection by default
tests: Use only 1 IMAP connection by default We don't want to hammmer IMAP servers for the test series too much to avoid being locked out. We will need a few tests to test concurrent connections, but by default one connection should be fine. Signed-off-by: Sebastian Spaeth <98dcb2717ddae152d5b359c6ea97e4fe34a29d4c@SS...
Python
apache-2.0
frioux/offlineimap,frioux/offlineimap
bc634d8c04bc15ca381019dda08982b9e1badd1c
sncosmo/tests/test_builtins.py
sncosmo/tests/test_builtins.py
import pytest import sncosmo @pytest.mark.might_download def test_hst_bands(): """ check that the HST and JWST bands are accessible """ for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m', 'f115w']: # jwst nircam sncosmo.get_bandpass(bandname) @pytest.mark.might_download de...
import pytest import sncosmo from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS from sncosmo.magsystems import _MAGSYSTEMS from sncosmo.models import _SOURCES bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()] bandpass_interpolators = [i['name'] for i in ...
Add tests for all builtins
Add tests for all builtins
Python
bsd-3-clause
sncosmo/sncosmo,sncosmo/sncosmo,sncosmo/sncosmo
d9e65fbf111f8584189a57059516afafb1e4d04c
test/projection_test.py
test/projection_test.py
from amii_tf_nn.projection import l1_projection_to_simplex import tensorflow as tf import pytest def test_l1_no_negative(): patient = l1_projection_to_simplex(tf.constant([2.0, 8.0, 0.0])) with tf.Session() as sess: print(sess.run(patient)) strat = sess.run(patient) x_strat = [0.2, 0.8...
from amii_tf_nn.projection import l1_projection_to_simplex import tensorflow as tf class ProjectionTest(tf.test.TestCase): def test_l1_no_negative(self): with self.test_session(): self.assertAllClose( l1_projection_to_simplex(tf.constant([2.0, 8.0, 0.0])).eval(), ...
Use TensorFlow's test utilities and add a test for the L1 projection to simplex.
Use TensorFlow's test utilities and add a test for the L1 projection to simplex.
Python
mit
AmiiThinks/amii-tf-nn
d7a91fe283666f01aa06a707c536893cf1473fe3
rtwilio/models.py
rtwilio/models.py
import datetime from django.db import models class TwilioResponse(models.Model): date = models.DateTimeField() message = models.CharField(max_length=64, primary_key=True) account = models.CharField(max_length=64) sender = models.CharField(max_length=16) recipient = models.CharField(max_length=16)...
from django.db import models from django.utils import timezone class TwilioResponse(models.Model): date = models.DateTimeField() message = models.CharField(max_length=64, primary_key=True) account = models.CharField(max_length=64) sender = models.CharField(max_length=16) recipient = models.CharFie...
Use timezone aware datetime now.
Use timezone aware datetime now.
Python
bsd-3-clause
caktus/rapidsms-twilio
6340e6f02c3655dc2ab33a67491cc9b16e63e5b0
redux/__main__.py
redux/__main__.py
from redux.codegenerator import compile_script from argparse import ArgumentParser from os.path import splitext parser = ArgumentParser(description='Compile a Redux script to Rescript.') parser.add_argument('filenames', metavar='FILE', nargs='+', help='script to be compiled to Rescript') args = pa...
from redux.codegenerator import compile_script from argparse import ArgumentParser from os.path import splitext parser = ArgumentParser(description='Compile a Redux script to Rescript.') parser.add_argument('input_filename', metavar='FILE', help='script to be compiled to Rescript') parser.add_argum...
Make compiler invocation more Makefile-friendly
Make compiler invocation more Makefile-friendly
Python
mit
Muon/redux
60743b33e5034776576073b151c7a02dc0a40b7e
tests/unit_project/test_fields.py
tests/unit_project/test_fields.py
from djangosanetesting.cases import DatabaseTestCase from djangomarkup.fields import RichTextField from djangomarkup.models import SourceText from exampleapp.models import Article class TestRichTextField(DatabaseTestCase): def setUp(self): super(TestRichTextField, self).setUp() self.field = Rich...
from djangosanetesting.cases import UnitTestCase from djangomarkup.fields import RichTextField from exampleapp.models import Article class TestRichTextField(UnitTestCase): def setUp(self): super(TestRichTextField, self).setUp() self.field = RichTextField( instance = Article(), ...
Check proper error when accessing source without instance
Check proper error when accessing source without instance
Python
bsd-3-clause
ella/django-markup
4313c5528efd02c45013907300b33436ce31eddd
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields, api ''' This module create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' name = fields.Char(string="Title", required=True) description = fields.Text(string="Description") resp...
from openerp import models, fields, api ''' This module create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' name = fields.Char(string="Title", required=True) description = fields.Text(string="Description") resp...
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
mapuerta/openacademy-proyect
440305707dfbf9a7a321b48250245edafc42aa73
candidates/csv_helpers.py
candidates/csv_helpers.py
from __future__ import unicode_literals from compat import BufferDictWriter from .models import CSV_ROW_FIELDS def _candidate_sort_by_name_key(row): return ( row['name'].split()[-1], not row['election_current'], row['election_date'], row['election'], row['post_label'] ...
from __future__ import unicode_literals from compat import BufferDictWriter from .models import CSV_ROW_FIELDS def _candidate_sort_by_name_key(row): return ( row['name'].split()[-1], row['name'].rsplit(None, 1)[0], not row['election_current'], row['election_date'], row['el...
Sort on first name after last name
Sort on first name after last name
Python
agpl-3.0
mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/you...
217af37f3aa7856770ce30b75df28bcd3582bb79
geotrek/trekking/tests/test_filters.py
geotrek/trekking/tests/test_filters.py
# -*- coding: utf-8 -*- from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def create_pair_of_distinct_path(self): u...
# -*- coding: utf-8 -*- from geotrek.land.filters import * from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_...
Make sure land filters are setup when testing
Make sure land filters are setup when testing
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,camillemonchicourt/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,makinacorpus/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,jo...
f531cfa07ba6e6e0d36ba768dbeb4706ae7cd259
tlslite/utils/pycrypto_rsakey.py
tlslite/utils/pycrypto_rsakey.py
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """PyCrypto RSA implementation.""" from .cryptomath import * from .rsakey import * from .python_rsakey import Python_RSAKey if pycryptoLoaded: from Crypto.PublicKey import RSA class PyCrypto_RSAKey(RSAKey): ...
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """PyCrypto RSA implementation.""" from cryptomath import * from .rsakey import * from .python_rsakey import Python_RSAKey if pycryptoLoaded: from Crypto.PublicKey import RSA class PyCrypto_RSAKey(RSAKey): ...
Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
Python
lgpl-2.1
ioef/tlslite-ng,ioef/tlslite-ng,ioef/tlslite-ng
6629a3a238432522d77f840b465eb99a3745593f
django_base64field/tests/models.py
django_base64field/tests/models.py
from django.db import models from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() name = models.CharField( default='Fucker', max_length=103 ) class Continent(models.Model): ek = Base64Field() nam...
from django.db import models from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): # Making `ek` unique just because it will be used as `FK` # in other models. ek = Base64Field(unique=True) name = models.CharField( default='Fucke...
Add little bit comments for Planet model
Add little bit comments for Planet model
Python
bsd-3-clause
Alir3z4/django-base64field
084eac5735404edeed62cee4e2b429c8f4f2a7a5
app/dao/inbound_numbers_dao.py
app/dao/inbound_numbers_dao.py
from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def...
from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.order_by(InboundNumber.updated_at, InboundNumber.number).all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumbe...
Update dao to order by updated_at, number
Update dao to order by updated_at, number
Python
mit
alphagov/notifications-api,alphagov/notifications-api
e8ebb4e9be78e32bc59b1f03cd4854add1148de3
extra.py
extra.py
Import('env') env.Append(CXXFLAGS=["-std=c++11"], CPPPATH=["src/wakaama", "wakaama"])
Import('env') env.Append(CFLAGS=["-std=gnu11"], CXXFLAGS=["-std=c++11"], CPPPATH=["src/wakaama", "wakaama"])
Make C11 default. pio should actually do this.
Make C11 default. pio should actually do this. Signed-off-by: David Graeff <cddf4d21ffd604ccd3fdffe1267f1f9d72e179ea@web.de>
Python
mit
Openhab-Nodes/libWakaamaEmb,Openhab-Nodes/libWakaamaEmb,Openhab-Nodes/libWakaamaEmb,Openhab-Nodes/libWakaamaEmb
ec867f87441af657f0138ec723de4a52299284d8
src/epiweb/apps/survey/urls.py
src/epiweb/apps/survey/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^profile/$', 'epiweb.apps.survey.views.profile_index'), (r'^thanks/$', 'epiweb.apps.survey.views.thanks'), url(r'^people/$', 'epiweb.apps.survey.views.people', name='survey_people'), url(r'^people/add/$', 'epiweb.apps.survey.views.pe...
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', (r'^profile/$', views.profile_index), (r'^thanks/$', views.thanks), url(r'^people/$', views.people, name='survey_people'), url(r'^people/add/$', views.people_add, name='survey_people_add'), (r'^$', views.index),...
Use view's function instead of its name
Use view's function instead of its name
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
e85e5ea6e2a8b188ff79d114ae0546c8d3ca4c73
examples/MNIST/mnist.py
examples/MNIST/mnist.py
import os import gzip import pickle import sys # Python 2/3 compatibility. try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve '''Adapted from theano tutorial''' def load_mnist(data_file = os.path.join(os.path.dirname(__file__), 'mnist.pkl.gz')): if not os.pa...
import os import gzip import pickle import sys # Python 2/3 compatibility. try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve '''Adapted from theano tutorial''' def load_mnist(data_file = os.path.join(os.path.dirname(__file__), 'mnist.pkl.gz')): if not os.pa...
Simplify code loading MNIST dataset.
Simplify code loading MNIST dataset.
Python
mit
VisualComputingInstitute/Beacon8,lucasb-eyer/DeepFried2,elPistolero/DeepFried2,yobibyte/DeepFried2,Pandoro/DeepFried2
6ce0b5fabd3573ac3c3feb30e8fb48af16d2504f
apps/users/tests/test_profile_admin.py
apps/users/tests/test_profile_admin.py
import fudge from django.test import TestCase, Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User from users.models import Profile, Link class ProfileAdmin(TestCase): def setUp(self): self.client = Client() self.User = User.objects.create( ...
from contextlib import contextmanager import fudge from django.test import TestCase, Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User from users.models import Profile, Link @contextmanager def given_user(fake_auth, user): """Context manager to respond to any login...
Fix the profile test to log in as the test user.
Fix the profile test to log in as the test user.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
bcfb29272d727ee2775c9f212053725e4a562752
pip_review/__init__.py
pip_review/__init__.py
from functools import partial import subprocess import requests import multiprocessing import json def get_pkg_info(pkg_name, session): r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,)) if r.status_code == requests.codes.ok: return json.loads(r.text) else: raise ValueErr...
from functools import partial import subprocess import urllib2 import multiprocessing import json def get_pkg_info(pkg_name): req = urllib2.Request('http://pypi.python.org/pypi/%s/json' % (pkg_name,)) handler = urllib2.urlopen(req) status = handler.getcode() if status == 200: content = handler...
Remove the requests dependency altogether.
Remove the requests dependency altogether. (Makes no sense for such small a tool.)
Python
bsd-2-clause
suutari-ai/prequ,suutari/prequ,suutari/prequ
f9f12e89e526b2645f013fc5856488d105a39d5a
bouncer/sentry.py
bouncer/sentry.py
"""Report exceptions to Sentry/Raven.""" from pyramid import tweens import raven from bouncer import __version__ def get_raven_client(request): """Return the Raven client for reporting crashes to Sentry.""" client = request.registry["raven.client"] client.http_context({ "url": request.url, ...
"""Report exceptions to Sentry/Raven.""" import os import raven from bouncer import __version__ def get_raven_client(request): """Return the Raven client for reporting crashes to Sentry.""" client = request.registry["raven.client"] client.http_context({ "url": request.url, "method": re...
Add environment name to Sentry client
Add environment name to Sentry client Skyliner provides the ENV environment variable for our application, which contains either "prod" or "qa" depending on the environment. Sentry supports partitioning reports based on the environment within a single application. Adding this metadata to the `Client` allows us to migr...
Python
bsd-2-clause
hypothesis/bouncer,hypothesis/bouncer,hypothesis/bouncer
79cb9edf45ed77cdaa851e45d71f10c69db41221
benchexec/tools/yogar-cbmc-parallel.py
benchexec/tools/yogar-cbmc-parallel.py
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer 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 ht...
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer 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 ht...
Add forgotten program file for deployment
Add forgotten program file for deployment
Python
apache-2.0
ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,dbeyer/benchexec,sosy-lab/benchexec
98f1df191febd889fcde861f94a9ca126c60ea37
tests/GIR/runalltests.py
tests/GIR/runalltests.py
# -*- Mode: Python -*- import os import glob import sys import shutil import unittest testLoader = unittest.TestLoader() names = [] for filename in glob.iglob("test_*.py"): names.append(filename[:-3]) names.sort() testSuite = testLoader.loadTestsFromNames(names) runner = unittest.TextTestRunner(verbosity=2) resu...
# -*- Mode: Python -*- import os import glob import sys import shutil import unittest if os.path.isfile("./test_data/test_gir.db"): os.remove("./test_data/test_gir.db") testLoader = unittest.TestLoader() names = [] for filename in glob.iglob("test_*.py"): names.append(filename[:-3]) names.sort() testSuite = t...
Remove SQLite database before running tests
Remove SQLite database before running tests
Python
lgpl-2.1
midgardproject/midgard-core,midgardproject/midgard-core,midgardproject/midgard-core,midgardproject/midgard-core
74dcf36c2eecab290c1c76c947b024e51d280ea7
tests/test_rover_init.py
tests/test_rover_init.py
def test_rover_init_with_default_parameters(): from rover import Rover rover = Rover() assert rover.x == 0 assert rover.y == 0 assert rover.direction == 'N' def test_rover_init_with_custom_parameters(): from rover import Rover rover = Rover(3, 7, 'W') assert rover.x == 3 assert rove...
def test_rover_init_with_default_parameters(): from rover import Rover rover = Rover() assert rover.x == 0 assert rover.y == 0 assert rover.direction == 'N' assert rover.grid_x == 50 assert rover.grid_y == 50 def test_rover_init_with_custom_parameters(): from rover import Rover rov...
Add testing for default grid_* values
Add testing for default grid_* values
Python
mit
authentik8/rover
cd189a5cbf8cbb567efaba0e92b3c31278817a39
pnrg/filters.py
pnrg/filters.py
from jinja2._compat import text_type import re def do_right(value, width=80): """Right-justifies the value in a field of a given width.""" return text_type(value).rjust(width) _LATEX_SUBS = ( (re.compile(r'\\'), r'\\textbackslash'), (re.compile(r'([{}_#%&$])'), r'\\\1'), (re.compile(r'~'), r'\~{}'...
from jinja2._compat import text_type import re def do_right(value, width=80): """Right-justifies the value in a field of a given width.""" return text_type(value).rjust(width) _LATEX_SUBS = ( (re.compile(r'\\'), r'\\textbackslash'), (re.compile(r'([{}_#%&$])'), r'\\\1'), (re.compile(r'~'), r'\~{}'...
Use Computer Modern for \LaTeX macro
Use Computer Modern for \LaTeX macro Source Sans pro (and most othe sans-serif fonts) render the LaTeX macro pretty weirdly, so the classic Computer Modern should be okay here. It may wind up being an odd contrast in an otherwise sans-serif document though, so this may eventually get reverted!
Python
mit
sjbarag/poorly-named-resume-generator,sjbarag/poorly-named-resume-generator