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 |
|---|---|---|---|---|---|---|---|
615fd3b0b7d67905cf4568971602c6dfd7c5eff3 | Remove outdated code from `fs.sshfs.error_tools` | fs/sshfs/error_tools.py | fs/sshfs/error_tools.py | # coding: utf-8
"""Utils to work with `paramiko` errors.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import errno
import sys
import six
from .. import errors
class _ConvertSSHFSErrors(object):
"""Context manager to convert OSErrors in to FS Errors."""
FILE_ERRORS = {... | # coding: utf-8
"""Utils to work with `paramiko` errors.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import errno
import sys
import six
from .. import errors
class _ConvertSSHFSErrors(object):
"""Context manager to convert OSErrors in to FS Errors."""
FILE_ERRORS = {... | Python | 0.000002 |
b83576644d5aacd4ab841a03ff228796ff1b1b67 | change name | coolTestly/__openerp__.py | coolTestly/__openerp__.py | {
"name": "coolTestly",
"author": "Ju",
"version": "1.0",
"category": "Generic Modules/Sales & Purchases",
"depends": [
"purchase",
],
"demo": [],
"data": [
],
"installable": True
}
| {
"name": "testly",
"author": "Ju",
"version": "1.0",
"category": "Generic Modules/Sales & Purchases",
"depends": [
"purchase",
],
"demo": [],
"data": [
],
"installable": True
} | Python | 0.000147 |
f844b95e7cb034985f1d284a41789d1e427b0f74 | Update env_detect.py | device/src/env_detect.py | device/src/env_detect.py | #!/usr/bin/env python
#Weather station.
#detect environment information from several sensors:
#water leverl, air humity, raining, air temperature, light sensitivity.
#Air temperature&humity sensor: DHT11.
#Add dht.py in micropython/stmhal/modules, refer to esp8266
#Compile the DHT in firmware, then use DHT lib in appli... | #!/usr/bin/env python
#Weather station.
#detect environment information from several sensors:
#water leverl, air humity, raining, air temperature, light sensitivity.
#Air temperature&humity sensor: DHT11.
#Add dht.py in micropython/stmhal/modules, refer to esp8266
#Compile the DHT in firmware, then use DHT lib in appli... | Python | 0.000001 |
ce948b49fbd4f3e8012b6d351bbf53db32172474 | fix repeated import of CascadeRPNHead (#8578) | mmdet/models/dense_heads/__init__.py | mmdet/models/dense_heads/__init__.py | # Copyright (c) OpenMMLab. All rights reserved.
from .anchor_free_head import AnchorFreeHead
from .anchor_head import AnchorHead
from .atss_head import ATSSHead
from .autoassign_head import AutoAssignHead
from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead
from .centernet_head import CenterNetHead
from .c... | # Copyright (c) OpenMMLab. All rights reserved.
from .anchor_free_head import AnchorFreeHead
from .anchor_head import AnchorHead
from .atss_head import ATSSHead
from .autoassign_head import AutoAssignHead
from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead
from .centernet_head import CenterNetHead
from .c... | Python | 0 |
5e7e60f8afb3ddeeec2714a9d11dd30a6ea3e52f | Add new calc_total_error tests | photutils/utils/tests/test_prepare_data.py | photutils/utils/tests/test_prepare_data.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
import astropy.units as u
from .. import calc_... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
from .. import calc_total_error
SHAPE = (5, 5... | Python | 0.000002 |
5dd6fa526eac5632f75d543342a7a5a45b866716 | Update plantcv/plantcv/visualize/obj_size_ecdf.py | plantcv/plantcv/visualize/obj_size_ecdf.py | plantcv/plantcv/visualize/obj_size_ecdf.py | # Plot Empirical Cumulative Distribution Function for Object Size
import os
import cv2
import pandas as pd
from plantcv.plantcv import params
from plantcv.plantcv._debug import _debug
from statsmodels.distributions.empirical_distribution import ECDF
from plotnine import ggplot, aes, geom_point, labels, scale_x_log10
... | # Plot Empirical Cumulative Distribution Function for Object Size
import os
import cv2
import pandas as pd
from plantcv.plantcv import params
from plantcv.plantcv._debug import _debug
from statsmodels.distributions.empirical_distribution import ECDF
from plotnine import ggplot, aes, geom_point, labels, \
scale_col... | Python | 0 |
77eefbefcdc5c04d194924e11fa491a0c4c91c14 | convert print statement to logger call | geopy/geocoders/bing.py | geopy/geocoders/bing.py | import xml.dom.minidom
from urllib import urlencode
from urllib2 import urlopen
from geopy.geocoders.base import Geocoder
from geopy.util import logger
class Bing(Geocoder):
"""Geocoder using the Bing Maps API."""
def __init__(self, api_key, format_string='%s', output_format='xml'):
"""Initialize a c... | import xml.dom.minidom
from urllib import urlencode
from urllib2 import urlopen
from geopy.geocoders.base import Geocoder
class Bing(Geocoder):
"""Geocoder using the Bing Maps API."""
def __init__(self, api_key, format_string='%s', output_format='xml'):
"""Initialize a customized Bing geocoder with l... | Python | 0.999999 |
ddf52f0a7c3ed2d276c32c9b60242449ce8bf272 | convert print statement to logger call | geopy/geocoders/bing.py | geopy/geocoders/bing.py | import xml.dom.minidom
from urllib import urlencode
from urllib2 import urlopen
from geopy.geocoders.base import Geocoder
from geopy.util import logger
class Bing(Geocoder):
"""Geocoder using the Bing Maps API."""
def __init__(self, api_key, format_string='%s', output_format='xml'):
"""Initialize a c... | import xml.dom.minidom
from urllib import urlencode
from urllib2 import urlopen
from geopy.geocoders.base import Geocoder
class Bing(Geocoder):
"""Geocoder using the Bing Maps API."""
def __init__(self, api_key, format_string='%s', output_format='xml'):
"""Initialize a customized Bing geocoder with l... | Python | 0.999999 |
22fdc870e6807a946f3e01b3c08b2ea5552c7555 | add end point for chamber member list | congress/members.py | congress/members.py | from .client import Client
from .utils import CURRENT_CONGRESS, check_chamber
class MembersClient(Client):
def list_chamber(self, chamber,congress=CURRENT_CONGRESS):
"Takes a bioguide_id, returns a legislator"
path = "{congress}/{chamber}/members.json".format(congress=congress,chamber=chamber)
... | from .client import Client
from .utils import CURRENT_CONGRESS, check_chamber
class MembersClient(Client):
def get(self, member_id):
"Takes a bioguide_id, returns a legislator"
path = "members/{0}.json".format(member_id)
return self.fetch(path)
def filter(self, chamber, congress=CURR... | Python | 0 |
e56df10f3e40b9287735f1295a0ed72e1525896f | change json to md RasaHQ/roadmap#280 | examples/restaurantbot/bot.py | examples/restaurantbot/bot.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import warnings
from policy import RestaurantPolicy
from rasa_core import utils
from rasa_core.agent import Agent
from rasa_core.policies.... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import warnings
from policy import RestaurantPolicy
from rasa_core import utils
from rasa_core.agent import Agent
from rasa_core.policies.... | Python | 0 |
40316f4a2f1e973ba98a50592a54f21a2d5ac18e | Add the exceptions module to describe exceptions from external target | rapidtest/executors/exceptions.py | rapidtest/executors/exceptions.py | from ..utils import Dictable
MSG_CANNOT_GUESS_METHOD = '''cannot find the target method. You may specify operations as \
arguments to Case if there are multiple methods to be called, or prepend all names of private \
methods with underscores.'''
class ExternalError(Exception):
pass
class ExternalEnvironmentErro... | class ExternalExecutionTargetError(Exception):
pass
| Python | 0 |
07aca8e96d5e93edb684d0c4684ef8f837e8fc58 | Use comment builder for dirhtml too | readthedocs/doc_builder/loader.py | readthedocs/doc_builder/loader.py | from django.utils.importlib import import_module
from django.conf import settings
# Managers
mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs'))
sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx'))
loading = {
# Possible HTML Builders
... | from django.utils.importlib import import_module
from django.conf import settings
# Managers
mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs'))
sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx'))
loading = {
# Possible HTML Builders
... | Python | 0 |
000e44df690a4a1a607224d5f53cc4feee7bcbc0 | add tests for related objects. | reciprocity/chef_profile/tests.py | reciprocity/chef_profile/tests.py | """Test ChefProfile model."""
from __future__ import unicode_literals
from django.conf import settings
from django.test import TestCase
from django.db.models import QuerySet, Manager
from recipe.tests import RecipeFactory, IngredientFactory
from .models import ChefProfile
import factory
USER_BATCH_SIZE = 20
class Us... | """Test ChefProfile model."""
from __future__ import unicode_literals
from django.conf import settings
from django.test import TestCase
from django.db.models import QuerySet, Manager
from .models import ChefProfile
import factory
USER_BATCH_SIZE = 20
class UserFactory(factory.django.DjangoModelFactory):
"""Facto... | Python | 0 |
5c22153b8b43e13266ea2b68a39bcf94b75ab993 | Add get_timestra and get_entry_monitor_dir | creation/lib/cgWConsts.py | creation/lib/cgWConsts.py | ####################################
#
# Keep all the constants used to
# create glidein entries in this
# module
#
# Author: Igor Sfiligoi
#
####################################
import time
import string
import os.path
def get_timestr(when=time.time()):
start_time_tuple=time.localtime(when)
timestr=(string.... | ####################################
#
# Keep all the constants used to
# create glidein entries in this
# module
#
# Author: Igor Sfiligoi
#
####################################
import time
import string
import os.path
start_time_tuple=time.localtime()
TIMESTR=(string.printable[start_time_tuple[0]-2000]+ #year, will... | Python | 0.000001 |
933dacc43a4d3db0ea134d374867e80e8144a539 | Fix pairing syntax bug | mycroft/managers/identity_manager.py | mycroft/managers/identity_manager.py | # Copyright (c) 2017 Mycroft AI, Inc.
#
# This file is part of Mycroft Light
# (see https://github.com/MatthewScholefield/mycroft-light).
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
... | # Copyright (c) 2017 Mycroft AI, Inc.
#
# This file is part of Mycroft Light
# (see https://github.com/MatthewScholefield/mycroft-light).
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
... | Python | 0.000001 |
adb9b262167beecb30edc281e4ab10fc05b3e6da | optimize imports and add common exceptions | voting-server/app/errors.py | voting-server/app/errors.py | from flask import jsonify
from werkzeug.exceptions import HTTPException, default_exceptions
from app import app
def json_error(error):
response = jsonify(message = str(error))
response.status_code = error.code if isinstance(error, HTTPException) else 500
return response
for code in default_exceptions.ke... | from flask import jsonify
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from app import app
def json_error(error):
response = jsonify(message = str(error))
response.status_code = error.code if isinstance(error, HTTPException) else 500
return response
fo... | Python | 0 |
7d650f3ee367a8eac710893c1818aa08cccf7598 | Add auth | bot/dao.py | bot/dao.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pymongo import MongoClient, IndexModel
class DAO:
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
if kwargs.get('mongo') is None:
self.default_mongo_init()
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pymongo import MongoClient, IndexModel
class DAO:
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
if kwargs.get('mongo') is None:
self.default_mongo_init()
... | Python | 0.000007 |
4b8339b53f1b9dcd79f2a9060933713328a13b90 | Mark dask-distributed tests on Windows as xfail (#1747) | xarray/tests/test_distributed.py | xarray/tests/test_distributed.py | import sys
import pytest
import xarray as xr
from xarray.core.pycompat import suppress
distributed = pytest.importorskip('distributed')
da = pytest.importorskip('dask.array')
import dask
from distributed.utils_test import cluster, loop, gen_cluster
from distributed.client import futures_of, wait
from xarray.tests.te... | import pytest
import xarray as xr
from xarray.core.pycompat import suppress
distributed = pytest.importorskip('distributed')
da = pytest.importorskip('dask.array')
import dask
from distributed.utils_test import cluster, loop, gen_cluster
from distributed.client import futures_of, wait
from xarray.tests.test_backends ... | Python | 0 |
6c3ff180c3bda17f1b6fdcf4500fdefdef9d713f | Fix copy & paste errors in setting I brought over from django-skel. | vsub/settings/production.py | vsub/settings/production.py | """Settings used in the production environment."""
from memcacheify import memcacheify
from postgresify import postgresify
from base import *
## Email configuration
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# See: https://... | """Settings used in the production environment."""
from memcacheify import memcacheify
from postgresify import postgresify
from base import *
## Email configuration
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# See: https://... | Python | 0 |
4fcdd2f4cea4899b3f7057f98b95fa7380682816 | Add else: return to break out of loop when BACK is selected | cs251tk/webapp/web_cli.py | cs251tk/webapp/web_cli.py | import os
from ..common import chdir
from ..student import stash, pull, checkout_date
from ..student.markdownify.process_file import process_file
from PyInquirer import style_from_dict, Token, prompt
def check_student(student, spec, basedir):
files = []
if os.path.exists('{}/{}'.format(student, spec['assignm... | import os
from ..common import chdir
from ..student import stash, pull, checkout_date
from ..student.markdownify.process_file import process_file
from PyInquirer import style_from_dict, Token, prompt
def check_student(student, spec, basedir):
files = []
if os.path.exists('{}/{}'.format(student, spec['assignm... | Python | 0.000001 |
c3b0d4b05314dc9fd51c790a86d30659d09c5250 | Allow negative numbers in the GEOS string | wagtailgeowidget/helpers.py | wagtailgeowidget/helpers.py | import re
geos_ptrn = re.compile(
"^SRID=([0-9]{1,});POINT\((-?[0-9\.]{1,})\s(-?[0-9\.]{1,})\)$"
)
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_pt... | import re
geos_ptrn = re.compile(
"^SRID=([0-9]{1,});POINT\(([0-9\.]{1,})\s([0-9\.]{1,})\)$"
)
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.m... | Python | 0 |
03ea21b744a1c499348a3d1b1ad87258efee1e33 | add helpful StrictJsonObject object | dimagi/ext/jsonobject.py | dimagi/ext/jsonobject.py | from __future__ import absolute_import
import datetime
import decimal
from jsonobject.base_properties import AbstractDateProperty
from jsonobject import *
import re
from jsonobject.api import re_date, re_time, re_decimal
from dimagi.utils.dates import safe_strftime
from dimagi.utils.parsing import ISO_DATETIME_FORMAT
f... | from __future__ import absolute_import
import datetime
import decimal
from jsonobject.base_properties import AbstractDateProperty
from jsonobject import *
import re
from jsonobject.api import re_date, re_time, re_decimal
from dimagi.utils.dates import safe_strftime
from dimagi.utils.parsing import ISO_DATETIME_FORMAT
f... | Python | 0.004985 |
9ad697081f62b63f966f998b6618bfb543717f4a | Allow to pass more attributes. | webapp/bootstrap/helpers.py | webapp/bootstrap/helpers.py | # -*- coding: utf-8 -*-
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.orga.models import OrgaFlag, OrgaTeam, \
Membership as OrgaTeamMembership
from byceps.blueprints.party.models import Party
from byceps.blueprints.seating.models import Area as SeatingArea, \
Category as SeatingCateg... | # -*- coding: utf-8 -*-
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.orga.models import OrgaFlag, OrgaTeam, \
Membership as OrgaTeamMembership
from byceps.blueprints.party.models import Party
from byceps.blueprints.seating.models import Area as SeatingArea, \
Category as SeatingCateg... | Python | 0 |
7e45a26f86095ee2f6972e08697aa132e642636e | Test for types in __mul__ | csympy/tests/test_arit.py | csympy/tests/test_arit.py | from nose.tools import raises
from csympy import Symbol, Integer
def test_arit1():
x = Symbol("x")
y = Symbol("y")
e = x + y
e = x * y
e = Integer(2)*x
e = 2*x
def test_arit2():
x = Symbol("x")
y = Symbol("y")
assert x+x == Integer(2) * x
assert x+x != Integer(3) * x
asser... | from csympy import Symbol, Integer
def test_arit1():
x = Symbol("x")
y = Symbol("y")
e = x + y
e = x * y
e = Integer(2)*x
e = 2*x
def test_arit2():
x = Symbol("x")
y = Symbol("y")
assert x+x == Integer(2) * x
assert x+x != Integer(3) * x
assert x+x == 2 * x
| Python | 0.000004 |
852c62eef3d9beea43927f75b1a8aaa021ce25f9 | Add a docstring to test helper | test/selenium/src/lib/test_helpers.py | test/selenium/src/lib/test_helpers.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""
Utility classes for page objects used in tests.
Details:
Most of the te... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""
Utility classes for page objects used in tests.
Details:
Most of the te... | Python | 0.000001 |
cfca983b909c4919d8478e81fca66bf01af80c74 | Fix failing tests. | test/services/updater/test_updater.py | test/services/updater/test_updater.py | import os
import logging
import time
from threading import Semaphore, Thread, Event
from unittest.mock import patch, Mock
import git
from weavelib.messaging import Receiver, Sender
from weavelib.rpc import RPCClient
from weaveserver.core.services import ServiceManager
from weaveserver.services.updater.service import ... | import os
import logging
import time
from threading import Semaphore, Thread, Event
from unittest.mock import patch, Mock
import git
from weavelib.messaging import Receiver, Sender
from weavelib.rpc import RPCClient
from weaveserver.core.services import ServiceManager
from weaveserver.services.updater.service import ... | Python | 0.000003 |
665ece3f699d6a62be0d9c859532ae73e250d86f | Update __init__.py | wellapplication/__init__.py | wellapplication/__init__.py | # -*- coding: utf-8 -*-
__version__ = '0.2.24'
__author__ = 'Paul Inkenbrandt'
__name__ = 'wellapplication'
from transport import *
from usgs import *
from chem import WQP
from mesopy import *
from graphs import piper, fdc, gantt
import MannKendall
import avgMeths
| # -*- coding: utf-8 -*-
__version__ = '0.2.24'
__author__ = 'Paul Inkenbrandt'
__name__ = 'wellapplication'
from transport import *
from usgs import *
from chem import WQP
from graphs import piper, fdc, gantt
import MannKendall
import avgMeths
| Python | 0.000072 |
f5e459e369f1a00d3407f7993e427b676047da21 | bump version | django_anger/__init__.py | django_anger/__init__.py | __version__ = "0.1.1-20130516"
| __version__ = "0.1-20130513.try3"
| Python | 0 |
ed37e4fc5968c7ab17fa55aca3958e72c963ea78 | replace with right code | demo/sort/sort.py | demo/sort/sort.py | #!/usr/bin/python2.7 -OOBRtt
import errno
import os
import operator
import sys
from pysec import alg
from pysec.io import fd
from pysec.utils import ilen, xrange
from pysec import tb
from pysec.xsplit import xbounds
# tb.set_excepthook(tb.short_tb)
BUFSIZE = 4096
MAX_MEMORY_SORT = 10240
TMP_DIR = os.path.abspath('... | #!/usr/bin/python2.7 -OOBRtt
import os
import sys
from pysec import alg
from pysec.io import fd
from pysec.xsplit import xbounds
def find_ck(fp, sub, chunk):
buf = fp[:chunk]
offset = len(buf)
sub_len = len(sub)
while buf:
pos = alg.find(sub)
if pos >= 0:
yield pos
... | Python | 0.999602 |
34db4460aa67fc9abfaaaf2c48a6ea7c5b801ff0 | Fix for libtest for cpython 2.6 / jython / pypy | examples/libtest/imports/__init__.py | examples/libtest/imports/__init__.py |
exec_order = []
class Imports(object):
exec_order = exec_order
def __init__(self):
self.v = 1
imports = Imports()
overrideme = "not overridden"
from . import cls as loccls
# This is not valid since Python 2.6!
try:
from .imports import cls as upcls
except ImportError:
upcls = loccls
def c... |
exec_order = []
class Imports(object):
exec_order = exec_order
def __init__(self):
self.v = 1
imports = Imports()
overrideme = "not overridden"
from . import cls as loccls
from .imports import cls as upcls
def conditional_func():
return "not overridden"
if True:
def conditional_func():
... | Python | 0.000001 |
e354eba380c6df2f0a14e324da9cbe6467494ddc | add - ModelIORedis & build up interface. | versus/tools/modelIO.py | versus/tools/modelIO.py | """
Class family for Model IO classes to handle read/write of learning models
"""
import redis
class ModelIO(object):
def __init__(self, **kwargs):
pass
def write(self, model):
raise NotImplementedError()
def validate(self, model):
""" Ensures that the model is valid. """
... | """
Class family for Model IO classes to handle read/write of learning models
"""
class ModelIO(object):
def __init__(self):
pass
def write(self):
raise NotImplementedError() | Python | 0 |
c1135762c32526b3dc70c186ab97404ac27422e6 | Handle missing plugin directory | repository.py | repository.py | import re
import os
import ttimer
import logging
import subprocess
import plugin
import static
class Repository():
def __init__(self, path):
self.ttl = static.ttl
self.path = path
self.system = static.system.lower()
self.logger = logging.getLogger('default')
self.load_plugins()
def pop_plugin(self, id):
... | import re
import os
import ttimer
import logging
import subprocess
import plugin
import static
class Repository():
def __init__(self, path):
self.ttl = static.ttl
self.path = path
self.system = static.system.lower()
self.logger = logging.getLogger('default')
self.load_plugins()
def pop_plugin(self, id):
... | Python | 0.000001 |
4b9da366b4169caf8802dcbbf20168512cc4e12e | Fix typo | ostrich/stages/stage_30_clone_osa.py | ostrich/stages/stage_30_clone_osa.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | Python | 0.999999 |
62f137072aa26999ad30dda01fe2a736c3e00495 | exclude in admin | django_typograf/admin.py | django_typograf/admin.py | from django.contrib import admin
from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name
class TypografAdmin(admin.ModelAdmin):
""" Admin class for hide typograf fields from admin site """
def _exclude(self, obj=None):
""" Mark typograf fields as exclude """
e... | from django.contrib import admin
from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name
class TypografAdmin(admin.ModelAdmin):
""" Admin class for hide typograf fields from admin site """
def _exclude(self, obj=None):
""" Mark typograf fields as exclude """
e... | Python | 0.00006 |
1ba74fc225d71bc071827291d9942738ef56dd1f | Correct login view | apps/__init__.py | apps/__init__.py | # -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.login import LoginManager
from .models import db, User
from .views import module
__all__ = ('create_app',)
def _init_db(app):
db.app = app
db.init_app(app)
def _init_jinja(app):
pass
def _init_login(app):
login_manager = LoginManage... | # -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.login import LoginManager
from .models import db, User
from .views import module
__all__ = ('create_app',)
def _init_db(app):
db.app = app
db.init_app(app)
def _init_jinja(app):
pass
def _init_login(app):
login_manager = LoginManage... | Python | 0.000001 |
586418860c0441eaebadd0fe79989d6d9f90fa28 | Fix for the component lookup error in vocabulary | src/bda/plone/productshop/vocabularies.py | src/bda/plone/productshop/vocabularies.py | from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.c... | from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.c... | Python | 0 |
3cade5788e55b124ce6c55350afb1beae4d3a5c3 | Update __init__.py | examples/quickhowto2/app/__init__.py | examples/quickhowto2/app/__init__.py | import logging
from flask import Flask
from flask.ext.appbuilder import SQLA, AppBuilder
#from sqlalchemy.engine import Engine
#from sqlalchemy import event
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)
app = Flask(__name__)
app.config.from_ob... | import logging
from flask import Flask
from flask.ext.appbuilder import SQLA, AppBuilder
#from sqlalchemy.engine import Engine
#from sqlalchemy import event
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)
app = Flask(__name__)
app.config.from_ob... | Python | 0.000072 |
14d12b1d6bbcf5784256b82f58974f02fe8d1503 | Remove unused imports. Gating tests so they do not run on Windows | tests/integration/states/test_cron.py | tests/integration/states/test_cron.py | # -*- coding: utf-8 -*-
'''
Tests for the cron state
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
# Import... | # -*- coding: utf-8 -*-
'''
Tests for the cron state
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from test... | Python | 0 |
6493cc31acdc09df6c0ad952e95380ac31a0e504 | Update __init__.py | vispy/color/__init__.py | vispy/color/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Convience interfaces to manipulate colors.
This module provides support for manipulating colors.
"""
__all__ = ['Color', 'ColorArray', 'Colormap',
'get_colorma... | # -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Convience interfaces to manipulate colors.
This module provides support for manipulating colors.
"""
<<<<<<< HEAD
__all__ = ['Color', 'ColorArray', 'Colormap',
... | Python | 0.000072 |
a364196814c3b33e7fd51a42b4c3a48a3aaeaee8 | Update list of extraordinary gentlemen | volaparrot/constants.py | volaparrot/constants.py | ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
"couns... | ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
BLA... | Python | 0 |
84965de8b53dcb5b10788808a2bf135df82cd4d9 | Update dev DB to sqlite3 | vpr/vpr/settings/dev.py | vpr/vpr/settings/dev.py | # Django settings for vpr project.
from base import *
DEBUG = True
DEVELOPMENT = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'vpr.sqlite3', # Or path to databas... | # Django settings for vpr project.
from base import *
DEBUG = True
DEVELOPMENT = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
#'NAME': 'vpr.sqlite3', # Or path to datab... | Python | 0 |
52f9d95582456754aa4e9f9cd5d59a308c9e256c | remove comments | server.py | server.py | import socket
import communication
import time
import cv2
import numpy as np
from picamera import PiCamera
import sys
import signal
run_condition = True
def signal_handler(signal, frame):
print('Exiting...')
global run_condition
run_condition = False
sys.exit(0)
def generateRandomImg(... | import socket
import communication
import time
import cv2
import numpy as np
from picamera import PiCamera
import sys
import signal
run_condition = True
def signal_handler(signal, frame):
print('Exiting...')
global run_condition
run_condition = False
sys.exit(0)
def generateRandomImg(... | Python | 0 |
95495c1b0ae1a696b95eb486c7a40d54f507dacb | Add cross origin requests. | server.py | server.py | import pymzn
import os
from subprocess import Popen, PIPE
from flask import Flask, json, Response
app = Flask(__name__)
folder = 'models' #where the .mzn files are stored
models = []
for file in os.listdir(folder):
if file.endswith('.mzn'):
models.append(file)
@app.route('/')
def Allmodels():
return json.jsonify(... | import pymzn
import os
from subprocess import Popen, PIPE
from flask import Flask, json, Response
app = Flask(__name__)
folder = 'models' #where the .mzn files are stored
models = []
for file in os.listdir(folder):
if file.endswith('.mzn'):
models.append(file)
@app.route('/')
def Allmodels():
return json.jsonify(... | Python | 0 |
11000be28e9c150adde2d9109bb5e078a5c553b6 | Assume the dimesions are good | server.py | server.py | #!/usr/bin/env python
import sys
import numpy
import math
import logging
from fuel.datasets import DogsVsCats
from fuel.schemes import ShuffledScheme
from fuel.server import start_server
from fuel.streams import DataStream
from fuel.transformers import ScaleAndShift, ForceFloatX
from fuel.transformers.image import (
... | #!/usr/bin/env python
import sys
import numpy
import math
import logging
from fuel.datasets import DogsVsCats
from fuel.schemes import ShuffledScheme
from fuel.server import start_server
from fuel.streams import DataStream
from fuel.transformers import ScaleAndShift, ForceFloatX
from fuel.transformers.image import (
... | Python | 0.999997 |
eb889d08c6031ba6c2b55a883d09e22f5684f0ee | Add mode (training|arena) option to the command line | server.py | server.py | #!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
def get_new_game_state(server_host, key, mode='training', number_of_turns = '20'):
if(mode=='training'):
params = { 'key': key, 'turns': number_of_turns}
r = requests.post(server_host + '/api/training', ... | #!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
def get_new_game_state(server_host, key, number_of_turns = '20', mode='training'):
if(mode=='training'):
params = { 'key': key, 'turns': number_of_turns}
r = requests.post(server_host + '/api/training', ... | Python | 0.000001 |
50a3805a16f75010fbaa6fc4e4c49c4da64f30b8 | edit and delete | shares.py | shares.py | # coding: utf-8
"""
share.py
~~~~~~~~
木犀分享的信息
"""
from flask import url_for, jsonify, request, g, current_app
from . import api
from muxiwebsite.models import Share, AnonymousUser
from muxiwebsite import db
from .authentication import auth
from flask_login import current_user
tags = ['frontend', 'backe... | # coding: utf-8
"""
share.py
~~~~~~~~
木犀分享的信息
"""
from flask import url_for, jsonify, request, g, current_app
from . import api
from muxiwebsite.models import Share, AnonymousUser
from muxiwebsite import db
from .authentication import auth
from flask_login import current_user
@api.route('/shares/', me... | Python | 0.000001 |
7542d224d2ab15adec31a2d896a22cab6a7a2b37 | add log | spider.py | spider.py | # -*- coding: utf-8 -*-
import http.client
from ltc.models import Record
import json
def get_current_price():
conn = http.client.HTTPSConnection('api.huobi.com')
conn.request('GET','/staticmarket/ticker_ltc_json.js')
r = conn.getResponse()
if r.status == 200 :
data = r.read()
string = ... | # -*- coding: utf-8 -*-
import http.client
from ltc.models import Record
import json
def get_current_price():
conn = http.client.HTTPSConnection('api.huobi.com')
conn.request('GET','/staticmarket/ticker_ltc_json.js')
r = conn.getResponse()
if r.status == 200 :
data = r.read()
string = ... | Python | 0.000002 |
7d2b0e1afa0606f7f4bcf4ff9005595120bd822c | Add method to find possible moves | src/ai.py | src/ai.py | from card import Card
from board import Board
class AI():
# Check for possible move given the state of the board
def possibleMoves(self, board):
# List of the possible moves
# a move is a tuple (cardOrigin, cardDestination)
moves = []
# Test cards of the tableau
for pi... | from card import Card
from board import Board
class AI():
# Check for possible move given the state of the board
def possibleMoves(self, board):
return
# Define if all the cards are discovered and placed in a way which
# will always let the player finish the game
def willWin(self, board)... | Python | 0.000019 |
195e5cde1d81d7f73b77ce1b1c52f0beea8a2595 | Fix tclist iterator slicing | ejdb/tc.py | ejdb/tc.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numbers
from . import c
from .utils import CObjectWrapper
class ListIterator(CObjectWrapper):
"""Python iterator wrapper for a `TCLIST *`.
"""
def __init__(self, wrapped, count=None):
super(ListIterator, self).__init__(
wrapped=wra... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numbers
from . import c
from .utils import CObjectWrapper
class ListIterator(CObjectWrapper):
"""Python iterator wrapper for a `TCLIST *`.
"""
def __init__(self, wrapped, count=None):
super(ListIterator, self).__init__(
wrapped=wra... | Python | 0.000009 |
1e7869a5b7c5503498634dc0161fdfb29bbb4c7b | Fix imports to restore schema import. | grano/logic/schemata.py | grano/logic/schemata.py | import os
import yaml
from pprint import pprint
from grano.core import db, url_for
from grano.model import Schema, Attribute
from grano.logic.validation import validate_schema, Invalid
from grano.logic import projects as projects_logic
from grano.logic import attributes
def save(project, data):
""" Create a sche... | import os
from grano.core import db, url_for
from grano.model import Schema, Attribute
from grano.logic.validation import validate_schema
from grano.logic import projects as projects_logic
from grano.logic import attributes
def save(project, data):
""" Create a schema. """
data = validate_schema(data)
... | Python | 0 |
1aed7a2b0213d457e1efdf5923a159fc053caae5 | Check for multiple teams in migrate_tips | gratipay/models/team.py | gratipay/models/team.py | """Teams on Gratipay are plural participants with members.
"""
from postgres.orm import Model
class Team(Model):
"""Represent a Gratipay team.
"""
typname = 'teams'
def __eq__(self, other):
if not isinstance(other, Team):
return False
return self.id == other.id
def _... | """Teams on Gratipay are plural participants with members.
"""
from postgres.orm import Model
class Team(Model):
"""Represent a Gratipay team.
"""
typname = 'teams'
def __eq__(self, other):
if not isinstance(other, Team):
return False
return self.id == other.id
def _... | Python | 0 |
87608781d7de4fe9977c14a3165f4540ae1e81f2 | simplify interaction example | examples/utils/interaction.py | examples/utils/interaction.py | import sys
from PySide.QtGui import QApplication, QColor
from pivy import quarter, coin, graphics
class ConnectionPolygon(graphics.Polygon):
std_col = "green"
def __init__(self, markers, dynamic=False):
super(ConnectionPolygon, self).__init__(
sum([m.points for m in markers], []), dynamic=... | import sys
from PySide.QtGui import QApplication, QColor
from pivy import quarter, coin, graphics
class ConnectionPolygon(graphics.Polygon):
std_col = "green"
def __init__(self, markers, lines, dynamic=False):
super(ConnectionPolygon, self).__init__(
sum([m.points for m in markers], []), d... | Python | 0.99796 |
93ed74d3c904c743f91f0c9e81f6d36bda731a10 | modify example.py | example.py | example.py | #! /usr/bin/python
import FixQueue
if __name__ == "__main__" :
fq = FixQueue(2) # 2 means queue size
fq.append('a')
fq.append('b')
print (fq) # ['a', 'b']
fq.append('c')
print (fq) # ['b', 'c']
print (fq.pop()) # b
print (fq) # ['b']
| #! /usr/bin/python
from FixQueue import FixQueue
if __name__ == "__main__" :
fq = FixQueue(2) # 2 means queue size
fq.append('a')
fq.append('b')
print (fq) # ['a', 'b']
fq.append('c')
print (fq) # ['b', 'c']
print (fq.pop()) # b
print (fq) # ['b']
| Python | 0.000001 |
80adb43a22f82a036d72bdd398d45ee4daa9a5ff | Update example.py | example.py | example.py | import pornhub
search_keywords = []
#client = pornhub.PornHub("5.135.164.72", 3128, search_keywords)
#With proxy, given a Proxy IP and Port. For the countries with restricted access like Turkey, etc.
client = pornhub.PornHub(search_keywords)
for star in client.getStars(10):
print(star)
print(star["name"])
... | import pornhub
search_keywords = []
#client = pornhub.PornHub("5.135.164.72", 3128, search_keywords)
#With proxy, given a Proxy IP and Port. For the countries with restricted access like Turkey, etc.
client = pornhub.PornHub(search_keywords)
for star in client.getStars(10):
print(star)
print(star["name"])
... | Python | 0.000001 |
4053baa698f1047f09540c9ff3d6e8a08d844335 | Comment example | example.py | example.py | """Example app to login to GitHub"""
import argparse
import mechanicalsoup
parser = argparse.ArgumentParser(description='Login to GitHub.')
parser.add_argument("username")
parser.add_argument("password")
args = parser.parse_args()
browser = mechanicalsoup.Browser()
# request github login page
login_page = browser.ge... | """Example app to login to GitHub"""
import argparse
import mechanicalsoup
parser = argparse.ArgumentParser(description='Login to GitHub.')
parser.add_argument("username")
parser.add_argument("password")
args = parser.parse_args()
browser = mechanicalsoup.Browser()
# request github login page
login_page = browser.ge... | Python | 0 |
c279eda7b56e1f793b0241a66fe155cfdbdd1d40 | Remove intermediate string during gzip compression | api/tasks.py | api/tasks.py | from __future__ import absolute_import
import os
from celery import shared_task
from celery.utils.log import get_task_logger
from api.StormReplayParser import StormReplayParser
import boto
import StringIO
import cStringIO
import json
import gzip
from boto.s3.key import Key
log = get_task_logger(__name__)
@share... | from __future__ import absolute_import
import os
from celery import shared_task
from celery.utils.log import get_task_logger
from api.StormReplayParser import StormReplayParser
import boto
import StringIO
import json
import gzip
from boto.s3.key import Key
log = get_task_logger(__name__)
@shared_task
def Locall... | Python | 0.001237 |
72b3642953d0e14d4b4c9ec03560a96d259f7d16 | Remove monkey patching in favor of inheritance for SpatialReference | contones/srs.py | contones/srs.py | """Spatial reference systems"""
from osgeo import osr
class BaseSpatialReference(osr.SpatialReference):
"""Base class for extending osr.SpatialReference."""
def __repr__(self):
return self.wkt
@property
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = ... | """Spatial reference systems"""
from osgeo import osr
# Monkey patch SpatialReference since inheriting from SWIG classes is a hack
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
retu... | Python | 0 |
aef91895b31a615bb9af4cfae96aae97d91cad91 | Add Intercept transformer. | dftransformers.py | dftransformers.py | import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class ColumnSelector(BaseEstimator, TransformerMixin):
"""Transformer that selects a column in a numpy array or DataFrame
by index or name.
"""
def __init__(self, idxs=None, name=None):
self.idxs = ... | import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class ColumnSelector(BaseEstimator, TransformerMixin):
"""Transformer that selects a column in a numpy array or DataFrame
by index or name.
"""
def __init__(self, idxs=None, name=None):
self.idxs = ... | Python | 0 |
4a67891a1b8a96fcc666e12b2d4c27e3598d20a2 | add support email | product_price_factor_online/__openerp__.py | product_price_factor_online/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Product price factor for web shop",
'summary': """Multiplies price depending on product attributes""",
'category': 'Website',
'license': 'GPL-3',
'author': "IT-Projects LLC, Ildar Nasyrov",
'price': 20.00,
'currency': 'EUR',
'images': ['images/1.png'],
... | # -*- coding: utf-8 -*-
{
'name': "Product price factor for web shop",
'summary': """Multiplies price depending on product attributes""",
'category': 'Website',
'license': 'GPL-3',
'author': "IT-Projects LLC, Ildar Nasyrov",
'price': 20.00,
'currency': 'EUR',
'images': ['images/1.png'],
... | Python | 0 |
6853fd1e45370a9db650b0983e9835c14ea9209e | Add diagnostics endpoint | gutenberg_http/views.py | gutenberg_http/views.py | from sanic.exceptions import RequestTimeout
from sanic.request import Request
from sanic.response import json
from gutenberg_http import app
from gutenberg_http.errors import InvalidUsage
from gutenberg_http.logic import body as _body
from gutenberg_http.logic import metadata as _metadata
from gutenberg_http.logic imp... | from sanic.exceptions import RequestTimeout
from sanic.request import Request
from sanic.response import json
from gutenberg_http import app
from gutenberg_http.errors import InvalidUsage
from gutenberg_http.logic import body as _body
from gutenberg_http.logic import metadata as _metadata
from gutenberg_http.logic imp... | Python | 0.000002 |
c33ffffb0f85e7db96f9856640ad0efdd9dc145f | Wrap all exceptions in JSON | gutenberg_http/views.py | gutenberg_http/views.py | from sanic.exceptions import RequestTimeout
from sanic.request import Request
from sanic.response import json
from gutenberg_http import app
from gutenberg_http.errors import InvalidUsage
from gutenberg_http.logic import body as _body
from gutenberg_http.logic import metadata as _metadata
from gutenberg_http.logic imp... | from sanic.exceptions import RequestTimeout
from sanic.request import Request
from sanic.response import json
from gutenberg_http import app
from gutenberg_http.errors import InvalidUsage
from gutenberg_http.logic import body as _body
from gutenberg_http.logic import metadata as _metadata
from gutenberg_http.logic imp... | Python | 0.999992 |
39f0e8ed68bea6318bcb58801b5368428582f549 | remove SF checks from user api endpoint | api/views.py | api/views.py | from django.core.management import call_command
from django.utils.six import StringIO
from rest_framework import viewsets
from salesforce.models import Adopter
from salesforce.functions import check_if_faculty_pending
from social.apps.django_app.default.models import \
DjangoStorage as SocialAuthStorage
from wagtai... | from django.core.management import call_command
from django.utils.six import StringIO
from rest_framework import viewsets
from salesforce.models import Adopter
from salesforce.functions import check_if_faculty_pending
from social.apps.django_app.default.models import \
DjangoStorage as SocialAuthStorage
from wagtai... | Python | 0 |
d994337007eb9cfe41edef591cbd30765660a822 | Prepare for next development iteration | yarn_api_client/__init__.py | yarn_api_client/__init__.py | # -*- coding: utf-8 -*-
__version__ = '0.3.8.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
| # -*- coding: utf-8 -*-
__version__ = '0.3.7'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
| Python | 0 |
18e3746969f9a2a4c10553cd7c59793fafd955aa | uniform multi-website public users handling | addons/website_sale/models/res_partner.py | addons/website_sale/models/res_partner.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.http import request
class ResPartner(models.Model):
_inherit = 'res.partner'
last_website_so_id = fields.Many2one('sale.order', compute='_compute_last_website_so_... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.http import request
class ResPartner(models.Model):
_inherit = 'res.partner'
last_website_so_id = fields.Many2one('sale.order', compute='_compute_last_website_so_... | Python | 0.999999 |
e3ff630917d6bb0f744330abace7c41d2b48ba8f | Add "pip_install" task | fabfile.py | fabfile.py | from fabric.api import env, task, local, cd, run, sudo, put
from tempfile import NamedTemporaryFile
env.use_ssh_config = True
env.hosts = ['skylines@skylines']
APP_DIR = '/home/skylines'
SRC_DIR = '%s/src' % APP_DIR
@task
def deploy(branch='master', force=False):
push(branch, force)
restart()
@task
def p... | from fabric.api import env, task, local, cd, run, sudo, put
from tempfile import NamedTemporaryFile
env.use_ssh_config = True
env.hosts = ['skylines@skylines']
APP_DIR = '/home/skylines'
SRC_DIR = '%s/src' % APP_DIR
@task
def deploy(branch='master', force=False):
push(branch, force)
restart()
@task
def p... | Python | 0.000011 |
2d6e3beb7ea4fb5448cba6a123feb73fe25da2a1 | add kobocat deployment details | fabfile.py | fabfile.py | import os
import sys
from fabric.api import env, run, cd
DEFAULTS = {
'home': '/home/wsgi/srv/',
'repo_name': 'formhub',
}
DEPLOYMENTS = {
'dev': {
'home': '/home/ubuntu/src/',
'host_string': 'ubuntu@dev.ona.io',
'project': 'ona',
'key_filename': os.path.expanduser('~/.ss... | import os
import sys
from fabric.api import env, run, cd
DEFAULTS = {
'home': '/home/wsgi/srv/',
'repo_name': 'formhub',
}
DEPLOYMENTS = {
'dev': {
'home': '/home/ubuntu/src/',
'host_string': 'ubuntu@dev.ona.io',
'project': 'ona',
'key_filename': os.path.expanduser('~... | Python | 0 |
6fae23c1d442880256ed2d4298844a50d6a7968e | Make sure "fab publish" cleans the dist folder | fabfile.py | fabfile.py | import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/de... | import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/de... | Python | 0 |
24c7c61b06ef8f1396d167bc0621d58d7a233fde | Generate local webserver using SimpleHTTPServer | fabfile.py | fabfile.py | from fabric.api import local
import urllib
def clean():
local('rm -rf output')
def update_cv():
"""Get current version of my CV."""
pdf_remote = "https://github.com/dplarson/CV/raw/master/David_Larson.pdf"
pdf_local = "output/David_Larson.pdf"
try:
urllib.urlretrieve(pdf_remote, pdf_loca... | from fabric.api import local
import urllib
def clean():
local('rm -rf output')
def update_cv():
"""Get current version of my CV."""
pdf_remote = "https://github.com/dplarson/CV/raw/master/David_Larson.pdf"
pdf_local = "output/David_Larson.pdf"
try:
urllib.urlretrieve(pdf_remote, pdf_loca... | Python | 0.999891 |
d94af25800a1e0b6d918659ef08d90f596c5a608 | change uwsgi worker reload option to graceful reload | fabfile.py | fabfile.py | # -*- coding: utf-8 -*-
import os
from fabric.api import local, run, cd, prefix, env, sudo, settings, shell_env
from deploy import server
env.host_string = '{user}@{host}:{port}'.format(
user=env.pycon_user,
host=env.pycon_host,
... | # -*- coding: utf-8 -*-
import os
from fabric.api import local, run, cd, prefix, env, sudo, settings, shell_env
from deploy import server
env.host_string = '{user}@{host}:{port}'.format(
user=env.pycon_user,
host=env.pycon_host,
... | Python | 0 |
fcdb3de7465467e4ea4a50faec1c39ec9a26e15c | set main function | async_crawler.py | async_crawler.py | #!/usr/bin/env python
# python 3.5 async web crawler.
# https://github.com/mehmetkose/python3.5-async-crawler
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2016 Mehmet Kose mehmet@linux.com
import aiohttp
import asyncio
from urllib.parse import urljoin, urldefrag... | #!/usr/bin/env python
# python 3.5 async web crawler.
# https://github.com/mehmetkose/python3.5-async-crawler
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2016 Mehmet Kose mehmet@linux.com
import aiohttp
import asyncio
from urllib.parse import urljoin, urldefrag... | Python | 0.000019 |
604d610d7d7e5d883c643daeba09f5b65db943ce | Make aws template use non-interactive apt-get (#1098) | parsl/providers/aws/template.py | parsl/providers/aws/template.py | template_string = """#!/bin/bash
#sed -i 's/us-east-2\.ec2\.//g' /etc/apt/sources.list
cd ~
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y python3 python3-pip libffi-dev g++ libssl-dev
pip3 install numpy scipy parsl
$worker_init
$user_script
# Shutdown the instance as soon as the worker sc... | template_string = """#!/bin/bash
#sed -i 's/us-east-2\.ec2\.//g' /etc/apt/sources.list
cd ~
apt-get update -y
apt-get install -y python3 python3-pip libffi-dev g++ libssl-dev
pip3 install numpy scipy parsl
$worker_init
$user_script
# Shutdown the instance as soon as the worker scripts exits
# or times out to avoid EC... | Python | 0 |
406987b860987894e297d5172a2a3eb0f4e082f8 | Fix a bug in the data resizer. | core/data/DataResizer.py | core/data/DataResizer.py | """
DataResizer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageResample
from vtk import vtkVersion
VTK_MAJOR_VERSION = vtkVersion.GetVTKMajorVersion()
class DataResizer(object):
"""
DataResizer is a tool that will resize a given image dataset.
You can specify a certain magnification factor or you c... | """
DataResizer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageResample
from vtk import vtkVersion
VTK_MAJOR_VERSION = vtkVersion.GetVTKMajorVersion()
class DataResizer(object):
"""
DataResizer is a tool that will resize a given image dataset.
You can specify a certain magnification factor or you c... | Python | 0 |
31b0b97590ce496ba22a39c396ff868c6f511637 | install pre-commit | dacsspace/client.py | dacsspace/client.py | #!/usr/bin/env python3
from configparser import ConfigParser
from asnake.aspace import ASpace
class ArchivesSpaceClient:
"""Handles communication with ArchivesSpace."""
def __init__(self):
config = ConfigParser()
config.read("local_settings.cfg")
self.aspace = ASpace(baseurl=config.g... | #!/usr/bin/env python3
import argparse
from configparser import ConfigParser
from asnake.aspace import ASpace
#published_only = False
class ArchivesSpaceClient:
"""Handles communication with ArchivesSpace."""
def __init__(self):
config = ConfigParser()
config.read("local_settings.cfg")
... | Python | 0 |
7cfc16d016906e1437580acff42e503d3b2fa188 | Change %s to .format | src/pip/_internal/distributions/source/legacy.py | src/pip/_internal/distributions/source/legacy.py | # The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
import logging
from pip._internal.build_env import BuildEnvironment
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.exceptions import InstallationError
from pip._internal.uti... | # The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
import logging
from pip._internal.build_env import BuildEnvironment
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.exceptions import InstallationError
from pip._internal.uti... | Python | 0.000007 |
0ca727f0ce5877ba2ca3ef74c9309c752a51fbf6 | Fix enable action on plugins | src/sentry/web/frontend/project_plugin_enable.py | src/sentry/web/frontend/project_plugin_enable.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
... | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
... | Python | 0 |
0599b259ed08121160196734f7212dc7fa33149f | Remove execute_auth_api_request method | devicehive/token.py | devicehive/token.py | from devicehive.api_request import ApiRequest
class Token(object):
"""Token class."""
AUTH_HEADER_NAME = 'Authorization'
AUTH_HEADER_VALUE_PREFIX = 'Bearer '
def __init__(self, transport, auth):
self._transport = transport
self._login = auth.get('login')
self._password = auth... | from devicehive.api_request import ApiRequest
from devicehive.api_response import ApiResponseError
class Token(object):
"""Token class."""
AUTH_HEADER_NAME = 'Authorization'
AUTH_HEADER_VALUE_PREFIX = 'Bearer '
def __init__(self, transport, auth):
self._transport = transport
self._lo... | Python | 0.000025 |
e32acfcfa14ec785a3d716f60b61cc66d6c496ea | add celery | app/tasks.py | app/tasks.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Kun Jia
# date: 20/06/2017
# email: me@jack003.com
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from flask import current_app
from pymongo import MongoClient
from app import celery
from .a... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Kun Jia
# date: 20/06/2017
# email: me@jack003.com
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from flask import current_app
from pymongo import MongoClient
from app import celery
from .a... | Python | 0.999861 |
0237fb8114f5a8423d39f44b2882d5dbf10954d7 | make .seen replies for CTCP ACTIONs say "doing nick message"; leaves .seen replies for PRIVMSG to channel the same ("saying message"). | willie/modules/seen.py | willie/modules/seen.py | # coding=utf8
"""
seen.py - Willie Seen Module
Copyright 2008, Sean B. Palmer, inamidst.com
Copyright © 2012, Elad Alfassa <elad@fedoraproject.org>
Licensed under the Eiffel Forum License 2.
http://willie.dftba.net
"""
from __future__ import unicode_literals
import time
import datetime
from willie.tools import Identi... | # coding=utf8
"""
seen.py - Willie Seen Module
Copyright 2008, Sean B. Palmer, inamidst.com
Copyright © 2012, Elad Alfassa <elad@fedoraproject.org>
Licensed under the Eiffel Forum License 2.
http://willie.dftba.net
"""
from __future__ import unicode_literals
import time
import datetime
from willie.tools import Identi... | Python | 0 |
b4af07754c64e915fcfc5fbec00389dee6a11020 | disable one unit test on travis | _unittests/ut_helpgen/test_notebooks_api.py | _unittests/ut_helpgen/test_notebooks_api.py | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if ... | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if ... | Python | 0 |
b03b9276e48edfa53a70a46dc5779cd1de2299e0 | add priv_dns_name sub command | aws_utils/ec2.py | aws_utils/ec2.py | #!/usr/bin/env python3
import sys
import argparse
import boto3
# --------------------------------------------------------------------------------
# arg parse
# --------------------------------------------------------------------------------
parser = argparse.ArgumentParser(description='ec2 utils')
parser.set_defaults... | #!/usr/bin/env python3
import sys
import argparse
import boto3
# --------------------------------------------------------------------------------
# arg parse
# --------------------------------------------------------------------------------
parser = argparse.ArgumentParser(description='ec2 utils')
parser.set_defaults... | Python | 0.000003 |
107b72da8629d97452dc6b7ee0f44eeb7d9e351c | remove x-based matplotlib rendering | gamma_limits_sensitivity/__init__.py | gamma_limits_sensitivity/__init__.py | '''
This is the hard working code in order to calculate ULs, sensitivities,
and time to detections.
'''
import matplotlib.pyplot as plt
matplotlib.use('Agg')
def upper_limit(N_on, N_off, alpha, l_lim, A_eff):
figures = [plt.figure()]
dictionary = {
'plots': figures
}
return dictionary
de... | '''
This is the hard working code in order to calculate ULs, sensitivities,
and time to detections.
'''
import matplotlib.pyplot as plt
def upper_limit(N_on, N_off, alpha, l_lim, A_eff):
figures = [plt.figure()]
dictionary = {
'plots': figures
}
return dictionary
def sensitivity(s_bg, a... | Python | 0.000001 |
2a67ef989fa79aefccb9bcefe543715346642f91 | Normalize time to UTC. | abusehelper/contrib/autoshun/autoshunbot.py | abusehelper/contrib/autoshun/autoshunbot.py | import idiokit
import time as _time
import calendar
from abusehelper.core import utils, cymruwhois, bot, events
AUTOSHUN_CSV_URL = "http://www.autoshun.org/files/shunlist.csv"
class AutoshunBot(bot.PollingBot):
COLUMNS = ["ip", "time", "type"]
feed_url = bot.Param(default=AUTOSHUN_CSV_URL)
use_cymru_whoi... | import idiokit
from abusehelper.core import utils, cymruwhois, bot, events
AUTOSHUN_CSV_URL = "http://www.autoshun.org/files/shunlist.csv"
class AutoshunBot(bot.PollingBot):
COLUMNS = ["ip", "time", "type"]
feed_url = bot.Param(default=AUTOSHUN_CSV_URL)
use_cymru_whois = bot.BoolParam(default=True)
... | Python | 0.960634 |
86af85e46b0b313ecd0804916539d18556fba84a | Use api.constrains | account_analytic_required/models/account.py | account_analytic_required/models/account.py | # -*- coding: utf-8 -*-
# © 2011 Akretion
# © 2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from openerp import _, api, exceptions, fields, models
from openerp.tools import float_is_zero
class AccountAccountType(models.Model):
_inherit = "account.account.type"
@api.model
... | # -*- coding: utf-8 -*-
# © 2011 Akretion
# © 2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from openerp import _, api, fields, models
from openerp.tools import float_is_zero
class AccountAccountType(models.Model):
_inherit = "account.account.type"
@api.model
def _get... | Python | 0.000001 |
19afe973bffe1bb90942757fcbf81f3630ffddda | Update code formatting. | crawler/args.py | crawler/args.py | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2015 ghostwords.
#
# 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/.
from os import path
import argparse
def ... | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2015 ghostwords.
#
# 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/.
from os import path
import argparse
def ... | Python | 0 |
696b4e093171e9d6f17502650f15c9299438b874 | Drop Py2 and six on tests/integration/modules/test_virtualenv_mod.py | tests/integration/modules/test_virtualenv_mod.py | tests/integration/modules/test_virtualenv_mod.py | import os
import tempfile
import salt.utils.path
from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES
from tests.support.case import ModuleCase
from tests.support.helpers import slowTest
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import skipIf
@skipIf(
salt.utils.path.which_bin... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
import tempfile
import salt.utils.path
from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES
from tests.support.case import ModuleCase
from tests.support.helpers import slowTest
from tests.support.runtests ... | Python | 0 |
d8b144c3142534714ecff90cf88749a6b8ed347d | Remove django 1.8 workaround no longer needed | pucas/management/commands/createcasuser.py | pucas/management/commands/createcasuser.py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from pucas.ldap import LDAPSearch, LDAPSearchException, \
user_info_from_ldap
class Command(BaseCommand):
help = 'Initialize a new CAS user account'
def add_arguments(self, parser):
parser.add_argu... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from pucas.ldap import LDAPSearch, LDAPSearchException, \
user_info_from_ldap
class Command(BaseCommand):
help = 'Initialize a new CAS user account'
def add_arguments(self, parser):
parser.add_argu... | Python | 0 |
872320e02d5c922e177434f6b9fa70af8cf822b9 | Revert "RT-26" | wkhtmltopdf/__init__.py | wkhtmltopdf/__init__.py | import os
if 'DJANGO_SETTINGS_MODULE' in os.environ:
from .utils import *
__author__ = 'Incuna Ltd'
__version__ = '2.0.3'
| # Have to comment this import to perfrom pip install at the same time as django install
# import os
# if 'DJANGO_SETTINGS_MODULE' in os.environ:
# from .utils import *
__author__ = 'Incuna Ltd'
__version__ = '2.0.3'
| Python | 0.000001 |
563a82246180d949917bcd444411bbeb82604e97 | Add an assertion in search.py | recipe_modules/buildbucket/tests/search.py | recipe_modules/buildbucket/tests/search.py | # Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
from recipe_engine import types
from google.protobuf import json_format
from PB.go.chromium.org.luci.buildbucket.proto import build as build_pb2... | # Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
from recipe_engine import types
from google.protobuf import json_format
from PB.go.chromium.org.luci.buildbucket.proto import build as build_pb2... | Python | 0 |
ebe5a4ce8c12489bceb8991f627fdea29329e854 | Enable discovery server to reply also when started w/o net connection | xfd_discovery_server.py | xfd_discovery_server.py | #!/usr/bin/env python
#
# Author Aske Olsson aske.olsson@switch-gears.dk
#
import socket
import struct
import time
#MCAST_GRP = '224.1.1.1'
#MCAST_PORT = 5007
MCAST_ADDR = "239.77.124.213"
MCAST_PORT = 19418
MCAST_ANS_PORT = 19419
def socket_setup():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_D... | #!/usr/bin/env python
#
# Author Aske Olsson aske.olsson@switch-gears.dk
#
import socket
import struct
#MCAST_GRP = '224.1.1.1'
#MCAST_PORT = 5007
MCAST_ADDR = "239.77.124.213"
MCAST_PORT = 19418
MCAST_ANS_PORT = 19419
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socke... | Python | 0 |
2cf4a0b93db423207798ffd93b2e91cdb73b6d2b | Add identifier for UT Brownsville | tx_salaries/utils/transformers/ut_brownsville.py | tx_salaries/utils/transformers/ut_brownsville.py | from . import base
from . import mixins
class TransformedRecord(mixins.GenericCompensationMixin,
mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin,
mixins.GenericJobTitleMixin, mixins.GenericPersonMixin,
mixins.MembershipMixin, mixins.OrganizationMixin, mixins.PostMixin,
mix... | from . import base
from . import mixins
class TransformedRecord(mixins.GenericCompensationMixin,
mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin,
mixins.GenericJobTitleMixin, mixins.GenericPersonMixin,
mixins.MembershipMixin, mixins.OrganizationMixin, mixins.PostMixin,
mix... | Python | 0.00011 |
c3df6a10d008441c79eb07b889f52fe0de22538b | Fix the default prefix | powerline_vaulted_segment/vaulted.py | powerline_vaulted_segment/vaulted.py | from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.theme import requires_segment_info
@requires_segment_info
def vaulted(pl, segment_info, prefix=''):
'''Return the current vaulted vault
:param string prefix:
The prefix to use in front of the vault na... | from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.theme import requires_segment_info
@requires_segment_info
def vaulted(pl, segment_info, prefix=None):
'''Return the current vaulted vault
:param string prefix:
The prefix to use in front of the vault ... | Python | 0.998784 |
1ba440ca24b0108d4dcf911f1f3c967ff7de1dc4 | Create a unique filename when uploading a team file. | hackday/teams/models.py | hackday/teams/models.py | import time
from django.contrib.auth.models import User
from django.db import models
from django import forms
from django.template.defaultfilters import slugify
from assets.models import Attachment, ImageAttachment, Link
from charities.models import Charity
from voting.moremodels import Category
class STATUS(object... | from django.contrib.auth.models import User
from django.db import models
from django import forms
from django.template.defaultfilters import slugify
from assets.models import Attachment, ImageAttachment, Link
from charities.models import Charity
from voting.moremodels import Category
class STATUS(object):
"""
... | Python | 0 |
e4cc4447bf9aca4f579eef34baccd3aaf73939c3 | Print statement verwijderd uit functie | hamming-code/hamming.py | hamming-code/hamming.py | from matrix import Matrix
#The encoding matrix
encoding_matrix = Matrix([
[1, 1, 0, 1],
[1, 0, 1, 1],
[1, 0, 0, 0],
[0, 1, 1, 1],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
])
#The parity checking matrix
checking_matrix = Matrix([
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 1],
[0, 0... | from matrix import Matrix
#The encoding matrix
encoding_matrix = Matrix([
[1, 1, 0, 1],
[1, 0, 1, 1],
[1, 0, 0, 0],
[0, 1, 1, 1],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
])
#The parity checking matrix
checking_matrix = Matrix([
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 1],
[0, 0... | Python | 0.999972 |
825eb37e15e2fb08ac205b7495e93a91acb79c26 | Add function for flashing all form errors | app/utils.py | app/utils.py | import re
from flask import url_for, flash
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields impo... | import re
from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import Hidd... | Python | 0 |
3289a259a7fa9ed959eb18d012c2d2e52198b033 | Update malshare.py | plugins/analytics/public/malshare.py | plugins/analytics/public/malshare.py | import json
import requests
import logging
from core.analytics import OneShotAnalytics
from core.errors import ObservableValidationError
from core.observables import Url, Hash
class MalshareAPI(object):
"""Base class for querying the Malshare API.
This is the public API, 1000 samples per day.
Limit rej... | import json
import requests
import logging
from core.analytics import OneShotAnalytics
from core.errors import ObservableValidationError
from core.observables import Url, Hash
class MalshareAPI(object):
"""Base class for querying the Malshare API.
This is the public API, 1000 samples per day.
Limit rej... | Python | 0 |
c0e1bed70bc331041622e0db06871d4f3e3277f3 | Update activate-devices.py | cron/activate-devices.py | cron/activate-devices.py | #!/usr/bin/env python
import MySQLdb
#import datetime
#import urllib2
#import os
import datetime
import RPi.GPIO as GPIO
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO!")
servername = "localhost"
username = "pi"
password = "password"
dbname = "pi_heating_db"
GPIO.setmode(G... | #!/usr/bin/env python
import MySQLdb
#import datetime
#import urllib2
#import os
import datetime
import RPi.GPIO as GPIO
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO!")
servername = "localhost"
username = "pi"
password = "password"
dbname = "pi_heating_db"
GPIO.setmode(G... | Python | 0.000001 |
8701318037b9d425149f0689fa137be78a782aa7 | return the name of the face found | app/views.py | app/views.py | from app import app
from flask import Flask, request, jsonify
import kairos
DEFAULT_GALLERY = 'default_gallery'
# App Logic
@app.route('/', methods=['GET'])
def index():
return 'yo'
@app.route('/upload/<name>', methods=['POST'])
def upload(name):
img_url = request.form['img_url']
success = kairos.add_fac... | from app import app
from flask import Flask, request, jsonify
import kairos
DEFAULT_GALLERY = 'default_gallery'
# App Logic
@app.route('/', methods=['GET'])
def index():
return 'yo'
@app.route('/upload/<name>', methods=['POST'])
def upload(name):
img_url = request.form['img_url']
success = kairos.add_fac... | Python | 0.999999 |
b3b489fb8b476a17e8d9e08d70f90aec38756c8a | Allow use of a custom user model | cuser/fields.py | cuser/fields.py | # Copyright (c) 2009-2011 Dennis Kaarsemaker <dennis@kaarsemaker.net>
# 2011 Atamert Olcgen <muhuk@muhuk.com>
# 2012 Alireza Savand <alireza.savand@gmail.com>
#
# Small piece of middleware to be able to access authentication data from
# everywhere in the django code.
#
# Redistribution and u... | # Copyright (c) 2009-2011 Dennis Kaarsemaker <dennis@kaarsemaker.net>
# 2011 Atamert Olcgen <muhuk@muhuk.com>
# 2012 Alireza Savand <alireza.savand@gmail.com>
#
# Small piece of middleware to be able to access authentication data from
# everywhere in the django code.
#
# Redistribution and u... | Python | 0 |
194dd71de22e34e5f262b8fe0735347d6b7f1bd8 | Support title page (-1) | portfolio/pdf-scripts/do-page-generate.py | portfolio/pdf-scripts/do-page-generate.py | import subprocess
from music21 import *
from pyPdf import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from reportlab.lib import pagesizes
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# some important constants
MUSIC_XML_... | import subprocess
from music21 import *
from pyPdf import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from reportlab.lib import pagesizes
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# some important constants
MUSIC_XML_... | Python | 0 |
f7ce07f6775fd88a0d8e5bf0f980eb22050f2d92 | Update file_regression.py | src/pytest_regressions/file_regression.py | src/pytest_regressions/file_regression.py | # encoding: UTF-8
from functools import partial
import six
from .common import perform_regression_check, check_text_files
class FileRegressionFixture(object):
"""
Implementation of `file_regression` fixture.
"""
def __init__(self, datadir, original_datadir, request):
"""
:type datad... | # encoding: UTF-8
from functools import partial
import six
from .common import perform_regression_check, check_text_files
class FileRegressionFixture(object):
"""
Implementation of `file_regression` fixture.
"""
def __init__(self, datadir, original_datadir, request):
"""
:type datad... | Python | 0.000001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.