commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3
values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
3f2d7df4082b39c6f1fce04ff015b06ab30ad9a1 | Use distutils.version instead of pkg_resources | tools/sosreport/tower.py | tools/sosreport/tower.py | # Copyright (c) 2014 Ansible, Inc.
# All Rights Reserved.
import sos
from distutils.version import LooseVersion
if LooseVersion(sos.__version__) >= LooseVersion('3.0'):
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin
class tower(Plugin, RedHatPlugin, UbuntuPlugin):
'''Collect Ansible Tower... | # Copyright (c) 2014 Ansible, Inc.
# All Rights Reserved.
import sos
from pkg_resources import parse_version
if parse_version(sos.__version__) >= parse_version('3.0'):
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin
class tower(Plugin, RedHatPlugin, UbuntuPlugin):
'''Collect Ansible Tower ... | Python | 0.000001 |
9c062d779fe7cb3fc439ff03f25ade58f6045ee5 | fix PythonActivity path | androidhelpers.py | androidhelpers.py | from jnius import PythonJavaClass, java_method, autoclass
# SERVICE = Autoclass('org.renpy.PythonService').mService
SERVICE = autoclass('org.renpy.android.PythonActivity').mActivity
Intent = autoclass('android.content.Intent')
BluetoothManager = SERVICE.getSystemService(SERVICE.BLUETOOTH_SERVICE)
ADAPTER = Bluetoot... | from jnius import PythonJavaClass, java_method, autoclass
# SERVICE = Autoclass('org.renpy.PythonService').mService
SERVICE = autoclass('org.renpy.PythonActivity').mActivity
Intent = autoclass('android.content.Intent')
BluetoothManager = SERVICE.getSystemService(SERVICE.BLUETOOTH_SERVICE)
ADAPTER = BluetoothManager... | Python | 0.00012 |
9ff6f01f7319270f66e2cc32aa5201ad53228e8f | Add __init__ and __call_internal__ for isotropicHernquistdf | galpy/df/isotropicHernquistdf.py | galpy/df/isotropicHernquistdf.py | # Class that implements isotropic spherical Hernquist DF
# computed using the Eddington formula
from .sphericaldf import sphericaldf
from .Eddingtondf import Eddingtondf
class isotropicHernquistdf(Eddingtondf):
"""Class that implements isotropic spherical Hernquist DF computed using the Eddington formula"""
de... | # Class that implements isotropic spherical Hernquist DF
# computed using the Eddington formula
from .sphericaldf import sphericaldf
from .Eddingtondf import Eddingtondf
class isotropicHernquistdf(Eddingtondf):
"""Class that implements isotropic spherical Hernquist DF computed using the Eddington formula"""
de... | Python | 0.000043 |
07f39fbd3e068a01105f0c3a13523d9fbd78cc29 | add tests for pathway results | tests/test_pathway_predictions.py | tests/test_pathway_predictions.py | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | Python | 0 |
035f77f9f5db6088a9331e0d9beb0c393982fbe4 | rename function plus refactor | web/impact/impact/v1/views/mentor_program_office_hour_list_view.py | web/impact/impact/v1/views/mentor_program_office_hour_list_view.py | # MIT License
# Copyright (c) 2019 MassChallenge, Inc.
from django.db.models import Value as V
from django.db.models.functions import Concat
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import (
MentorProgramOfficeHourHelper,
)
ID_FIELDS = ['mentor_id', 'finalist_id']
NAME_FIELDS... | # MIT License
# Copyright (c) 2019 MassChallenge, Inc.
from django.db.models import Value as V
from django.db.models.functions import Concat
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import (
MentorProgramOfficeHourHelper,
)
ID_FIELDS = ['mentor_id', 'finalist_id']
NAME_FIELDS... | Python | 0.000001 |
c5c509ff9e2c4599fcf51044abc9e7cbe4a152e1 | remove redundant method [skip ci] | custom/enikshay/management/commands/base_model_reconciliation.py | custom/enikshay/management/commands/base_model_reconciliation.py | import csv
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import EmailMessage
from django.conf import settings
from custom.enikshay.const import ENROLLED_IN_PRIVATE
class BaseModelReconciliationCommand(BaseCommand):
email_subject = None
... | import csv
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import EmailMessage
from django.conf import settings
from custom.enikshay.const import ENROLLED_IN_PRIVATE
class BaseModelReconciliationCommand(BaseCommand):
email_subject = None
... | Python | 0.000003 |
8f90b8cd67b6bca0c8c2123c229b18bd0ee078d8 | Implement FlatfileCommentProvider._load_one. | firmant/plugins/datasource/flatfile/comments.py | firmant/plugins/datasource/flatfile/comments.py | import datetime
import pytz
import os
import re
from firmant.utils import not_implemented
from firmant.datasource.comments import Comment
comment_re = r'(?P<year>\d{4}),(?P<month>\d{2}),(?P<day>\d{2}),(?P<slug>.+)' +\
r',(?P<created>[1-9][0-9]*),(?P<id>[0-9a-f]{40})'
comment_re = re.compile(comment_re)
class F... | import datetime
import pytz
import os
import re
from firmant.utils import not_implemented
comment_re = r'(?P<year>\d{4}),(?P<month>\d{2}),(?P<day>\d{2}),(?P<slug>.+)' +\
r',(?P<created>[1-9][0-9]*),(?P<id>[0-9a-f]{40})'
comment_re = re.compile(comment_re)
class FlatfileCommentProvider(object):
def __init_... | Python | 0 |
68ecbb59c856a20f8f00cae47f1075086da982c7 | Add bitmask imports to nddata.__init__.py | astropy/nddata/__init__.py | astropy/nddata/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData`
class and related tools to manage n-dimensional array-based data (e.g.
CCD images, IFU Data, grid-based simulation data, ...). This is more than
just `numpy.ndarray` objects, becaus... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData`
class and related tools to manage n-dimensional array-based data (e.g.
CCD images, IFU Data, grid-based simulation data, ...). This is more than
just `numpy.ndarray` objects, becaus... | Python | 0.000015 |
1156be60da01ee34230dcf5e9e993e72fbe7b635 | make linter happy | test_project/test_project/urls.py | test_project/test_project/urls.py | """test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | """test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | Python | 0.000001 |
e716a71bad4e02410e2a0908d630abbee1d4c691 | Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. | django/contrib/admin/__init__.py | django/contrib/admin/__init__.py | # ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInli... | from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. T... | Python | 0.000002 |
74b3b60cfe6f12f119ac91f04177abc4c7427e5c | bump version | sensorbee/_version.py | sensorbee/_version.py | # -*- coding: utf-8 -*-
__version__ = '0.1.2'
| # -*- coding: utf-8 -*-
__version__ = '0.1.1'
| Python | 0 |
ff41218c0a63959a34969eefafd9951c48ef667f | convert `test/test_sparql/test_sparql_parser.py` to pytest (#2063) | test/test_sparql/test_sparql_parser.py | test/test_sparql/test_sparql_parser.py | import math
import sys
from typing import Set, Tuple
from rdflib import Graph, Literal
from rdflib.namespace import Namespace
from rdflib.plugins.sparql.processor import processUpdate
from rdflib.term import Node
def triple_set(graph: Graph) -> Set[Tuple[Node, Node, Node]]:
return set(graph.triples((None, None, ... | import math
import sys
import unittest
from typing import Set, Tuple
from rdflib import Graph, Literal
from rdflib.namespace import Namespace
from rdflib.plugins.sparql.processor import processUpdate
from rdflib.term import Node
def triple_set(graph: Graph) -> Set[Tuple[Node, Node, Node]]:
return set(graph.tripl... | Python | 0 |
6668b6daca1707be4bacfcf26f03af94b6c82551 | raise useful error if dir missing #1540 | bcbio/upload/filesystem.py | bcbio/upload/filesystem.py | """Extract files from processing run into output directory, organized by sample.
"""
import os
import shutil
from bcbio import utils
from bcbio.log import logger
from bcbio.upload import shared
def copy_finfo(finfo, storage_dir, pass_uptodate=False):
"""Copy a file into the output storage directory.
"""
i... | """Extract files from processing run into output directory, organized by sample.
"""
import os
import shutil
from bcbio import utils
from bcbio.log import logger
from bcbio.upload import shared
def copy_finfo(finfo, storage_dir, pass_uptodate=False):
"""Copy a file into the output storage directory.
"""
i... | Python | 0 |
7e24165c828a64389d593c63299df4ff22dcb881 | disable swagger docs for tests | rest_auth/urls.py | rest_auth/urls.py | from django.conf import settings
from django.conf.urls import patterns, url, include
from rest_auth.views import Login, Logout, Register, UserDetails, \
PasswordChange, PasswordReset, VerifyEmail, PasswordResetConfirm
urlpatterns = patterns('rest_auth.views',
# URLs that do not require a s... | from django.conf import settings
from django.conf.urls import patterns, url, include
from rest_auth.views import Login, Logout, Register, UserDetails, \
PasswordChange, PasswordReset, VerifyEmail, PasswordResetConfirm
urlpatterns = patterns('rest_auth.views',
# URLs that do not require a s... | Python | 0 |
fbabdb62ae4ca02bca4318d085bf0ec9cc7ab3ef | Add color always to easy get the messages (#334) | travis/test_precommit.py | travis/test_precommit.py | #!/usr/bin/env python
import logging
import os
import re
import subprocess
import sys
logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger(__name__)
overwrite = os.environ.get("PRECOMMIT_OVERWRITE_CONFIG_FILES", "") == "1"
exclude_lint = os.environ.get("EXCLUDE_LINT", "")
root_dir = os.path.dirname(o... | #!/usr/bin/env python
import logging
import os
import re
import subprocess
import sys
logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger(__name__)
overwrite = os.environ.get("PRECOMMIT_OVERWRITE_CONFIG_FILES", "") == "1"
exclude_lint = os.environ.get("EXCLUDE_LINT", "")
root_dir = os.path.dirname(o... | Python | 0 |
33ef365bffb3aefa053409a72d44b069bdae8c77 | Make django middleware not crash if user isn't set. | blueox/contrib/django/middleware.py | blueox/contrib/django/middleware.py | import sys
import traceback
import logging
import blueox
from django.conf import settings
class Middleware(object):
def __init__(self):
host = getattr(settings, 'BLUEOX_HOST', '127.0.0.1')
port = getattr(settings, 'BLUEOX_PORT', 3514)
blueox.configure(host, port)
def process_request(... | import sys
import traceback
import logging
import blueox
from django.conf import settings
class Middleware:
def __init__(self):
host = getattr(settings, 'BLUEOX_HOST', '127.0.0.1')
port = getattr(settings, 'BLUEOX_PORT', 3514)
blueox.configure(host, port)
def process_request(self, re... | Python | 0.000001 |
a53d54d9a446147cc115b3329722e1e51e9aff3e | remove locks for pulling difficulty to stop causing api crashing sooner | diff.py | diff.py | #License#
#bitHopper by Colin Rice is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import re
import eventlet
from eventlet.green import threading, socket, urllib2
# Global timeout for sockets in case something leaks
socket.setdefaulttim... | #License#
#bitHopper by Colin Rice is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import re
import eventlet
from eventlet.green import threading, socket, urllib2
# Global timeout for sockets in case something leaks
socket.setdefaulttim... | Python | 0 |
d1b1a6d845419b5c1b8bec3d7f3bded83cf6c9a1 | Fix ObjectNodeItem upperBound visibility | gaphor/UML/actions/objectnode.py | gaphor/UML/actions/objectnode.py | """Object node item."""
from gaphor import UML
from gaphor.core.modeling.properties import attribute
from gaphor.diagram.presentation import ElementPresentation, Named
from gaphor.diagram.shapes import Box, EditableText, IconBox, Text, draw_border
from gaphor.diagram.support import represents
from gaphor.UML.modelfact... | """Object node item."""
from gaphor import UML
from gaphor.core.modeling.properties import attribute
from gaphor.diagram.presentation import ElementPresentation, Named
from gaphor.diagram.shapes import Box, EditableText, IconBox, Text, draw_border
from gaphor.diagram.support import represents
from gaphor.UML.modelfact... | Python | 0.000003 |
7894e7b31f16dd716ac2483ce5b3cd22e13f2d1f | Add Neal (2000) DPMM sampling algorithm 2 | dpmm.py | dpmm.py | """ Going to try algorithm 1 from Neal (2000)
"""
import numpy as np
import bisect
def pick_discrete(p):
"""Pick a discrete integer between 0 and len(p) - 1 with probability given by p array."""
c = np.cumsum(p)
u = np.random.uniform()
return bisect.bisect_left(c, u)
class DPMM(object):
"""Diri... | """ Going to try algorithm 1 from Neal (2000)
"""
import numpy as np
import bisect
def pick_discrete(p):
"""Pick a discrete integer between 0 and len(p) - 1 with probability given by p array."""
c = np.cumsum(p)
u = np.random.uniform()
return bisect.bisect_left(c, u)
class DPMM(object):
"""Diri... | Python | 0 |
0d7add686605d9d86e688f9f65f617555282ab60 | Add debugging CLI hook for email sending | opwen_email_server/backend/email_sender.py | opwen_email_server/backend/email_sender.py | from typing import Tuple
from opwen_email_server import azure_constants as constants
from opwen_email_server import config
from opwen_email_server.services.queue import AzureQueue
from opwen_email_server.services.sendgrid import SendgridEmailSender
QUEUE = AzureQueue(account=config.QUEUES_ACCOUNT, key=config.QUEUES_K... | from typing import Tuple
from opwen_email_server import azure_constants as constants
from opwen_email_server import config
from opwen_email_server.services.queue import AzureQueue
from opwen_email_server.services.sendgrid import SendgridEmailSender
QUEUE = AzureQueue(account=config.QUEUES_ACCOUNT, key=config.QUEUES_K... | Python | 0 |
13a146c5e4a96d2f01aaecb6fd6839a9c290a2b3 | Fix bug assuming multiple '/' in URL | tools/pluginmanager.py | tools/pluginmanager.py | #----------------------------------------------------------------------
# Copyright (c) 2011-2016 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including ... | #----------------------------------------------------------------------
# Copyright (c) 2011-2016 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including ... | Python | 0.000023 |
5875de6fb894a2903ec1f10c7dbc65c7071c7732 | Fix NullHandler logger addition | rmqid/__init__.py | rmqid/__init__.py | __version__ = '0.4.0'
from rmqid.connection import Connection
from rmqid.exchange import Exchange
from rmqid.message import Message
from rmqid.queue import Queue
from rmqid.tx import Tx
from rmqid.simple import consumer
from rmqid.simple import get
from rmqid.simple import publish
import logging
try:
from loggi... | __version__ = '0.4.0'
from rmqid.connection import Connection
from rmqid.exchange import Exchange
from rmqid.message import Message
from rmqid.queue import Queue
from rmqid.tx import Tx
from rmqid.simple import consumer
from rmqid.simple import get
from rmqid.simple import publish
import logging
try:
from loggi... | Python | 0.000003 |
d5345e34deaf5510c8b45f7d5fbed49f9cee8e41 | echo 0 | echo.py | echo.py | import IPYthon
import warnings
from golix import Ghid
from hypergolix.service import HypergolixLink
hgxlink = HypergolixLink(threaded=True)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
IPython.embed() | Python | 0.999334 | |
c260b974426da547600725b9d5814c0e3d35bb53 | make more pythonic | robogrid/robot.py | robogrid/robot.py | from .grids import Simple_Grid
class Robot(object):
def __init__(self, name, grid=None):
self.name = name
if grid == None:
grid = Simple_Grid(20)
self.grid = grid
start_pos = self.grid.free_position()
if start_pos == None:
raise ValueError("No space... | from .grids import Simple_Grid
class Robot(object):
def __init__(self, name, grid=None):
self.name = name
if grid == None:
grid = Simple_Grid(20)
self.grid = grid
start_pos = self.grid.free_position()
if start_pos == None:
raise ValueError("No space... | Python | 0.000028 |
157f5151b4935c1f7f963addb06ea33ea12146e6 | replace StreamFieldPanel | meinberlin/apps/cms/models/pages.py | meinberlin/apps/cms/models/pages.py | from django.db import models
from wagtail import blocks
from wagtail import fields
from wagtail.admin import edit_handlers
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.models import Page
from wagtail.snippets.edit_handlers import SnippetChooserPanel
from meinberlin.apps.actions import blocks... | from django.db import models
from wagtail import blocks
from wagtail import fields
from wagtail.admin import edit_handlers
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.models import Page
from wagtail.snippets.edit_handlers import SnippetChooserPanel
from meinberlin.apps.actions import blocks... | Python | 0 |
3e8e59656892b8ba8e46affb5987a2fbf633ae00 | Add some authentication reference documentation. | googleanalytics/auth/__init__.py | googleanalytics/auth/__init__.py | # encoding: utf-8
"""
Convenience functions for authenticating with Google
and asking for authorization with Google, with
`authenticate` at its core.
`authenticate` will do what it says on the tin, but unlike
the basic `googleanalytics.oauth.authenticate`, it also tries
to get existing credentials from the keyring... | # encoding: utf-8
"""
Convenience functions for authenticating with Google
and asking for authorization with Google, with
`authenticate` at its core.
`authenticate` will do what it says on the tin, but unlike
the basic `googleanalytics.oauth.authenticate`, it also tries
to get existing credentials from the keyring... | Python | 0 |
e3ac422da8a0c873a676b57ff796d15fac6fc532 | change haproxy config formatting | bin/haproxy_get_ssl.py | bin/haproxy_get_ssl.py | #!/usr/bin/env python
import redis, sys, os, json, jinja2
from jinja2 import Template
r_server = redis.StrictRedis('127.0.0.1', db=2)
check = r_server.get("need_CSR")
if check == "1":
i_key = "owner-info"
data=json.loads (r_server.get(i_key))
email = data['Email']
hostname = data['Hostname']
fron... | #!/usr/bin/env python
import redis, sys, os, json, jinja2
from jinja2 import Template
r_server = redis.StrictRedis('127.0.0.1', db=2)
check = r_server.get("need_CSR")
if check == "1":
i_key = "owner-info"
data=json.loads (r_server.get(i_key))
email = data['Email']
hostname = data['Hostname']
fron... | Python | 0 |
cc6c80ad64fe7f4d4cb2b4e367c595f1b08f9d3b | Remove script crash when no sonos is found | i3blocks-sonos.py | i3blocks-sonos.py | #!/usr/bin/env python3
#
# By Henrik Lilleengen (mail@ithenrik.com)
#
# Released under the MIT License: https://opensource.org/licenses/MIT
import soco, sys
speakers = list(soco.discover())
if len(speakers) > 0:
state = speakers[0].get_current_transport_info()['current_transport_state']
if state == 'PLAYING... | #!/usr/bin/env python3
#
# By Henrik Lilleengen (mail@ithenrik.com)
#
# Released under the MIT License: https://opensource.org/licenses/MIT
import soco, sys
speakers = list(soco.discover())
state = speakers[0].get_current_transport_info()['current_transport_state']
if state == 'PLAYING':
if len(sys.argv) > 1 a... | Python | 0 |
74084defad8222ba69340d0d983acdf33ddef17c | Correct the test of assertEqual failing. | calexicon/dates/tests/test_dates.py | calexicon/dates/tests/test_dates.py | import unittest
from datetime import date, timedelta
from calexicon.dates import DateWithCalendar
class TestDateWithCalendar(unittest.TestCase):
def setUp(self):
date_dt = date(2010, 8, 1)
self.date_wc = DateWithCalendar(None, date_dt)
def test_equality(self):
self.assertTrue(self.d... | import unittest
from datetime import date, timedelta
from calexicon.dates import DateWithCalendar
class TestDateWithCalendar(unittest.TestCase):
def setUp(self):
date_dt = date(2010, 8, 1)
self.date_wc = DateWithCalendar(None, date_dt)
def test_equality(self):
self.assertTrue(self.d... | Python | 0.000021 |
a51231f4a9e588718f77c06481d20eb6d090e996 | fix authorization policy a bit | caliopen/api/user/authentication.py | caliopen/api/user/authentication.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import base64
from zope.interface import implements, implementer
from pyramid.interfaces import IAuthenticationPolicy, IAuthorizationPolicy
from pyramid.security import Everyone, NO_PERMISSION_REQUIRED
from caliopen.base.user.core import ... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import base64
from zope.interface import implements, implementer
from pyramid.interfaces import IAuthenticationPolicy, IAuthorizationPolicy
from pyramid.security import Everyone, NO_PERMISSION_REQUIRED
from pyramid.httpexceptions import HTT... | Python | 0.000001 |
fed9996c90dccb8c6ba66a7f07910fcebb90303b | Finished the code | ex41.py | ex41.py | import random
from urllib import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)" :
"class %%% has-a __init__ that takes self and *** parameter... | import random
from urllib import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)":
"class %%% has-a __init__ that takes self and *** par... | Python | 0.999987 |
ce48ef985a8e79d0cd636abf2116917fde24d6d2 | Remove an unnecessary method override | candidates/tests/test_posts_view.py | candidates/tests/test_posts_view.py | from __future__ import unicode_literals
from django_webtest import WebTest
from .uk_examples import UK2015ExamplesMixin
class TestPostsView(UK2015ExamplesMixin, WebTest):
def test_single_election_posts_page(self):
response = self.app.get('/posts')
self.assertTrue(
response.html.fi... | from __future__ import unicode_literals
from django_webtest import WebTest
from .uk_examples import UK2015ExamplesMixin
class TestPostsView(UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestPostsView, self).setUp()
def test_single_election_posts_page(self):
response = self.app.get... | Python | 0.000023 |
eb96a44e87bc29d24695ea881014d41b8fc793b1 | split cell search out of general search function | ichnaea/search.py | ichnaea/search.py | from statsd import StatsdTimer
from ichnaea.db import Cell, RADIO_TYPE
from ichnaea.decimaljson import quantize
def search_cell(session, data):
radio = RADIO_TYPE.get(data['radio'], 0)
cell = data['cell'][0]
mcc = cell['mcc']
mnc = cell['mnc']
lac = cell['lac']
cid = cell['cid']
query = ... | from statsd import StatsdTimer
from ichnaea.db import Cell, RADIO_TYPE
from ichnaea.decimaljson import quantize
def search_request(request):
data = request.validated
if not data['cell']:
# we don't have any wifi entries yet
return {
'status': 'not_found',
}
radio = RA... | Python | 0.000001 |
3746dbdb9ba645e3ff19a984afb62f48661185be | Exclude hidden files from coverage check. | cc/core/management/commands/test.py | cc/core/management/commands/test.py | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor 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... | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor 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... | Python | 0 |
a64215f5b6b242893448478a2dfdd4c4b2f6ac46 | Add the actual content to test_cc_license.py | cc/license/tests/test_cc_license.py | cc/license/tests/test_cc_license.py | """Tests for functionality within the cc.license module.
This file is a catch-all for tests with no place else to go."""
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in ... | Python | 0.000003 | |
22ecb3f90d598a7801d1a8bb545f23e8567fb3f2 | don't attach a backend property to user objects if the session user id is invalid and the user is None | lazysignup/backends.py | lazysignup/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class LazySignupBackend(ModelBackend):
def authenticate(self, username=None):
users = [u for u in User.objects.filter(username=username)
if not u.has_usable_password()]
if len(users) ... | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class LazySignupBackend(ModelBackend):
def authenticate(self, username=None):
users = [u for u in User.objects.filter(username=username)
if not u.has_usable_password()]
if len(users) ... | Python | 0.999856 |
1b2e0f19079fda6e5710b0065ce41b3bc2bebc71 | Rename helper func | lc0062_unique_paths.py | lc0062_unique_paths.py | """Leetcode 62. Unique Paths.
Medium
URL: https://leetcode.com/problems/unique-paths/
A robot is located at the top-left corner of a m x n grid
(marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid
... | """Leetcode 62. Unique Paths.
Medium
URL: https://leetcode.com/problems/unique-paths/
A robot is located at the top-left corner of a m x n grid
(marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid
... | Python | 0.000002 |
014925aa73e85fe3cb0d939a3d5d9c30424e32b4 | Add Numbers and Symbols Exception | func.py | func.py | # PyArt by MohamadKh75
# 2017-10-05
# ********************
from pathlib import Path
# Set the Alphabet folder path
folder_path = Path("Alphabet").resolve()
# Read all Capital Letters - AA is Capital A
def letter_reader(letter):
# if it's Capital - AA is Capital A
if 65 <= ord(letter) <= 90:
letter_... | # PyArt by MohamadKh75
# 2017-10-05
# ********************
from pathlib import Path
# Set the Alphabet folder path
folder_path = Path("Alphabet").resolve()
# Read all Capital Letters - AA is Capital A
def letter_reader(letter):
# if it's Capital - AA is Capital A
if 65 <= ord(letter) <= 90:
letter_... | Python | 0.000001 |
262e60aa8da3430c860e574e8141495bc7043cab | Move hook render logic from app to hook | hook.py | hook.py | import json
from flask import Blueprint, render_template, request
import requests
import config
hook = Blueprint('hooks', __name__, 'templates')
@hook.route('/hook')
def home():
return render_template('new.html')
@hook.route('/hook/new', methods=['POST'])
def new():
data = {
"name": request.form['name'],
... | import json
from flask import Blueprint, render_template, request
import requests
import config
hook = Blueprint('hooks', __name__, 'templates')
@hook.route('/hook/new', methods=['POST'])
def new():
data = {
"name": request.form['name'],
"active": request.form['active'] if 'active' in request.form else 'f... | Python | 0 |
b82b8d7af363b58902e1aa3920b26c47f5b34aa4 | Use python3 if available to run gen_git_source.py. | third_party/git/git_configure.bzl | third_party/git/git_configure.bzl | """Repository rule for Git autoconfiguration.
`git_configure` depends on the following environment variables:
* `PYTHON_BIN_PATH`: location of python binary.
"""
_PYTHON_BIN_PATH = "PYTHON_BIN_PATH"
def _fail(msg):
"""Output failure message when auto configuration fails."""
red = "\033[0;31m"
no_color... | """Repository rule for Git autoconfiguration.
`git_configure` depends on the following environment variables:
* `PYTHON_BIN_PATH`: location of python binary.
"""
_PYTHON_BIN_PATH = "PYTHON_BIN_PATH"
def _fail(msg):
"""Output failure message when auto configuration fails."""
red = "\033[0;31m"
no_color... | Python | 0.000009 |
6968792b38981616b7a00526d2ab24985dcd2ce3 | include host flags in cluster command | distributed/cluster.py | distributed/cluster.py | import paramiko
from time import sleep
from toolz import assoc
def start_center(addr):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(addr)
channel = ssh.invoke_shell()
channel.settimeout(20)
sleep(0.1)
channel.send('dcenter --host %s\n' ... | import paramiko
from time import sleep
from toolz import assoc
def start_center(addr):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(addr)
channel = ssh.invoke_shell()
channel.settimeout(20)
sleep(0.1)
channel.send('dcenter\n')
chann... | Python | 0 |
ed6d94d27d4274c5a1b282c6d092852ea0a5626d | Fix exception on User admin registration if not already registered. Closes #40 | djangotoolbox/admin.py | djangotoolbox/admin.py | from django import forms
from django.contrib import admin
from django.contrib.admin.sites import NotRegistered
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Group
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email'... | from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Group
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'is_active',
... | Python | 0 |
0bca16d808c7bb48c8af75974989eddf853cb6ba | Add models.SubfieldBase metaclass | djorm_pgjson/fields.py | djorm_pgjson/fields.py | # -*- coding: utf-8 -*-
import json
import re
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.db.backends.postgresql_psycopg2.version import get_version
from django.utils import six
class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
rx_int... | # -*- coding: utf-8 -*-
import json
import re
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.db.backends.postgresql_psycopg2.version import get_version
from django.utils import six
class JSONField(models.Field):
rx_int = re.compile(r'^[\d]+$')
rx_float = ... | Python | 0.000015 |
917013e2e5c02a4a263f13c1874736fca5ad2cf9 | combine import statement | entity_extract/examples/pos_extraction.py | entity_extract/examples/pos_extraction.py |
#from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.utilities import SentSplit, Tokenizer
from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.pos_tagger import PosTagger
#p = PosExtractor()
#data = p.extract_entities('This is a sentence ab... |
#from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.utilities import SentSplit
from entity_extract.extractor.utilities import Tokenizer
from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.pos_tagger import PosTagger
#p = PosExtractor()
#da... | Python | 0.000004 |
995209472d9a9a843d05f0649da38015f8e8a195 | update requirements for metadata extractor | etk/extractors/html_metadata_extractor.py | etk/extractors/html_metadata_extractor.py | from typing import List
from etk.extractor import Extractor
from etk.etk_extraction import Extraction, Extractable
class HTMLMetadataExtractor(Extractor):
"""
Extracts META, microdata, JSON-LD and RDFa from HTML pages.
Uses https://stackoverflow.com/questions/36768068/get-meta-tag-content-property-with-b... | from typing import List
from etk.extractor import Extractor
from etk.etk_extraction import Extraction, Extractable
class HTMLMetadataExtractor(Extractor):
"""
Extracts microdata, JSON-LD and RDFa from HTML pages
"""
def __init__(self):
"consider parameterizing as in extruct, to select only sp... | Python | 0 |
fbe268300142a47d4923109bd7ee81689084dd7b | add z, objectIndex, compositing and alpha attribute to Options | settingMod/Options.py | settingMod/Options.py | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Rendering Options'''
import xml.etree.ElementTree as xmlMod
import os
class Options:
'''class to manage Rendering Options'''
def __init__(self, xml= None):
'''initialize Rendering Options with default value or values extracted from an xml object'''
... | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Rendering Options'''
import xml.etree.ElementTree as xmlMod
import os
class Options:
'''class to manage Rendering Options'''
def __init__(self, xml= None):
'''initialize Rendering Options with default value or values extracted from an xml object'''
... | Python | 0 |
08d5616e2a6a48d15c6840269e7bb933bd19318b | Use objects.create on User model. PEP8 changes | reddit/tests/test_registration.py | reddit/tests/test_registration.py | from django.test import TestCase, Client
from reddit.forms import UserForm
from django.contrib.auth.models import User
from reddit.models import RedditUser
class RegistrationFormTestCase(TestCase):
def setUp(self):
User.objects.create(username="user", password="password")
def test_valid_form(self):
... | from django.test import TestCase, Client
from reddit.forms import UserForm
from django.contrib.auth.models import User
from reddit.models import RedditUser
class RegistrationFormTestCase(TestCase):
def setUp(self):
u = User(username = "user", password="password")
u.save()
def test_valid_form... | Python | 0 |
5cddb33397e714461d589054d054bc3d509bb679 | use proper logging formatting | disco_aws_automation/disco_acm.py | disco_aws_automation/disco_acm.py | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
CERT_SUMMARY_LIST_KEY = 'CertificateSummaryList'
CERT_ARN_KEY = 'CertificateArn'
DOMAIN_NAME_KEY = 'DomainName'
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
WI... | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
CERT_SUMMARY_LIST_KEY = 'CertificateSummaryList'
CERT_ARN_KEY = 'CertificateArn'
DOMAIN_NAME_KEY = 'DomainName'
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
WI... | Python | 0.000003 |
51b611fa8d1a8b2567aec21bd7aee8eeecb6d12a | Remove another comment from is_list_like docstring that's no longer relevant | bravado_core/schema.py | bravado_core/schema.py | from collections import Mapping
from bravado_core.exception import SwaggerMappingError
# 'object' and 'array' are omitted since this should really be read as
# "Swagger types that map to python primitives"
SWAGGER_PRIMITIVES = (
'integer',
'number',
'string',
'boolean',
'null',
)
def has_defaul... | from collections import Mapping
from bravado_core.exception import SwaggerMappingError
# 'object' and 'array' are omitted since this should really be read as
# "Swagger types that map to python primitives"
SWAGGER_PRIMITIVES = (
'integer',
'number',
'string',
'boolean',
'null',
)
def has_defaul... | Python | 0.000001 |
f120be17e4b1d63bd98c2390cf4ec39b8e61e8fd | define _VersionTupleEnumMixin class | Lib/fontTools/ufoLib/utils.py | Lib/fontTools/ufoLib/utils.py | """The module contains miscellaneous helpers.
It's not considered part of the public ufoLib API.
"""
import warnings
import functools
numberTypes = (int, float)
def deprecated(msg=""):
"""Decorator factory to mark functions as deprecated with given message.
>>> @deprecated("Enough!")
... def some_funct... | """The module contains miscellaneous helpers.
It's not considered part of the public ufoLib API.
"""
import warnings
import functools
numberTypes = (int, float)
def deprecated(msg=""):
"""Decorator factory to mark functions as deprecated with given message.
>>> @deprecated("Enough!")
... def some_funct... | Python | 0.000001 |
dff9df9463fd302665169dc68c17252a08a96739 | add HRK currency | shop/money/iso4217.py | shop/money/iso4217.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# Dictionary of currency representations:
# key: official ISO 4217 code
# value[0]: numeric representation
# value[1]: number of digits
# value[2]: currency symbol in UTF-8
# value[3]: textual descri... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# Dictionary of currency representations:
# key: official ISO 4217 code
# value[0]: numeric representation
# value[1]: number of digits
# value[2]: currency symbol in UTF-8
# value[3]: textual descri... | Python | 0.000212 |
f9d29a5ba9bc196fdd669a1de01d8b8dde5ae8b8 | Corrige l'espacement | openfisca_france/model/caracteristiques/capacite_travail.py | openfisca_france/model/caracteristiques/capacite_travail.py | # -*- coding: utf-8 -*-
from openfisca_france.model.base import *
class taux_capacite_travail(Variable):
value_type = float
default_value = 1.0
entity = Individu
label = u"Taux de capacité de travail, appréciée par la commission des droits et de l'autonomie des personnes handicapées (CDAPH)"
defi... | # -*- coding: utf-8 -*-
from openfisca_france.model.base import *
class taux_capacite_travail(Variable):
value_type = float
default_value = 1.0
entity = Individu
label = u"Taux de capacité de travail, appréciée par la commission des droits et de l'autonomie des personnes handicapées (CDAPH)"
defi... | Python | 0.000002 |
03c7498dc8ba09a2135a7c214d7903f7509b956b | Use log-uniform distribution for learning-rate. | hyperparam_opt/tensorflow/hyperopt_dnn_mnist.py | hyperparam_opt/tensorflow/hyperopt_dnn_mnist.py | import sys
import argparse
import numpy as np
import tensorflow as tf
from hyperparam_opt.tensorflow.dnn_mnist import HyperParams, train
from hyperopt import fmin, hp, Trials, tpe, STATUS_OK
from tensorflow.examples.tutorials.mnist import input_data
MNIST = None
def optimizer(args):
hyper = HyperParams(**args)... | import sys
import argparse
import tensorflow as tf
from hyperparam_opt.tensorflow.dnn_mnist import HyperParams, train
from hyperopt import fmin, hp, Trials, tpe, STATUS_OK
from tensorflow.examples.tutorials.mnist import input_data
MNIST = None
def optimizer(args):
hyper = HyperParams(**args)
print(hyper.to_... | Python | 0 |
ec3e08da9551e2a7e7e114c4d425871b2a915425 | fix leaked greenlet | ion/agents/platform/rsn/test/test_oms_client.py | ion/agents/platform/rsn/test/test_oms_client.py | #!/usr/bin/env python
"""
@package ion.agents.platform.rsn.test.test_oms_client
@file ion/agents/platform/rsn/test/test_oms_client.py
@author Carlos Rueda
@brief Test cases for CIOMSClient.
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
from pyon.public import log
from ion.agents.platform.rsn.simul... | #!/usr/bin/env python
"""
@package ion.agents.platform.rsn.test.test_oms_simple
@file ion/agents/platform/rsn/test/test_oms_simple.py
@author Carlos Rueda
@brief Test cases for CIOMSClient.
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
from pyon.public import log
from ion.agents.platform.rsn.simul... | Python | 0 |
5a33d1c5e52bf26eb90e53381a58ed89c9a1185e | Make 0.3.1 | siloscript/version.py | siloscript/version.py | # Copyright (c) The SimpleFIN Team
# See LICENSE for details.
__version__ = "0.3.1"
| # Copyright (c) The SimpleFIN Team
# See LICENSE for details.
__version__ = "0.4.0-dev"
| Python | 0.999999 |
87c7899f7ed14d64f2015ce6363bf50e7d5b5008 | Update yle_articles collector | sites/yle_articles.py | sites/yle_articles.py | import requests
def parse(api_request):
app_id = ""
app_key = ""
example_request = "https://articles.api.yle.fi/v2/articles.json?published_after=2016-12-20T12:00:00%2b0300&offset=0&limit=10"
#r = requests.get( api_request )
r = requests.get( example_request + "&app_id=" + app_id + "&app_key=" + ... | import requests
def parse(api_request):
app_id = "f3365695"
app_key = "7010dcef0cf2393423e747473b6068c"
example_request = "https://articles.api.yle.fi/v2/articles.json?published_after=2016-12-20T12:00:00%2b0300&offset=0&limit=10"
#r = requests.get( api_request )
r = requests.get( example_request... | Python | 0 |
8913a1ca25b51fc52b08187ab67a1e8763015d07 | handle ndarray to matrix conversion | skmultilearn/utils.py | skmultilearn/utils.py | import numpy as np
import scipy.sparse as sp
SPARSE_FORMAT_TO_CONSTRUCTOR = {
"bsr": sp.bsr_matrix,
"coo": sp.coo_matrix,
"csc": sp.csc_matrix,
"csr": sp.csr_matrix,
"dia": sp.dia_matrix,
"dok": sp.dok_matrix,
"lil": sp.lil_matrix
}
def get_matrix_in_format(original_matrix, matrix_format):... | import scipy.sparse as sp
def get_matrix_in_format(original_matrix, matrix_format):
if original_matrix.getformat() == matrix_format:
return original_matrix
return original_matrix.asformat(matrix_format)
def matrix_creation_function_for_format(sparse_format):
SPARSE_FORMAT_TO_CONSTRUCTOR = {
... | Python | 0.000001 |
e8d27f7c058fb73600fe6860c3fa8ed26dbc63ad | Add files endpoints. | slack/endpoints_v1.py | slack/endpoints_v1.py | """
API MAPPING FOR Slack API V1
"""
mapping_table = {
'content_type': 'application/x-www-form-urlencoded',
'path_prefix': '/api',
'api_test': {
'path': '/api.test',
'valid_params': ['format', 'auth_token']
},
'channels_history': {
'path': '/channels.history',
'va... | """
API MAPPING FOR Slack API V1
"""
mapping_table = {
'content_type': 'application/x-www-form-urlencoded',
'path_prefix': '/api',
'api_test': {
'path': '/api.test',
'valid_params': ['format', 'auth_token']
},
'channels_history': {
'path': '/channels.history',
'va... | Python | 0 |
ae70fccdc7fe5348e3729283866df4ed0c256beb | Fix tabs. | sllurp/sllurp/host.py | sllurp/sllurp/host.py | #!/usr/bin/python
from twisted.internet import reactor, defer
index = 0
# Read the hex file.
f = open("wisp_app.hex", 'r')
lines = f.readlines()
class Getter:
def processLine(self, line):
if self.d is None:
print "No callback given!"
return
d = self.d
self.d = None
global lines
global inde... | #!/usr/bin/python
from twisted.internet import reactor, defer
index = 0
# Read the hex file.
f = open("wisp_app.hex", 'r')
lines = f.readlines()
class Getter:
def processLine(self, line):
"""
The Deferred mechanism provides a mechanism to signal error
conditions. In this case, odd numb... | Python | 0 |
374981fd60c0116e861d598eec763cc2b8165189 | Add -- to git log call | cs251tk/common/check_submit_date.py | cs251tk/common/check_submit_date.py | import os
from dateutil.parser import parse
from ..common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and ret... | import os
from dateutil.parser import parse
from ..common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and ret... | Python | 0 |
6c4537b41ae4362354bd03236d8e902c7e955a8c | add support fields for big unsigned ints | twitter_stream/fields.py | twitter_stream/fields.py | from django.db import models
from django import forms
from django.core import exceptions
import math
from south.modelsinspector import add_introspection_rules
class PositiveBigIntegerField(models.BigIntegerField):
description = "Positive Big integer"
def get_internal_type(self):
return "PositiveBigInt... | from django.db import models
from django import forms
from django.core import exceptions
import math
from south.modelsinspector import add_introspection_rules
class PositiveBigAutoField(models.AutoField):
description = "Unsigned Big Integer"
empty_strings_allowed = False
MAX_BIGINT = 9223372036854775807
... | Python | 0 |
30d9d45612b760e2ce6c2d90e516ba8de58a0c12 | put start_date back in ordering fields | api/v2/views/instance_history.py | api/v2/views/instance_history.py | from django.db.models import Q
from rest_framework import filters
import django_filters
from core.models import InstanceStatusHistory
from api.v2.serializers.details import InstanceStatusHistorySerializer
from api.v2.views.base import AuthReadOnlyViewSet
from api.v2.views.mixins import MultipleFieldLookup
class Ins... | from django.db.models import Q
from rest_framework import filters
import django_filters
from core.models import InstanceStatusHistory
from api.v2.serializers.details import InstanceStatusHistorySerializer
from api.v2.views.base import AuthReadOnlyViewSet
from api.v2.views.mixins import MultipleFieldLookup
class Ins... | Python | 0 |
a6ab9d8af09eace392a3d9320eb46af4ec6394c9 | add test_report_progress() | tests/unit/loop/test_EventLoop.py | tests/unit/loop/test_EventLoop.py | # Tai Sakuma <tai.sakuma@gmail.com>
import sys
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from alphatwirl.loop import EventLoop
from alphatwirl import progressbar
##__________________________________________________________________||
@pytest.fixture()
def events():
ev... | # Tai Sakuma <tai.sakuma@gmail.com>
import logging
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from alphatwirl.loop import EventLoop
##__________________________________________________________________||
@pytest.fixture()
def events():
event1 = mock.Mock(name='event1')... | Python | 0.000001 |
8706b9dd6226bed5dc89ff8a6fcbcff952be3c2e | fix droidbot ime bug | droidbot/adapter/droidbot_ime.py | droidbot/adapter/droidbot_ime.py | # coding=utf-8
import logging
import time
from .adapter import Adapter
DROIDBOT_APP_PACKAGE = "io.github.ylimit.droidbotapp"
IME_SERVICE = DROIDBOT_APP_PACKAGE + "/.DroidBotIME"
class DroidBotImeException(Exception):
"""
Exception in telnet connection
"""
pass
class DroidBotIme(Adapter):
"""
... | # coding=utf-8
import logging
import time
from .adapter import Adapter
DROIDBOT_APP_PACKAGE = "io.github.ylimit.droidbotapp"
IME_SERVICE = DROIDBOT_APP_PACKAGE + "/.DroidBotIME"
class DroidBotImeException(Exception):
"""
Exception in telnet connection
"""
pass
class DroidBotIme(Adapter):
"""
... | Python | 0.000001 |
042f005b8e22f9d8844e0c16329598ca13eb4567 | Update formatting for better compatibility with unit tests. | lib/python2.5/aquilon/aqdb/utils/table_admin.py | lib/python2.5/aquilon/aqdb/utils/table_admin.py | #!/ms/dist/python/PROJ/core/2.5.0/bin/python
""" A collection of table level functions for maintenance """
from confirm import confirm
import sys
import os
if __name__ == '__main__':
DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.realpath(os.path.join(DIR, '..', '..', '..')))
... | #!/ms/dist/python/PROJ/core/2.5.0/bin/python
""" A collection of table level functions for maintenance """
from confirm import confirm
import sys
import os
if __name__ == '__main__':
DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.realpath(os.path.join(DIR, '..', '..', '..')))
... | Python | 0 |
1c7b881b62f9d1931957322874f6c38d610c2cf4 | Rename setting to match name of app | append_url_to_sql/models.py | append_url_to_sql/models.py | """
:mod:`django-append-url-to-sql` --- Appends the request URL to SQL statements in Django
=======================================================================================
Whilst the `Django Debug Toolbar
<https://github.com/robhudson/django-debug-toolbar>`_ is invaluable for
development in a local environment... | """
:mod:`django-append-url-to-sql` --- Appends the request URL to SQL statements in Django
=======================================================================================
Whilst the `Django Debug Toolbar
<https://github.com/robhudson/django-debug-toolbar>`_ is invaluable for
development in a local environment... | Python | 0 |
d6e63289e33d094dd49cef2e63ab48e1753cc434 | Make get_id() return None if no/multiple records found | ingestion/base.py | ingestion/base.py | import os
import csv
import glob
import json
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
class BaseIngest(object):
def __init__(self, session):
self.session = session
def get_id(self, model, **conditions):
try:
record_id = self.session.query(model).filter... | import os
import csv
import glob
import json
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
class BaseIngest(object):
def __init__(self, session):
self.session = session
def get_id(self, model, **conditions):
try:
record_id = self.session.query(model).filter... | Python | 0.001504 |
bd48e1f5d8f838632a65b4ffbba16ea2dacb02b0 | Add NetworkKeyComparison and implementation for NetworkUserComparison | ircstat/graphs.py | ircstat/graphs.py | # Copyright 2013 John Reese
# Licensed under the MIT license
import matplotlib.pyplot as plt
import numpy as np
from .ent import Struct
FADED = '#e8e8e8'
class Graph(Struct):
"""Generic graph interface."""
def __init__(self, title, legend=True, **kwargs):
Struct.__init__(self, title=title, legend=... | # Copyright 2013 John Reese
# Licensed under the MIT license
import matplotlib.pyplot as plt
import numpy as np
from .ent import Struct
FADED = '#e8e8e8'
class Graph(Struct):
"""Generic graph interface."""
def __init__(self, title, legend=True, **kwargs):
Struct.__init__(self, title=title, legend... | Python | 0 |
8f3b16e23bc29465d9b6cfc5e9afbe9c7e8727df | Bump to 1.2.0 | jnius/__init__.py | jnius/__init__.py | '''
Pyjnius
=======
Accessing Java classes from Python.
All the documentation is available at: http://pyjnius.readthedocs.org
'''
__version__ = '1.2.0'
from .jnius import * # noqa
from .reflect import * # noqa
from six import with_metaclass
# XXX monkey patch methods that cannot be in cython.
# Cython doesn't al... | '''
Pyjnius
=======
Accessing Java classes from Python.
All the documentation is available at: http://pyjnius.readthedocs.org
'''
__version__ = '1.1.5.dev0'
from .jnius import * # noqa
from .reflect import * # noqa
from six import with_metaclass
# XXX monkey patch methods that cannot be in cython.
# Cython doesn... | Python | 0.000041 |
4dbeae65f0dab8575c5ccc79324129e6eb9b6329 | Support python3 | jps/subscriber.py | jps/subscriber.py | import zmq
from zmq.utils.strtypes import cast_bytes
from zmq.utils.strtypes import cast_unicode
import time
class Subscriber(object):
'''Subscribe the topic and call the callback function
Example:
>>> def callback(msg):
... print msg
...
>>> sub = jps.Subscriber('topic_name', callback)
... | import zmq
from zmq.utils.strtypes import cast_bytes
from zmq.utils.strtypes import cast_unicode
import time
class Subscriber(object):
'''Subscribe the topic and call the callback function
Example:
>>> def callback(msg):
... print msg
...
>>> sub = jps.Subscriber('topic_name', callback)
... | Python | 0 |
cae39f838049dbeeaf0ae7962ff3bb618b360b09 | remove token from notifier middleware | neutron/openstack/common/middleware/notifier.py | neutron/openstack/common/middleware/notifier.py | # Copyright (c) 2013 eNovance
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | # Copyright (c) 2013 eNovance
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | Python | 0.000004 |
97a70a818772db4bd71d5976814c772ca69d5697 | Implement logic to retrieve regressions for boot | app/handlers/boot_regressions.py | app/handlers/boot_regressions.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | Python | 0 |
33898c42b4441a10d7bb12cdf5da08ee572b1750 | Add BSN plugin to agent migration script | neutron/db/migration/alembic_migrations/versions/511471cc46b_agent_ext_model_supp.py | neutron/db/migration/alembic_migrations/versions/511471cc46b_agent_ext_model_supp.py | # Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | # Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | Python | 0.000004 |
d4479df64a2fd7a53327bc3ce79e48ec4cc30efc | Update course forum url | notebooks/feature_engineering_new/track_meta.py | notebooks/feature_engineering_new/track_meta.py | track = dict(
author_username="ryanholbrook",
course_name="Feature Engineering",
course_url="https://www.kaggle.com/learn/feature-engineering",
course_forum_url="https://www.kaggle.com/learn-forum/221677",
)
TOPICS = [
"What is Feature Engineering", # 1
"Mutual Information", # 2
"Creating... | track = dict(
author_username="ryanholbrook",
course_name="Feature Engineering",
course_url="https://www.kaggle.com/learn/feature-engineering",
course_forum_url="https://www.kaggle.com/learn-forum/161443",
)
TOPICS = [
"What is Feature Engineering", # 1
"Mutual Information", # 2
"Creating... | Python | 0 |
8de0c35cccc316a6e9bc6dc9cff04d37e6c975a9 | Update track_meta | notebooks/feature_engineering_new/track_meta.py | notebooks/feature_engineering_new/track_meta.py | track = dict(
author_username='',
course_name="Feature Engineering",
course_url='https://www.kaggle.com/learn/feature-engineering',
course_forum_url='https://www.kaggle.com/learn-forum/',
)
TOPICS = ["What is Feature Engineering?", # 1
"Polynomial and Interaction Features", # 2
... | # See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='',
)
lessons = [
dict(
# By convention, this should be a lowercase noun-phrase.
topic='exemplar examples',
),
]
notebooks = [
dict(
filename='tut1.... | Python | 0.000001 |
957a381f81baf8cb9f7f4e3cbd8f437f1dbf858c | Use 'config' instead 'device' to speficy device type for session creation | example/mnist_mlp_auto_shape_inference.py | example/mnist_mlp_auto_shape_inference.py | """TinyFlow Example code.
Automatic variable creation and shape inductions.
The network structure is directly specified via forward node numbers
The variables are automatically created, and their shape infered by tf.infer_variable_shapes
"""
import tinyflow as tf
from tinyflow.datasets import get_mnist
# Create the m... | """TinyFlow Example code.
Automatic variable creation and shape inductions.
The network structure is directly specified via forward node numbers
The variables are automatically created, and their shape infered by tf.infer_variable_shapes
"""
import tinyflow as tf
from tinyflow.datasets import get_mnist
# Create the m... | Python | 0.000172 |
396034628c12026f5b44e6bb76268cc943c25f3f | fix for no-repo-state-problem | admin/src/data/scoville/Modules.py | admin/src/data/scoville/Modules.py | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# Copyright 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Scoville.
#
# Scoville is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as... | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# Copyright 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Scoville.
#
# Scoville is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as... | Python | 0.000037 |
b483522f8af1d58a8ca8e25eb0ba44a98acf1df7 | Fix Client call | airtng_flask/models/reservation.py | airtng_flask/models/reservation.py | from airtng_flask.models import app_db, auth_token, account_sid, phone_number
from flask import render_template
from twilio.rest import Client
db = app_db()
class Reservation(db.Model):
__tablename__ = "reservations"
id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.String, nullable=Fa... | from airtng_flask.models import app_db, auth_token, account_sid, phone_number
from flask import render_template
from twilio.rest import Client
db = app_db()
class Reservation(db.Model):
__tablename__ = "reservations"
id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.String, nullable=Fa... | Python | 0.000001 |
b09e735c26a176ef201983b404a95dff008b942e | modify the composition function so that it also returns the developer ID | devmine/lib/composition.py | devmine/lib/composition.py | """This file provides abstraction over the tasks of computing the ranking"""
import numpy as np
import time
from devmine.app.models.feature import Feature
from devmine.app.models.score import Score
__scores_matrix = None
__users_list = None
def __construct_weight_vector(db, query):
"""
Construct a weight v... | """This file provides abstraction over the tasks of computing the ranking"""
import numpy as np
import time
from devmine.app.models.feature import Feature
from devmine.app.models.score import Score
__scores_matrix = None
__users_list = None
def __construct_weight_vector(db, query):
"""
Construct a weight v... | Python | 0 |
95249bb773c57daa15e1b85765e5e75254f8ba6e | Update __init__.py | djangoautoconf/__init__.py | djangoautoconf/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Richard Wang'
__email__ = 'richardwangwang@gmail.com'
__version__ = '2.0.2'
# from .django_autoconf import DjangoAutoConf
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Richard Wang'
__email__ = 'richardwangwang@gmail.com'
__version__ = '2.0.1'
# from .django_autoconf import DjangoAutoConf
| Python | 0.000072 |
05190c5dc6fc680bea245184b74f46f781ce998c | Prepare for inital release | wagtailpolls/__init__.py | wagtailpolls/__init__.py | __version__ = '0.1.0'
| __version__ = '0.1'
| Python | 0 |
3115a85ded7ca7adcdc650b65e3795d580e1dfdb | Fix identity when no image | wapps/models/identity.py | wapps/models/identity.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from wagtail.contrib.settings.models import BaseSetting, register_setting
from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel
from wagtail.wagtailimages.edit_handlers... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from wagtail.contrib.settings.models import BaseSetting, register_setting
from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel
from wagtail.wagtailimages.edit_handlers... | Python | 0.001489 |
7b80fdfe3487d3f5f32c69b03707963d3f8e1e3a | Update cpuinfo from b40bae2 to 9fa6219 | third_party/cpuinfo/workspace.bzl | third_party/cpuinfo/workspace.bzl | """Loads the cpuinfo library, used by XNNPACK."""
load("//third_party:repo.bzl", "tf_http_archive", "tf_mirror_urls")
def repo():
tf_http_archive(
name = "cpuinfo",
strip_prefix = "cpuinfo-9fa621933fc6080b96fa0f037cdc7cd2c69ab272",
sha256 = "810708948128be2da882a5a3ca61eb6db40186bac9180d20... | """Loads the cpuinfo library, used by XNNPACK."""
load("//third_party:repo.bzl", "tf_http_archive", "tf_mirror_urls")
def repo():
tf_http_archive(
name = "cpuinfo",
strip_prefix = "cpuinfo-b40bae27785787b6dd70788986fd96434cf90ae2",
sha256 = "5794c7b37facc590018eddffec934c60aeb71165b59a375b... | Python | 0 |
c8678b430249f0624fd014d57661b365708a8f43 | Include request params in oauth header | twitter/twr_account.py | twitter/twr_account.py | #!/usr/bin/env python
#
# Copyright (c) 2013 Martin Abente Lahaye. - tch@sugarlabs.org
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the righ... | #!/usr/bin/env python
#
# Copyright (c) 2013 Martin Abente Lahaye. - tch@sugarlabs.org
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the righ... | Python | 0 |
adafee9ea64501632331d2681f93ada9b24d05da | Fix publish with dict | unicornclient/mission.py | unicornclient/mission.py |
import json
from . import message
class Mission():
def __init__(self, manager):
self.manager = manager
def send(self, msg: message.Message):
self.manager.sender.send(msg)
def publish(self, topic, data):
self.manager.mqtt_sender.publish(topic, self.serialize(data))
def post(... |
import json
from . import message
class Mission():
def __init__(self, manager):
self.manager = manager
def send(self, msg):
self.manager.sender.send(msg)
def publish(self, topic, msg):
self.manager.mqtt_sender.publish(topic, msg)
def post(self, name, data):
msg = me... | Python | 0 |
9d64c5ce9126b05ecf77bf64efa5aef534383d85 | Correct test that retrieves from local mongo DB | bdp/platform/frontend/src/bdp_fe/jobconf/tests/views.py | bdp/platform/frontend/src/bdp_fe/jobconf/tests/views.py | """
Views tests
"""
from django.contrib.auth.models import User, UserManager
import django.test as djangotest
from django.utils import unittest
from pymongo import Connection
from bdp_fe.jobconf.models import CustomJobModel, Job
class LoginTestCase(djangotest.TestCase):
def test_login_redirect(self):
re... | """
Views tests
"""
from django.utils import unittest
import django.test as djangotest
from pymongo import Connection
class LoginTestCase(djangotest.TestCase):
def test_login_redirect(self):
response = self.client.get('/')
self.assertRedirects(response, '/accounts/login/?next=/')
class Retrie... | Python | 0.000001 |
803a6e495966b5281b376b4e28f0bcb04f44ee50 | Change args to api | indra/sources/sofia/sofia_api.py | indra/sources/sofia/sofia_api.py | import openpyxl
from .processor import SofiaProcessor
def process_table(fname):
"""Return processor by processing a given sheet of a spreadsheet file.
Parameters
----------
fname : str
The name of the Excel file (typically .xlsx extension) to process
Returns
-------
sp : indra.sou... | import openpyxl
from .processor import SofiaProcessor
def process_table(fname, sheet_name):
"""Return processor by processing a given sheet of a spreadsheet file.
Parameters
----------
fname : str
The name of the Excel file (typically .xlsx extension) to process
Returns
-------
sp... | Python | 0.999322 |
124cef21de78c84aa32808d4287733e616df4095 | Update colorbars test. | usr/examples/15-Tests/colorbar.py | usr/examples/15-Tests/colorbar.py | # Colorbar Test Example
#
# This example is the color bar test run by each OpenMV Cam before being allowed
# out of the factory. The OMV sensors can output a color bar image which you
# can threshold to check the the camera bus is connected correctly.
import sensor, time
sensor.reset()
# Set sensor settings
sensor.se... | # Colorbar Test Example
#
# This example is the color bar test run by each OpenMV Cam before being allowed
# out of the factory. The OMV sensors can output a color bar image which you
# can threshold to check the the camera bus is connected correctly.
import sensor, time
sensor.reset()
# Set sensor settings
sensor.se... | Python | 0 |
60fe51f3e193dd42c24001cf5a01e689df12730b | support the limit on the max number of points | hyperengine/model/hyper_tuner.py | hyperengine/model/hyper_tuner.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxim'
import numpy as np
import time
from ..base import *
from ..spec import ParsedSpec
from ..bayesian.sampler import DefaultSampler
from ..bayesian.strategy import BayesianStrategy, BayesianPortfolioStrategy
strategies = {
'bayesian': lambda sampler... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxim'
import numpy as np
import time
from ..base import *
from ..spec import ParsedSpec
from ..bayesian.sampler import DefaultSampler
from ..bayesian.strategy import BayesianStrategy, BayesianPortfolioStrategy
strategies = {
'bayesian': lambda sampler... | Python | 0.000329 |
f0e29748ff899d7e65d1f4169e890d3e3c4bda0e | Update instead of overriding `DATABASES` setting in `test` settings. | icekit/project/settings/_test.py | icekit/project/settings/_test.py | from ._base import *
# DJANGO ######################################################################
DATABASE_NAME = 'test_%s' % DATABASES['default']['NAME']
DATABASES['default'].update({
'NAME': DATABASE_NAME,
'TEST': {
'NAME': DATABASE_NAME,
# See: https://docs.djangoproject.com/en/1.7/ref/... | from ._base import *
# DJANGO ######################################################################
DATABASE_NAME = 'test_%s' % DATABASES['default']['NAME']
DATABASES = {
'default': {
'NAME': DATABASE_NAME,
'TEST': {
'NAME': DATABASE_NAME,
# See: https://docs.djangoprojec... | Python | 0 |
b34315f4b4c77dfcc4bc83901ca8786af1a3f12a | Add more content | ideascube/conf/kb_gin_conakry.py | ideascube/conf/kb_gin_conakry.py | # -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
from django.utils.translation import ugettext_lazy as _
LANGUAGE_CODE = 'fr'
IDEASCUBE_NAME = 'Conakry'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'bsfcampus',
... | # -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'fr'
IDEASCUBE_NAME = 'CONAKRY'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'koombookedu',
},
{
'id': 'bsfcampus',
},
]
| Python | 0 |
e4abc4dbde81b21d1d66439a482249887bfd56a7 | Fix TypeError on callback | ikalog/scenes/game/kill_combo.py | ikalog/scenes/game/kill_combo.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA, Shingo MINAMIYAMA
#
# 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... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA, Shingo MINAMIYAMA
#
# 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... | Python | 0 |
c2f3b514fc0fd88f93e1fc80951bd808f4fd2001 | Add more logging to TPU health monitor. (#141) | images/health-monitor/monitor.py | images/health-monitor/monitor.py | # Copyright 2020 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
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2020 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
#
# Unless required by applicable law or agreed to in writing, ... | Python | 0 |
1a54a1648253726ace82c02e15c9833acc5f27dc | use sklearn interface to read svmlight format file | libact/base/dataset.py | libact/base/dataset.py | """
The dataset class used in this package.
Datasets consists of data used for training, represented by a list of
(feature, label) tuples.
May be exported in different formats for application on other libraries.
"""
import random
import numpy as np
class Dataset(object):
def __init__(self, X=[], y=[]):
... | """
The dataset class used in this package.
Datasets consists of data used for training, represented by a list of
(feature, label) tuples.
May be exported in different formats for application on other libraries.
"""
import random
import numpy as np
class Dataset(object):
def __init__(self, X=[], y=[]):
... | Python | 0 |
bafa26c28399b43d15e23d1fca66bf98938f329d | fix treasury yield bugs | examples/treasury_yield/treasury_yield.py | examples/treasury_yield/treasury_yield.py | #!/usr/bin/env python
# encoding: utf-8
import datetime
#from app.MongoSplitter import calculate_splits
#from disco.core import Job, result_iterator
#from mongodb_io import mongodb_output_stream, mongodb_input_stream
from job import DiscoJob
"""
Description: calculate the average 10 year treasury bond yield for given... | #!/usr/bin/env python
# encoding: utf-8
import datetime
from app.MongoSplitter import calculate_splits
from disco.core import Job, result_iterator
from mongodb_io import mongodb_output_stream, mongodb_input_stream
"""
Description: calculate the average 10 year treasury bond yield for given data.
Note: run parse_yield... | Python | 0.000001 |
e637e5f53990709ed654b661465685ad9d05a182 | Update cluster config map key format | api/spawner/templates/constants.py | api/spawner/templates/constants.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from django.conf import settings
JOB_NAME = 'plxjob-{task_type}{task_idx}-{experiment_uuid}'
DEFAULT_PORT = 2222
ENV_VAR_TEMPLATE = '{name: "{var_name}", value: "{var_value}"}'
VOLUME_NAME = 'pv-{vol_name}'
VOLUME_CLAIM_NAME = 'p... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from django.conf import settings
JOB_NAME = 'plxjob-{task_type}{task_idx}-{experiment_uuid}'
DEFAULT_PORT = 2222
ENV_VAR_TEMPLATE = '{name: "{var_name}", value: "{var_value}"}'
VOLUME_NAME = 'pv-{vol_name}'
VOLUME_CLAIM_NAME = 'p... | Python | 0 |
8171af80ab1bff2ffac4b85642217a37fb485d74 | Rewrite serializer | rest_framework_gis/serializers.py | rest_framework_gis/serializers.py | # rest_framework_gis/serializers.py
from django.contrib.gis.db import models
from rest_framework.serializers import ModelSerializer
from .fields import GeometryField
class GeoModelSerializer(ModelSerializer):
pass
GeoModelSerializer.field_mapping.update({
models.GeometryField: GeometryField,
models.Po... | # rest_framework_gis/serializers.py
from django.contrib.gis.db import models
from rest_framework.serializers import ModelSerializer
from .fields import GeometryField
class GeoModelSerializer(ModelSerializer):
def get_field(self, model_field):
"""
Creates a default instance of a basic non-rel... | Python | 0.000104 |
70d009834123cb5a10788763fed3193017cc8162 | Add a default null logger per python recommendations. | libpebble2/__init__.py | libpebble2/__init__.py | __author__ = 'katharine'
import logging
from .exceptions import *
logging.getLogger('libpebble2').addHandler(logging.NullHandler())
| __author__ = 'katharine'
from .exceptions import *
| Python | 0 |
69fe87e0dd8deb194159f264bc30c50391806149 | fix scheduler_error_mailer | scheduler_error_mailer/ir_cron.py | scheduler_error_mailer/ir_cron.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Scheduler Error Mailer module for OpenERP
# Copyright (C) 2012-2013 Akretion (http://www.akretion.com/)
# @author: Sébastien Beau <sebastien.beau@akretion.com>
# @author David Beal <bealdavid@gmail.c... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Scheduler Error Mailer module for OpenERP
# Copyright (C) 2012-2013 Akretion (http://www.akretion.com/)
# @author: Sébastien Beau <sebastien.beau@akretion.com>
# @author David Beal <bealdavid@gmail.c... | Python | 0.000007 |
eb9d297d14741f311cb4bf27c384077ba98cc789 | Add missing slot. | web/db/mongo/__init__.py | web/db/mongo/__init__.py | # encoding: utf-8
"""MongoDB database connection extension."""
import re
from pymongo import MongoClient
from pymongo.errors import ConfigurationError
from .model import Model
from .resource import MongoDBResource
from .collection import MongoDBCollection
__all__ = ['Model', 'MongoDBResource', 'MongoDBCollection'... | # encoding: utf-8
"""MongoDB database connection extension."""
import re
from pymongo import MongoClient
from pymongo.errors import ConfigurationError
from .model import Model
from .resource import MongoDBResource
from .collection import MongoDBCollection
__all__ = ['Model', 'MongoDBResource', 'MongoDBCollection'... | Python | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.