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 |
|---|---|---|---|---|---|---|---|---|---|
22ecda2f6879a140783a4e0105fb215e8cb12536 | passwd_change.py | passwd_change.py | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 4:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.s... | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 5:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
log_file = _args[4]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
... | Add log file name to command line. | Add log file name to command line.
| Python | mit | maxsocl/oldmailer |
4271d2ce0fc1cd2db4dab30aa59fece48c83f0bf | go/base/models.py | go/base/models.py | from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.conf import settings
from vumi.persist.riak_manager import RiakManager
from go.vumitools.account import AccountStore
from go.base.utils import vumi_api_for_user
def get_account_store():... | from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.conf import settings
from vumi.persist.riak_manager import RiakManager
from go.vumitools.account import AccountStore
from go.base.utils import vumi_api_for_user
def get_account_store():... | Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly). | Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
473e900fba1378e212a42c93624d1dd4f8acfb6e | fjord/alerts/migrations/0002_alertflavor_allowed_tokens.py | fjord/alerts/migrations/0002_alertflavor_allowed_tokens.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api_auth', '0001_initial'),
('alerts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api_auth', '0001_initial'),
('alerts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name... | Fix migration for fixing AlertFlavor.allowed_tokens | Fix migration for fixing AlertFlavor.allowed_tokens
Recently, I changed AlertFlavor.allowed_tokens so that you could create
a flavor without specifying the tokens that go with it (i.e. I added
blank=True).
The resulting migration for that change does a bunch of SQL, but doesn't
actually change the db.
So I'm tweakin... | Python | bsd-3-clause | hoosteeno/fjord,mozilla/fjord,Ritsyy/fjord,rlr/fjord,mozilla/fjord,rlr/fjord,hoosteeno/fjord,staranjeet/fjord,Ritsyy/fjord,hoosteeno/fjord,staranjeet/fjord,lgp171188/fjord,lgp171188/fjord,rlr/fjord,lgp171188/fjord,mozilla/fjord,lgp171188/fjord,Ritsyy/fjord,rlr/fjord,hoosteeno/fjord,staranjeet/fjord,staranjeet/fjord,moz... |
471d9c2ab901a018ef7b64464f19898dfbc9dd12 | ca_mb/__init__.py | ca_mb/__init__.py | from utils import CanadianJurisdiction
class Manitoba(CanadianJurisdiction):
classification = 'legislature'
division_id = 'ocd-division/country:ca/province:mb'
division_name = 'Manitoba'
name = 'Legislative Assembly of Manitoba'
url = 'http://www.gov.mb.ca/legislature/'
parties = [
{'n... | from utils import CanadianJurisdiction
class Manitoba(CanadianJurisdiction):
classification = 'legislature'
division_id = 'ocd-division/country:ca/province:mb'
division_name = 'Manitoba'
name = 'Legislative Assembly of Manitoba'
url = 'http://www.gov.mb.ca/legislature/'
parties = [
{'n... | Fix for new divisions and parties | ca_mb: Fix for new divisions and parties
| Python | mit | opencivicdata/scrapers-ca,opencivicdata/scrapers-ca |
0afdab2f6feced873c88ba1e73fdde0dad5f041e | skytap/Quotas.py | skytap/Quotas.py | """Support for Skytap API access to the company quotas.
If accessed via the command line (``python -m skytap.Quotas``) this will
return the quotas from Skytap in a JSON format.
"""
import json
import sys
from skytap.models.Quota import Quota
from skytap.models.SkytapGroup import SkytapGroup
class Quotas(SkytapGroup... | """Support for Skytap API access to the company quotas.
If accessed via the command line (``python -m skytap.Quotas``) this will
return the quotas from Skytap in a JSON format.
"""
import json
import sys
from skytap.models.Quota import Quota
from skytap.models.SkytapGroup import SkytapGroup
class Quotas(SkytapGroup... | Comment re: API usage to clarify quotas. | Comment re: API usage to clarify quotas.
| Python | mit | mapledyne/skytap,FulcrumIT/skytap |
829f71c488f2332d66362d7aea309a8b8958d522 | jarviscli/tests/test_voice.py | jarviscli/tests/test_voice.py | import unittest
from tests import PluginTest
from plugins import voice
from CmdInterpreter import JarvisAPI
from Jarvis import Jarvis
# this test class contains test cases for the plugins "gtts" and "disable_gtts"
# which are included in the "voice.py" file in the "plugins" folder
class VoiceTest(PluginTest):
# ... | import unittest
from tests import PluginTest
from plugins import voice
from CmdInterpreter import JarvisAPI
from Jarvis import Jarvis
# this test class contains test cases for the plugins "gtts" and "disable_gtts"
# which are included in the "voice.py" file in the "plugins" folder
class VoiceTest(PluginTest):
# ... | Fix unit test of voice function | Fix unit test of voice function
| Python | mit | sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis |
d5e5ddbd1e1108f327a8d4c27cc18925cf7a3e1a | src/sentry/api/endpoints/project_stats.py | src/sentry/api/endpoints/project_stats.py | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.app import tsdb
from sentry.api.base import BaseStatsEndpoint
from sentry.api.permissions import assert_perm
from sentry.models import Project
class ProjectStatsEndpoint(BaseStatsEndpoint):
def get(self, request, pro... | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.app import tsdb
from sentry.api.base import BaseStatsEndpoint, DocSection
from sentry.api.permissions import assert_perm
from sentry.models import Project
class ProjectStatsEndpoint(BaseStatsEndpoint):
doc_section = ... | Add project stats to docs | Add project stats to docs
| Python | bsd-3-clause | looker/sentry,kevinlondon/sentry,pauloschilling/sentry,1tush/sentry,daevaorn/sentry,wong2/sentry,fuziontech/sentry,gencer/sentry,imankulov/sentry,felixbuenemann/sentry,ifduyue/sentry,gg7/sentry,1tush/sentry,camilonova/sentry,hongliang5623/sentry,boneyao/sentry,camilonova/sentry,songyi199111/sentry,llonchj/sentry,mvaled... |
2230832033df7f5d8511dc75f799a9cc738dc46f | games/managers.py | games/managers.py | from django.db.models import Manager
class ScreenshotManager(Manager):
def published(self, user=None, is_staff=False):
query = self.get_query_set()
query = query.order_by('uploaded_at')
if is_staff:
return query
elif user:
return query.filter(Q(published=Tru... | from django.db.models import Manager
from django.db.models import Q
class ScreenshotManager(Manager):
def published(self, user=None, is_staff=False):
query = self.get_query_set()
query = query.order_by('uploaded_at')
if is_staff:
return query
elif user:
retu... | Fix missing import and bad query for screenshots | Fix missing import and bad query for screenshots
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website |
ebba310de088d8d295e1fc94d368da4edc430756 | user/admin.py | user/admin.py | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'email',
'is_staff',
'is_superuser')
list_filter = (
'is_staff',
'is_superuser',
'profile__joined')
search_fi... | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'email',
'is_staff',
'is_superuser')
list_filter = (
'is_staff',
'is_superuser',
'profile__joined')
ordering ... | Set User Admin default ordering. | Ch23: Set User Admin default ordering.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
602d1ceb755d5d74312e965b5515bbe22c868fd4 | sale_commission_pricelist/models/sale_order.py | sale_commission_pricelist/models/sale_order.py | # -*- coding: utf-8 -*-
# Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
@api.onchange('product_id', 'product_uom_qty')
de... | # -*- coding: utf-8 -*-
# Copyright 2018 Tecnativa - Carlos Dauden <carlos.dauden@tecnativa.com>
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
def _get_... | Make this to work on button recompute | [FIX] sale_commission_pricelist: Make this to work on button recompute
| Python | agpl-3.0 | OCA/commission,OCA/commission |
40bfd177cea186bc975fdc51ab61cf4d9e7026a3 | tests/testapp/manage.py | tests/testapp/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | Make sure to use abspath when adding dynamic_choices to sys.path | Make sure to use abspath when adding dynamic_choices to sys.path
| Python | mit | charettes/django-dynamic-choices,charettes/django-dynamic-choices,charettes/django-dynamic-choices |
5b563f91d5e7bad48d8a90a190749bcbf09264c0 | tests/test_basic.py | tests/test_basic.py | import sys
import pubrunner
import pubrunner.command_line
import os
def test_countwords():
parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line... | import sys
import pubrunner
import pubrunner.command_line
import os
import time
def test_countwords():
parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.... | Add sleeps to test to avoid eutils issues | Add sleeps to test to avoid eutils issues
| Python | mit | jakelever/pubrunner,jakelever/pubrunner |
bfbc156d9efca37c35d18481c4366d3e6deed1ba | slave/skia_slave_scripts/chromeos_run_bench.py | slave/skia_slave_scripts/chromeos_run_bench.py | #!/usr/bin/env python
# Copyright (c) 2013 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.
""" Run the Skia bench executable. """
from build_step import BuildStep, BuildStepWarning
from chromeos_build_step import ChromeOS... | #!/usr/bin/env python
# Copyright (c) 2013 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.
""" Run the Skia bench executable. """
from build_step import BuildStep
from chromeos_build_step import ChromeOSBuildStep
from run... | Stop skipping Bench on ChromeOS | Stop skipping Bench on ChromeOS
(RunBuilders:Skia_ChromeOS_Alex_Debug_32)
Unreviewed.
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8094 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbo... |
e781229453a5d6d654c6ab6acae5ad2866b28f9c | tools/srenqueuer.py | tools/srenqueuer.py | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import json
import requests
import stoneridge
@stoneridge.main
def main():
parser = stoner... | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import json
import requests
import stoneridge
@stoneridge.main
def main():
parser = stoner... | Handle exceptions better in enqueuer | Handle exceptions better in enqueuer
We don't care too much, so just swallow them. People will complain at me
if their "pushed" jobs don't get run (eventually).
| Python | mpl-2.0 | mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge |
1de37d04c71713f811d057f63f505348f7124c54 | {{cookiecutter.repo_name}}/config/urls.py | {{cookiecutter.repo_name}}/config/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^users/', include('apps.users.urls', namespace='users')),
url(r'^$', TemplateView.as_view(template_name='start.html'), na... | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'),
]
| Revert to old master 2 | Revert to old master 2
| Python | mit | ameistad/amei-django-template,ameistad/dokku-django-template,ameistad/amei-django-template,ameistad/dokku-django-template,ameistad/amei-django-template,ameistad/django-template,ameistad/amei-django-template,ameistad/dokku-django-template,ameistad/django-template,ameistad/django-template |
86142c9893d52f3c339675c89b50f27c4bdc64e6 | localtv/openid/__init__.py | localtv/openid/__init__.py | from django.contrib.auth.models import User
from localtv.models import SiteLocation
class OpenIdBackend:
def authenticate(self, openid_user=None):
"""
We assume that the openid_user has already been externally validated,
and simply return the appropriate User,
"""
return op... | from django.contrib.auth.models import User
from localtv.models import SiteLocation
class OpenIdBackend:
def authenticate(self, openid_user=None, username=None, password=None):
"""
If we get an openid_userassume that the openid_user has already been
externally validated, and simply return ... | Make all users get logged in through the OpenIdBackend | Make all users get logged in through the OpenIdBackend
By routing all the logins through the OpenIdBackend, we can handle the
permissions checking on our own. This allows us use apps (like comments) which
depend on the Django authentication system, but with our own permissions
system.
| Python | agpl-3.0 | natea/Miro-Community,natea/Miro-Community,pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity |
6696451b7c7a9b2de5b624b47159efae8fcf06b7 | opwen_email_server/api/lokole.py | opwen_email_server/api/lokole.py | def upload(upload_info):
"""
:type upload_info: dict
"""
client_id = upload_info['client_id']
resource_id = upload_info['resource_id']
resource_type = upload_info['resource_type']
raise NotImplementedError
def download(client_id):
"""
:type client_id: str
:rtype dict
"""... | def upload(upload_info):
"""
:type upload_info: dict
"""
client_id = upload_info['client_id'] # noqa: F841
resource_id = upload_info['resource_id'] # noqa: F841
resource_type = upload_info['resource_type'] # noqa: F841
raise NotImplementedError
def download(client_id): # noqa: F841
... | Disable linter in in-progress code | Disable linter in in-progress code
| Python | apache-2.0 | ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver |
199caafc817e4e007b2eedd307cb7bff06c029c6 | imagersite/imager_images/tests.py | imagersite/imager_images/tests.py | from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
| from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Pho
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
... | Add a UserFactory for images test | Add a UserFactory for images test
| Python | mit | jesseklein406/django-imager,jesseklein406/django-imager,jesseklein406/django-imager |
de42731ab97a7d4272c44cc750891906aa5b4417 | buildlet/runner/ipythonparallel.py | buildlet/runner/ipythonparallel.py | """
Task runner using IPython parallel interface.
See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.
.. _The IPython task interface:
http://ipython.org/ipython-doc/dev/parallel/parallel_task.html
.. _DAG Dependencies:
http://ipython.org/ipython-doc/dev/parallel/dag_depe... | """
Task runner using IPython parallel interface.
See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.
.. _The IPython task interface:
http://ipython.org/ipython-doc/dev/parallel/parallel_task.html
.. _DAG Dependencies:
http://ipython.org/ipython-doc/dev/parallel/dag_depe... | Raise error if any in IPythonParallelRunner.wait_tasks | Raise error if any in IPythonParallelRunner.wait_tasks
| Python | bsd-3-clause | tkf/buildlet |
b198dd91082dd5ae2fdddb7f7bd6ef05c35ba4f4 | jdleden/local_settings_example.py | jdleden/local_settings_example.py |
LDAP_NAME = 'ldap://'
LDAP_PASSWORD = ''
LDAP_DN = 'cn=writeuser,ou=sysUsers,dc=jd,dc=nl'
SECRET_KEY = ''
DATABASES = {
"default": {
# Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.sqlite3",
# DB name or path to database file if using sqlite3.
... |
DATABASES = {
"default": {
# Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.sqlite3",
# DB name or path to database file if using sqlite3.
"NAME": "dev.db",
# Not used with sqlite3.
"USER": "",
# Not used with sqlite3... | Add Janeus settings to local_settings example | Add Janeus settings to local_settings example
| Python | mit | jonge-democraten/jdleden,jonge-democraten/jdleden |
9e406380196a51a2502878a641ea90a11d6a19c3 | comrade/core/context_processors.py | comrade/core/context_processors.py | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['current_site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
... | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['current_site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
... | Add a context processor that adds the UserProfile to each context. | Add a context processor that adds the UserProfile to each context.
| Python | mit | bueda/django-comrade |
2a71b48fb3ff2ec720ace74e30a83102c31863dc | labonneboite/common/email_util.py | labonneboite/common/email_util.py | # coding: utf8
import json
import logging
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class M... | # coding: utf8
import json
import logging
from urllib.error import HTTPError
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouvea... | Handle HttpError when sending email | Handle HttpError when sending email
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite |
60352e8a3c41ec804ac1bd6b9f3af4bf611edc0b | profiles/views.py | profiles/views.py | from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.views.generic import FormView, TemplateView
from django.utils.datastructures import MultiValueDictKeyError
from incuna.utils im... | from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.utils.datastructures import MultiValueDictKeyError
from django.views.generic import TemplateView, UpdateView
from incuna.utils ... | Use an update view instead of form view | Use an update view instead of form view
| Python | bsd-2-clause | incuna/django-extensible-profiles |
b89716c4e7ba69c36a04bca00da20cfa8bb6a5e7 | ideascube/conf/idb_col_llavedelsaber.py | ideascube/conf/idb_col_llavedelsaber.py | """Configuration for Llave Del Saber, Colombia"""
from .idb import * # noqa
LANGUAGE_CODE = 'es'
DOMAIN = 'bibliotecamovil.lan'
ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost']
| """Configuration for Llave Del Saber, Colombia"""
from .idb import * # noqa
LANGUAGE_CODE = 'es'
DOMAIN = 'bibliotecamovil.lan'
ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost']
USER_FORM_FIELDS = USER_FORM_FIELDS + (
(_('Personal informations'), ['extra']),
)
USER_EXTRA_FIELD_LABEL = 'Etnicidad'
| Add a custom 'extra' field to idb_col_llavadelsaber | Add a custom 'extra' field to idb_col_llavadelsaber
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
263e31a5d87b8134a25df97eee06f1fe9c1e94bc | django_countries/release.py | django_countries/release.py | """
This file provides zest.releaser entrypoints using when releasing new
django-countries versions.
"""
import os
from txclib.commands import cmd_pull
from txclib.utils import find_dot_tx
from txclib.log import logger
from zest.releaser.utils import ask, execute_command
from django.core.management import call_command... | """
This file provides zest.releaser entrypoints using when releasing new
django-countries versions.
"""
import os
import re
import shutil
from txclib.commands import cmd_pull
from txclib.utils import find_dot_tx
from txclib.log import logger
from zest.releaser.utils import ask, execute_command
from django.core.manage... | Fix locale paths when pulling from transifex | Fix locale paths when pulling from transifex
| Python | mit | SmileyChris/django-countries |
6448691ed77be2fd74761e056eeb5f16a881fd54 | test_settings.py | test_settings.py | from foundry.settings import *
# We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
# in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
... | from foundry.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# Need this last line until django-setuptest is improved.
| Adjust test settings to be in line with jmbo-skeleton | Adjust test settings to be in line with jmbo-skeleton
| Python | bsd-3-clause | praekelt/jmbo-competition,praekelt/jmbo-competition |
66a1fb19aadfcf90d5627b36755d700291cef4b4 | py/desisurvey/test/test_rules.py | py/desisurvey/test/test_rules.py | import unittest
import numpy as np
import desisurvey.tiles
from desisurvey.test.base import Tester
from desisurvey.rules import Rules
class TestRules(Tester):
def test_rules(self):
rules = Rules()
tiles = desisurvey.tiles.get_tiles()
completed = np.ones(tiles.ntiles, bool)
rules... | import unittest
import numpy as np
import desisurvey.tiles
from desisurvey.test.base import Tester
from desisurvey.rules import Rules
class TestRules(Tester):
def test_rules(self):
rules = Rules('rules-layers.yaml')
tiles = desisurvey.tiles.get_tiles()
completed = np.ones(tiles.ntiles, ... | Use simpler rules file for testing with tiles subset | Use simpler rules file for testing with tiles subset
| Python | bsd-3-clause | desihub/desisurvey,desihub/desisurvey |
44dce5edc73199ffb0c151280cfe9e75acb73c5e | polling/tests/factories.py | polling/tests/factories.py | from datetime import datetime
import factory
from polling.models import State
from polling.models import CANDIDATE_NONE
class StateFactory(factory.DjangoModelFactory):
class Meta:
model = State
name = factory.Sequence(lambda n: "state-%d" % n)
updated = factory.LazyFunction(datetime.now)
ab... | from datetime import datetime
import us
import factory
from polling.models import State
from polling.models import CANDIDATE_NONE
class StateFactory(factory.DjangoModelFactory):
class Meta:
model = State
name = factory.Sequence(lambda n: us.STATES[n])
updated = factory.LazyFunction(datetime.now... | Use real states in StateFactory | Use real states in StateFactory
| Python | mit | sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap |
57015bec555ca2a3f2e5893158d00f2dd2ca441c | errs.py | errs.py | import sys
class ConfigError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ParseError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + st... | import sys
class GenericException(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ConfigError(GenericException):
pass
class ParseError(GenericException):
pass
| Make errors a bit easier to copy | Make errors a bit easier to copy
| Python | agpl-3.0 | OpenTechStrategies/anvil |
0f9884e884751aab6be342f68d917afafa61ea54 | marten/__init__.py | marten/__init__.py | """Stupid simple Python configuration management"""
from __future__ import absolute_import
import os as _os
__version__ = '0.5.1'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
_marten_dir = _os.path.join(_os.getc... | """Stupid simple Python configuration management"""
from __future__ import absolute_import
import os as _os
__version__ = '0.5.2'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
_marten_dir = _os.path.join(_os.getc... | Handle ImportError at package root | Handle ImportError at package root
| Python | mit | nick-allen/marten |
25d909d95fe4a065d91eec49f4c3e0fa810233e5 | DownloadData/download_data.py | DownloadData/download_data.py | import ocpaccess.download
ocpaccess.download.get_data(
token = "kasthuri11", zoom = 1,
x_start = 0, x_stop = 10752,
y_start = 0, y_stop = 13312,
z_start = 1, z_stop = 1850,
location =... | import ocpaccess.download
"""
Two sets of tokens are supplied below -- `common` and `full`.
common The most common data download.)
full LARGE FILE WARNING
For the compressed data, visit [our website].
"""
# Common
common = ['kasthuri11',
'kat11vesicles',
'kat11segments',
'k... | Add script to download by 'set' | Add script to download by 'set'
| Python | apache-2.0 | openconnectome/kasthuri2015,neurodata/kasthuri2015,openconnectome/kasthuri2015,openconnectome/Kasthuri-et-al-2014,neurodata/kasthuri2015,openconnectome/Kasthuri-et-al-2014,openconnectome/Kasthuri-et-al-2014,neurodata/kasthuri2015,openconnectome/kasthuri2015 |
01b25dd0df59ba7a309a25433abc09f86d5d5096 | app/main/messaging.py | app/main/messaging.py | from flask import request, session
from . import main
import twilio.twiml
@main.route("/report_incident", methods=['GET', 'POST'])
def handle_message():
step = session.get('step', 0)
message = request.values.get('Body') # noqa
resp = twilio.twiml.Response()
if step is 0:
resp.message("Welco... | from flask import request, session
from . import main
import twilio.twiml
@main.route("/report_incident", methods=['GET', 'POST'])
def handle_message():
message = request.values.get('Body') # noqa
resp = twilio.twiml.Response()
if message.lower().contains('report'):
step = session.get('step', 0)
... | Add scret key for sessioning | Add scret key for sessioning
| Python | mit | hack4impact/clean-air-council,hack4impact/clean-air-council,hack4impact/clean-air-council |
db5f4d9325d1f1c67160c925b83e8a4574d4cb9a | portal/factories/celery.py | portal/factories/celery.py | from __future__ import absolute_import
from celery import Celery
__celery = None
def create_celery(app):
global __celery
if __celery:
return __celery
celery = Celery(
app.import_name,
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
TaskBase = c... | from __future__ import absolute_import
from celery import Celery
from ..extensions import db
__celery = None
def create_celery(app):
global __celery
if __celery:
return __celery
celery = Celery(
app.import_name,
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update... | Remove DB session after task | Remove DB session after task
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal |
eb796cc0473ee1c3805e172e5f8035ef16f89c76 | micromanager/resources/base.py | micromanager/resources/base.py | from abc import ABCMeta, abstractmethod
from googleapiclienthelpers.discovery import build_subresource
class ResourceBase(metaclass=ABCMeta):
@abstractmethod
def get(self):
pass
@abstractmethod
def update(self):
pass
class GoogleAPIResourceBase(ResourceBase, metaclass=ABCMeta):
... | from abc import ABCMeta, abstractmethod
from googleapiclienthelpers.discovery import build_subresource
class ResourceBase(metaclass=ABCMeta):
@abstractmethod
def get(self):
pass
@abstractmethod
def update(self):
pass
class GoogleAPIResourceBase(ResourceBase, metaclass=ABCMeta):
... | Add a 'type()' function to resources for policy engines to lookup policies | Add a 'type()' function to resources for policy engines to lookup policies
| Python | apache-2.0 | forseti-security/resource-policy-evaluation-library |
df3ccf1b848ab3829f16ff0486c677763e5b383b | lc034_find_first_and_last_position_of_element_in_sorted_array.py | lc034_find_first_and_last_position_of_element_in_sorted_array.py | """Leetcode 34. Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in ascending order,
find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, retu... | """Leetcode 34. Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in ascending order,
find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, retu... | Complete sol by 2 binary searches | Complete sol by 2 binary searches
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
bcec4724dc434218f7b2bce0aaabf391f86847b6 | ocradmin/core/decorators.py | ocradmin/core/decorators.py | # Miscellaneos functions relating the projects app
import os
from datetime import datetime
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
from django.conf import settings
def project_required(func):
"""
Decorator function for other actions that
require a project to be ... | # Miscellaneos functions relating the projects app
import os
from datetime import datetime
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
from django.conf import settings
def project_required(func):
"""
Decorator function for other actions that
require a project to be ... | Add plugins to the domains which handle temp files | Add plugins to the domains which handle temp files
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium |
dde17a556103120ffbdf3dc08b822da2a781ff7e | myproject/myproject/project_settings.py | myproject/myproject/project_settings.py | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | Use production settings by default; Display settings version in use | Use production settings by default; Display settings version in use
| Python | unlicense | django-settings/django-settings |
c321a8fea477608172ac9f0421b8b3318ff6d388 | carbonitex/carbonitex.py | carbonitex/carbonitex.py | import asyncio
from urllib.request import urlopen
from jshbot import configurations
from jshbot.exceptions import BotException
from jshbot.utilities import future
__version__ = '0.1.0'
EXCEPTION = 'Carbonitex Data Pusher'
uses_configuration = True
def get_commands():
return []
async def bot_on_ready_boot(bot... | import asyncio
from urllib.request import urlopen
from jshbot import configurations
from jshbot.exceptions import BotException
from jshbot.utilities import future
__version__ = '0.1.1'
EXCEPTION = 'Carbonitex Data Pusher'
uses_configuration = True
def get_commands():
return []
async def bot_on_ready_boot(bot... | Adjust for multiple bot instances | Adjust for multiple bot instances
| Python | mit | jkchen2/JshBot-plugins |
8994c346bcd319e97e93b9eb66707df1016d28e9 | nilmtk/__init__.py | nilmtk/__init__.py | # re-enable deprecation warnings
import warnings
warnings.simplefilter('default')
from nilmtk import *
from nilmtk.version import version as __version__
from nilmtk.timeframe import TimeFrame
from nilmtk.elecmeter import ElecMeter
from nilmtk.datastore import DataStore, HDFDataStore, CSVDataStore, Key
from nilmtk.mete... | # re-enable deprecation warnings
import warnings
warnings.simplefilter('default')
from nilmtk import *
from nilmtk.version import version as __version__
from nilmtk.timeframe import TimeFrame
from nilmtk.elecmeter import ElecMeter
from nilmtk.datastore import DataStore, HDFDataStore, CSVDataStore, Key
from nilmtk.mete... | Make sure all .h5 files are closed before trying to remove them while testing | Make sure all .h5 files are closed before trying to remove them while testing
| Python | apache-2.0 | nilmtk/nilmtk,nilmtk/nilmtk |
1cc892fd521ae33b1d492004411db3f1392295c4 | enhydris/telemetry/tasks.py | enhydris/telemetry/tasks.py | from django.core.cache import cache
from celery.utils.log import get_task_logger
from enhydris.celery import app
from enhydris.telemetry.models import Telemetry
FETCH_TIMEOUT = 300
LOCK_TIMEOUT = FETCH_TIMEOUT + 60
logger = get_task_logger(__name__)
@app.task
def fetch_all_telemetry_data():
for telemetry in T... | from django.core.cache import cache
from celery.utils.log import get_task_logger
from enhydris.celery import app
from enhydris.telemetry.models import Telemetry
FETCH_TIMEOUT = 300
LOCK_TIMEOUT = FETCH_TIMEOUT + 60
logger = get_task_logger(__name__)
@app.task
def fetch_all_telemetry_data():
for telemetry in T... | Fix error in telemetry task | Fix error in telemetry task
A condition had been changed to always match for debugging purposes, and
was accidentally committed that way.
| Python | agpl-3.0 | openmeteo/enhydris,openmeteo/enhydris,openmeteo/enhydris,aptiko/enhydris,aptiko/enhydris,aptiko/enhydris |
b8764f6045bbc1067806405ca2fba9c1622f997b | gweetr/utils.py | gweetr/utils.py | """utils.py"""
import random
from pyechonest import config as echonest_config
from pyechonest import song as echonest_song
import rfc3987
from gweetr import app
from gweetr.exceptions import GweetrError
echonest_config.ECHO_NEST_API_KEY = app.config['ECHO_NEST_API_KEY']
def fetch_track(track_params):
"""
... | """utils.py"""
import random
from pyechonest import config as echonest_config
from pyechonest import song as echonest_song
import rfc3987
from gweetr import app
from gweetr.exceptions import GweetrError
echonest_config.ECHO_NEST_API_KEY = app.config['ECHO_NEST_API_KEY']
def fetch_track(track_params):
"""
... | Remove unnecessary if true/else false | Remove unnecessary if true/else false | Python | mit | jbarbuto/gweetr |
284cfbb4297d1d91c8c82e0f9a159a1614510ace | example.py | example.py | #!/usr/bin/env python
from confman import ConfigSource
options = \
{
'tags': ['desktop'],
'hostname': 'test',
}
from sys import argv
from os import path
samples_path = path.join(path.dirname(argv[0]), 'samples')
c = ConfigSource(samples_path, "/tmp/dotfiles-test", None, options)
c.analyze()
c.check()
c.sync(... | #!/usr/bin/env python
from confman import ConfigSource
options = \
{
'tags': ['desktop'],
'hostname': 'test',
}
from os import path
samples_path = path.join(path.dirname(__file__), 'samples')
c = ConfigSource(samples_path, "/tmp/dotfiles-test", None, options)
c.analyze()
c.check()
c.sync()
print
from pprint... | Use __file__ instead of argv[0] | Use __file__ instead of argv[0]
| Python | mit | laurentb/confman |
7f51f153f0fd1fd1dde06808879911897686f819 | cities/Sample_City.py | cities/Sample_City.py | from bs4 import BeautifulSoup
import json
import datetime
import pytz
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for ne... | from bs4 import BeautifulSoup
import datetime
import pytz
from geodata import GeoData
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py... | Clean up sample city file | Clean up sample city file
| Python | mit | offenesdresden/ParkAPI,Mic92/ParkAPI,offenesdresden/ParkAPI,Mic92/ParkAPI |
07e9b55784f856c0175b4fbfeeceeb387abf7ad5 | red_green_bar2.py | red_green_bar2.py | #!/usr/bin/env python2
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
if len(sys.argv) >= 2:
value = int(sys.argv[1])
cols_limit = int(sys.argv[2])
esc = chr(27)
if value:
col_cha... | #!/usr/bin/env python2
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
if len(sys.argv) >= 2:
value = int(sys.argv[1])
if value:
col_char = '1'
else:
col_char = '2'
cols_li... | Prepare for y (yellow) first argument | Prepare for y (yellow) first argument
| Python | mit | kwadrat/rgb_tdd |
084eb32734731ee23e33e7360ec9f92e1e533f01 | __init__.py | __init__.py | from spinsys import constructors
from spinsys import exceptions
from spinsys import half
from spinsys import hamiltonians
from spinsys import quantities
from spinsys import state_generators
from spinsys import tests
from spinsys import utils
__all__ = [
"constructors",
"exceptions",
"half",
"hamiltonia... | from spinsys import constructors
from spinsys import exceptions
from spinsys import half
from spinsys import hamiltonians
from spinsys import quantities
from spinsys import state_generators
from spinsys import tests
from spinsys import utils
import shutil
import numpy
__all__ = [
"constructors",
"exceptions",
... | Set better defaults for numpy's print function | Set better defaults for numpy's print function
| Python | bsd-3-clause | macthecadillac/spinsys |
98506d6ba1d1e7c8d3cf62d97f7c3f2f23bc4841 | chainer/training/extensions/value_observation.py | chainer/training/extensions/value_observation.py | from chainer.training import extension
def observe_value(observation_key, target_func):
"""Returns a trainer extension to continuously record a value.
Args:
observation_key (str): Key of observation to record.
target_func (function): Function that returns the value to record.
It m... | from chainer.training import extension
def observe_value(observation_key, target_func):
"""Returns a trainer extension to continuously record a value.
Args:
observation_key (str): Key of observation to record.
target_func (function): Function that returns the value to record.
It m... | Document observe_value and observe_lr trigger interval | Document observe_value and observe_lr trigger interval
| Python | mit | hvy/chainer,niboshi/chainer,okuta/chainer,hvy/chainer,keisuke-umezawa/chainer,chainer/chainer,chainer/chainer,niboshi/chainer,niboshi/chainer,wkentaro/chainer,keisuke-umezawa/chainer,pfnet/chainer,chainer/chainer,okuta/chainer,hvy/chainer,niboshi/chainer,wkentaro/chainer,wkentaro/chainer,okuta/chainer,wkentaro/chainer,... |
3a5a6db3b869841cf5c55eed2f5ec877a443a571 | chrome/test/functional/chromeos_html_terminal.py | chrome/test/functional/chromeos_html_terminal.py | #!/usr/bin/env python
# Copyright (c) 2012 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 os
import pyauto_functional # must be imported before pyauto
import pyauto
class ChromeosHTMLTerminalTest(pyauto.PyUITes... | #!/usr/bin/env python
# Copyright (c) 2012 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 os
import pyauto_functional # must be imported before pyauto
import pyauto
class ChromeosHTMLTerminalTest(pyauto.PyUITes... | Add uninstall HTML Terminal extension | Add uninstall HTML Terminal extension
BUG=
TEST=This is a test to uninstall HTML terminal extension
Review URL: https://chromiumcodereview.appspot.com/10332227
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@137790 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | hgl888/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/ch... |
e1703021a467b38d61e59da5aff5e7280b021ade | TutsPy/tut.py | TutsPy/tut.py |
import re
import requests
from bs4 import BeautifulSoup
from utils import download_file
import os
SUBJECT = 'seo'
INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm'
DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf'
def get_all_chapters():
r = requests.get(INDEX_ENDPOINT%SUBJECT)
soup = ... |
import re
import requests
from bs4 import BeautifulSoup
from utils import download_file
import os
SUBJECT = 'seo'
INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm'
DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf'
def get_all_chapters():
r = requests.get(INDEX_ENDPOINT%SUBJECT)
soup = ... | Add check of command line program execution | Add check of command line program execution | Python | mit | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts |
4026b8e352229c6f640d428640cd08919ba440e6 | dodo_commands/extra/webdev_commands/django-manage.py | dodo_commands/extra/webdev_commands/django-manage.py | """Run a django-manage command."""
import argparse
from dodo_commands.extra.standard_commands import DodoCommand
from dodo_commands.util import remove_trailing_dashes
class Command(DodoCommand): # noqa
decorators = ['docker']
def add_arguments_imp(self, parser): # noqa
parser.add_argument(
... | """Run a django-manage command."""
import argparse
from dodo_commands.extra.standard_commands import DodoCommand
from dodo_commands.framework.util import remove_trailing_dashes
class Command(DodoCommand): # noqa
decorators = ['docker']
def add_arguments_imp(self, parser): # noqa
parser.add_argument... | Fix remaining broken import of remove_trailing_dashes | Fix remaining broken import of remove_trailing_dashes
| Python | mit | mnieber/dodo_commands |
81d6119f452afa0f69db4a7ab1f37906469d3b64 | annotator/model/__init__.py | annotator/model/__init__.py | from .annotation import Annotation
from .consumer import Consumer
from .user import User
| __all__ = ['Annotation', 'Consumer', 'User']
from .annotation import Annotation
from .consumer import Consumer
from .user import User
| Make annotator.model 'import *' friendly | Make annotator.model 'import *' friendly
| Python | mit | ningyifan/annotator-store,nobita-isc/annotator-store,happybelly/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,openannotation/annotator-store |
a925c19b85fcd3a2b6d08d253d3c8d1ef3c7b02f | core/migrations/0008_auto_20151029_0953.py | core/migrations/0008_auto_20151029_0953.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.contrib.contenttypes.management import update_all_contenttypes
def add_impersonate_permission(apps, schema_editor):
update_all_contenttypes() # Fixes tests
ContentType = apps.get_model('conte... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.contrib.contenttypes.management import update_all_contenttypes
def add_impersonate_permission(apps, schema_editor):
update_all_contenttypes() # Fixes tests
ContentType = apps.get_model('conte... | Update latest migration to use the database provided to the migrate management command | Update latest migration to use the database provided to the migrate management command
| Python | agpl-3.0 | tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador |
d74f7d2384d48115ea58737332e4636ba9fdd4aa | ini_tools/get_ini_fields.py | ini_tools/get_ini_fields.py | """
collect information about fields and values in ini file
usage run script with file name in directory with unpacked stats.
Script will collect data from all files with name.
You can specify path as second argument.
python get_ini_fields.py body.ini
python get_ini_fields.py body.ini "C:/games/warzone2100"
"""
i... | """
collect information about fields and values in ini file
usage run script with file name in directory with unpacked stats.
Script will collect data from all files with name.
You can specify path as second argument.
python get_ini_fields.py body.ini
python get_ini_fields.py body.ini "C:/games/warzone2100"
"""
i... | Update collect ini script. Now it shows if field is required. | Update collect ini script. Now it shows if field is required.
| Python | cc0-1.0 | haoNoQ/wztools2100,haoNoQ/wztools2100,haoNoQ/wztools2100 |
733ea52d5374c4c5d5c10f1a04e3300fd6f4695c | features/steps/interactive.py | features/steps/interactive.py | import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
ENTER = "\n"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', proce... | import time, pexpect, re
PROMPT = "root@\w+:[^\r]+"
UP_ARROW = "\x1b[A"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', process.before).strip()
@when(u'I run the inter... | Allow tty process longer time to spawn in feature tests | Allow tty process longer time to spawn in feature tests
| Python | mit | michaelbarton/command-line-interface,bioboxes/command-line-interface,michaelbarton/command-line-interface,bioboxes/command-line-interface,pbelmann/command-line-interface,pbelmann/command-line-interface |
5a79acaccab59e50788cd2da31a93f2f1b69ca53 | codeforces/div3/579/C/C.py | codeforces/div3/579/C/C.py | from math import gcd, sqrt, ceil
n = int(input())
a = list(map(int, input().split()))
a = list(set(a))
divisor = a[0]
for ai in a[1:]:
divisor = gcd(divisor, ai)
result = 1 # 1 is always a divisor
limit = ceil(sqrt(divisor)) + 1
primes = [2] + list(range(3, limit, 2))
for prime_factor in primes:
power =... | from math import gcd, sqrt, ceil
n = int(input())
a = list(map(int, input().split()))
a = list(set(a))
divisor = a[0]
for ai in a[1:]:
divisor = gcd(divisor, ai)
result = 1 # 1 is always a divisor
limit = divisor // 2 + 1
primes = [2] + list(range(3, limit, 2))
for prime_factor in primes:
if prime_facto... | Fix WA 10: remove limit heuristics | Fix WA 10: remove limit heuristics
- in CF Div 3 579C
Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
| Python | mit | mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming |
3dd22e9c88a0b02655481ef3ca0f5376b8aae1b5 | spacy/tests/regression/test_issue834.py | spacy/tests/regression/test_issue834.py | # coding: utf-8
from __future__ import unicode_literals
from io import StringIO
word2vec_str = """, -0.046107 -0.035951 -0.560418
de -0.648927 -0.400976 -0.527124
. 0.113685 0.439990 -0.634510
-1.499184 -0.184280 -0.598371"""
def test_issue834(en_vocab):
f = StringIO(word2vec_str)
vector_length = en_vocab... | # coding: utf-8
from __future__ import unicode_literals
from io import StringIO
import pytest
word2vec_str = """, -0.046107 -0.035951 -0.560418
de -0.648927 -0.400976 -0.527124
. 0.113685 0.439990 -0.634510
-1.499184 -0.184280 -0.598371"""
@pytest.mark.xfail
def test_issue834(en_vocab):
f = StringIO(word2vec_... | Mark vectors test as xfail (temporary) | Mark vectors test as xfail (temporary)
| Python | mit | oroszgy/spaCy.hu,oroszgy/spaCy.hu,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,raphael0202/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,raphael0202/spaCy,aikramer2/spaCy,aikramer2/spaCy,banglakit/spaCy,recognai/spaCy,honnibal/spaCy,Gre... |
7a4f4d2456c5ed0609efe7777d2b9e22854ac449 | social_django/compat.py | social_django/compat.py | # coding=utf-8
import six
import django
from django.db import models
if django.VERSION >= (2, 0):
from django.urls import reverse
else:
from django.core.urlresolvers import reverse
if django.VERSION >= (1, 10):
from django.utils.deprecation import MiddlewareMixin
else:
MiddlewareMixin = object
def g... | # coding=utf-8
import six
import django
from django.db import models
if django.VERSION >= (2, 0):
from django.urls import reverse
else:
from django.core.urlresolvers import reverse
if django.VERSION >= (1, 10):
from django.utils.deprecation import MiddlewareMixin
else:
MiddlewareMixin = object
def g... | Fix getting model of foreign key field. | Fix getting model of foreign key field.
| Python | bsd-3-clause | python-social-auth/social-app-django,python-social-auth/social-app-django,python-social-auth/social-app-django |
54a6031c54c8b64eeeed7a28f7836f886022bdd0 | main.py | main.py | from evaluate_user import evaluate_user
def main():
user_id = ""
while user_id != 'exit':
user_id = raw_input("Enter user id: ")
if user_id != 'exit' and evaluate_user(user_id) == 1:
print("Cannot evaluate user.\n")
if __name__ == "__main__":
main() | from evaluate_user import evaluate_user
from Tkinter import *
from ScrolledText import ScrolledText
from ttk import Frame, Button, Label, Style
import re
class EvaluatorWindow(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Twitte... | Replace line endings with whitespace instead of deleting them. | Replace line endings with whitespace instead of deleting them.
| Python | apache-2.0 | ngrudzinski/sentiment_analysis_437 |
fdc1c82533ca541d6e666f2834b86fa9d7cb9969 | bin/update/deploy_dev_base.py | bin/update/deploy_dev_base.py | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
@task
def database(ctx):
with ctx.lcd(settings.SRC_DIR):
# only ever run this one on demo and dev.
ctx.local("python2.6 manage.py bedrock_truncate_database --yes-i-am-sure")
... | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
@task
def database(ctx):
with ctx.lcd(settings.SRC_DIR):
# only ever run this one on demo and dev.
ctx.local("python2.6 manage.py bedrock_truncate_database --yes-i-am-sure")
... | Call rnasync after truncating db on dev deploy | Call rnasync after truncating db on dev deploy
| Python | mpl-2.0 | ckprice/bedrock,gerv/bedrock,CSCI-462-01-2017/bedrock,ericawright/bedrock,pmclanahan/bedrock,bensternthal/bedrock,pascalchevrel/bedrock,ckprice/bedrock,kyoshino/bedrock,schalkneethling/bedrock,CSCI-462-01-2017/bedrock,pmclanahan/bedrock,amjadm61/bedrock,Jobava/bedrock,mermi/bedrock,alexgibson/bedrock,ckprice/bedrock,gl... |
cba07745953e4b5c2c66c1698841b5f081e5da9d | greenmine/settings/__init__.py | greenmine/settings/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
try:
print "Trying import local.py settings..."
from .local import *
except ImportError:
print "Trying import development.py settings..."
from .development import *
| # -*- coding: utf-8 -*-
from __future__ import (
absolute_import,
print_function
)
import os, sys
try:
print("Trying import local.py settings...", file=sys.stderr)
from .local import *
except ImportError:
print("Trying import development.py settings...", file=sys.stderr)
from .development impor... | Send more print message to sys.stderr | Smallfix: Send more print message to sys.stderr
| Python | agpl-3.0 | joshisa/taiga-back,WALR/taiga-back,jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,CMLL/taiga-back,astronaut1712/taiga-back,bdang2012/taiga-back-casting,joshisa/taiga-back,dycodedev/taiga-back,Zaneh-/bearded-tribble-back,CoolCloud/taiga-back,Rademade/taiga-back,gam-phon/taiga-back,bdang2012/taiga-back-casting,19kest... |
d28cb95d7033b34e34661700dc8a1aafd6a61bc8 | src/db/schema.py | src/db/schema.py | import logging
from datetime import datetime
import sqlalchemy as sql
from sqlalchemy import Table, Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
import db
Base = declarative_base()
Base.metadata.bind = db.engine
class Round(Ba... | import logging
from datetime import datetime
import sqlalchemy as sql
from sqlalchemy import Table, Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
import db
Base = declarative_base()
Base.metadata.bind = db.engine
class Round(Ba... | Allow round_id for submissions to be calculated dynamically | Allow round_id for submissions to be calculated dynamically
| Python | apache-2.0 | pascalc/narrative-roulette,pascalc/narrative-roulette |
028cf52b2d09c6cd1ca8c0e1e779cd5d8ff3ca3a | tests/test_ubuntupkg.py | tests/test_ubuntupkg.py | # MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.
import pytest
pytestmark = pytest.mark.asyncio
async def test_ubuntupkg(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"
async def test_ubuntupkg_strip_release(get_version):
as... | # MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.
from flaky import flaky
import pytest
pytestmark = pytest.mark.asyncio
@flaky
async def test_ubuntupkg(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"
@flaky
async def test_ubuntu... | Mark ubuntupkg tests as flaky | Mark ubuntupkg tests as flaky
| Python | mit | lilydjwg/nvchecker |
67f39d1b51014b06877b93ba32a18a1f53cd231c | mama_cas/urls.py | mama_cas/urls.py | """
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import never_cache
from mama_cas.views import login
from mama_cas.views import logout
from mama_cas.views import validate
from mama_cas.views ... | """
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import never_cache
from mama_cas.views import login
from mama_cas.views import logout
from mama_cas.views import validate
from mama_cas.views ... | Remove prefix from URL paths | Remove prefix from URL paths
This path information should be set by the including project.
| Python | bsd-3-clause | harlov/django-mama-cas,harlov/django-mama-cas,forcityplatform/django-mama-cas,orbitvu/django-mama-cas,forcityplatform/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,jbittel/django-mama-cas |
b379c60e59584c931cc441fd1d64a9049d1c2b55 | src/formatter.py | src/formatter.py | import json
from collections import OrderedDict
from .command import Command
from .settings import FormatterSettings
class Formatter():
def __init__(self, name, command='', args=''):
self.__name = name
self.__command = command.split(' ') if command else []
self.__args = args.split(' ') if ... | import json
from collections import OrderedDict
from .command import Command
from .settings import FormatterSettings
class Formatter():
def __init__(self, name, command=None, args=None, formatter=None):
self.__name = name
self.__format = formatter
self.__settings = FormatterSettings(name.l... | Allow format function to be provided to Formatter constructor | Allow format function to be provided to Formatter constructor
| Python | mit | Rypac/sublime-format |
1ae797e18286fd781797689a567f9d23ab3179d1 | modules/tools.py | modules/tools.py | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callbac... | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def update(self, time):
if self.expired:
return... | Add a restart() method to Timer. | Add a restart() method to Timer.
| Python | mit | kxgames/kxg |
5cdc5755b1a687c9b34bfd575163ac367816f12a | migrations/versions/3961ccb5d884_increase_artifact_name_length.py | migrations/versions/3961ccb5d884_increase_artifact_name_length.py | """increase artifact name length
Revision ID: 3961ccb5d884
Revises: 1b229c83511d
Create Date: 2015-11-05 15:34:28.189700
"""
# revision identifiers, used by Alembic.
revision = '3961ccb5d884'
down_revision = '1b229c83511d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('artifact... | """increase artifact name length
Revision ID: 3961ccb5d884
Revises: 1b229c83511d
Create Date: 2015-11-05 15:34:28.189700
"""
# revision identifiers, used by Alembic.
revision = '3961ccb5d884'
down_revision = '1b229c83511d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('artifact... | Fix extend artifact name migration script. | Fix extend artifact name migration script.
Test Plan: ran migration locally and checked table schema
Reviewers: anupc, kylec
Reviewed By: kylec
Subscribers: changesbot
Differential Revision: https://tails.corp.dropbox.com/D151824
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes |
223f248a1d1791b1a098876317905f4930330487 | salesforce/backend/__init__.py | salesforce/backend/__init__.py | # django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
Database backend for the Salesforce API.
"""
import socket
from django.conf import settings
import logging
log = logging.getLogger(__name__)
sf_alias = getattr(settings, ... | # django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
Database backend for the Salesforce API.
No code in this directory is used with standard databases, even if a standard
database is used for running some application tests ... | Comment about the directory structure | Comment about the directory structure
| Python | mit | django-salesforce/django-salesforce,chromakey/django-salesforce,django-salesforce/django-salesforce,philchristensen/django-salesforce,chromakey/django-salesforce,philchristensen/django-salesforce,chromakey/django-salesforce,hynekcer/django-salesforce,philchristensen/django-salesforce,hynekcer/django-salesforce,hynekcer... |
b23ed2d6d74c4604e9bb7b55faf121661ee9f785 | statePointsGen.py | statePointsGen.py | # Thermo State Solver
# Solves for state parameters at various points in a simple thermodynamic model
# Developed by Neal DeBuhr
import csv
import argparse
import itertools
| # Thermo State Solver
# Solves for state parameters at various points in a simple thermodynamic model
# Developed by Neal DeBuhr
import csv
import argparse
import itertools
import string
numPoints=int(input('Number of points in analysis:'))
num2alpha = dict(zip(range(1, 27), string.ascii_uppercase))
outRow=['']
outR... | Develop program for points file generation | Develop program for points file generation
| Python | mit | ndebuhr/thermo-state-solver,ndebuhr/thermo-state-solver |
ef003a3ebf14545927d055a0deda7e1982e90e53 | scripts/capnp_test_pycapnp.py | scripts/capnp_test_pycapnp.py | #!/usr/bin/env python
import capnp
import os
capnp.add_import_hook([os.getcwd(), "/usr/local/include/"]) # change this to be auto-detected?
import test_capnp
import sys
def decode(name):
print getattr(test_capnp, name)._short_str()
def encode(name):
val = getattr(test_capnp, name)
class_name = name[0].u... | #!/usr/bin/env python
from __future__ import print_function
import capnp
import os
capnp.add_import_hook([os.getcwd(), "/usr/local/include/"]) # change this to be auto-detected?
import test_capnp
import sys
def decode(name):
class_name = name[0].upper() + name[1:]
print(getattr(test_capnp, class_name).from_b... | Fix decode test to actually decode message from stdin | Fix decode test to actually decode message from stdin
| Python | bsd-2-clause | tempbottle/pycapnp,tempbottle/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,SymbiFlow/pycapnp,SymbiFlow/pycapnp,rcrowder/pycapnp,jparyani/pycapnp,jparyani/pycapnp,rcrowder/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,rcrowder/pycapnp,rcrowder/pycapnp,tempbottle/pycapnp |
52e9390d88062e9442b18a7793e6696a36f5b9c3 | testinfra/functional/test_tor_interfaces.py | testinfra/functional/test_tor_interfaces.py | import os
import re
import pytest
sdvars = pytest.securedrop_test_vars
@pytest.mark.xfail
@pytest.mark.parametrize('site', sdvars.tor_url_files)
@pytest.mark.skipif(os.environ.get('FPF_CI', 'false') == "false",
reason="Can only assure Tor is configured in CI atm")
def test_www(Command, site):
... | import os
import re
import pytest
sdvars = pytest.securedrop_test_vars
@pytest.mark.parametrize('site', sdvars.tor_url_files)
@pytest.mark.skipif(os.environ.get('FPF_CI', 'false') == "false",
reason="Can only assure Tor is configured in CI atm")
def test_www(Command, site):
"""
Ensure tor... | Remove XFAIL on functional tor test | Remove XFAIL on functional tor test
| Python | agpl-3.0 | conorsch/securedrop,ehartsuyker/securedrop,garrettr/securedrop,ehartsuyker/securedrop,conorsch/securedrop,heartsucker/securedrop,garrettr/securedrop,ehartsuyker/securedrop,ehartsuyker/securedrop,conorsch/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,conorsch/securedrop,heartsucker/securedrop,ehartsuyker/secu... |
aee49d59b76400389ffa768950b479094059e385 | linguist/tests/translations.py | linguist/tests/translations.py | # -*- coding: utf-8 -*_
from django.db import models
from ..base import ModelTranslationBase
from ..mixins import ModelMixin, ManagerMixin
class FooManager(ManagerMixin, models.Manager):
pass
class BarManager(ManagerMixin, models.Manager):
pass
class FooModel(ModelMixin, models.Model):
title = models... | # -*- coding: utf-8 -*_
from django.db import models
from ..base import ModelTranslationBase
from ..mixins import ModelMixin, ManagerMixin
class FooManager(ManagerMixin, models.Manager):
pass
class BarManager(ManagerMixin, models.Manager):
pass
class FooModel(ModelMixin, models.Model):
title = models... | Update test models for new metaclass support. | Update test models for new metaclass support.
| Python | mit | ulule/django-linguist |
786bc416ca00c7021f5881e459d2634e8fcd8458 | src/vdb/src/_vdb/common.py | src/vdb/src/_vdb/common.py | # Copyright (c) 2005-2016 Stefanos Harhalakis <v13@v13.gr>
# Copyright (c) 2016-2022 Google LLC
#
# 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
... | # Copyright (c) 2005-2016 Stefanos Harhalakis <v13@v13.gr>
# Copyright (c) 2016-2022 Google LLC
#
# 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
... | Add ipaddress.IPv[46]Network to the supported types | Add ipaddress.IPv[46]Network to the supported types
| Python | apache-2.0 | sharhalakis/vdns |
decc454dfb50258eaab4635379b1c18470246f62 | indico/modules/events/views.py | indico/modules/events/views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 3 of the
# License, or (a... | Fix highlighting of "External ID Types" menu entry | Fix highlighting of "External ID Types" menu entry
| Python | mit | ThiefMaster/indico,pferreir/indico,mic4ael/indico,ThiefMaster/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,pferreir/indico,OmeGak/indico,OmeGak/indico,mic4ael/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,i... |
6d3180ffd84e126ee4441a367a48a750d270892e | sumy/document/_sentence.py | sumy/document/_sentence.py | # -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import to_unicode, to_string, unicode_compatible
@unicode_compatible
class Sentence(object):
__slots__ = ("_words", "_is_heading",)
def ... | # -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import re
from itertools import chain
from .._compat import to_unicode, to_string, unicode_compatible
_WORD_PATTERN = re.compile(r"^[^\W_]+$", re.UNICODE)
@unicode_compatible
class Sent... | Return only alphabetic words from sentence | Return only alphabetic words from sentence
| Python | apache-2.0 | miso-belica/sumy,miso-belica/sumy |
503924f054f6f81eb08eda9884e5e4adc4df1609 | cupcake/smush/plot.py | cupcake/smush/plot.py | """
User-facing interface for plotting all dimensionality reduction algorithms
"""
def smushplot(data, smusher='PCA', x=1, y=2, n_components=2, marker='o',
marker_order=None, text=False, text_order=None, linewidth=1,
linewidth_order=None, edgecolor='k', edgecolor_order=None,
s... | """
User-facing interface for plotting all dimensionality reduction algorithms
"""
def smushplot(data, smusher='PCA', x=1, y=2, n_components=2, marker='o',
marker_order=None, text=False, text_order=None, linewidth=1,
linewidth_order=None, edgecolor='k', edgecolor_order=None,
s... | Add x, y and n_components to docstring | Add x, y and n_components to docstring
| Python | bsd-3-clause | olgabot/cupcake |
a81c5bf24ab0271c60ed1db97d93c7d2e5ec6234 | cutplanner/planner.py | cutplanner/planner.py | import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_... | import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_... | Make largest stock a property | Make largest stock a property
| Python | mit | alanc10n/py-cutplanner |
75d7441f90e077eeeb955e4eb0c514a1736a88fb | tohu/v3/utils.py | tohu/v3/utils.py | __all__ = ['identity', 'print_generated_sequence']
def identity(x):
"""
Helper function which returns its argument unchanged.
That is, `identity(x)` returns `x` for any input `x`.
"""
return x
def print_generated_sequence(gen, num, *, sep=", ", seed=None):
"""
Helper function which print... | from collections import namedtuple
__all__ = ['identity', 'print_generated_sequence']
def identity(x):
"""
Helper function which returns its argument unchanged.
That is, `identity(x)` returns `x` for any input `x`.
"""
return x
def print_generated_sequence(gen, num, *, sep=", ", seed=None):
... | Add helper function to produce some dummy tuples (for testing and debugging) | Add helper function to produce some dummy tuples (for testing and debugging)
| Python | mit | maxalbert/tohu |
9e0ab4bfcd9e22447e66bb87f2ed849ffcd0c57a | shutter/service.py | shutter/service.py | class Shutter(object):
def setup_database(self, pool):
self.__dbpool = pool
def snapshots(self, url):
def _get_snapshot_urls(txn, url):
txn.execute("""SELECT s.file_path
FROM shutter.urls u
,shutter.snapshots s
... | class Shutter(object):
def setup_database(self, pool):
self.__dbpool = pool
def snapshots(self, url):
def _get_snapshot_urls(txn, url):
txn.execute("""SELECT s.file_path
FROM shutter.urls u
,shutter.snapshots s
... | Remove additional nesting from Shutter.snapshots results | Remove additional nesting from Shutter.snapshots results
In order to remove the bug we flatten the return value of txn.fetchall().
After the change rerunning the tests confirms that the service is behaving accordingly to our expectations.
| Python | bsd-3-clause | mulander/shutter |
a1cd2c326f9dba608ee3c6ce82dd425e93e8265d | python/xchainer/__init__.py | python/xchainer/__init__.py | from xchainer._core import * # NOQA
_global_context = Context()
_global_context.get_backend('native')
set_global_default_context(_global_context)
| from xchainer._core import * # NOQA
_global_context = Context()
set_global_default_context(_global_context)
set_default_device('native')
| Set the default device to native in Python binding | Set the default device to native in Python binding
| Python | mit | ktnyt/chainer,hvy/chainer,hvy/chainer,pfnet/chainer,chainer/chainer,ktnyt/chainer,jnishi/chainer,okuta/chainer,hvy/chainer,ktnyt/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,wkentaro/chainer,ktnyt/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,okuta/chainer,hvy/chainer,tkerola/chainer,chainer/... |
99dd45582cba9f54a5cc9042812d255fe57b1222 | oauthclientbridge/__init__.py | oauthclientbridge/__init__.py | # flake8: noqa
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
__version__ = '1.0.1'
app = Flask(__name__)
app.config.from_object('oauthclientbridge.default_settings')
app.config.from_envvar('OAUTH_SETTINGS', silent=True)
if app.config['OAUTH_NUM_PROXIES']:
wrapper = ProxyFix(app.wsgi_app,... | # flake8: noqa
from flask import Flask
try:
from werkzeug.middleware.proxy_fix import ProxyFix
except ImportError:
from werkzeug.contrib.fixers import ProxyFix
__version__ = '1.0.1'
app = Flask(__name__)
app.config.from_object('oauthclientbridge.default_settings')
app.config.from_envvar('OAUTH_SETTINGS', si... | Support new location of ProxyFix helper | Support new location of ProxyFix helper
| Python | apache-2.0 | adamcik/oauthclientbridge |
d48e59f4b1174529a4d2eca8731472a5bf371621 | simpleseo/templatetags/seo.py | simpleseo/templatetags/seo.py | from django.template import Library
from django.utils.translation import get_language
from simpleseo import settings
from simpleseo.models import SeoMetadata
register = Library()
@register.filter
def single_quotes(description):
return description.replace('\"', '\'')
@register.inclusion_tag('simpleseo/metadata... | from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language
from simpleseo import settings
from simpleseo.models import SeoMetadata
register = Library()
@register.filter
def single_quotes(description):
return description.replace('\"', '\'')... | Allow to set default value in template | Allow to set default value in template
| Python | bsd-3-clause | Glamping-Hub/django-painless-seo,Glamping-Hub/django-painless-seo,AMongeMoreno/django-painless-seo,AMongeMoreno/django-painless-seo |
91122afafa9fb5872f905dde391ce5b587d5d70a | frappe/patches/v8_0/install_new_build_system_requirements.py | frappe/patches/v8_0/install_new_build_system_requirements.py | import subprocess
def execute():
subprocess.call([
'npm', 'install',
'babel-core',
'chokidar',
'babel-preset-es2015',
'babel-preset-es2016',
'babel-preset-es2017',
'babel-preset-babili'
]) | from subprocess import Popen, call, PIPE
def execute():
# update nodejs version if brew exists
p = Popen(['which', 'brew'], stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
if output:
subprocess.call(['brew', 'upgrade', 'node'])
else:
print 'Please update your NodeJS version'... | Update build system requirements patch | Update build system requirements patch
| Python | mit | mhbu50/frappe,ESS-LLP/frappe,tmimori/frappe,frappe/frappe,mhbu50/frappe,ESS-LLP/frappe,mbauskar/frappe,bcornwellmott/frappe,bohlian/frappe,adityahase/frappe,tmimori/frappe,paurosello/frappe,almeidapaulopt/frappe,RicardoJohann/frappe,paurosello/frappe,ESS-LLP/frappe,mhbu50/frappe,bohlian/frappe,chdecultot/frappe,frappe/... |
bd540e3a0bcc13c6c50c1d72f1982084ab5cb87e | django_enumfield/fields.py | django_enumfield/fields.py | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
... | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
... | Allow string arguments (as slugs) when saving/updating EnumFields | Allow string arguments (as slugs) when saving/updating EnumFields
This fixes issues where:
MyModel.objects.update(my_enum_field='slug')
would result in SQL like:
UPDATE app_mymodel SET my_enum_field = 'slug'
.. instead of what that's slug's integer value is.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039... | Python | bsd-3-clause | playfire/django-enumfield |
e4dfb192d9984973888354ae73f2edc8486a9843 | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2018 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2018 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released ... | Add () to fixture definitions | Add () to fixture definitions | Python | mit | njvack/masterfile |
aba661dccae7ef43bdb43d9909b9e84b632bb7a4 | qipipe/helpers/file_helper.py | qipipe/helpers/file_helper.py | import os
class FileIterator(object):
"""
This FileIterator iterates over the paths contained in one or more directories.
"""
def __init__(self, *paths):
"""
@param paths: the file or directory paths.
"""
self._paths = paths
def __iter__(self):
return se... | import os
class FileIterator(object):
"""
This FileIterator iterates over the paths contained in one or more directories.
"""
def __init__(self, *paths):
"""
@param paths: the file or directory paths.
"""
self._paths = paths
def __iter__(self):
return se... | Rename paths variable to fnames. | Rename paths variable to fnames.
| Python | bsd-2-clause | ohsu-qin/qipipe |
ea3e327bb602689e136479ce41f568aa2ee47cf4 | databot/utils/html.py | databot/utils/html.py | import bs4
import cgi
def get_content(data, errors='strict'):
headers = {k.lower(): v for k, v in data.get('headers', {}).items()}
content_type_header = headers.get('content-type', '')
content_type, params = cgi.parse_header(content_type_header)
if content_type.lower() in ('text/html', 'text/xml'):
... | import bs4
import cgi
def get_page_encoding(soup, default_encoding=None):
for meta in soup.select('head > meta[http-equiv="Content-Type"]'):
content_type, params = cgi.parse_header(meta['content'])
if 'charset' in params:
return params['charset']
return default_encoding
def get_c... | Improve detection of page encoding | Improve detection of page encoding
| Python | agpl-3.0 | sirex/databot,sirex/databot |
52884380ce9a6dc79e44e3ce81b7e9757de6fb04 | tests/integration/test_impersonation.py | tests/integration/test_impersonation.py | import pytest
from tenable_io.api.users import UserCreateRequest
from tests.base import BaseTest
from tests.config import TenableIOTestConfig
class TestImpersonation(BaseTest):
@pytest.fixture(scope='class')
def user(self, app, client):
user_id = client.users_api.create(UserCreateRequest(
... | import pytest
from tenable_io.api.users import UserCreateRequest
from tests.base import BaseTest
from tests.config import TenableIOTestConfig
class TestImpersonation(BaseTest):
@pytest.fixture(scope='class')
def user(self, app, client):
user_id = client.users_api.create(UserCreateRequest(
... | Update password in unit test to comply with password rules | Update password in unit test to comply with password rules
| Python | mit | tenable/Tenable.io-SDK-for-Python |
8f330d4d07ed548a9cab348895124f5f5d92a6e8 | dask_ndmeasure/_test_utils.py | dask_ndmeasure/_test_utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask.array.utils
def _assert_eq_nan(a, b, **kwargs):
a = a.copy()
b = b.copy()
a_nan = (a != a)
b_nan = (b != b)
a[a_nan] = 0
b[b_nan] = 0
dask.array.utils.assert_eq(a_nan, b_nan, **kwargs)
dask.array.utils.asse... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask.array.utils
def _assert_eq_nan(a, b, **kwargs):
a = a.copy()
b = b.copy()
a = a[...]
b = b[...]
a_nan = (a != a)
b_nan = (b != b)
a[a_nan] = 0
b[b_nan] = 0
dask.array.utils.assert_eq(a_nan, b_nan, **kw... | Handle scalar values in _assert_eq_nan | Handle scalar values in _assert_eq_nan
Add some special handling in `_assert_eq_nan` to handle having scalar
values passed in. Basically ensure that everything provided is an array.
This is a no-op for arrays, but converts scalars into 0-D arrays. By
doing this, we are able to use the same `nan` handling code. Also
co... | Python | bsd-3-clause | dask-image/dask-ndmeasure |
892bc14cc087c47909778a178772d0895d2fb599 | docker/chemml/src/run.py | docker/chemml/src/run.py | import json
from chemml.models.keras.trained import OrganicLorentzLorenz
from openbabel import OBMol, OBConversion
def ob_convert_str(str_data, in_format, out_format):
mol = OBMol()
conv = OBConversion()
conv.SetInFormat(in_format)
conv.SetOutFormat(out_format)
conv.ReadString(mol, str_data)
... | import json
from chemml.models.keras.trained import OrganicLorentzLorenz
from openbabel import OBMol, OBConversion
def ob_convert_str(str_data, in_format, out_format):
mol = OBMol()
conv = OBConversion()
conv.SetInFormat(in_format)
conv.SetOutFormat(out_format)
conv.ReadString(mol, str_data)
... | Change structure of the output properties | Change structure of the output properties
| Python | bsd-3-clause | OpenChemistry/mongochemdeploy,OpenChemistry/mongochemdeploy |
5b0f7412f88400e61a05e694d4883389d812f3d2 | tests/runtests.py | tests/runtests.py | #!/usr/bin/env python
import os
import sys
from unittest import defaultTestLoader, TextTestRunner, TestSuite
TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n')
def make_suite(prefix='', extra=()):
tests = TESTS + extra
test_names = list(prefix + x for ... | #!/usr/bin/env python
import os
import sys
from unittest import defaultTestLoader, TextTestRunner, TestSuite
TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n')
def make_suite(prefix='', extra=()):
tests = TESTS + extra
test_names = list(prefix + x for ... | Add back in running of extra tests | Add back in running of extra tests
| Python | bsd-3-clause | maxcountryman/wtforms |
c272e73c0d3112425e0ba25c58448f7c1d492d11 | api/src/SearchApi.py | api/src/SearchApi.py | from apiclient.discovery import build
import json
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
devKeyFile = open("search-api.key", "rb")
DEVELOPER_KEY = devKeyF... | from apiclient.discovery import build
import json
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
devKeyFile = open("search-api.key", "rb")
DEVELOPER_KEY = devKeyF... | Update search api filter out unwanted information | Update search api filter out unwanted information
| Python | mit | jghibiki/mopey,jghibiki/mopey,jghibiki/mopey,jghibiki/mopey,jghibiki/mopey |
444bba442e581226b650af929c85ccc885c60297 | microcosm/tracing.py | microcosm/tracing.py | from jaeger_client.config import (
DEFAULT_REPORTING_HOST,
DEFAULT_REPORTING_PORT,
DEFAULT_SAMPLING_PORT,
Config,
)
from microcosm.api import binding, defaults, typed
SPAN_NAME = "span_name"
@binding("tracer")
@defaults(
sample_type="ratelimiting",
sample_param=typed(int, 10),
sampling_... | from jaeger_client.config import (
DEFAULT_REPORTING_HOST,
DEFAULT_REPORTING_PORT,
DEFAULT_SAMPLING_PORT,
Config,
)
from microcosm.api import binding, defaults, typed
from microcosm.config.types import boolean
SPAN_NAME = "span_name"
@binding("tracer")
@defaults(
sample_type="ratelimiting",
... | Disable jaeger logging by default | Disable jaeger logging by default
| Python | apache-2.0 | globality-corp/microcosm,globality-corp/microcosm |
864555f431a5dc0560e93ef9055e6cc49c499835 | tests/test_basic_create.py | tests/test_basic_create.py | from common import *
class TestBasicCreate(TestCase):
def test_create_default_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
spec = dict(name=mini_uuid())
proj = sg.create(type_, spec)
self.assertIsNot(spec, proj)
self.assertEqual(len(proj),... | from common import *
class TestBasicCreate(TestCase):
def test_create_default_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
spec = dict(name=mini_uuid())
proj = sg.create(type_, spec)
print proj
self.assertIsNot(spec, proj)
self.ass... | Adjust test for returned name | Adjust test for returned name | Python | bsd-3-clause | westernx/sgmock |
1b80972fe97bebbb20d9e6073b41d286f253c1ef | documents/views/utils.py | documents/views/utils.py | import mimetypes
import os
from django.http import HttpResponse
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def re... | import mimetypes
import os
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
m... | Use FileWrapper to send files to browser in chunks of 8KB | Use FileWrapper to send files to browser in chunks of 8KB
Maybe this will fix a problem on the test server when it tries to send a huge file.
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer |
a12e3f0de9e8c10c279d795744f87b7e716bd34c | markitup_filebrowser/fields.py | markitup_filebrowser/fields.py | from markitup.fields import MarkupField
import widgets
class MarkupFilebrowserFiled(MarkupField):
def formfield(self, **kwargs):
defaults = {'widget': widgets.MarkitUpFilebrowserWiget}
defaults.update(kwargs)
return super(MarkupFilebrowserFiled, self).formfield(**defaults)
from django.con... | from markitup.fields import MarkupField
import widgets
class MarkupFilebrowserFiled(MarkupField):
def formfield(self, **kwargs):
defaults = {'widget': widgets.MarkitUpFilebrowserWiget}
defaults.update(kwargs)
return super(MarkupFilebrowserFiled, self).formfield(**defaults)
from django.con... | Allow south to handle MarkupFilebrowserFiled | Allow south to handle MarkupFilebrowserFiled
| Python | bsd-3-clause | Iv/django-markiup-filebrowser,Iv/django-markiup-filebrowser |
2ace9ce514d7299a8f3e8dca134a6e4eb3284937 | parser2.py | parser2.py | from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
class Hand:
def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None):
self.seats = se
self.preflop = p
self.flop = f
self.turn = t
self.river = r
self.summ... | from pprint import pprint
class Hand:
def __init__(self, string):
segments = "seats preflop flop turn river".split()
self.seats = None
self.preflop = None
self.flop = None
self.turn = None
self.river = None
self.summary = None
## step 2: split each ha... | Move parsing loop into the class itself. | Move parsing loop into the class itself.
| Python | mit | zimolzak/Ignition-poker-parser |
eb5dc3ef7e7904549f50a4255477ed50d3ee53ab | twinsies/clock.py | twinsies/clock.py | from apscheduler.schedulers.blocking import BlockingScheduler
from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins,
update_status)
from memory_profiler import profile
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=16)
@profile
def twinsy_finder(fetch_size=10000):
... | from apscheduler.schedulers.blocking import BlockingScheduler
from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins,
update_status)
from memory_profiler import profile
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=16)
@profile
def twinsy_finder(fetch_size=5000):
... | Reduce fetch size to 5000. Don't run job on startup. | Reduce fetch size to 5000. Don't run job on startup.
| Python | mit | kkwteh/twinyewest |
796e734f67ea3c4afcb6c17204108d9b2c3d7120 | website/forms.py | website/forms.py | from django import forms
from .models import Issue,Bounty,UserProfile
from django.contrib.auth.models import User
class IssueCreateForm(forms.ModelForm):
issueUrl = forms.CharField(label="issueUrl")
class Meta:
model = Issue
fields = ('title','language','content')
class BountyCreateForm(forms.... | from django import forms
from .models import Issue,Bounty,UserProfile
from django.contrib.auth.models import User
class IssueCreateForm(forms.ModelForm):
issueUrl = forms.CharField(label="issueUrl")
class Meta:
model = Issue
fields = ('title','language','content')
class BountyCreateForm(forms.... | Validate email id, while editing user profile | Validate email id, while editing user profile
| Python | agpl-3.0 | CoderBounty/coderbounty,CoderBounty/coderbounty,atuljain/coderbounty,atuljain/coderbounty,atuljain/coderbounty,CoderBounty/coderbounty,atuljain/coderbounty,CoderBounty/coderbounty |
7b9a04cb8655fad955829936c2b43b9ca37b3fe8 | ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/db.py | ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/db.py | import uuid
from ckan import model
from ckan.lib import dictization
from ckan.plugins import toolkit
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base
import logging
log = logging.getLogger(__name__)
Base = declarative_base()
def make_uuid():
return unicode(uuid.uuid4(... | import uuid
from ckan import model
from ckan.lib import dictization
from ckan.plugins import toolkit
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base
import logging
log = logging.getLogger(__name__)
Base = declarative_base()
def make_uuid():
return unicode(uuid.uuid4(... | Add state column to user create api | Add state column to user create api
| Python | mit | vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog |
98b0eb3d492cb816db7ffa7ad062dde36a1feadf | tests/unit/test_gettext.py | tests/unit/test_gettext.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, 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/l... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, 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/l... | Use testtools as test base class. | Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtoo... | Python | apache-2.0 | varunarya10/oslo.i18n,openstack/oslo.i18n |
c65306f78f1eb97714fd2086d20ff781faf78c3a | problems/starterpackages/SteinerStarter.py | problems/starterpackages/SteinerStarter.py | import math
import sys
# A helper class for working with points.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Edge:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def getProblem(filename):
pts = []
with open(filename, 'r') as input:
for line in input:
l = line.split(' ')
... | import math
import sys
# A helper class for working with points.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Edge:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
# Gets a problem from a file as an list of points.
def getProblem(filename):
pts = []
with open(filename, 'r') as ... | Make py starterpackage more like java/c++ one | Make py starterpackage more like java/c++ one
| Python | mit | HMProgrammingClub/NYCSL,HMProgrammingClub/NYCSL,HMProgrammingClub/NYCSL,HMProgrammingClub/NYCSL,HMProgrammingClub/NYCSL,HMProgrammingClub/NYCSL,HMProgrammingClub/NYCSL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.