repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
torchbox/webassets | src/webassets/filter/clevercss.py | from __future__ import absolute_import
from webassets.filter import Filter
__all__ = ('CleverCSS',)
class CleverCSS(Filter):
"""Converts `CleverCSS <http://sandbox.pocoo.org/clevercss/>`_ markup
to real CSS.
If you want to combine it with other CSS filters, make sure this one
runs first.
"""
... |
w0rp/w0rpzone | blog/migrations/0004_articlecomment_modified_date.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_article_modified_date'),
]
operations = [
migrations.AddF... |
vlegoff/tsunami | src/secondaires/magie/types/__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... |
yl565/statsmodels | statsmodels/compat/pandas.py | from __future__ import absolute_import
from distutils.version import LooseVersion
import numpy as np
import pandas
version = LooseVersion(pandas.__version__)
if version >= '0.17.0':
def sort_values(df, *args, **kwargs):
return df.sort_values(*args, **kwargs)
elif version >= '0.14.0':
def sort_value... |
cedriclaunay/gaffer | python/GafferTest/StringAlgoTest.py | ##########################################################################
#
# Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
yangjiandong/newsmeme | scripts/generate_models.py | #-*- coding: utf-8 -*-
#使用SqlAutocode,根据数据库已有表,产生符合Flask-SqlAlchemy要求的models的定义
import os.path
from flask import Flask
from sqlautocode import config
from sqlautocode.declarative import *
from sqlautocode.formatter import _repr_coltype_as
from flask.ext.sqlalchemy import SQLAlchemy
singular = plural = lambda x: x
con... |
StanczakDominik/PythonPIC | pythonpic/tests/test_charge_interpolation.py | # # coding=utf-8
# import matplotlib.pyplot as plt
# import numpy as np
# import pytest
#
# from ..algorithms.field_interpolation import PeriodicInterpolateField
# from ..classes import Species, PeriodicGrid
#
# @pytest.mark.parametrize("power", range(6))
# def test_poly(power, plotting=False):
# NG = 16
# NG_p... |
TomAugspurger/pandas | pandas/tests/groupby/aggregate/test_aggregate.py | """
test .agg behavior / note that .apply is tested generally in test_groupby.py
"""
import functools
import numpy as np
import pytest
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series, concat
import pandas._testing as tm
from pandas.co... |
shincling/MemNN_and_Varieties | QA/matlab/format_plane.py | import jieba
import re
f=open('/home/shin/DeepLearning/MemoryNetwork/QA/planeplane.txt','r')
content=f.read().decode('gbk').encode('utf8')
fw=open('/home/shin/DeepLearning/MemoryNetwork/QA/planeplane_shin','w')
content=content.split('dialogue ')
for i in range(1,5000):
sent_id=1
dia=content[i][(content[i].inde... |
atiro/obesitydata | config/settings/production.py | # -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use sendgrid to send emails
- Use MEMCACHIER on Heroku
'''
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django... |
fusionbox/satchless | satchless/category/fields.py | # -*- coding:utf-8 -*-
from django import forms
class CategoryMixin:
def label_from_instance(self, obj):
level = getattr(obj, obj._mptt_meta.level_attr)
indent = max(0, level - 1) * u'│'
if obj.parent:
last = (obj.parent.rght - obj.rght == 1) \
and (obj.rght... |
cbertinato/pandas | asv_bench/benchmarks/gil.py | import numpy as np
import pandas.util.testing as tm
from pandas import DataFrame, Series, read_csv, factorize, date_range
from pandas.core.algorithms import take_1d
try:
from pandas import (rolling_median, rolling_mean, rolling_min, rolling_max,
rolling_var, rolling_skew, rolling_kurt, rolli... |
dimagi/commcare-hq | corehq/apps/sso/tasks.py | import datetime
import logging
from celery.schedules import crontab
from celery.task import periodic_task
from corehq.apps.hqwebapp.tasks import send_html_email_async
from corehq.apps.sso.models import IdentityProvider
from corehq.apps.sso.utils.context_helpers import get_idp_cert_expiration_email_context
log = log... |
MapofLife/MOL | earthengine/google-api-python-client/samples/gtaskqueue_sample/gtaskqueue/taskqueue_cmds.py | #!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# 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 ... |
stormi/tsunami | src/secondaires/navigation/editeurs/matedit/__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... |
amccloud/django-stripe | django_stripe/management/commands/stripe_clear_test_customers.py | from django.core.management.base import BaseCommand
from ...shortcuts import stripe
class Command(BaseCommand):
help = "Clear all test customers from your stripe account."
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 1))
count, offset = 100, 0
if verbo... |
serzans/wagtail | wagtail/tests/settings.py | import os
import django
from django.conf import global_settings
WAGTAIL_ROOT = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(WAGTAIL_ROOT, 'test-static')
MEDIA_ROOT = os.path.join(WAGTAIL_ROOT, 'test-media')
MEDIA_URL = '/media/'
DATABASES = {
'default': {
'ENGINE': os.environ.get('DATABASE_ENGI... |
lochiiconnectivity/exabgp | lib/exabgp/bgp/message/notification.py | # encoding: utf-8
"""
notification.py
Created by Thomas Mangin on 2009-11-05.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
import string
from exabgp.bgp.message import Message
def hexstring (value):
def spaced (value):
for v in value:
yield '%02X' % ord(v)
return '0x' + ''.join(spaced(valu... |
javierwilson/forocacao | forocacao/app/views.py | # -*- coding: utf-8 -*-
from datetime import date
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from djang... |
UECIDE/UECIDE_data | compilers/arm-eabi-gcc/linux/arm-eabi-gcc/arm-none-eabi/lib/thumb/armv6s-m/libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009, 2010 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later versi... |
WarrenWeckesser/numpy | numpy/core/tests/test_umath_accuracy.py | import numpy as np
import platform
from os import path
import sys
import pytest
from ctypes import c_float, c_int, cast, pointer, POINTER
from numpy.testing import assert_array_max_ulp
from numpy.core._multiarray_umath import __cpu_features__
IS_AVX = __cpu_features__.get('AVX512F', False) or \
(__cpu_features... |
jameslao/QuantSoftwareToolkit | QSTK/qstklearn/mldiagnostics.py | # (c) 2011, 2012 Georgia Tech Research Corporation
# This source code is released under the New BSD license. Please see
# http://wiki.quantsoftware.org/index.php?title=QSTK_License
# for license details.
#
# Created on Month day, Year
#
# @author: Vishal Shekhar
# @contact: mailvishalshekhar@gmail.com
# @summary: ML A... |
paulondc/gaffer | python/GafferSceneTest/SeedsTest.py | ##########################################################################
#
# Copyright (c) 2012, John Haddon. All rights reserved.
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided t... |
jdddog/hri | hri_api/src/hri_api/tests/timer_action_server.py | #!/usr/bin/env python
import roslib
roslib.load_manifest('hri_framework')
from hri_msgs.msg import TimerAction, TimerResult, TimerFeedback
from hri_framework.multi_goal_action_server import MultiGoalActionServer
import threading
class TimerActionServer(object):
def __init__(self, node_name):
self.action_se... |
petrus-jvrensburg/flask-admin | flask_admin/contrib/mongoengine/form.py | from mongoengine import ReferenceField
from mongoengine.base import BaseDocument, DocumentMetaclass, get_document
from wtforms import fields, validators
from flask_mongoengine.wtf import orm, fields as mongo_fields
from flask_admin import form
from flask_admin.model.form import FieldPlaceholder
from flask_admin.model... |
jait/tupelo | tupelo/xmlrpc.py | #!/usr/bin/env python
# vim: set sts=4 sw=4 et:
import time
import xmlrpc.client
from . import players
from . import rpc
from .common import GameState, CardSet, GameError, RuleError, ProtocolError, simple_decorator
from .events import EventList, CardPlayedEvent, MessageEvent, TrickPlayedEvent, TurnEvent, StateChangedE... |
jwheare/digest | lib/reportlab/pdfbase/ttfonts.py | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfbase/ttfonts.py
"""TrueType font support
This defines classes to represent TrueType fonts. They know how to calculate
their own width and ho... |
dalou/django-cargo | cargo/models/user.py | # encoding: utf-8
import datetime
import operator
import hashlib
import urllib
import random
from django.db import models
from django.conf import settings
from django.core import validators
from django.core.urlresolvers import reverse
from django.contrib import auth, messages
from django.utils.translation import uget... |
leonardo-modules/leonardo-module-forms | leonardo_module_forms/widget/form/forms.py | # -#- coding: utf-8 -#-
import copy
from crispy_forms.bootstrap import *
from crispy_forms.bootstrap import Tab, TabHolder
from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.layout import HTML, Layout
from django import forms
from django.utils.translation import ugettext_la... |
jyt109/termite-data-server | bin/import_corpus.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import json
import sqlite3
import subprocess
from import_abstr import ImportAbstraction
CORPUS_WRITER = 'utils/mallet/CorpusWriter.jar'
class ImportCorpus( ImportAbstraction ):
def __init__( self, app_name, app_model = 'corpus', app_desc = 'Corpus Meta... |
SiLab-Bonn/basil | basil/TL/Dummy.py | #
# ------------------------------------------------------------
# Copyright (c) All rights reserved
# SiLab, Institute of Physics, University of Bonn
# ------------------------------------------------------------
#
import logging
import array
from basil.TL.SiTransferLayer import SiTransferLayer
logger = logging.get... |
agoragames/chai | chai/chai.py | '''
Copyright (c) 2011-2017, Agora Games, LLC All rights reserved.
https://github.com/agoragames/chai/blob/master/LICENSE.txt
'''
from __future__ import absolute_import
try:
import unittest2
unittest = unittest2
except ImportError:
import unittest
import re
import sys
import inspect
import traceback
from... |
jnovinger/django-compiling-loader | compiling_loader/compiler.py | import os.path
from . import generator, compiler_state
def convert_template(template, state):
body = generator.generate_nodelist(template.nodelist, state)
state.add_render_function(body, name='render')
module = state.build_module()
return module
def compile_template(template):
origin_name = ... |
cherrypy/magicbus | docs/conf.py | #! /usr/bin/env python3
# Requires Python 3.6+
# pylint: disable=invalid-name
"""Configuration of Sphinx documentation generator."""
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'jaraco.packaging.sphinx',
'rst.linker',
]
master_doc = 'index'
intersphinx_mapping = {
'cheroot': ('... |
jpopelka/osbs-client | osbs/conf.py | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, absolute_import, unicode_literals
import logging
import os
import warnings
from pkg_resources import p... |
sirloon/jaluino | ide/plugins/JaluinoDebugger/picshell/ui/debug/comp/uart.py | from picshell.engine.util.Format import Format
import wx
import wx.lib.newevent
class UARTReceiver:
def __init__(self):
self.type ="uartReceiver"
self.dataReady = False
self.address = 0x19 #TXREG
# callbacks allow acces to emu's state
def CreateUI(self,parent,ps... |
Shizmob/pydle | tests/test_client_users.py | import pydle
from .fixtures import with_client
@with_client()
def test_client_same_nick(server, client):
assert client.is_same_nick('WiZ', 'WiZ')
assert not client.is_same_nick('WiZ', 'jilles')
assert not client.is_same_nick('WiZ', 'wiz')
@with_client()
def test_user_creation(server, client):
client... |
bokeh/bokeh | tests/unit/bokeh/models/test_tools.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
2083008/blog | Blog/users/views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from braces.views import LoginRequiredMixin
from .forms import UserForm
from .models import User
from django.s... |
bitcraft/pyglet | examples/image_display.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are me... |
ericholscher/django | django/contrib/formtools/tests/wizard/namedwizardtests/forms.py | import os
import tempfile
from django import forms
from django.core.files.storage import FileSystemStorage
from django.forms.formsets import formset_factory
from django.http import HttpResponse
from django.template import Template, Context
from django.contrib.auth.models import User
from django.contrib.formtools.wiz... |
ericholscher/django | django/core/management/color.py | """
Sets up the terminal color scheme.
"""
import os
import sys
from django.utils import termcolors
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
unsupported_platform = (sys.platform in ('win32', 'Pocket PC'))
# isatty is not ... |
kcompher/FreeDiscovUI | freediscovery/dupdet/simhash.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import six
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_array
class SimhashDuplicates(... |
HPI-SWA-Lab/RSqueak | rsqueakvm/model/pointers.py | from rsqueakvm import constants, error
from rsqueakvm.model.base import W_AbstractObjectWithIdentityHash
from rsqueakvm.model.numeric import W_SmallInteger
from rpython.rlib import objectmodel, jit
from rpython.rlib.rstrategies import rstrategies as rstrat
class W_PointersObject(W_AbstractObjectWithIdentityHash):
... |
alex/django-filter | tests/test_fields.py | import decimal
from datetime import datetime, time, timedelta, tzinfo
import pytz
from django import forms
from django.test import TestCase, override_settings
from django.utils import timezone
from django_filters.fields import (
BaseCSVField,
BaseRangeField,
DateRangeField,
DateTimeRangeField,
Iso... |
jreback/pandas | pandas/tests/indexes/categorical/test_astype.py | from datetime import date
import numpy as np
import pytest
from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index, IntervalIndex
import pandas._testing as tm
class TestAstype:
def test_astype(self):
ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
... |
clips/pattern | examples/05-vector/03-lsa.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from builtins import str, bytes, dict, int
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import time
from pattern.vector import Document, Model, KNN
from patter... |
rthornton/booktracker | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import booktracker
version = booktracker.__version__
setup(
name='BookTracker',
version=version,
author='',
author_email='robert.thornton... |
phretor/django-academic | academic/apps/content/migrations/0001_initial.py | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Download'
db.create_table('content_download', (
('id', self.gf('django.db.mode... |
toastdriven/piecrust | piecrust/storage.py | class BaseStorage(object):
# Read-only (NECESSARY) methods.
def all_objects(self, request):
raise NotImplementedError()
def list(self, **kwargs):
raise NotImplementedError()
def single(self, **kwargs):
raise NotImplementedError()
# Methods needed for write-access.
def ... |
justquick/django-native-tags | native_tags/contrib/op.py | import operator
from native_tags.decorators import comparison, function
# Comparison operators
def lt(a, b):
return operator.lt(a, b)
lt = comparison(lt, doc=operator.lt.__doc__)
def le(a, b):
return operator.le(a, b)
le = comparison(le, doc=operator.le.__doc__)
def eq(a, b):
return operator.eq(... |
zjj/trac_hack | trac/web/tests/session.py | from Cookie import SimpleCookie as Cookie
import time
from datetime import datetime
import unittest
from trac.test import EnvironmentStub, Mock
from trac.web.session import DetachedSession, Session, PURGE_AGE, \
UPDATE_INTERVAL, SessionAdmin
from trac.core import TracError
def _prep_sess... |
westurner/pbm | docs/conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pbm documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogen... |
pkom/gestionies | gestionies/contrib/sites/migrations/0002_set_site_domain_and_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSakurahonyakuBlogspotCom.py | def extractSakurahonyakuBlogspotCom(item):
'''
Parser for 'sakurahonyaku.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if item['tags'] != []:
return None
titlemap = [
('Hyouketsu Kyouka... |
Neurita/boyle | boyle/nifti/check.py | # coding=utf-8
"""
Nifti file consistency checking utilities
"""
#------------------------------------------------------------------------------
#Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
#Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
#Universidad del Pais Vasco UPV/EHU
#
#2013, Alexandre Manha... |
httpPrincess/metahosting | queue_managers/rabbit.py | import pika
import logging
import json
from retrying import retry
import threading
class BlockingPikaManager(object):
def __init__(self, host, port, user='guest', password='guest', queue=None):
logging.debug('Initializing...')
credentials = pika.PlainCredentials(user, password)
self.parame... |
OWASP/django-DefectDojo | dojo/tools/retirejs/parser.py | import json
import hashlib
from dojo.models import Finding
class RetireJsParser(object):
def __init__(self, json_output, test):
self.target = None
self.port = "80"
self.host = None
tree = self.parse_json(json_output)
if tree:
self.items = [data for data in se... |
mseeger/apbsint | python/test/potentials/test_epup_quad_poissonexp.py | #! /usr/bin/env python
# EPTOOLS Python Interface
# Test of quadrature implementation of EP updates. Laplace transformation
# and adaptive quadrature.
#
# Potential: Poisson with exponential rate function.
# NOTE: This is not a real test against ground truth, but rather checking
# a consistency constraint between resu... |
vlegoff/tsunami | src/primaires/joueur/config.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... |
endlessm/chromium-browser | third_party/catapult/tracing/tracing/value/diagnostics/generic_set.py | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
from tracing.proto import histogram_proto
from tracing.value.diagnostics import diagnostic
class GenericSet(diagnostic.Diagnostic):
"""Conta... |
kantai/passe-framework-prototype | django/views/generic/simple.py | from django.template import loader, RequestContext
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGone
from django.utils.log import getLogger
import warnings
warnings.warn(
'Function-based generic views have been deprecated; use class-based views instead.',
... |
st4lk/cookiecutter-django | {{cookiecutter.repo_name}}/apps/users/views.py | # -*- coding: utf-8 -*-
from django.views.generic import DetailView
from django.views.generic import UpdateView
from django.views.generic import ListView
from braces.views import LoginRequiredMixin
from .forms import UserForm
from .models import User
class UserDetailView(LoginRequiredMixin, DetailView):
model = U... |
diegobz/django-admin-sso | example/settings.py | # Django settings for example project.
import os.path
ROOT = os.path.dirname(os.path.realpath(__file__))
DEBUG = True
ADMINS = (
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite',
'USER': '',
'PASSWORD': '',
'HOST'... |
mogoweb/chromium-crosswalk | chrome/common/extensions/docs/server2/api_schema_graph_test.py | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from api_schema_graph import APISchemaGraph
API_SCHEMA = [{
'namespace': 'tabs',
'properties': {
'lowercase'... |
fgregg/felzenszwalb | felzenszwalb/_felzenszwalb.py | import warnings
import numpy as np
from _felzenszwalb_cy import _felzenszwalb_grey
def felzenszwalb(image, scale=1, sigma=0.8, min_size=20):
"""Computes Felsenszwalb's efficient graph based image segmentation.
Produces an oversegmentation of a multichannel (i.e. RGB) image
using a fast, minimum spanning... |
b-cannon/my_djae | djangae/contrib/pagination/tests.py | from django.db import models
from djangae.test import TestCase
from djangae.contrib import sleuth
from djangae.contrib.pagination import (
paginated_model,
Paginator,
PaginationOrderingRequired
)
from .paginator import queryset_identifier, _get_marker
@paginated_model(orderings=[
("first_name",),
... |
mitsuhiko/sentry | src/sentry/social_auth/urls.py | from __future__ import absolute_import, print_function
from django.conf.urls import patterns, url
from social_auth.views import complete
from sentry.social_auth.views import auth, disconnect
urlpatterns = patterns('',
# authentication
url(r'^login/(?P<backend>[^/]+)/$', auth,
name='socialauth_begin'... |
beeftornado/sentry | tests/sentry/integrations/github/test_webhooks.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import six
from datetime import datetime, timedelta
from django.utils import timezone
from sentry.models import Commit, CommitAuthor, GroupLink, Integration, PullRequest, Repository
from sentry.testutils import APITestCase
from uuid import uuid4
from .te... |
eunchong/build | scripts/slave/recipe_modules/auto_bisect/PRESUBMIT.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Local presubmit script for the auto_bisect recipe module directory.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts.
"""
... |
BetterWorks/healthchecks | hc/api/migrations/0011_notification.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0010_channel'),
]
operations = [
migrations.CreateModel(
name='Notification',
fields=[
... |
luzfcb/django-simple-history | simple_history/registry_tests/tests.py | from __future__ import unicode_literals
import unittest
from datetime import datetime, timedelta
import django
from django.contrib.auth import get_user_model
from django.core import management
from django.test import TestCase
from simple_history import exceptions, register
from six.moves import cStringIO as StringIO
... |
atztogo/phonopy | phonopy/spectrum/dynamic_structure_factor.py | """Calculate dynamic structure factor at harmonic level."""
# Copyright (C) 2016 Atsushi Togo
# All rights reserved.
#
# This file is part of phonopy.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractAngleanuwordsWordpressCom.py | def extractAngleanuwordsWordpressCom(item):
'''
Parser for 'angleanuwords.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('rebirth of medicine', 'rebirth of medicine', ... |
zostera/django-fa | testsettings.py | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
SECRET_KEY = 'ishalltellyouonlyonce'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messa... |
stormi/tsunami | src/secondaires/navigation/config.py | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... |
akarki15/mozillians | mozillians/common/tests/__init__.py | from __future__ import absolute_import
from contextlib import contextmanager, nested
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.test import TestCase as BaseTestCase
from django.test.client import Client
from django.test.utils import override_settings
f... |
bokeh/bokeh | bokeh/server/__init__.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
uoscompsci/PRISONER | examples/dockerdemo/demo.py | import json
import os
import requests
import urllib
import urllib2
import urlparse
from jinja2 import Environment, FileSystemLoader
from werkzeug.contrib.securecookie import SecureCookie
from werkzeug.contrib.sessions import SessionMiddleware, FilesystemSessionStore
#from werkzeug.formparser import parse_form_data
fro... |
gt-ros-pkg/rcommander-core | nodebox_qt/src/nodebox/gui/qt/dashboard.py | from PyQt4.QtGui import QDialog, QGridLayout, QLayout, QFont, QLabel, QSlider, QLineEdit, QCheckBox, QPushButton
from PyQt4.QtCore import Qt, SIGNAL
from nodebox import graphics
class DashboardController(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setWindowFlags(s... |
tovmeod/anaf | anaf/projects/identities.py | """
Handle objects from this module relevant to a Contact or a User
"""
from __future__ import unicode_literals
from anaf.core.models import Object
from templatetags.projects import projects_task_list
CONTACT_OBJECTS = {'manager': {'label': 'Managed Projects',
'objects': [],
... |
rackerlabs/django-DefectDojo | dojo/api_v2/permissions.py | import re
from rest_framework.exceptions import ParseError
from dojo.models import Endpoint, Engagement, Finding, Product_Type, Product, Test, Dojo_Group
from django.shortcuts import get_object_or_404
from rest_framework import permissions
from dojo.authorization.authorization import user_has_permission
from dojo.auth... |
takeflight/wagtail | wagtail/admin/widgets/filtered_select.py | from django import forms
from wagtail.admin.staticfiles import versioned_static
class FilteredSelect(forms.Select):
"""
A select box where the options are shown and hidden dynamically in response to another
form field whose HTML `id` is specified in `filter_field`.
The `choices` list accepts entries... |
jszakmeister/trac-backlog | backlog/schema.py | # Copyright (C) 2009, 2012 John Szakmeister
# All rights reserved.
#
# This software is licensed as described in the file LICENSE.txt, which
# you should have received as part of this distribution.
from trac.db import Table, Column, Index
# The version of the database schema
schema_version = 1
# The database schema... |
vrutkovs/atomic-reactor | tests/plugins/test_koji_parent.py | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals
import os
try:
import koji as koji
except ImportError:
import inspect
import sys
#... |
derks/cement | cement/core/output.py | """Cement core output module."""
from ..core import backend, exc, interface, handler
Log = backend.minimal_logger(__name__)
def output_validator(klass, obj):
"""Validates an handler implementation against the IOutput interface."""
members = [
'_setup',
'render',
]
interface.v... |
daniel-severo/dask-ml | tests/test_kmeans.py | """
Mostly just smoke tests, and verifying that the parallel implementation is
the same as the serial.
"""
import dask.array as da
import dask.dataframe as dd
import numpy as np
import pandas as pd
import pytest
from dask.array.utils import assert_eq
from dask_ml.cluster import k_means
from dask_ml.cluster import KMea... |
sbrodeur/ros-icreate-bbb | src/action/scripts/record/data/convert_hdf5.py | #!/usr/bin/env python
# Copyright (c) 2016, Simon Brodeur
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, th... |
DarrelHsu/cvsClient | testing_support/filesystem_mock.py | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import errno
import fnmatch
import os
import re
import StringIO
def _RaiseNotFound(path):
raise IOError(errno.ENOENT, path, os.strerror(errno.ENOENT)... |
yarikoptic/NiPy-OLD | examples/neurospin/need_data/permutation_test.py | import numpy as np
from nipy.neurospin.group.permutation_test import permutation_test_onesample
# Get group data
f = np.load('data/offset_002.npz')
data, vardata, xyz = f['mat'], f['var'], f['xyz']
# Create one-sample permutation test instance
ptest = permutation_test_onesample(data, xyz, stat_id='wilcoxon')
# Clu... |
zingale/hydro_examples | compressible/riemann.py | # solve the Riemann problem for a gamma-law gas
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as optimize
class State(object):
""" a simple object to hold a primitive variable state """
def __init__(self, p=1.0, u=0.0, rho=1.0):
self.p... |
MarkusH/django-nap | nap/auth.py | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test... |
madphysicist/numpy | numpy/core/tests/test_ufunc.py | import warnings
import itertools
import sys
import pytest
import numpy as np
import numpy.core._umath_tests as umt
import numpy.linalg._umath_linalg as uml
import numpy.core._operand_flag_tests as opflag_tests
import numpy.core._rational_tests as _rational_tests
from numpy.testing import (
assert_, assert_equal, ... |
eggsandbeer/scheduler | synergy/scheduler/state_machine_continuous.py | __author__ = 'Bohdan Mushkevych'
from datetime import datetime
from logging import ERROR, WARNING, INFO
from synergy.db.model import job
from synergy.db.model.job import Job
from synergy.db.model.unit_of_work import UnitOfWork
from synergy.db.manager import ds_manager
from synergy.conf import context
from synergy.sys... |
mortada/scipy | scipy/interpolate/tests/test_polyint.py | from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.testing import (assert_almost_equal, assert_array_equal,
TestCase, run_module_suite, assert_allclose, assert_equal, assert_)
from scipy.interpolate import (splrep, splev,
KroghInterpolator, ... |
globocom/database-as-a-service | dbaas/account/forms/change_password_form.py | # -*- coding:utf-8 -*-
from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _
from ..backends import DbaasBackend
import ldap
class ChangePasswordForm(forms.Form):
"""
A form that lets a user change set his/her password without entering the
old password
"""
err... |
phsmit/iwclul2016-scripts | 01_dataprep/parse_transcripts.py | #!/usr/bin/env python3
import itertools
import os
import re
import string
from subprocess import Popen, PIPE
import sys
import collections
def main(txt_file, phn_file, transcript_file, langdat_dir, sentence_per_line):
phone_map = {v[0]: v[1].strip() for v in (l.split(None, 1) for l in open('{}/phones'.format(lan... |
r-owen/stui | TUI/Base/StateSet.py | #!/usr/bin/env python
"""Keep track of named states in sorted order.
History:
2015-11-03 ROwen Replace "== None" with "is None" and "!= None" with "is not None" to modernize the code.
"""
import RO.AddCallback
class State(object):
def __init__(self, name, severity, isCurrent, stateStr):
self.name = nam... |
lk-geimfari/elizabeth | mimesis/exceptions.py | """Custom exceptions which used in Mimesis."""
from typing import Any, Optional, Union
from mimesis.enums import Locale
class LocaleError(ValueError):
"""Raised when a locale isn't supported."""
def __init__(self, locale: Union[Locale, str]) -> None:
"""Initialize attributes for informative output.... |
wangpanjun/doit | doc/tutorial/my_tasks.py | from __future__ import print_function
def task(*fn, **kwargs):
# decorator without parameters
if fn:
function = fn[0]
function.task_metadata = {}
return function
# decorator with parameters
def wrap(function):
function.task_metadata = kwargs
return function
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.