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 |
|---|---|---|---|---|---|---|---|---|---|
ce67500ec566784f6f8883e1ffcaef6ad768d810 | 2018/05/solve.py | 2018/05/solve.py | data = open("input.txt").read().strip()
import re
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.rep... | data = open("input.txt").read().strip()
import re
import string
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
d... | Fix bug with omitting v | Fix bug with omitting v
| Python | mit | lamperi/aoc,lamperi/aoc,lamperi/aoc,lamperi/aoc,lamperi/aoc |
c43ddf1f36535604167e496508d242a15c813496 | roamer/main.py | roamer/main.py | #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
... | #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
... | Fix references not available after pulling up two instances of roamer | Fix references not available after pulling up two instances of roamer
| Python | mit | abaldwin88/roamer |
2aef43fcd44f075ff718475ea57ae23711de02aa | event/models.py | event/models.py | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
def _... | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class... | Add Artist ordering by name | Add Artist ordering by name
| Python | mit | FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack |
aebc3440c98ee2b4cc5f880d648e106e1f9d6b9d | source/urls.py | source/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries'... | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.... | Add the base_name to the API routers for the custom query_set | Add the base_name to the API routers for the custom query_set
| Python | apache-2.0 | toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile |
a099eab75245005527e03fb5278a49a6d565c8f9 | wagtailstartproject/project_template/tests/test_selenium/test_pages.py | wagtailstartproject/project_template/tests/test_selenium/test_pages.py | from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
fixtures = ['basic_site.json']
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
... | from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_s... | Remove unnecessary fixtures attribute, already set by base class. | Remove unnecessary fixtures attribute, already set by base class.
| Python | mit | leukeleu/wagtail-startproject,leukeleu/wagtail-startproject |
104da4df7e0cd09d32457cf56fc00dc96fcdbdac | euler/p005.py | euler/p005.py | """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
"""
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
| """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
... | Replace deprecated fractions.gcd with Euclid's Algorithm | Replace deprecated fractions.gcd with Euclid's Algorithm
| Python | mit | 2Cubed/ProjectEuler |
740762be1565690f78111861afe3152bdab4fadc | tests/test_soi.py | tests/test_soi.py | import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self)... | import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self)... | Change unit test syntax for pandas > 0.12.0 compat | Change unit test syntax for pandas > 0.12.0 compat
| Python | bsd-3-clause | amacd31/bom_data_parser,amacd31/bom_data_parser |
638e6a0f5b906e9cf63d95728da328b24f506173 | ananas/default/__init__.py | ananas/default/__init__.py | __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
| __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
from .announce import AnnounceBot
| Add announcebot to default module root for ease of import | Add announcebot to default module root for ease of import
| Python | mit | Chronister/ananas |
de96fab9b84c66b1d3bc3c200713bb595bce81b3 | examples/chart_maker/my_chart.py | examples/chart_maker/my_chart.py | from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, co... | from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_presentation()
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
... | Expand on the Chart Maker example tests | Expand on the Chart Maker example tests
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase |
e4d271011ff352d4fa83c252739a71dc74a6c0d8 | packages/Python/lldbsuite/test/lang/swift/protocols/class_protocol/TestClassConstrainedProtocolArgument.py | packages/Python/lldbsuite/test/lang/swift/protocols/class_protocol/TestClassConstrainedProtocolArgument.py | """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
lldbinline.MakeInlineTest(__file__, globals())
| """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[decorators.skipUnlessDarwin])
| Mark a test relying on foundation as darwin only. | [SwiftLanguageRuntime] Mark a test relying on foundation as darwin only.
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb |
2ba4e34af7a1078d4c19d5f964df42d291f9862a | slaveapi/clients/pdu.py | slaveapi/clients/pdu.py | class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
| class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
| Mark PDUs as not implemented to avoid false positives in reboots. | Mark PDUs as not implemented to avoid false positives in reboots.
| Python | mpl-2.0 | lundjordan/slaveapi |
4115cee1aa913346d5495230a98a5e723de9f5ab | bilgisayfam/utils/encoding.py | bilgisayfam/utils/encoding.py | # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u... | # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u... | Make normalize lower case as well. | Make normalize lower case as well.
| Python | mit | tayfun/bilgisayfam,tayfun/bilgisayfam,tayfun/bilgisayfam |
18545c519c23e9463fa7558191552e69304dfef7 | blog/myblog/tests.py | blog/myblog/tests.py | import datetime
from django.test import TestCase
from django.utils import timezone
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Auth... | import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""... | Add test for article view | Add test for article view
| Python | mit | mileto94/Django-tutorial,mileto94/Django-tutorial |
897bbe8b4d70ca68fb0336774b8c549ed2fe4c3e | buildtools/cleanup-ghpages.py | buildtools/cleanup-ghpages.py | #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expec... | #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expec... | Remove greenkeeper directories from gh-pages | Remove greenkeeper directories from gh-pages
| Python | mit | camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo |
0e68fd50428ceaf53e00e22c11a45ec98185e738 | avocado/export/__init__.py | avocado/export/__init__.py | from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
... | from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
reg... | Replace exporter registry keys with short_name derivative | Replace exporter registry keys with short_name derivative
Fix #203
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
| Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado |
d55389580160c4585c131537c04c4045a38ea134 | fluxghost/http_server_base.py | fluxghost/http_server_base.py |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):... |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):... | Add auto select port function | Add auto select port function
| Python | agpl-3.0 | flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost |
ffdd11e7aeed179868618dd7b4666e5e149962b0 | solar/solar/core/handlers/__init__.py | solar/solar/core/handlers/__init__.py | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleT... | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleT... | Add lost handler for puppet | Add lost handler for puppet
| Python | apache-2.0 | loles/solar,openstack/solar,zen/solar,dshulyak/solar,loles/solar,loles/solar,CGenie/solar,torgartor21/solar,pigmej/solar,Mirantis/solar,torgartor21/solar,zen/solar,Mirantis/solar,pigmej/solar,loles/solar,openstack/solar,pigmej/solar,zen/solar,Mirantis/solar,Mirantis/solar,zen/solar,openstack/solar,CGenie/solar,dshulyak... |
d3beb067abca8a2c014ca8039556181881310392 | app/groups/utils.py | app/groups/utils.py | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard ... | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard ... | Switch to default mail from variable | Switch to default mail from variable
| Python | bsd-3-clause | nikdoof/test-auth |
0ffd3699fc696bca7d7bd1b35870aa66fb0598ef | lms/djangoapps/instructor_task/admin.py | lms/djangoapps/instructor_task/admin.py | """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import Instruct... | """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import Instructor... | Add ability to manually fail instructor tasks in batches. | Add ability to manually fail instructor tasks in batches.
When an InstructorTask is stuck in QUEUING (say if there was a
problem with celery), the support team needs to manually intervene
and mark the task as "FAILED" so that new tasks of that type can
be created for that course. This is usually done one at a time,
bu... | Python | agpl-3.0 | EDUlib/edx-platform,eduNEXT/edunext-platform,stvstnfrd/edx-platform,arbrandes/edx-platform,stvstnfrd/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,eduNEXT/edx-platform,edx/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform,angelapper/edx-platform,edx/ed... |
7e50594c47ff0f8fdaaa3c6fb3a7b6ec222fc9fa | hgallpaths.py | hgallpaths.py | # hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
... | # hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, *... | Update license header to reference BSD. | Update license header to reference BSD.
| Python | bsd-2-clause | keegancsmith/hgallpaths |
ca8263ecf33798acc01bb4a5f5aeb3d8005da026 | karmaworld/apps/users/views.py | karmaworld/apps/users/views.py | #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_... | #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_... | Fix to make user profile display | Fix to make user profile display
| Python | agpl-3.0 | FinalsClub/karmaworld,FinalsClub/karmaworld,FinalsClub/karmaworld,FinalsClub/karmaworld |
b0904677e9687932099406a38cc7cd8f7ba67573 | examples/cifar-autoencoder.py | examples/cifar-autoencoder.py | #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
... | #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
... | Access weights using new interface. | Access weights using new interface.
| Python | mit | chrinide/theanets,lmjohns3/theanets,devdoer/theanets |
c99c275e1304335d210054c3838dc4bfe1618ac9 | stl/__init__.py | stl/__init__.py |
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO... |
import stl.ascii
import stl.binary
from stl.types import Solid, Facet, Vector3d
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
d... | Make the types available in the main "stl" module. | Make the types available in the main "stl" module.
| Python | mit | ng110/python-stl,apparentlymart/python-stl,zachwick/python-stl |
43e6a2e3bf90f5edee214d1511a6805a67f79595 | stl/__init__.py | stl/__init__.py |
import stl.ascii
import stl.binary
def parse_ascii_file(file):
return stl.ascii.parse(file)
def parse_binary_file(file):
return stl.binary.parse(file)
def parse_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def parse_binary_string(data):
from Stri... |
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO... | Rename the reading functions "read_" rather than "parse_". | Rename the reading functions "read_" rather than "parse_".
"Parsing" is what they do internally, but "read" is a better opposite to
"write" and matches the name of the underlying raw file operation.
| Python | mit | apparentlymart/python-stl,zachwick/python-stl,ng110/python-stl |
dbe8d7a4f43521e7aeba8f2670e70ac91f40ec3c | enthought/mayavi/tests/test_mlab_scene_model.py | enthought/mayavi/tests/test_mlab_scene_model.py | """
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###########################################################... | """
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
#######################################... | Fix a failing test due to refactor | BUG: Fix a failing test due to refactor
| Python | bsd-3-clause | dmsurti/mayavi,liulion/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,liulion/mayavi |
2c4c527e6bb63f7db7a1c2d32f71b76fad65f92a | src/core/tests/test_callexplorer.py | src/core/tests/test_callexplorer.py | # Copyright (c) 2013 The SAYCBridge 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 unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):... | # Copyright (c) 2013 The SAYCBridge 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 unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):... | Add another test for CallExplorer.history_glob | Add another test for CallExplorer.history_glob
| Python | bsd-3-clause | abortz/saycbridge,eseidel/saycbridge,eseidel/saycbridge,abortz/saycbridge,abortz/saycbridge,eseidel/saycbridge,abortz/saycbridge,abortz/saycbridge |
a9b22b76203467ec63ce0592e32498cfecdedca3 | tests/config.py | tests/config.py | from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.co... | import sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
s... | Add the directory of the project module to system path | Add the directory of the project module to system path
| Python | mit | joausaga/ideascaly |
4f5b171b972b2255dfc3cdb8eea8b4a2745ae437 | centinel/backend.py | centinel/backend.py | import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
... | import os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
... | Send results to the server | Send results to the server
| Python | mit | rpanah/centinel,rpanah/centinel,lianke123321/centinel,JASONews/centinel,iclab/centinel,iclab/centinel,lianke123321/centinel,rpanah/centinel,iclab/centinel,Ashish1805/centinel,ben-jones/centinel,lianke123321/centinel |
392ee6bec1041730b9859e70b9abe9b28a012d45 | libs/__init__.py | libs/__init__.py | # Copyright 2015-2015 ARM Limited
#
# 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 w... | # Copyright 2015-2015 ARM Limited
#
# 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 w... | Add automodule sphinx directive for wlgen package | libs: Add automodule sphinx directive for wlgen package
| Python | apache-2.0 | credp/lisa,credp/lisa,ARM-software/lisa,credp/lisa,credp/lisa,ARM-software/lisa,ARM-software/lisa,ARM-software/lisa |
36c97aea9d3ea143f6a494c5f436ad7c0392cd6a | jsonsempai.py | jsonsempai.py | import sys
class SempaiLoader(object):
def __init__(self, *args):
print args
def find_module(self, fullname, path=None):
print 'finding', fullname, path
if fullname == 'simple':
return self
return None
sys.path_hooks.append(SempaiLoader)
sys.path.insert(0, 'simple'... | import os
import sys
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(json_path):
print json_path
return self
return None
def loa... | Add the import hook to sys.meta_path | Add the import hook to sys.meta_path
| Python | mit | kragniz/json-sempai |
2c2fef3b8cf52219ee6bb2196fe5d3c9f9ae4443 | tacyt_sdk/api_requests/tag_request.py | tacyt_sdk/api_requests/tag_request.py | """
This library offers an API to use Tacyt in a python environment.
Copyright (C) 2015-2020 Eleven Paths
"""
try:
import simplejson as json
except ImportError:
import json
class TagRequest(object):
LIST_REQUEST = "LIST"
CREATE_REQUEST = "CREATE"
REMOVE_REQUEST = "REMOVE"
REMOVE_ALL_REQUEST = ... | """
This library offers an API to use Tacyt in a python environment.
Copyright (C) 2015-2020 Eleven Paths
"""
try:
import simplejson as json
except ImportError:
import json
class TagRequest(object):
LIST_REQUEST = "LIST"
CREATE_REQUEST = "CREATE"
REMOVE_REQUEST = "REMOVE"
REMOVE_ALL_REQUEST = ... | Fix normalization of tags in case is None | Fix normalization of tags in case is None
| Python | lgpl-2.1 | ElevenPaths/tacyt-sdk-python |
522279e967a8864e4404c8d05536b3d418da521f | cellcounter/urls.py | cellcounter/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.contrib.auth.views import login, logout
from cellcounter.main.views import new_count, view_cou... | from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.contrib.auth.views import login, logout
from cellcounter.main.views import new_count, view_cou... | Use 'my_counts' as name for MyCountsListView | Use 'my_counts' as name for MyCountsListView
| Python | mit | cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcountr,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,oghm2/hackdayoxford,haematologic/cellcounter,oghm2/hackdayoxford,haematologic/cellcountr |
2e6df2a332217d0e3da225075807360fe230b600 | tools/po2js.py | tools/po2js.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os.path
import codecs
import dfstrings
import time
def make_js_from_po(path):
strings = []
for po in [p for p in dfstrings.get_po_strings(path) if "scope" in p and "dragonfly" in p["scope"] ]:
strings.append(u"""ui_strings.%s="%s";""... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os.path
import codecs
import dfstrings
import time
def make_js_from_po(path):
strings = []
for po in [p for p in dfstrings.get_po_strings(path) if "scope" in p and "dragonfly" in p["scope"] ]:
strings.append(u"""ui_strings.%s="%s";""... | Add the language code to the translated file | Add the language code to the translated file
| Python | apache-2.0 | runeh/dragonfly-stp-1,runeh/dragonfly-stp-1,runeh/dragonfly-stp-1 |
bc20e8d01dc154d45f9dfc8f2b610d415a40f253 | broadbean/__init__.py | broadbean/__init__.py | # flake8: noqa (ignore unused imports)
# Version 1.0
from . import ripasso
from .element import Element
from .segment import Segment
from .sequence import Sequence
from .blueprint import BluePrint
from .tools import makeVaryingSequence, repeatAndVarySequence
from .broadbean import PulseAtoms
| # flake8: noqa (ignore unused imports)
# Version 1.0
from . import ripasso
from .element import Element
from .sequence import Sequence
from .blueprint import BluePrint
from .tools import makeVaryingSequence, repeatAndVarySequence
from .broadbean import PulseAtoms
| Remove import of version 1.0 feature | Remove import of version 1.0 feature
| Python | mit | WilliamHPNielsen/broadbean |
52d7a26237cb1e594456127b775524596c3fb1ac | tests/test_barebones.py | tests/test_barebones.py | # -*- coding: utf-8 -*-
"""
Tests for the barebones example project
"""
import os
import py.path
from tarbell.app import EXCLUDES, TarbellSite
PATH = os.path.realpath('examples/barebones')
def test_get_site():
site = TarbellSite(PATH)
assert os.path.realpath(site.path) == os.path.realpath(PATH)
assert s... | # -*- coding: utf-8 -*-
"""
Tests for the barebones example project
"""
import os
import py.path
from tarbell.app import EXCLUDES, TarbellSite
PATH = os.path.realpath('examples/barebones')
def test_get_site():
site = TarbellSite(PATH)
assert os.path.realpath(site.path) == os.path.realpath(PATH)
assert s... | Test exclude equality with sets | Test exclude equality with sets
| Python | bsd-3-clause | tarbell-project/tarbell,eyeseast/tarbell,eyeseast/tarbell,tarbell-project/tarbell |
0f22d72aeb4fc872dfa1c5e75d40102c27cf2a8c | tabtranslator/model.py | tabtranslator/model.py | class sheet(object):
""" sheet: Top level object.
Models the entire music sheet """
def __init__(self, name):
super(sheet, self).__init__()
self.name = name
self.bars = list()
def add_bar(bar):
self.bars.append(bar)
class stave(sheet):
""" stave: sheet that is displayed in music theory representation... | class sheet(object):
""" sheet: Top level object.
Models the entire music sheet """
def __init__(self, name):
super(sheet, self).__init__()
self.name = name
self.bars = list()
class bar(object):
""" bar: Models a measure.
Compose the sheet as the temporal layer
=> Where the notes are displayed on the s... | CLEAN simplify useless dep and methods | CLEAN simplify useless dep and methods
| Python | mit | ograndedjogo/tab-translator,ograndedjogo/tab-translator |
ee5bd327bb3070277c87a96f72ca7e019c92f777 | publisher/build_paper.py | publisher/build_paper.py | #!/usr/bin/env python
import docutils.core as dc
from writer import writer
import os.path
import sys
import glob
preamble = '\n'.join([r'% PDF Standard Fonts',
r'\usepackage{mathptmx}',
r'\usepackage[scaled=.80]{helvet}',
r'\usepackage{courier}'],)
... | #!/usr/bin/env python
import docutils.core as dc
from writer import writer
import os.path
import sys
import glob
preamble = r'''
% These preamble commands are from build_paper.py
% PDF Standard Fonts
\usepackage{mathptmx}
\usepackage[scaled=.90]{helvet}
\usepackage{courier}
% Make verbatim environment smaller
\ma... | Update preamble: no indent on quote, smaller verbatim font size. | Update preamble: no indent on quote, smaller verbatim font size.
| Python | bsd-2-clause | dotsdl/scipy_proceedings,sbenthall/scipy_proceedings,juhasch/euroscipy_proceedings,chendaniely/scipy_proceedings,springcoil/euroscipy_proceedings,euroscipy/euroscipy_proceedings,mjklemm/euroscipy_proceedings,mikaem/euroscipy_proceedings,SepidehAlassi/euroscipy_proceedings,sbenthall/scipy_proceedings,katyhuff/scipy_proc... |
069d6085946a21c5e78621abf13fb60fd7eb4dcf | threadedcomments/migrations/0001_initial.py | threadedcomments/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations, connection
import django.db.models.deletion
is_index = connection.vendor != 'mysql'
class Migration(migrations.Migration):
dependencies = [
('django_comments', '__first__'),
]
operations =... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations, connection
import django.db.models.deletion
is_index = connection.vendor != 'mysql'
if 'django.contrib.comments' in settings.INSTALLED_APPS:
BASE_APP = 'comments'
else:
B... | Fix Django 1.7 migration support | Fix Django 1.7 migration support
| Python | bsd-3-clause | HonzaKral/django-threadedcomments,HonzaKral/django-threadedcomments |
de3722bdd4e5261ffe2ffd6264134ed51c131075 | src/test_dll.py | src/test_dll.py | """Testing dll.py."""
import pytest
@pytest.fixture
def new_dll():
"""Return empty dll."""
from dll import DoublyLinkedList
return DoublyLinkedList()
def test_init(new_dll):
"""Test initialization of empty doubly linked list."""
assert new_dll.head is None and new_dll.tail is None
def test_pus... | """Testing dll.py."""
import pytest
@pytest.fixture
def new_dll():
"""Return empty dll."""
from dll import DoublyLinkedList
return DoublyLinkedList()
def test_init(new_dll):
"""Test initialization of empty doubly linked list."""
assert new_dll.head is None and new_dll.tail is None
def test_pus... | Test for creating a new node | Test for creating a new node
| Python | mit | fordf/data-structures |
f1afd87c3a13fe47321c242d3586b1fa670125df | stationspinner/accounting/models.py | stationspinner/accounting/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
from django_pgjson.fields import JsonField
class Capsuler(AbstractUser):
settings = JsonField(blank=True, default={})
def __unicode__(self):
return self.username
def get_active_keys(self):
return APIKey.object... | from django.db import models
from django.contrib.auth.models import AbstractUser
from django_pgjson.fields import JsonField
class Capsuler(AbstractUser):
settings = JsonField(blank=True, default={})
def __unicode__(self):
return self.username
def get_active_keys(self):
return APIKey.obje... | Make it easier to use corporate keys | Make it easier to use corporate keys
| Python | agpl-3.0 | kriberg/stationspinner,kriberg/stationspinner |
5b7cd2f62bb86658b6fce7503a4fab9238b8faa5 | channelguide/init.py | channelguide/init.py | """Contains code needed to initialize channelguide. This should be run at
startup, before any real work starts.
"""
import locale
import logging
import logging.handlers
import random
import os
import sys
import traceback
from django.conf import settings
from django.core import signals
from django.dispatch import dis... | """Contains code needed to initialize channelguide. This should be run at
startup, before any real work starts.
"""
import locale
import logging
import logging.handlers
import random
import os
import sys
import traceback
from django.conf import settings
from django.core import signals
from django.dispatch import dis... | Fix for django trying to rollback connections on request exceptions. | Fix for django trying to rollback connections on request exceptions.
git-svn-id: 98eea730e22c7fb5f8b38c49248ce5c7e9bb5936@525 be7adf91-e322-0410-8f47-e6edb61c52aa
| Python | agpl-3.0 | kmshi/miroguide,kmshi/miroguide,kmshi/miroguide |
721f6f7916d698f22c9d96ce52cce3773fa514cc | uwsgiplugin.py | uwsgiplugin.py | import os
import os.path
import inspect
base_path = os.path.dirname(inspect.getframeinfo(inspect.currentframe())[0])
NAME = 'rust'
GCC_LIST = ['rust', '%s/plugin.a' % base_path]
CFLAGS = []
if os.uname()[0] == 'Darwin':
CFLAGS.append('-mmacosx-version-min=10.7')
if os.system("rustc -o %s/plugin.a --crate-type... | import os
import os.path
import inspect
base_path = os.path.dirname(inspect.getframeinfo(inspect.currentframe())[0])
NAME = 'rust'
GCC_LIST = ['rust', '%s/target/release/libuwsgi_rust.a' % base_path]
CFLAGS = []
if os.uname()[0] == 'Darwin':
CFLAGS.append('-mmacosx-version-min=10.7')
if os.system("cargo build ... | Update script to build rust code via cargo | Update script to build rust code via cargo
Signed-off-by: Luca Bruno <d11e81b0438fe9a6fbb85b72e5bb4c36a65f49c7@debian.org>
| Python | mit | unbit/uwsgi-rust,unbit/uwsgi-rust,unbit/uwsgi-rust |
692141042bd21bfd7d72567bdabf080304a48474 | planner/admin.py | planner/admin.py | from django.contrib import admin
from planner.models import Route, Waypoint, RoadTrip, TripDetail
class WaypointInline(admin.StackedInline):
model = Waypoint
extra = 1
class RouteAdmin(admin.ModelAdmin):
model = Route
inlines = [WaypointInline]
class RoadTripAdmin(admin.ModelAdmin):
model = R... | from django.contrib import admin
from planner.models import Route, Waypoint, RoadTrip, TripDetail
class WaypointInline(admin.StackedInline):
model = Waypoint
extra = 1
class RouteAdmin(admin.ModelAdmin):
model = Route
inlines = [WaypointInline]
class RoadTripAdmin(admin.ModelAdmin):
def route... | Add route waypoints to list display in Admin interface | Add route waypoints to list display in Admin interface
| Python | apache-2.0 | jwarren116/RoadTrip,jwarren116/RoadTrip,jwarren116/RoadTrip |
8351b73693019360c3f0ea3c60531ac13bef1c24 | structure/models.py | structure/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class Organization(models.Model):
name = models.CharField(_('Name'), max_length=80)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Team(... | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class Organization(models.Model):
name = models.CharField(_('Name'), max_length=80)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Team(... | Add name to User model. | Add name to User model.
| Python | bsd-3-clause | RocknRoot/LIIT |
38aed64e1c20d25a6bda750a096a513b7d414c45 | websod/views.py | websod/views.py | from werkzeug import redirect
from werkzeug.exceptions import NotFound
from websod.utils import session, expose, url_for, serve_template
from websod.models import Integration
from datetime import timedelta, datetime
@expose('/')
def home(request):
# show results from last 3 days
integrations_from = datetime.... | from werkzeug import redirect
from werkzeug.exceptions import NotFound
from websod.utils import session, expose, url_for, serve_template
from websod.models import Integration
from datetime import timedelta, datetime
def home(request):
# show results from last 3 days
integrations_from = datetime.now() + timed... | Set integrations for the index page now | Set integrations for the index page now
| Python | mit | schettino72/serveronduty |
291d6c51d545cb46117ff25a5a01da8e08e78127 | ynr/apps/sopn_parsing/management/commands/sopn_parsing_extract_tables.py | ynr/apps/sopn_parsing/management/commands/sopn_parsing_extract_tables.py | from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand
from sopn_parsing.helpers.extract_tables import extract_ballot_table
from sopn_parsing.helpers.text_helpers import NoTextInDocumentError
class Command(BaseSOPNParsingCommand):
help = """
Parse tables out of PDFs in to ParsedSOPN models fo... | from django.db.models import OuterRef, Subquery
from official_documents.models import OfficialDocument
from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand
from sopn_parsing.helpers.extract_tables import extract_ballot_table
from sopn_parsing.helpers.text_helpers import NoTextInDocumentError
class... | Fix query to exclude objects without relevant pages | Fix query to exclude objects without relevant pages
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
f812fa8f0df0f3b8c8bb56f446dd01f64cff5cae | wapps/migrations/0016_auto_20161024_0925.py | wapps/migrations/0016_auto_20161024_0925.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-24 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wapps', '0015_identitysettings_amp_logo'),
]
opera... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-24 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from wapps.utils import get_image_model
class Migration(migrations.Migration):
dependencies = [
('wapps', '0015_iden... | Fix image model in migration | Fix image model in migration
| Python | mit | apihackers/wapps,apihackers/wapps,apihackers/wapps,apihackers/wapps |
7d2d94d69797586860f7bb8c21a0b0e217fbc394 | components/mgmtworker/scripts/start.py | components/mgmtworker/scripts/start.py | #!/usr/bin/env python
from os.path import join, dirname
from cloudify import ctx
ctx.download_resource(
join('components', 'utils.py'),
join(dirname(__file__), 'utils.py'))
import utils # NOQA
MGMT_WORKER_SERVICE_NAME = 'mgmtworker'
CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create... | #!/usr/bin/env python
from os.path import join, dirname
from cloudify import ctx
ctx.download_resource(
join('components', 'utils.py'),
join(dirname(__file__), 'utils.py'))
import utils # NOQA
MGMT_WORKER_SERVICE_NAME = 'mgmtworker'
CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create... | Use the stored broker_config instead of working it out ourselves | Use the stored broker_config instead of working it out ourselves
Fixes SSL
Means we're verifying the config is written properly too
| Python | apache-2.0 | isaac-s/cloudify-manager-blueprints,Cloudify-PS/cloudify-manager-blueprints,cloudify-cosmo/cloudify-manager-blueprints,cloudify-cosmo/cloudify-manager-blueprints,isaac-s/cloudify-manager-blueprints,Cloudify-PS/cloudify-manager-blueprints |
d6fcedb2b479da20cbe061bcba52758a18a6ed0b | noweats/__init__.py | noweats/__init__.py | """
The NowEats application scrapes Twitter for what people are eating now.
"""
| """
The NowEats application scrapes Twitter for what people are eating now.
"""
import analysis
import collection
import extraction
| Add module imports to noweats init. | Add module imports to noweats init.
| Python | mit | blr246/noweats,blr246/noweats |
ed97a1f811f04693203f6d1c0e9b64649a3da152 | coney/exceptions.py | coney/exceptions.py |
class ConeyException(Exception):
def __repr__(self):
return 'An unspecified error has occurred'
class CallTimeoutException(ConeyException):
def __repr__(self):
return 'An RPC call did not return before the time out period'
class MalformedRequestException(ConeyException):
def __init__(s... |
class ConeyException(Exception):
def __repr__(self):
return 'An unspecified error has occurred'
class CallTimeoutException(ConeyException):
def __repr__(self):
return 'An RPC call did not return before the time out period'
class MalformedRequestException(ConeyException):
def __init__(s... | Add a new exception to handle a non-callable handler. | Add a new exception to handle a non-callable handler.
| Python | mit | cbigler/jackrabbit |
80ea1fd6dc5ad47a3689f64ebe6e639f037f7d20 | ln/backend/reduction.py | ln/backend/reduction.py | '''Functions that perform the different reduction strategies.'''
import numpy as np
def closest(times, values, center_time):
abs_delta = np.abs(np.array([(t - center_time).total_seconds()
for t in times]))
closest_index = np.argmin(abs_delta)
return values[closest_index]
def sum(times, values, c... | '''Functions that perform the different reduction strategies.'''
# Needed for get_total_seconds() implementation
from __future__ import division
import numpy as np
# Implementation for python 2.6
def get_total_sections(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
def clos... | Fix for Python 2.6 that lacks timedelta.total_seconds() | Fix for Python 2.6 that lacks timedelta.total_seconds()
| Python | bsd-2-clause | seibert/ln |
52b6dac7528232dfd41841f4697c7a78e2a2e675 | www/src/Lib/_weakref.py | www/src/Lib/_weakref.py | class ProxyType:
def __init__(self,obj):
self.obj = obj
CallableProxyType = ProxyType
ProxyTypes = [ProxyType,CallableProxyType]
class ReferenceType:
def __init__(self,obj,callback):
self.obj = obj
self.callback = callback
class ref:
def __init__(self,obj,callback=None):
... | class ProxyType:
def __init__(self,obj):
self.obj = obj
CallableProxyType = ProxyType
ProxyTypes = [ProxyType,CallableProxyType]
class ReferenceType:
def __init__(self,obj,callback):
self.obj = obj
self.callback = callback
class ref:
def __init__(self,obj,callback=None):
... | Add method __call__ to _weaksetref.WeakSet | Add method __call__ to _weaksetref.WeakSet
| Python | bsd-3-clause | olemis/brython,Lh4cKg/brython,molebot/brython,kikocorreoso/brython,Isendir/brython,Mozhuowen/brython,Isendir/brython,amrdraz/brython,Hasimir/brython,olemis/brython,firmlyjin/brython,JohnDenker/brython,olemis/brython,firmlyjin/brython,Mozhuowen/brython,jonathanverner/brython,molebot/brython,jonathanverner/brython,kevinm... |
7d3fd06884bc11b9e1c60250052a1abdb6e7d44d | pycassa/__init__.py | pycassa/__init__.py | from pycassa.columnfamily import *
from pycassa.columnfamilymap import *
from pycassa.types import *
from pycassa.index import *
from pycassa.pool import *
from pycassa.connection import *
from pycassa.system_manager import *
from pycassa.cassandra.ttypes import ConsistencyLevel,\
InvalidRequestException, NotFound... | from pycassa.columnfamily import *
from pycassa.columnfamilymap import *
from pycassa.types import *
from pycassa.index import *
from pycassa.pool import *
from pycassa.system_manager import *
from pycassa.cassandra.ttypes import ConsistencyLevel,\
InvalidRequestException, NotFoundException, UnavailableException,\... | Remove connection from pycassa package import | Remove connection from pycassa package import
| Python | mit | pycassa/pycassa,pycassa/pycassa |
3da2c4a83de97407c69b9144475441e9bb0a3073 | backdrop/write/config/development_tokens.py | backdrop/write/config/development_tokens.py | TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token'
}
| TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'licensing_journey': 'licensing_journey-bearer-token'
}
| Add dev token for licensing_journey bucket | Add dev token for licensing_journey bucket
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop |
966c8e549e1cb78c64ad2f359162bc5a2171a732 | fabfile.py | fabfile.py | from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd(... | from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd(... | Add push task (but not use it yet) | Add push task (but not use it yet)
| Python | mit | zkan/puppet-untitled-2016,zkan/puppet-untitled-2016 |
23540359422501ebd8a1b833c426cdfb1a3dfe00 | fabfile.py | fabfile.py | # -*- coding: UTF-8 -*-
from fabric.api import *
def move_sampledocs_to_fixture():
local("cp fs_doc/fixtures/foreskrift/*.pdf uploads/foreskrift/")
local("cp fs_doc/fixtures/bilaga/*.pdf uploads/bilaga/")
local("cp fs_doc/fixtures/allmanna_rad/*.pdf uploads/allmanna_rad/")
def clean_db():
local("r... | # -*- coding: UTF-8 -*-
from fabric.api import *
def move_sampledocs_to_fixture():
local("mkdir -p uploads/foreskrift")
local("rm -f uploads/foreskrift/*.pdf")
local("cp fs_doc/fixtures/foreskrift/*.pdf uploads/foreskrift/")
local("mkdir -p uploads/bilaga")
local("rm -f uploads/bilaga/*.pdf")
... | Add new fixture to fabric script | Add new fixture to fabric script
| Python | bsd-3-clause | kamidev/autobuild_fst,kamidev/autobuild_fst,rinfo/fst,rinfo/fst,kamidev/autobuild_fst,rinfo/fst,kamidev/autobuild_fst,rinfo/fst |
b13494292bc8cc42783db1e4500a525a0e457222 | dashboard_app/tests/__init__.py | dashboard_app/tests/__init__.py | """
Package with all tests for dashboard_app
"""
import unittest
from testscenarios.scenarios import generate_scenarios
TEST_MODULES = [
'models.attachment',
'models.bundle',
'models.bundle_stream',
'models.hw_device',
'models.named_attribute',
'models.sw_package',
'models.test',
'mod... | """
Package with all tests for dashboard_app
"""
import unittest
from testscenarios.scenarios import generate_scenarios
TEST_MODULES = [
'models.attachment',
'models.bundle',
'models.bundle_stream',
'models.hw_device',
'models.named_attribute',
'models.sw_package',
'models.test',
'mod... | Add reference to csrf tests in tests loader list | Add reference to csrf tests in tests loader list
| Python | agpl-3.0 | OSSystems/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server |
fa5f9ad96c52d5977913a4e8c41c0ec0bd2214f1 | coheoka/utils.py | coheoka/utils.py | # -*- coding: utf-8 -*-
'''
Preprocessing utilities
'''
from nltk import sent_tokenize
from random import shuffle, sample
def shuffle_sents(text, times):
sents = sent_tokenize(text)
res = []
for i in range(times):
shuffle(sents)
res.append(' '.join(sents))
return res
def remove_sents... | # -*- coding: utf-8 -*-
'''
Preprocessing utilities
'''
from random import shuffle, sample
from nltk import sent_tokenize
from scipy.stats import kendalltau as tau
def shuffle_sents(text, times):
sents = sent_tokenize(text)
res = []
for i in range(times):
shuffle(sents)
res.append(' '.jo... | Add util function to score sentences with kendall's tau | Add util function to score sentences with kendall's tau
| Python | apache-2.0 | kigawas/coheoka |
7c8a90a6bc0a51788966b0035bc97b24a6680611 | populous/cli.py | populous/cli.py | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
... | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError, BackendError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickExceptio... | Add a CLI command for Postgres backend | Add a CLI command for Postgres backend
| Python | mit | novafloss/populous |
c25e735216dd1969ed09d24fcca9eaafe1dc8405 | Lib/__init__.py | Lib/__init__.py | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | Put numpy namespace in scipy for backward compatibility... | Put numpy namespace in scipy for backward compatibility...
| Python | bsd-3-clause | Newman101/scipy,kleskjr/scipy,mikebenfield/scipy,njwilson23/scipy,giorgiop/scipy,mikebenfield/scipy,Stefan-Endres/scipy,trankmichael/scipy,argriffing/scipy,ilayn/scipy,anntzer/scipy,rmcgibbo/scipy,ortylp/scipy,zerothi/scipy,raoulbq/scipy,mtrbean/scipy,sargas/scipy,newemailjdm/scipy,felipebetancur/scipy,ales-erjavec/sci... |
53b8c8efcef4c419c06197365448cc271a5f6aef | Lib/test/test_pep3120.py | Lib/test/test_pep3120.py | # This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import support
class PEP3120Test(unittest.TestCase):
def test_pep3120(self):
self.assertEqual(
"Питон".encode("utf-8"),
b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
... | # This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import support
class PEP3120Test(unittest.TestCase):
def test_pep3120(self):
self.assertEqual(
"Питон".encode("utf-8"),
b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
... | Make the exception message check for malformed UTF-8 source looser so that SyntaxError triggered from UnicodeDecodeError is also acceptable. | Make the exception message check for malformed UTF-8 source looser so that SyntaxError triggered from UnicodeDecodeError is also acceptable.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
e3f6be6f2ce00e335ebc4d17ff6b89f230dc34fa | rotor.py | rotor.py | """
Rotor model using mbwind
"""
from numpy import pi, dot
from mbwind import rotations, RigidConnection, RigidBody
from mbwind.elements.modal import ModalElementFromFE
class Rotor(object):
def __init__(self, num_blades, root_length, blade_fe):
self.num_blades = num_blades
self.root_length = root_... | """
Rotor model using mbwind
"""
from numpy import pi, dot
from mbwind import rotations, RigidConnection, RigidBody, Hinge
from mbwind.elements.modal import ModalElementFromFE
class Rotor(object):
def __init__(self, num_blades, root_length, blade_fe, pitch=False):
self.num_blades = num_blades
self... | Test step change in pitch in aeroelastic simulation | Test step change in pitch in aeroelastic simulation
| Python | mit | ricklupton/py-bem |
9ddbc2c319993a1084317f9af8796f25211c6d33 | sample-client.py | sample-client.py | import zlib
import zmq
import simplejson
import sys
def main():
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.connect('tcp://localhost:9500')
subscriber.setsockopt(zmq.SUBSCRIBE, "")
while True:
market_json = zlib.decompress(subscriber.recv())
market_data... | import zlib
import zmq
import simplejson
import sys
def main():
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.connect('tcp://firehose.elite-market-data.net:9500')
subscriber.setsockopt(zmq.SUBSCRIBE, "")
while True:
market_json = zlib.decompress(subscriber.recv()... | Use official URL for sample client. | Use official URL for sample client.
| Python | bsd-2-clause | andreas23/emdn |
198f6b0e0a98d0f5ef34d1aec44d5e9704d2cae9 | urllib3/__init__.py | urllib3/__init__.py | # urllib3/__init__.py
# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
urllib3 - Thread-safe connection pooling and re-using.
"""
__author__ = "Andrey Petrov (a... | # urllib3/__init__.py
# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
urllib3 - Thread-safe connection pooling and re-using.
"""
__author__ = "Andrey Petrov (a... | Set default logging level to ERROR, to avoid excessive "No handlers could be found" messages. | Set default logging level to ERROR, to avoid excessive "No handlers could be found" messages.
| Python | mit | Lukasa/urllib3,Geoion/urllib3,msabramo/urllib3,mikelambert/urllib3,haikuginger/urllib3,tutumcloud/urllib3,haikuginger/urllib3,luca3m/urllib3,boyxuper/urllib3,Lukasa/urllib3,sornars/urllib3,Geoion/urllib3,mikelambert/urllib3,tutumcloud/urllib3,gardner/urllib3,msabramo/urllib3,matejcik/urllib3,asmeurer/urllib3,urllib3/ur... |
fd297665f1cb95ba3e8e069a18a9e8af18b449c8 | socketio/sdjango.py | socketio/sdjango.py | import logging
from socketio import socketio_manage
from django.conf.urls import patterns, url, include
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
SOCKETIO_NS = {}
class namespace(object):
def __init__(self, name=''):
self.name = name
def __call__(self... | import logging
from socketio import socketio_manage
from django.conf.urls import patterns, url, include
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
SOCKETIO_NS = {}
class namespace(object):
def __init__(self, name=''):
self.name = name
def __call__(sel... | Return namespace class after decorating. | Return namespace class after decorating.
| Python | bsd-3-clause | smurfix/gevent-socketio,abourget/gevent-socketio,kazmiruk/gevent-socketio,arnuschky/gevent-socketio,bobvandevijver/gevent-socketio,hzruandd/gevent-socketio,yacneyac/gevent-socketio,Eugeny/gevent-socketio,theskumar-archive/gevent-socketio,arnuschky/gevent-socketio,kazmiruk/gevent-socketio,theskumar-archive/gevent-socket... |
0a300314c0fae8420db1aa773e4ec8c96fca1cf5 | setup.py | setup.py | from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np
# To compile and install locally run "python setup.py build_ext --inplace"
# To install library to Python site-packages run "python setup.py build_ext install"
ext_modules = [
Extension... | from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np
import sys
# To compile and install locally run "python setup.py build_ext --inplace"
# To install library to Python site-packages run "python setup.py build_ext install"
extra_compile_args... | Make it compile on windows | Make it compile on windows | Python | mit | matteorr/coco-analyze,matteorr/coco-analyze,matteorr/coco-analyze |
e9fe645af28bd93a6ee2b38184254c8295b70d3d | sn.py | sn.py | import tables as tb
hdf5_filename = 'hdf5/sn_data.h5'
class SN(object):
"""A supernova is the explosion that ends the life of a star
The SN needs to be conatained within the HDF5 database before it is used
by SNoBoL. Once there, simply create a supernova by calling the constructor
with the name of the... | import tables as tb
hdf5_filename = 'hdf5/sn_data.h5'
class SN(object):
"""A supernova is the explosion that ends the life of a star
The SN needs to be conatained within the HDF5 database before it is used
by SNoBoL. Once there, simply create a supernova by calling the constructor
with the name of the... | Add method to check for the SN in the HDF5 file | Add method to check for the SN in the HDF5 file
| Python | mit | JALusk/SuperBoL,JALusk/SNoBoL,JALusk/SNoBoL |
0524a403bb2d4d26f28f535bcadcfc3fdd0a9484 | hr_attendance_calendar/__manifest__.py | hr_attendance_calendar/__manifest__.py | # -*- coding: utf-8 -*-
# © 2016 Coninckx David (Open Net Sarl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Attendance - Calendar',
'summary': 'Compute extra hours based on attendances',
'category': 'Human Resources',
'author': "CompassionCH, Open Net Sàrl",
'depends'... | # -*- coding: utf-8 -*-
# © 2016 Coninckx David (Open Net Sarl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Attendance - Calendar',
'summary': 'Compute extra hours based on attendances',
'category': 'Human Resources',
'author': "CompassionCH, Open Net Sàrl",
'depends'... | FIX - remove inconsistent dependence | FIX - remove inconsistent dependence
| Python | agpl-3.0 | maxime-beck/compassion-modules,ecino/compassion-modules,eicher31/compassion-modules,maxime-beck/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,maxime-beck/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,C... |
a0907ff742c81b676f602d1e17d820152f95d22e | django_docs/urls.py | django_docs/urls.py | from django.conf.urls import patterns, url, include
from docs.sitemaps import DocsSitemap
from docs.urls import urlpatterns as docs_urlpatterns
sitemaps = {'docs': DocsSitemap}
urlpatterns = patterns('',
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
) + docs_urlpatterns... | from django.conf.urls import patterns, url, include
from django.http import HttpResponse
from docs.sitemaps import DocsSitemap
from docs.urls import urlpatterns as docs_urlpatterns
sitemaps = {'docs': DocsSitemap}
urlpatterns = docs_urlpatterns + patterns('',
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views... | Add validation URL for Google Webmaster Tools. | Add validation URL for Google Webmaster Tools.
| Python | bsd-3-clause | hassanabidpk/djangoproject.com,hassanabidpk/djangoproject.com,gnarf/djangoproject.com,rmoorman/djangoproject.com,vxvinh1511/djangoproject.com,rmoorman/djangoproject.com,nanuxbe/django,vxvinh1511/djangoproject.com,relekang/djangoproject.com,alawnchen/djangoproject.com,rmoorman/djangoproject.com,django/djangoproject.com,... |
d1b7b629218830e4b7c584fc1c0804a3b9ee553a | src/vault.py | src/vault.py | from fabric.api import task, local
from buildercore import project
import utils
import sys
import logging
LOG = logging.getLogger(__name__)
def vault_addr():
defaults, _ = project.raw_project_map()
return defaults['aws']['vault']['address']
def vault_policy():
return 'builder-user'
@task
def login():
... | from fabric.api import task, local
from buildercore import project
import utils
import sys
import logging
LOG = logging.getLogger(__name__)
def vault_addr():
defaults, _ = project.raw_project_map()
return defaults['aws']['vault']['address']
def vault_policy():
return 'builder-user'
@task
def login():
... | Add warning about root token necessity | Add warning about root token necessity
| Python | mit | elifesciences/builder,elifesciences/builder |
a39b7b2b9b0c9179d3aedcc29286cdcebf568d54 | tests.py | tests.py | #!/usr/bin/env python
'''
Copyright 2009 Slide, Inc.
'''
import unittest
import pyecc
DEFAULT_DATA = 'This message will be signed\n'
DEFAULT_SIG = '$HPI?t(I*1vAYsl$|%21WXND=6Br*[>k(OR9B!GOwHqL0s+3Uq'
DEFAULT_PUBKEY = '8W;>i^H0qi|J&$coR5MFpR*Vn'
DEFAULT_PRIVKEY = 'my private key'
class ECC_Verify_Tests(unittest... | #!/usr/bin/env python
'''
Copyright 2009 Slide, Inc.
'''
import unittest
import pyecc
DEFAULT_DATA = 'This message will be signed\n'
DEFAULT_SIG = '$HPI?t(I*1vAYsl$|%21WXND=6Br*[>k(OR9B!GOwHqL0s+3Uq'
DEFAULT_PUBKEY = '8W;>i^H0qi|J&$coR5MFpR*Vn'
DEFAULT_PRIVKEY = 'my private key'
class ECC_Verify_Tests(unittest... | Implement a bad sig test | Implement a bad sig test
| Python | lgpl-2.1 | rtyler/PyECC,slideinc/PyECC,rtyler/PyECC,slideinc/PyECC |
109b753c807dae30ee736a6f071a058fa8b68d92 | tests/scoring_engine/web/views/test_services.py | tests/scoring_engine/web/views/test_services.py | from tests.scoring_engine.web.web_test import WebTest
class TestServices(WebTest):
def test_auth_required_services(self):
self.verify_auth_required('/services')
def test_auth_required_service_id(self):
self.verify_auth_required('/service/1')
| from tests.scoring_engine.web.web_test import WebTest
from tests.scoring_engine.helpers import generate_sample_model_tree
class TestServices(WebTest):
def set_team_color(self, team, color):
team.color = color
self.session.add(team)
self.session.commit()
def set_blue_team(self, team):... | Update tests for services view | Update tests for services view
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
ccf4ceab6fafb6f32668500f913eb256106bcc34 | test/integration/console_scripts_test.py | test/integration/console_scripts_test.py | """Test the PUDL console scripts from within PyTest."""
import pytest
@pytest.mark.parametrize(
"script_name", [
"pudl_setup",
"pudl_datastore",
"ferc1_to_sqlite",
"pudl_etl",
"datapkg_to_sqlite",
"epacems_to_parquet",
"pudl_territories",
])
@pytest.mar... | """Test the PUDL console scripts from within PyTest."""
import pkg_resources
import pytest
# Obtain a list of all deployed entry point scripts to test:
PUDL_SCRIPTS = [
ep.name for ep in pkg_resources.iter_entry_points('console_scripts')
if ep.module_name.startswith("pudl")
]
@pytest.mark.parametrize("scrip... | Automate generation of list of console scripts to test. | Automate generation of list of console scripts to test.
| Python | mit | catalyst-cooperative/pudl,catalyst-cooperative/pudl |
ea6a84cee4f452f4503c6ce0fdd04b77d9017bdd | tinyblog/management/commands/import_tinyblog.py | tinyblog/management/commands/import_tinyblog.py | from django.core.management.base import BaseCommand, CommandError
from django.core import serializers
import requests
from tinyblog.models import Post
class Command(BaseCommand):
args = 'url'
help = u'Fetches blog entries from <url>, and loads them into tinyblog.'
def handle(self, *args, **options):
... | from django.core.management.base import BaseCommand, CommandError
from django.core import serializers
import requests
from requests import exceptions
from tinyblog.models import Post
class Command(BaseCommand):
args = 'url'
help = u'Fetches blog entries from <url>, and loads them into tinyblog.'
def hand... | Fix for bad URL schemes | Fix for bad URL schemes
| Python | bsd-3-clause | dominicrodger/tinyblog,dominicrodger/tinyblog |
09d33da8657ec4c86855032f5ae16566c12fc2a5 | l10n_br_coa/models/l10n_br_account_tax_template.py | l10n_br_coa/models/l10n_br_account_tax_template.py | # Copyright 2020 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create... | # Copyright 2020 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create... | Create account.tax.template with external ids | [ADD] Create account.tax.template with external ids
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil |
e745cbd16cd2eef2a5805aa7bd113bcaf147af4e | waterfall_wall/serializers.py | waterfall_wall/serializers.py | from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Image
fields = ('path', 'url', 'nude_percent')
| from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
... | Correct the url format of image API | Correct the url format of image API
| Python | mit | carlcarl/rcard,carlcarl/rcard |
35c97d14eede0e48a0daff8e7f04aeba09f02268 | get.py | get.py |
from requests import get
from bs4 import BeautifulSoup as BS
from os.path import exists
url = "https://www.projecteuler.net/problem=%d"
def get_info(i):
soup = BS(get(url % i, verify=False).content)
problem = soup.find(id="content")
title = problem.h2.string
content = problem.find(class_="problem_co... |
from requests import get
from bs4 import BeautifulSoup as BS
from os.path import exists
from multiprocessing import Pool
url = "https://www.projecteuler.net/problem=%d"
def get_info(i):
soup = BS(get(url % i, verify=False).content)
problem = soup.find(id="content")
title = problem.h2.string
content ... | Use multiprocessing.Pool to speed up | Use multiprocessing.Pool to speed up
| Python | mit | zlsun/ProjectEuler |
eddd7f856c7dc423c387d496a87cf5fdf941215b | helpers/visited_thread_set.py | helpers/visited_thread_set.py |
class VisitedThreadSet():
set = None
def __init__(self):
pass
def load(self):
pass
def save(self):
pass
def add_thread(self):
pass
def check_thread_exists(self):
pass
|
class VisitedThreadSet():
set = None
def __init__(self):
self.set = set()
def load_set(self):
pass
def save_set(self):
pass
def add(self, value):
self.set.add(str(value))
def contains(self, value):
if str(value) in self.set:
return True
... | Add value to VisitedThreadSet or check if it exists | New: Add value to VisitedThreadSet or check if it exists
| Python | mit | AFFogarty/SEP-Bot,AFFogarty/SEP-Bot |
25bfdfccc89c8150ea8bc4a024415861808d4a6e | fabfile/__init__.py | fabfile/__init__.py | """
Fabric's own fabfile.
"""
from __future__ import with_statement
import nose
from fabric.api import *
import docs, tag
from utils import msg
@task(default=True)
def test(args=None):
"""
Run all unit tests and doctests.
Specify string argument ``args`` for additional args to ``nosetests``.
"""
... | """
Fabric's own fabfile.
"""
from __future__ import with_statement
import nose
from fabric.api import *
import docs, tag
from utils import msg
@task(default=True)
def test(args=None):
"""
Run all unit tests and doctests.
Specify string argument ``args`` for additional args to ``nosetests``.
"""
... | Fix test runner to exit correctly. | Fix test runner to exit correctly.
The attempt at catching ImportError-driven exits seemed broken, so nuked it. Bah.
| Python | bsd-2-clause | fernandezcuesta/fabric,xLegoz/fabric,tolbkni/fabric,askulkarni2/fabric,hrubi/fabric,StackStorm/fabric,cgvarela/fabric,bitprophet/fabric,mathiasertl/fabric,jaraco/fabric,cmattoon/fabric,rbramwell/fabric,rodrigc/fabric,rane-hs/fabric-py3,MjAbuz/fabric,bitmonk/fabric,kmonsoor/fabric,tekapo/fabric,sdelements/fabric,qinrong... |
72870bfe77e7e8669cc4ed46e112e0710dabc609 | Koko/views.py | Koko/views.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import render_template
from base import app
@app.route('/', methods = ['GET'])
@app.route('/koko', methods = ['GET'])
def start():
''' Returns a landing page. '''
return render_template('start.html')
| #!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
from hashlib import md5
from flask import request, render_template, Response
from base import app, cache
@app.route('/', methods = ['GET'])
@app.route('/koko', methods = ['GET'])
def start():
''' Returns a landing page. '''
return render_template('start.ht... | Add a wrapper route to LLTK-RESTful | Add a wrapper route to LLTK-RESTful
| Python | agpl-3.0 | lltk/Koko,lltk/Koko |
a20fc95d3a4dc194ef4f6d227976ff5bba229aaa | feincms/__init__.py | feincms/__init__.py | VERSION = (1, 4, 2)
__version__ = '.'.join(map(str, VERSION))
class LazySettings(object):
def _load_settings(self):
from feincms import default_settings
from django.conf import settings as django_settings
for key in dir(default_settings):
if not key.startswith(('FEINCMS_', '_H... | VERSION = (1, 4, 2)
__version__ = '.'.join(map(str, VERSION))
class LazySettings(object):
def _load_settings(self):
from feincms import default_settings
from django.conf import settings as django_settings
for key in dir(default_settings):
if not (key.startswith('FEINCMS_') or ... | Fix a Python 2.4 incompatibility that snuck in | Fix a Python 2.4 incompatibility that snuck in
Fixes github issue #214
| Python | bsd-3-clause | matthiask/django-content-editor,nickburlett/feincms,matthiask/django-content-editor,matthiask/feincms2-content,michaelkuty/feincms,matthiask/feincms2-content,pjdelport/feincms,mjl/feincms,joshuajonah/feincms,matthiask/django-content-editor,feincms/feincms,nickburlett/feincms,nickburlett/feincms,mjl/feincms,joshuajonah/... |
169d5b56ab5936a785ae501a91005fcfe3af6674 | ibmcnx/test/test.py | ibmcnx/test/test.py | #import ibmcnx.test.loadFunction
import sys
from java.lang import String
from java.util import HashSet
from java.util import HashMap
import java
import lotusConnectionsCommonAdmin
globdict = globals()
def loadFilesService():
global globdict
execfile( "filesAdmin.py", globdict )
ibmcnx.test.loadFunction.loadF... | #import ibmcnx.test.loadFunction
import sys
from java.lang import String
from java.util import HashSet
from java.util import HashMap
import java
import lotusConnectionsCommonAdmin
globdict = globals()
def loadFilesService():
global globdict
execfile( "filesAdmin.py", globdict )
loadFilesService()
FilesPolic... | Customize scripts to work with menu | Customize scripts to work with menu
| Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
d7ca978c696deb13c53fc3fdc9d227d0836b97f8 | test/data/testCC.py | test/data/testCC.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Test coupled cluster logfiles"""
import os
import unittest
import numpy
__filedir__ = os.path.realpath(os.path.dirna... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Test coupled cluster logfiles"""
import os
import unittest
import numpy
__filedir__ = os.path.realpath(os.path.dirna... | Test size and shape of ccenergies | Test size and shape of ccenergies
| Python | bsd-3-clause | berquist/cclib,berquist/cclib,cclib/cclib,ATenderholt/cclib,ATenderholt/cclib,langner/cclib,cclib/cclib,berquist/cclib,cclib/cclib,langner/cclib,langner/cclib |
16acf6dba180d17b142e5799f62e59a2771099fa | numscons/checkers/__init__.py | numscons/checkers/__init__.py | from blas_lapack_checkers import CheckCLAPACK, CheckCBLAS, CheckF77BLAS, CheckF77LAPACK
from fft_checkers import CheckFFT
from simple_check import NumpyCheckLibAndHeader
from perflib import *
from fortran import *
from perflib_info import write_info
import blas_lapack_checkers
import fft_checkers
import perflib
imp... | from blas_lapack_checkers import CheckCLAPACK, CheckCBLAS, CheckF77BLAS, CheckF77LAPACK
from fft_checkers import CheckFFT
from simple_check import NumpyCheckLibAndHeader
from perflib import *
from fortran import *
from perflib_info import write_info
import blas_lapack_checkers
import fft_checkers
import perflib
imp... | Add fortran module import to numscons top level namespace. | Add fortran module import to numscons top level namespace. | Python | bsd-3-clause | cournape/numscons,cournape/numscons,cournape/numscons |
80cecb69170adf7235ecbff3eec4e737cf5d9292 | impersonate/urls.py | impersonate/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('impersonate.views',
url(r'^stop/$',
'stop_impersonate',
name='impersonate-stop'),
url(r'^list/$',
'list_users',
{'template': 'impersonate/list_users.html'},
name='impersonate-list... | # -*- coding: utf-8 -*-
from django.conf.urls import url
from .views import stop_impersonate, list_users, search_users, impersonate
urlpatterns = [
url(r'^stop/$',
stop_impersonate,
name='impersonate-stop'),
url(r'^list/$',
list_users,
{'template': 'impersonate/list_users.html... | Replace deprecated string view arguments to url | Replace deprecated string view arguments to url
| Python | bsd-3-clause | Top20Talent/django-impersonate,Top20Talent/django-impersonate |
1e04152b69f88f6512920db8ccdd9ba2f0201517 | geotrek/api/mobile/urls.py | geotrek/api/mobile/urls.py | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import url, include
from rest_framework import routers
if 'geotrek.flatpages' and 'geotrek.trekking' and 'geotrek.tourism':
from geotrek.api.mobile import views as api_mobile
router = routers.DefaultRouter()
ur... | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import url, include
from rest_framework import routers
if 'geotrek.flatpages' and 'geotrek.trekking' and 'geotrek.tourism' in settings.INSTALLED_APPS:
from geotrek.api.mobile import views as api_mobile
router = rou... | Fix api mobile only with geotrek flatpages trekking tourism | Fix api mobile only with geotrek flatpages trekking tourism
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin |
3166d48bed0bd7663a3332736a236d8f424b6cd3 | room/views.py | room/views.py | from .models import Room
from rest_framework import viewsets
from .serializers import RoomDetailSerializer, RoomListSerializer
from rest_framework.decorators import detail_route
from django.core.exceptions import PermissionDenied
from rest_framework.exceptions import ParseError
from rest_framework.response import Respo... | from .models import Room
from rest_framework import viewsets
from .serializers import RoomDetailSerializer, RoomListSerializer
from rest_framework.decorators import detail_route
from django.core.exceptions import PermissionDenied
from rest_framework.exceptions import ParseError
from rest_framework.response import Respo... | Check hub permission @ report_availability | Check hub permission @ report_availability
| Python | mit | iver56/useat-api |
71fd42a92b41529d9f5c784840ab4c190946adef | social_auth/backends/pipeline/associate.py | social_auth/backends/pipeline/associate.py | from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from social_auth.utils import setting
from social_auth.models import UserSocialAuth
from social_auth.backends.pipeline import warn_setting
from social_auth.backends.exceptions import AuthException
def associate_by_email(details, user=None... | from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from social_auth.utils import setting
from social_auth.models import UserSocialAuth
from social_auth.backends.pipeline import warn_setting
from social_auth.backends.exceptions import AuthException
def associate_by_email(details, user=None... | Remove spammy warning which doesn't apply when stores check emails | Remove spammy warning which doesn't apply when stores check emails
| Python | bsd-3-clause | antoviaque/django-social-auth-norel |
6811b04a0a2e311fc2d014cd601da61a2f17a451 | sell/views.py | sell/views.py | from django.core.urlresolvers import reverse
from django.forms import model_to_dict
from django.http.response import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from common.models import Student
from sell.forms import PersonalDataForm
def index(request):
return HttpResponseRedirect(re... | from django.core.urlresolvers import reverse
from django.forms import model_to_dict
from django.http.response import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from common.models import Student
from sell.forms import PersonalDataForm
def index(request):
return HttpResponseRedirect(re... | Fix KeyError in Provide personal data form | Fix KeyError in Provide personal data form
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda |
9a5d2a6f9efefb5b1647de5e467a9dfb74b86c9b | buffpy/tests/test_link.py | buffpy/tests/test_link.py | from nose.tools import eq_
from mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
'''
Test link's shares retrieving from constructor
'''
mocked_api = MagicMock()
mocked_api.get.return_value = {'shares': 123}
link = Link(api=mocked_api, url='www.google.com')
eq_(link... | from unittest.mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
""" Test link"s shares retrieving from constructor. """
mocked_api = MagicMock()
mocked_api.get.return_value = {"shares": 123}
link = Link(api=mocked_api, url="www.google.com")
assert link["shares"... | Migrate link tests to pytest | Migrate link tests to pytest
| Python | mit | vtemian/buffpy |
7989252dd687dfaa1fd12ed8900c947190bfe4f7 | ichnaea/cache.py | ichnaea/cache.py | import redis
import urlparse
def redis_client(redis_url):
r_url = urlparse.urlparse(redis_url)
r_host = r_url.netloc.split(":")[0]
r_port = int(r_url.netloc.split(":")[1])
r_db = int(r_url.path[1:])
pool = redis.ConnectionPool(
max_connections=100,
socket_timeout=10.0,
sock... | import redis
import urlparse
def redis_client(redis_url):
r_url = urlparse.urlparse(redis_url)
r_host = r_url.netloc.split(":")[0]
r_port = int(r_url.netloc.split(":")[1])
r_db = int(r_url.path[1:])
pool = redis.ConnectionPool(
max_connections=100,
host=r_host,
port=r_port,... | Set redis connection info on the right class (the pool). | Set redis connection info on the right class (the pool).
| Python | apache-2.0 | therewillbecode/ichnaea,mozilla/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea |
a29d712b69f64ec248fb7f6829da9996dc5b217a | tests/integration/test_with_activemq.py | tests/integration/test_with_activemq.py | from . import base
class ActiveMQTestCase(base.IntegrationTestCase):
'''RabbitMQ integration test case.'''
CTXT = {
'plugin.activemq.pool.1.port': 61614,
'plugin.activemq.pool.1.password': 'marionette',
}
class TestWithActiveMQMCo20x(base.MCollective20x, ActiveMQTestCase):
'''MCollec... | import os
from pymco.test import ctxt
from . import base
class ActiveMQTestCase(base.IntegrationTestCase):
'''RabbitMQ integration test case.'''
CTXT = {
'plugin.activemq.pool.1.port': 61614,
'plugin.activemq.pool.1.password': 'marionette',
}
class TestWithActiveMQMCo20x(base.MCollecti... | Test ActiveMQ under SSL connection | Test ActiveMQ under SSL connection
| Python | bsd-3-clause | rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective |
8c0af29e7b6ec3a5e76fdb1efc56068bf276ad39 | helenae/flask_app.py | helenae/flask_app.py | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from db import tables as dbTables
app = Flask(__name__, template_folder='./web/templates/')
app.config['SECRET_KEY'] = 'some_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/csan'
db_connection = SQLAlchemy(app)
i... | from flask import Flask, request, session
from flask_sqlalchemy import SQLAlchemy
from flask.ext.babelex import Babel
from db import tables as dbTables
app = Flask(__name__, template_folder='./web/templates/', static_folder='./web/static/', static_url_path='')
app.config['SECRET_KEY'] = 'some_secret_key'
app.config['S... | Add babel plugin for Flask | Add babel plugin for Flask
| Python | mit | Relrin/Helenae,Relrin/Helenae,Relrin/Helenae |
747af88d56dc274638f515825405f58b0e59b8d7 | invoice/views.py | invoice/views.py | from django.shortcuts import get_object_or_404
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
def pdf_user_view(reque... | from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pd... | Make sure user in logged in for showing invoice | Make sure user in logged in for showing invoice
| Python | bsd-3-clause | Chris7/django-invoice,Chris7/django-invoice,simonluijk/django-invoice |
4e40575147fd9af02c0e0a380e4d35f6c5d8f67a | polling_stations/apps/data_collection/management/commands/import_breckland.py | polling_stations/apps/data_collection/management/commands/import_breckland.py | from data_collection.management.commands import BaseXpressWebLookupCsvImporter
class Command(BaseXpressWebLookupCsvImporter):
council_id = 'E07000143'
addresses_name = 'May 2017/BrecklandPropertyPostCodePollingStationWebLookup-2017-02-20.TSV'
stations_name = 'May 2017/BrecklandPropertyPostCodePolli... | from data_collection.management.commands import BaseXpressWebLookupCsvImporter
class Command(BaseXpressWebLookupCsvImporter):
council_id = 'E07000143'
addresses_name = 'May 2017/BrecklandPropertyPostCodePollingStationWebLookup-2017-02-20.TSV'
stations_name = 'May 2017/BrecklandPropertyPostCodePolli... | Discard dodgy points in Breckland | Discard dodgy points in Breckland
These are clearly very wrong
use geocoding instead
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations |
4a20a36aa920a6450eb526a9913d8fb0ab08fa8c | buildlet/runner/simple.py | buildlet/runner/simple.py | from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
task.pre_run()
try:
for p... | from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
for parent in task.get_parents():
... | Tweak SimpleRunner.run: make it close to the parallel one | Tweak SimpleRunner.run: make it close to the parallel one
| Python | bsd-3-clause | tkf/buildlet |
7a1a90cbaba73da44efeaf385865519cfa078a6c | astropy/vo/samp/tests/test_hub_script.py | astropy/vo/samp/tests/test_hub_script.py | import sys
from ..hub_script import hub_script
from ..utils import ALLOW_INTERNET
def setup_module(module):
ALLOW_INTERNET.set(False)
def test_hub_script():
sys.argv.append('-m') # run in multiple mode
sys.argv.append('-w') # disable web profile
hub_script(timeout=3)
| import sys
from ..hub_script import hub_script
from ..utils import ALLOW_INTERNET
def setup_module(module):
ALLOW_INTERNET.set(False)
def setup_function(function):
function.sys_argv_orig = sys.argv
sys.argv = ["samp_hub"]
def teardown_function(function):
sys.argv = function.sys_argv_orig
def t... | Fix isolation of SAMP hub script test. | Fix isolation of SAMP hub script test. | Python | bsd-3-clause | StuartLittlefair/astropy,dhomeier/astropy,saimn/astropy,funbaker/astropy,larrybradley/astropy,MSeifert04/astropy,kelle/astropy,lpsinger/astropy,bsipocz/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,lpsinger/astropy,lpsinger/astropy,astropy/astropy,funbaker/astropy,AustereCuriosity/astropy,StuartLittlefair/astropy... |
44749393191aebf730c4dca17766fbdb713e636b | systempay/app.py | systempay/app.py | from django.conf.urls import patterns, url
from oscar.core.application import Application
from systempay import views
class SystemPayApplication(Application):
name = 'systempay'
place_order_view = views.PlaceOrderView
cancel_response_view = views.CancelResponseView
secure_redirect_view = views.Secu... | from django.conf.urls import patterns, url
from oscar.core.application import Application
from systempay import views
class SystemPayApplication(Application):
name = 'systempay'
place_order_view = views.PlaceOrderView
cancel_response_view = views.CancelResponseView
secure_redirect_view = views.Secu... | Add missing handle ipn url | Add missing handle ipn url
| Python | mit | bastien34/django-oscar-systempay,bastien34/django-oscar-systempay,dulaccc/django-oscar-systempay |
3d7e02e58353fdc3290440344efd5591d233f449 | bot/__init__.py | bot/__init__.py | import os
PACKAGEDIR = os.path.abspath(os.path.dirname(__file__))
| import os
PACKAGEDIR = os.path.abspath(os.path.dirname(__file__))
from .webapp import goldstarsapp
| Make the flask app easier to import | Make the flask app easier to import
| Python | mit | barentsen/AstroGoldStars,barentsen/AstroGoldStars |
b946768acb8c9e34dbb72cb6d3bc33a7e67f4548 | setup.py | setup.py | from distutils.core import setup
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
license='MIT',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
descrip... | from distutils.core import setup
with open('README.md') as file:
long_description = file.read()
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
download_url='https://github... | Add download url and long description | Add download url and long description
| Python | mit | sashgorokhov/python-ninegag |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.