repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
Gustry/inasafe | safe/definitions/reports/__init__.py | Python | gpl-3.0 | 2,816 | 0 | # coding=utf-8
"""Definitions for basic report.
"""
from __future__ import absolute_import
from safe.utilities.i18n import tr
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
# Meta description about component
# component... | r('Tag this product as PNG output.')
}
svg_product_tag = {
'key': 'svg_produ | ct_tag',
'name': tr('SVG'),
'description': tr('Tag this product as SVG output.')
}
product_output_type_tag = [
html_product_tag,
pdf_product_tag,
qpt_product_tag,
png_product_tag,
]
|
nathanbjenx/cairis | cairis/controllers/ConceptReferenceController.py | Python | apache-2.0 | 3,396 | 0.00265 | # 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
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | ntent-Type'] = "application/json"
return resp
def put(self, name):
session_id = get_sessi | on_id(session, request)
dao = ConceptReferenceDAO(session_id)
upd_cr = dao.from_json(request)
dao.update_concept_reference(upd_cr, name)
dao.close()
resp_dict = {'message': 'Concept Reference successfully updated'}
resp = make_response(json_serialize(resp_dict), OK)
resp.contenttype = 'app... |
mnaughto/trigger-statusbar | .trigger/module_dynamic/module.py | Python | mit | 2,707 | 0.026967 | import json
import os
import shutil
import zipfile
from build import cd
def create_template(name, path, **kw):
os.makedirs(os.path.join(path, 'module'))
with open(os.path.join(path, 'module', 'manifest.json'), 'w') as manifest_file:
manifest = {
"name": name,
"version": "0.1",
"description": "My module t... | latform_version.txt")
}
module_model['directories'] = {
'module_directory': os.path.join(path, 'module')
}
return module_model
def create_upload_zip(path, subd | irs = [], **kw):
module_path = os.path.abspath(os.path.join(path, 'module'))
zip_base = os.path.abspath(os.path.join(path, '.trigger', 'upload_tmp'))
if os.path.exists(zip_base+".zip"):
os.unlink(zip_base+".zip")
if len(subdirs):
zip_path = _make_partial_archive(zip_base, subdirs, root_dir=module_path)
els... |
KungFuLucky7/server_admin | server_admin/wsgi.py | Python | gpl-2.0 | 1,551 | 0.001289 | """
WSGI config for server_admin project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | iddleware here.
# fr | om helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
looker/sentry | src/sentry/api/base.py | Python | bsd-3-clause | 11,066 | 0.000633 | from __future__ import absolute_import
import functools
import logging
import six
import time
from datetime import datetime, timedelta
from django.conf import settings
from django.utils.http import urlquote
from django.views.decorators.csrf import csrf_exempt
from enum import Enum
from pytz import utc
from rest_frame... | request, 'auth', None)
if rv.user is None:
rv.user = getattr(request, 'user', None)
return rv
@csrf_exempt
def dispatch(self, request, *args, **kwargs):
"""
Identical to rest framework's dispatch except we add the ability
to convert arguments (for com... | self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
if settings.SENTRY_API_RESPONSE_DELAY:
time.sleep(settings.SENTRY_API_RESPONSE_DELAY / 1000.0)
origin = request.META.get('HTTP_ORIGIN', 'null'... |
Ibuprofen/gizehmoviepy | gif_parsers/read_rgb.py | Python | mit | 1,281 | 0.014832 | import json
from PIL import Image
import collections
with open('../config/nodes.json') as data_file:
nodes = json.load(data_file)
# empty fucker
ordered_nodes = [None] * len(nodes)
# populate fucker
for i, pos in nodes.items():
ordered_nodes[int(i)] = [pos['x'], pos['y']]
filename = "04_rgb_vertica | l_lines"
im = Image.open("../gif_generators/output/"+filename+".gif") #Can be many different formats.
target_size = 400, 400
resize = False
if target_size != im.size:
resize = True
data = []
# To iterate through the entire gif
try:
| frame_num = 0
while True:
im.seek(frame_num)
frame_data = []
# do something to im
img = im.convert('RGB')
if resize == True:
print "Resizing"
img.thumbnail(target_size, Image.ANTIALIAS)
for x, y in ordered_nodes:
frame_data.append(img.getpixel((x, y)))
#print r, g,... |
pziarsolo/bam_crumbs | bam_crumbs/utils/bin.py | Python | gpl-3.0 | 370 | 0 |
import os.path
from crumbs.utils.bin_utils import create_get_binary_path
from ba | m_crumbs.settings import get_setting
BIN_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', 'bin'))
get_binary_path = create_get_binary_path(os.path.split(__file__)[0],
g | et_setting)
|
MirzaBaig715/DjangoURLShortner | urlshortenerapp/admin.py | Python | mit | 114 | 0 | from django.contrib impo | rt adm | in
from .models import Line
# Register your models here.
admin.site.register(Line)
|
DaveBackus/Data_Bootcamp | Code/Lab/fred_CooleyRupert_run.py | Python | mit | 1,002 | 0.001996 | """
Runs peaktrough.py, which generates Cooley-Rupert figures for specified
series from FRED.
Execute peaktrough.py first, then run this program.
Written by Dave Backus under the watchful eye of Chase Coleman and Spencer Lyon
Date: July 10, 2014
"""
# import functions from peaktrough.py. * means all of them
# genera... | ne at a time
manhandle_freddata("GDPC1", saveshow="show")
print("aaaa")
# do plots all at once with map
fred_series = ["GDPC1", "PCECC96", "GPDIC96", "OPHNFB"]
# uses default saveshow parameter
gdpc1, pcecc96, gpdic96, ophnfb = map(manhandle_freddata, fred_series)
print("xxxx")
# lets us change saveshow parameter
gd... | yy")
# skip lhs (this doesn't seem to work, not sure why)
map(lambda s:
manhandle_freddata(s, saveshow="show"), fred_series)
print("zzzz")
|
mittya/duoclub | duoclub/posts/apps.py | Python | mit | 144 | 0 | # -*- coding: utf-8 -*-
from django.apps import AppConfig
class PostsConfig(AppCon | fig):
name = 'posts'
v | erbose_name = '图片列表'
|
PatrickKennedy/pygab | common/mounts.py | Python | bsd-2-clause | 1,656 | 0.006039 | #!/usr/bin/env python
#
# PyGab - Python Jabber Framework
# Copyright (c) 2008, Patrick Kennedy
# 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 r... | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TOR | T (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from common import utils
from core.mounts import *
try:
exec(utils.get_import(
mod=utils.get_module(), from_=['mounts'], import_=['*']))
except ImportError, e:
# If t... |
renzon/appengineepython | backend/appengine/routes/updown/home.py | Python | mit | 1,716 | 0.002914 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.api.app_identity.app_identity import get_default_gcs_bucket_name
from google.appengine.ext.blobstore import blobstore
from blob_app import blob_facade
from config.template_middleware import TemplateResponse
from gaec... | elete_path = router.to_path(delete)
download_path = router.to_path(download)
blob_file_form = blob_facade.blob_file_form()
def localize_blob_file(blob_file):
blob_file_dct = blob_file_form.fill_with_model(blob_file, 64)
blob_file_dct['delete_path'] = router.to_path(delete_path, blob_file_dc... | ownload_path'] = router.to_path(download_path,
blob_file.blob_key,
blob_file_dct['filename'])
return blob_file_dct
localized_blob_files = [localize_blob_file(blob_file) for blob_file in blob_file... |
kiddinn/plaso | tests/containers/init_imports.py | Python | apache-2.0 | 558 | 0.007168 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests that all containers are imported | correctly."""
import unittest
from tests import test_lib
class ContainersImportTest(test_lib.ImportCheckTestCase):
"""Tests that container classes are imported correctly."""
_IGNORABLE_FILES = frozenset(['manager.py', 'interface.py'])
def testContainersImported(self):
"""Tests that all parsers are impor... | '__main__':
unittest.main()
|
50wu/gpdb | gpMgmt/bin/gppylib/operations/test/regress/test_package/test_regress_simple_gppkg.py | Python | apache-2.0 | 1,745 | 0.006304 | #!/usr/bin/env python3
import unittest
from gppylib.operations.test.regress.test_package import GppkgTestCase, GppkgSpec, BuildGppkg, RPMSpec, BuildRPM, run_command, run_remote_command
class SimpleGppkgTestCase(GppkgTestCase):
"""Covers simple build/install/remove/update test cases"""
def test00_sim | ple_build(self):
self.build(self.alpha_spec, self.A_spec)
def test01_simple_install(self):
gppkg_file = self.alpha_spec.get_filename()
self.install(gppkg_file)
#Check RPM database
| self.check_rpm_install(self.A_spec.get_package_name())
def test02_simple_update(self):
gppkg_file = self.alpha_spec.get_filename()
self.install(gppkg_file)
update_rpm_spec = RPMSpec("A", "1", "2")
update_gppkg_spec = GppkgSpec("alpha", "1.1")
update_gppkg_file = self... |
apple/swift-lldb | packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVector.py | Python | apache-2.0 | 1,822 | 0.001098 | """
Test basic std::vector functionality but with a declaration from
the debug info (the Foo struct) as content.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestDbgInfoContentVector(TestBase):
mydir = TestBase.compute_mydir(__file__)... | .back().a", substrs=['(int) $3 = 2'])
self.expect("expr std::reverse(a.begin(), a.end())")
self.expect("expr (int)a.front().a", substrs=['(int) $4 = 2'])
self.expect("expr (int)(a.begin()->a)", substrs=['(int) $5 = 2'])
self.expect("expr (int)(a.rbegin()->a)", substrs=['(int) $6 = 3'])... | self.expect("expr (int)a.back().a", substrs=['(int) $7 = 1'])
self.expect("expr (size_t)a.size()", substrs=['(size_t) $8 = 2'])
self.expect("expr (int)a.at(0).a", substrs=['(int) $9 = 2'])
self.expect("expr a.push_back({4})")
self.expect("expr (int)a.back().a", substrs=['(int) $10... |
NaturalHistoryMuseum/inselect | setup.py | Python | bsd-3-clause | 7,651 | 0.001699 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-lea... | heet
(project_root.joinpath('inselect/gui/inselect.qss'), 'inselect.qss'),
] + [
# DLLs that are not detected because they are loaded by ctypes
(dep._name, Path(dep._name).name)
for dep in pylibdmtx.EXTERNAL_DEPENDENCIES + pyzbar.EXTERNAL_DEPENDENCIES
] + _qt_files(site_packages)... | , str(dest)) for source, dest in include_files]
# Directories as strings
include_files += [
# Fixes scipy freeze
# http://stackoverflow.com/a/32822431/1773758
str(Path(scipy.__file__).parent),
]
# Packages to exclude.
exclude_packages = [
str(p.relative_to(site_pack... |
17zuoye/luigi | test/parameter_test.py | Python | apache-2.0 | 25,868 | 0.002203 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
class Baz(luigi.Task):
bool = luigi.BoolParameter()
def run(self):
Baz._val = self.bool
class ForgotParam(luigi.Task):
param = luigi.Parameter()
def run(self):
pass
class ForgotParamDep(luigi.Task):
def requ | ires(self):
return ForgotParam()
def run(self):
pass
class HasGlobalParam(luigi.Task):
x = luigi.Parameter()
global_param = luigi.IntParameter(is_global=True, default=123) # global parameters need default values
global_bool_param = luigi.BoolParameter(is_global=True, default=False)
... |
pmghalvorsen/gramps_branch | gramps/plugins/lib/maps/dummylayer.py | Python | gpl-2.0 | 2,350 | 0.005106 | # -*- python -*-
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011-2012 Serge Noiraud
#
# 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; eithe... | ry import GObject
#------------------------------------------------------------------------
#
# Set up logging
#
#------------------------------------------------------------------------
import logging
_LOG = logging.getLogger("maps.dummylayer")
#---------------------------------------- | ---------------------------------
#
# Gramps Modules
#
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#
# osmGpsMap
#
#-------------------------------------------------------------------------
try:
from gi.repos... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/utils/functional.py | Python | bsd-3-clause | 11,110 | 0.00144 | import copy
import operator
from functools import wraps, update_wrapper
# You can't trivially replace this `functools.partial` because this binds to
# classes and returns bound instances, whereas functools.partial (on CPython)
# is a type and its instances don't bind.
def curry(_curried_func, *args, **kwargs):
de... | **dict(kwargs, **morekwargs))
return _curried
def memoize(func, cache, num_args):
"""
Wrap a function so that r | esults for any argument tuple are stored in
'cache'. Note that the args to the function must be usable as dictionary
keys.
Only the first num_args are considered when creating the key.
"""
@wraps(func)
def wrapper(*args):
mem_args = args[:num_args]
if mem_args in cache:
... |
kaplun/Invenio-OpenAIRE | modules/webcomment/lib/webcomment_templates.py | Python | gpl-2.0 | 109,494 | 0.006694 | # -*- coding: utf-8 -*-
## Comments and reviews for records.
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 Softwar... | nickname, display) = get_user_info(comment[c_user_id])
messaging_link = self.create_messaging_link(nickname, displa | y, ln)
comment_rows += """
<tr>
<td>"""
report_link = '%s/record/%s/comments/report?ln=%s&comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id])
reply_link = '%s/record/%s/comments/add?ln=%s&comid=%s&action=REP... |
ridelore/sopel-modules | rep.py | Python | apache-2.0 | 4,834 | 0.008068 | from sopel import module
from sopel.tools import Identifier
import time
import re
TIMEOUT = 36000
@module.rule('^(</?3)\s+([a-zA-Z0-9\[\]\\`_\^\{\|\}-]{1,32})\s*$')
@module.intent('ACTION')
@module.require_chanmsg("You may only modify someone's rep in a channel.")
def heart_cmd(bot, trigger):
luv_h8(... | return # avoid processing commands if people try to be tricky
for (nick, act) in re.findall('(?:([a-zA-Z0-9\[\]\\`_\^\{\|\}-]{1,32})(\+{2}|-{2}))', trigger.raw):
if luv_h8(bot, trigger, nick, 'luv' if act == '++' else 'h8', warn_nonexistent=False):
break
@module.commands('luv', 'h8'... | |
vienin/python-ufo | ufo/notify.py | Python | gpl-2.0 | 8,320 | 0.007452 | # Copyright (C) 2010 Agorabox. All Rights Reserved.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program ... | ("Accepting the follow request from '%s' to '%s'"
% (self.initiator, self.target))
user.accept_following(self.initiator)
@action(_("Refuse"))
def refuse_invitation(self):
self.debug("Refusing the follow request from '%s' to '%s'"
% (self.initiator, | self.target))
user.refuse_following(self.initiator)
@action(_("Block user"))
def block_invitation(self):
self.debug("Blocking the follow request from '%s' to '%s'"
% (self.initiator, self.target))
user.block_user(self.initiator)
class AcceptedFriendshipNotificatio... |
thisisshi/cloud-custodian | tools/c7n_mailer/c7n_mailer/utils.py | Python | apache-2.0 | 16,298 | 0.000675 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import base64
from datetime import datetime, timedelta
import functools
import json
import os
import time
import yaml
import jinja2
import jmespath
from dateutil import parser
from dateutil.tz import gettz, tzutc
try:
from botocore.exc... | _resource_tag_value'] = get_resource_tag_value
env.globals['search'] = jmespath.search
env.loader = jinja2.FileSystemLoader(template_folders)
return env
def get_rendered_jinja(
target, sqs_message, resources, logger,
specified_template, default_template, template_folders):
env = get_ji... | fied_template, default_template)
if not os.path.isabs(mail_template):
mail_template = '%s.j2' % mail_template
try:
template = env.get_template(mail_template)
except Exception as error_msg:
logger.error("Invalid template reference %s\n%s" % (mail_template, error_msg))
return
... |
imvu/bluesteel | app/logic/logger/migrations/0002_auto_20191123_1904.py | Python | mit | 679 | 0.001473 | # -*- coding: utf-8 | -*-
# Generated by Django 1.11.3 on 2019-11-24 03:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='logen... | nfo'), (2, 'Warning'), (3, 'Error'), (4, 'Critical')], default=1),
),
migrations.AlterField(
model_name='logentry',
name='message',
field=models.TextField(default=''),
),
]
|
RickHutten/paparazzi | sw/tools/px4/px_mkfw.py | Python | gpl-2.0 | 4,811 | 0.017044 | #!/usr/bin/env python
############################################################################
#
# Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | e firmware image")
args = parser.parse_args()
# Fetch the firmware descriptor prototype if specified
if args.prototype != None:
f = open(args.prototype,"r")
desc = json.load(f)
f.close()
else:
desc = mkdesc()
desc['build_ | time'] = int(time.time())
if args.board_id != None:
desc['board_id'] = int(args.board_id)
if args.board_revision != None:
desc['board_revision'] = int(args.board_revision)
if args.version != None:
desc['version'] = str(args.version)
if args.summary != None:
desc['summary'] = str(args.summary)
if args.descripti... |
zalando/turnstile | tests/checks/test_specification_check.py | Python | apache-2.0 | 1,332 | 0.00301 | # -*- coding: utf-8 -*-
import pytest
import turnstile.models.message as message
from turnstile.checks import CheckIgnore
from turnstile.checks.commit_msg.specification import check
d | ef test_check():
commit_1 = message.CommitMessage('something', 'https://github.com/jmcs/turnstile/issues/42 m€sságe')
result_1 = check(None, {}, commit_1)
assert result_1.successful
assert result_1.details == []
commit_2 = message.CommitMessage('something', 'invalid-1')
result_2 = check(None, {... | tion.']
# Merge messages are ignored
with pytest.raises(CheckIgnore):
commit_3 = message.CommitMessage('something', 'Merge stuff')
check(None, {}, commit_3)
commit_4 = message.CommitMessage('something', 'ftp://example.com/spec')
result_4 = check(None, {'specification': {'allowed_scheme... |
ehabkost/virt-test | qemu/tests/timedrift.py | Python | gpl-2.0 | 7,552 | 0.001457 | import logging, time, commands
from autotest.client.shared import error
from virttest import utils_test, aexpect
def run_timedrift(test, params, env):
"""
Time drift test (mainly for Windows guests):
1) Log into a guest.
2) Take a time reading from the guest and host.
3) Run load on the guest and... | imeout)
# Collect test parameters:
# Command to run to get the current time
time_command = params.get("time_command")
# Filter which should match a string to be passed to time.strptime()
time_filter_re = params.get("time_filter_re")
# Time format for time.strptime()
time_format = params.get... | op_command = params.get("guest_load_stop_command")
host_load_command = params.get("host_load_command")
guest_load_instances = int(params.get("guest_load_instances", "1"))
host_load_instances = int(params.get("host_load_instances", "0"))
# CPU affinity mask for taskset
cpu_mask = params.get("cpu_mask... |
eirki/script.service.koalahbonordic | tests/mock_constants.py | Python | mit | 370 | 0.002703 | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, absolute_import, division)
i | mport os as os_module
import xbmc
from lib.constants import *
userdatafolder = os_module.path.join(xbmc.translatePath("special://profile").decode("utf-8"), "a | ddon_data", addonid, "test data")
libpath = os_module.path.join(userdatafolder, "Library")
|
TwoUnderscorez/KalutServer | KalutServer/RESTfulAPI/SSLbottle.py | Python | apache-2.0 | 772 | 0.002591 | from mybottle import Bottle, run, ServerAdapter, get, post, request
import KalutServer.conf as myconf
class SSLWSGIRefServer(ServerAdapter):
def run(self, handler, quiet=False):
from wsgiref.simple_ser | ver import make_server, WSGIRequestHandler
import ssl
if quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw): pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options) |
srv.socket = ssl.wrap_socket (
srv.socket,
certfile=myconf.certfile, # path to chain file
keyfile=myconf.keyfile, # path to RSA private key
server_side=True)
srv.serve_forever()
|
rickyrish/rickyblog | publicaciones/urls.py | Python | gpl-2.0 | 234 | 0.012821 | from | django.conf.urls import patterns, url
from publicaciones import views
urlpatterns = patterns('',
url(r'^$', views.index | , name='index'),
url(r'^(?P<articulo_titulo>[\W\w]+)/$', views.ver_articulo, name='ver_articulo'),
) |
JeffRoy/mi-dataset | mi/dataset/driver/optaa_dj/cspp/optaa_dj_cspp_telemetered_driver.py | Python | bsd-2-clause | 2,238 | 0.002681 | """
@package mi.dataset.driver.optaa_dj.cspp
@file mi-dataset/mi/dataset/driver/optaa_dj/c | spp/optaa_dj_cspp_telemetered_driver.py
@author Joe Padula
@brief Telemetered driver for the optaa_dj_cspp instrument
Release notes:
Initial Release
"""
__author__ = 'jpadula'
from mi.dataset.dataset_driver import SimpleDatasetDriver
from mi.dataset.dataset_parser import | DataSetDriverConfigKeys
from mi.dataset.parser.cspp_base import \
DATA_PARTICLE_CLASS_KEY, \
METADATA_PARTICLE_CLASS_KEY
from mi.dataset.parser.optaa_dj_cspp import \
OptaaDjCsppParser, \
OptaaDjCsppMetadataTelemeteredDataParticle, \
OptaaDjCsppInstrumentTelemeteredDataParticle
from mi.core.versioni... |
hamiltonkibbe/PyAbleton | pyableton/__init__.py | Python | mit | 1,356 | 0.00885 | #!/usr/bin/env python
#
# Copyright (c) 2014 Hamilton Kibbe <ham@hamiltonkib.be>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation ... | it persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR... | TICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
""" ... |
VimanyuAgg/Have_a_seat | dbanalytics tester.py | Python | apache-2.0 | 1,275 | 0.004706 | from pymongo import MongoClient
import schedule
import time
##############
## This script will be deployed in bluemix with --no-route set to true
########## | ####
con = MongoClient("mongodb://abcd:qwerty@ds111798.mlab.com:11798/have_a_sea | t")
db = con.have_a_seat
cursor = db.Bookings.find()
#Bookings is {customerName:"", customerEmail: "", customerPhone: "", Slot: ""}
dict = {}
db.Exploration.delete_many({})
db.Exploitation.delete_many({})
for i in range(4): # Finding for all slots
for c in cursor:
if c['Slot'] == i and c['customerEmail... |
floppp/programming_challenges | project_euler/051-100/97.py | Python | mit | 29 | 0 | print 284 | 33 * 2* | *7830457 + 1
|
j4n7/record-q | qualitative_variation.py | Python | gpl-3.0 | 1,382 | 0.003618 | from collections import Counter
def unalk_coeff(l):
'''Source: https://ww2.amstat.org/publications/jse/v15n2/kader.html'''
n = len(l)
freq = Counter(l)
freqsum = 0
for key, freq in freq.items():
p = freq / n
freqsum += p**2
unalk_coeff = 1 - freqsum
return unalk_coeff
def... | (['A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', ' | B'])) |
hexlism/css_platform | sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/geoa/typefmt.py | Python | apache-2.0 | 988 | 0.004049 | from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS
import json
from jinja2 import Markup
from wtforms.widgets import html_params
from geoalchemy2.shape import to_shape
from geoalchemy2.elements import WKBElement
from sqlalchemy import func
from flask import current_ap | p
def geom_formatter(view, value):
params = html_params(**{
"data-role": "leafle | t",
"disabled": "disabled",
"data-width": 100,
"data-height": 70,
"data-geometry-type": to_shape(value).geom_type,
"data-zoom": 15,
})
if value.srid is -1:
geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value))
else:
... |
fergalmoran/Chrome2Kindle | server/reportlab/graphics/renderSVG.py | Python | mit | 30,282 | 0.009412 | __doc__="""An experimental SVG renderer for the ReportLab graphics framework.
This will create SVG code from the ReportLab Graphics API (RLG).
To read existing SVG code and convert it into ReportLab graphics
objects download the svglib module here:
http://python.net/~gherman/#svglib
"""
import math, types, sys, os... | , attr in attrDict.items():
sattr = str(attr)
if not node:
newNode.setAttribute(newAttr, sattr)
else:
attrVal = node.getAttribute(sattr)
newNode.setAttribute(newAttr, attrVal or sattr)
return newNode
### classes ###
class SVGCanvas:
def __init__(sel... | # self.height = size[1]
self.code = []
self.style = {}
self.path = ''
self._strokeColor = self._fillColor = self._lineWidth = \
self._font = self._fontSize = self._lineCap = \
self._lineJoin = self._color = None
implementation = getDOMImplementation('m... |
sirk390/coinpy | coinpy-lib/src/coinpy/lib/serialization/structures/s11n_varint.py | Python | lgpl-3.0 | 1,579 | 0.005066 | import struct
from coinpy.lib.serialization.common.serializer import Serializer
from coinpy.lib.serialization.exceptions import Mi | ssingDataException |
class VarintSerializer(Serializer):
def __init__(self, desc=""):
self.desc = desc
def serialize(self, value):
if (value < 0xfd):
return (struct.pack("<B", value))
if (value <= 0xffff):
return ("\xfd" + struct.pack("<H", value))
if (value <= 0xffffff... |
MSFTOSSMgmt/WPSDSCLinux | Providers/Scripts/2.4x-2.5x/Scripts/nxOMSAgentNPMConfig.py | Python | mit | 15,607 | 0.006023 | #!/usr/bin/env python
# ===================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# See license.txt for license information.
# ===================================
import socket
import os
import sys
import imp
import md5
import sha
import codecs
import base64
import platform
import... | ConfigID = ''
if Contents is not None:
Contents = base64.b64decode(Contents)#Contents.encode('ascii', 'ignore')
else:
Contents = ''
if Ensure is not None and Ensure != '':
Ensure = Ensure.encode('ascii', 'ignore')
else:
Ensure = 'Present'
if ContentChecksum is not No... | ontentChecksum
def Set_Marshall(ConfigType, ConfigID, Contents, Ensure, ContentChecksum):
recvdContentChecksum = md5.md5(Contents).hexdigest().upper()
if recvdContentChecksum != ContentChecksum:
LOG_ACTION.log(LogType.Info, 'Content received did not match checksum with md5, trying with sha1')
... |
nisavid/spruce-project | doc/conf.tmpl.py | Python | lgpl-3.0 | 11,930 | 0.006287 | # -*- coding: utf-8 -*-
"""API documentation build configuration file.
This file is :func:`execfile`\\ d with the current directory set to its
containing dir.
Note that not all possible configuration values are present in this
autogenerated file.
All configuration values have a default; values that are commented ou... | Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the proje | ct.
project = u''
author = u''
copyright = u'{} {}'.format(_date.today().year, author)
description = u''
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ''
... |
honor6-dev/android_kernel_huawei_h60 | drivers/vendor/hisi/build/scripts/obj_cmp_tools/vxworks_dassemble.py | Python | gpl-2.0 | 348 | 0.022989 | import os
import sys
import string
filenames = os.listdir(os.getcwd())
for file in filenames:
if os.path.splitext(file)[1] == ".o" or os.path.splitex | t(file)[1] == ".elf" :
print "objdumparm.exe -D "+file
os.system("C:/WindRiver/gnu/4.1.2-vxworks-6.8/x | 86-win32/bin/objdumparm.exe -D "+file +" > " +file + ".txt")
os.system("pause")
|
drunken-pypers/cloudlynt | cloudlynt/wsgi.py | Python | mit | 1,140 | 0.000877 | """
WSGI config for cloudlynt project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
os.environ.setdefault("DJANGO_S | ETTINGS_MODULE", "cloudlynt.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middl... |
andrewgailey/robogen | robogen/rgkit/backup bots/stupid272.py | Python | unlicense | 6,333 | 0.011211 | # stupid 2.7.2 by peterm, patch by Smack
# http://robotgame.org/viewrobot/5715
import random
import math
import rg
def around(l):
return rg.locs_around(l)
def around2(l):
return [(l[0]+2, l[1]), (l[0]+1, l[1]+1), | (l[0], l[1]+2), (l[0]-1, l[1]+1),
(l[0]-2, l[1]), (l[0]-1, l[1]-1), (l[0], l[1]-2), (l[0]+1, l[1]-1)]
def diag(l1, l2):
if rg.wdist(l1, | l2) == 2:
if abs(l1[0] - l2[0]) == 1:
return True
return False
def infront(l1, l2):
if rg.wdist(l1, l2) == 2:
if diag(l1, l2):
return False
else:
return True
return False
def mid(l1, l2):
return (int((l1[0]+l2[0]) / 2), int((l1[1]+l2... |
charles-g-young/Table2NetCDF | gov/noaa/gmd/table_2_netcdf/TableDataDesc.py | Python | apache-2.0 | 11,062 | 0.013741 | '''
Given an XML file that describes a text file containing a header and a table, parse
the XML into it's descriptive elements.
Created on Feb 27, 2017
@author: cyoung
'''
import xml.etree.ElementTree as ElementTree
from gov.noaa.gmd.table_2_netcdf.Util import Util
class TableDataDesc:
#XML elem... | other.columnName:
return False
if self.index != other.index:
return False
if self.dataType != other.dataType:
return False
return True
class GlobalAttributeDesc:
d | ef __init__ (self, attributeName, attributeType, globalAttributeStrategyDesc):
self.attributeName=attributeName
self.attributeType=attributeType
self.globalAttributeStrategyDesc=globalAttributeStrategyDesc
def getAttributeName(self):
return self.attributeName
def getAttrib... |
sedders123/phial | phial/errors.py | Python | mit | 286 | 0 | """phial's custom errors."""
class ArgumentValidationError(Exception):
"""Exception indicating ar | gument validation has failed."""
pass
class ArgumentTypeValidationError(ArgumentValidationError):
"""Exce | ption indicating argument type validation has failed."""
pass
|
citrix-openstack/build-python-troveclient | troveclient/flavors.py | Python | apache-2.0 | 1,700 | 0 | # Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | a specific flavor.
:rtype: :class:`Flavor`
"""
return self._get( | "/flavors/%s" % base.getid(flavor),
"flavor")
|
bx5974/desktop-mirror | lib/advanced.py | Python | apache-2.0 | 35,589 | 0.001264 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import wx
import wx.lib.newevent
from threading import Thread, Lock
import signal
import logging
from argparse import ArgumentParser, SUPPRESS
from ConfigParser import ConfigParser
from subprocess import Popen
import subprocess as sb
# CoreEventHandler... | - {}:{}'.format(t['host'],
| t['ip'],
t['port']))
widget.SetClientData(widget.GetCount() - 1, t)
# After appending, widget value will be cleared
widget.SetValue(val)
def OnSelection(self, data):
self._input['x'].SetValue(str(data[0]))
... |
miracle2k/stgit | stgit/stack.py | Python | gpl-2.0 | 40,808 | 0.007131 | """Basic quilt-like functionality
"""
__copyright__ = """
Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is d... | lambda t: t == (__patch_ | prefix + '\n')
lines = [l for l in lines if patch_filter(l, until_test, __comment_prefix)]
# remove empty lines at the end
while len(lines) != 0 and lines[-1] == '\n':
del lines[-1]
f.seek(0); f.truncate()
f.writelines(lines)
# TODO: move this out of the stgit.stack module, it is really f... |
tensorflow/tensorflow | tensorflow/python/training/session_manager.py | Python | apache-2.0 | 23,320 | 0.004417 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | nit_op: An `Operation` run immediately after session creation.
Usually used to initialize tables and local variables.
ready_op: An `Operation` to check if the model is initialize | d.
ready_for_local_init_op: An `Operation` to check if the model is ready
to run local_init_op.
graph: The `Graph` that the model will use.
recovery_wait_secs: Seconds between checks for the model to be ready.
local_init_run_options: RunOptions to be passed to session.run when
e... |
freerangerouting/frr | tests/topotests/bgp_multi_vrf_topo1/test_bgp_multi_vrf_topo1.py | Python | gpl-2.0 | 229,521 | 0.00132 | #!/usr/bin/env python
#
# Copyright (c) 2020 by VMware, Inc. ("VMware")
# Used Copyright (c) 2018 by Network Device Education Foundation,
# Inc. ("NetDEF") in this file.
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the abo... | tise same set of prefixes from different VRFs
and verify on remote router that these prefixes are not
leaking to each other
FUNC_7:
Redistribute Static routes and verify on remote routers
that routes are advertised within specific VRF instance, which
those static routes belong to.
FUNC_8:
Test e... | mmunication between
iBGP peers.
FUNC_11:
Verify intra-vrf and inter-vrf communication
between eBGP peers.
FUNC_12_a:
Configure route-maps within a VRF, to alter BGP attributes.
Verify that route-map doesn't affect any other VRF instances'
routing on DUT.
FUNC_12_b:
Configure route-maps withi... |
gameduell/duell | pylib/click/core.py | Python | bsd-2-clause | 68,206 | 0.000088 | import os
import sys
import codecs
from contextlib import contextmanager
from itertools import repeat
from functools import update_wrapper
from .types import convert_type, IntRange, BOOL
from .utils import make_str, make_default_short_help, echo
from .exceptions import ClickException, UsageError, BadParameter, Abort, ... | hould be processed.
| """
def sort_key(item):
try:
idx = invocation_order.index(item)
except ValueError:
idx = float('inf')
return (not item.is_eager, idx)
return sorted(declaration_order, key=sort_key)
class Context(object):
"""The context is a special internal object that ... |
openstack/sahara | sahara/service/edp/oozie/engine.py | Python | apache-2.0 | 19,118 | 0 | # Copyright (c) 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | n)
def _prepare_run_job(self, job_execution):
ctx = context.ctx()
# This will be a dictionary of tuples, (native_url, runtime_url)
# keyed by data_source id
data_source_urls = {}
prepared_job_params = {}
job = conductor.job_get(ctx, job_execution.job_id)
... | b_execution, job, data_source_urls, self.cluster)
# Updated_job_configs will be a copy of job_execution.job_configs with
# any name or uuid references to data_sources resolved to paths
# assuming substitution is enabled.
# If substitution is not enabled then updated_job_configs will
... |
Lvl4Sword/Acedia | setup.py | Python | agpl-3.0 | 1,191 | 0.005877 | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt'), encoding='utf-8') as f:
CHANGES = f.read()
setup(
name='sloth',
v... | keywords
#keywor | ds='',
install_requires = ['python-dateutil', 'arrow'],
classifiers = [
"License :: OSI Approved :: GNU Affero General Public License v3"
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX :: Linux",
"Programming... |
marcoapintoo/Biosignal-Intermediate-Format | biosignalformat/test.py | Python | apache-2.0 | 5,325 | 0.005446 | #!/usr/bin/python
import unittest
from biosignalformat import *
class TestBaseObjects(unittest.TestCase):
def test_MinimalExperiment(self):
provider = XArchiveProvider("experiment001.7z")
#provider = ZipArchiveProvider("experiment001.zip")
experiment = Experiment({
"name": "Exp!... | leEDFAs | cii.bif.zip"))
importer.convert()
def atest_multiple_edf(self):
from biosignalformat.external import base_converter
importer = base_converter.EDFImporter("ExampleEDF.edf", XZipArchiveProvider("ExampleMultipleEDFAscii.bif.7z"))
#importer = base_converter.EDFImporter("ExampleEDF.edf",... |
szykin/django-mock-queries | tests/test_utils.py | Python | mit | 11,117 | 0.001889 | from datetime import date, datetime
from mock import patch, MagicMock
from unittest import TestCase
from django_mock_queries import utils, constants
class TestUtils(TestCase):
def test_merge_concatenates_lists(self):
l1 = [1, 2, 3]
l2 = [4, 5, 6]
result = utils.merge(l1, l2)
for x... | j = MagicMock(foo='test')
value, comparison = utils.get_attribute(obj, 'foo')
assert value == 'test'
assert comparison is None
def test_get_attribute_returns_value_with_defined_comparison(self):
obj = MagicMock(foo='test')
value, comparison = utils.get_attribute(obj, 'foo__'... | T
def test_get_attribute_returns_none_with_isnull_comparison(self):
obj = MagicMock(foo=None)
value, comparison = utils.get_attribute(obj, 'foo__' + constants.COMPARISON_ISNULL)
assert value is None
assert comparison == constants.COMPARISON_ISNULL, comparison
def test_get_attri... |
codebhendi/alfred-bot | speaker.py | Python | mit | 490 | 0.004082 | import talkey
from gtts import gTTS
import vlc
import time
import wave
import contextlib
class Speaker:
def __init__(self):
self.engine =talkey.Talkey()
def say(self, text_to_say):
self.engine.say(text_to_say)
def google_say(self, text_to_say, fname="1.mp3"):
| tts = gTTS(text=text_to_say, lang="en")
tts.save(fname)
self.player = v | lc.MediaPlayer(fname)
self.player.play()
self.player.stop()
os.remove(fname)
|
larsks/cloud-init | tests/cloud_tests/testcases/modules/ssh_keys_generate.py | Python | gpl-3.0 | 1,674 | 0 | # This file is part of cloud-init. See LICENSE file for license information.
"""cloud-init Integration Test Verify Script."""
from tests.cloud_tests.testcases import base
class TestSshKeysGenerate(base.CloudTestCase):
"""Test ssh keys module."""
# TODO: Check cloud-init-output for the correct keys being gen... | """Test dsa public key not generated."""
out = self.get_data_file('dsa_public')
self.assertEqual('', out)
def test_dsa_private(self):
"""Test dsa private key not generated."""
out = self.get_data_file('dsa_private')
self.assertEqual('', out)
def test_rsa_public(self):
... | l('', out)
def test_rsa_private(self):
"""Test rsa public key not generated."""
out = self.get_data_file('rsa_private')
self.assertEqual('', out)
def test_ecdsa_public(self):
"""Test ecdsa public key generated."""
out = self.get_data_file('ecdsa_public')
self.as... |
texas/tx_tecreports | tx_tecreports/migrations/0007_auto__add_field_contributor_zipcode_short.py | Python | apache-2.0 | 13,870 | 0.007354 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Contributor.zipcode_short'
db.add_column(u'tx_tecreports_... | tionalMaxCharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}),
'title': ('tx_tecreports.fields.OptionalMaxCharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}),
'type_of': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'contributors'", '... | 'zipcode_short': ('django.db.models.fields.CharField', [], {'max_length': '5', 'null': 'True'})
},
u'tx_tecreports.contributortype': {
'Meta': {'object_name': 'ContributorType'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': (... |
lnielsen/invenio | invenio/modules/documentation/__init__.py | Python | gpl-2.0 | 834 | 0.015588 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2014 CERN.
##
## Invenio 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 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS ... |
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Integrate Sphinx documentation pages."""
|
frhumanes/consulting | web/src/stadistic/__init__.py | Python | apache-2.0 | 1,076 | 0.001859 | class StadisticRouter(object):
"""A router to control all database operations on models in
the stadistic application"""
def db_for_read(self, model | , **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'stadistic':
return 'nonrel'
return 'default'
def db_for_write(self, model, **hints):
"Point all operations on stadistic models to 'other'"
if model._meta.app_label == 'stad... | j1, obj2, **hints):
"Deny any relation if a model in stadistic is involved"
if obj1._meta.app_label == 'stadistic' or obj2._meta.app_label == 'stadistic':
return True
return True
def allow_syncdb(self, db, model):
"Make sure the stadistic app only appears on the 'nonrel'... |
benbox69/pyload | module/plugins/hooks/ExtractArchive.py | Python | gpl-3.0 | 21,976 | 0.008282 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import traceback
# monkey patch bug in python 2.6 and lower
# http://bugs.python.org/issue6122 , http://bugs.python.org/issue1236 , http://bugs.python.org/issue1731717
if sys.version_info < (2, 7) and os.name != "nt":
import errno... | ads_processed",
'packageDeleted' : "package_deleted" | }
self.queue = ArchiveQueue(self, "Queue")
self.failed = ArchiveQueue(self, "Failed")
self.interval = 60
self.extracting = False
self.last_package = False
self.extractors = []
self.passwords = []
self.repair = False
def activate(self... |
samhoo/askbot-realworld | askbot/migrations/0031_synchronize_badge_slug_with_name.py | Python | gpl-3.0 | 26,451 | 0.008468 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
def deslugify(text):
in_bits = text.split('-')
out_bits = list()
for bit in in_bits:
out_bit = bit[0].upper() + bit[1:]
out_bits.append(out_bit)
return ' '.join(out_... | , {'related_name': "'answers'", 'to': "orm['askbot.Questi | on']"}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'vote_down_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'vote_up_count': ('django.db.models.fi... |
nicolewu/cerbero | cerbero/utils/svn.py | Python | lgpl-2.1 | 1,732 | 0.000577 | # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation... | ut a url to a given destination
@param url: url t | o checkout
@type url: string
@param dest: path where to do the checkout
@type url: string
'''
shell.call('svn co %s %s' % (url, dest))
def update(repo, revision='HEAD'):
'''
Update a repositry to a given revision
@param repo: repository path
@type revision: str
@... |
cloudify-cosmo/softlayer-python | SoftLayer/CLI/virt/create.py | Python | mit | 10,420 | 0 | """Manage, delete, order compute instances."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer.CLI import template
from SoftLayer.CLI import v... | in': like_details['domain'],
'cp | u': like_details['maxCpu'],
'memory': like_details['maxMemory'],
'hourly': like_details['hourlyBillingFlag'],
'datacenter': like_details['datacenter']['name'],
'network': like_details['networkComponents'][0]['maxSpeed'],
'user-data': like_details['userData'] o... |
JoeJasinski/evesch | evesch/core/feed/views.py | Python | gpl-2.0 | 8,264 | 0.0144 | from icalendar import Calendar, vCalAddress, vText
import icalendar
from datetime import timedelta
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.core.exceptions import Objec... | 'home'))
if not user_feed_hash == current_user.user_feed_hash:
return HttpResponseRedirect(reverse('euser_user_view', kwargs={'username':current_user.username}))
|
user_events = Event.objects.filter(attendee__in=current_user.attendee_set.all()).order_by('-event_date')
orgfeed = feedgenerator.Rss201rev2Feed(title=current_user.username,
link="http://%s%s" % (host, reverse('euser_user_view', kwargs={'username':current_user.username})) ,
... |
looooo/pivy | scons/scons-local-1.2.0.d20090919/SCons/Tool/sgiar.py | Python | isc | 2,570 | 0.006226 | """SCons.Tool.sgiar
Tool-specific initialization for SGI ar (library archive). If CC
exists, static libraries should be built with it, so the prelinker has
a chance to resolve C++ template instantiations.
There norm | ally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a c... | his software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do s... |
docker-tow/tow | tests/dockerfile_tests.py | Python | apache-2.0 | 4,097 | 0.004882 | import unittest
from tow.dockerfile import Dockerfile
class DockerfileTest(unittest.TestCase):
def test_parse_spaced_envs(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ["ENV test 1"]
envs = d.envs()
self.assertEqual(envs, {"test": "1"})
def test_parse_many_e... | copy_after_maintainer(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ["FROM ubuntu", "MAINTAINER test","ENTRY | POINT [/bin/sh]"]
mapping = ("/tets1", "/test2")
d.add_copy([mapping])
self.assertListEqual(d._Dockerfile__dockerfile, ["FROM ubuntu",
"MAINTAINER test",
"# TOW COPY BLOCK FROM MAPPI... |
GlobalBoost/GlobalBoost-Y | test/functional/rpc_rawtransaction.py | Python | mit | 24,022 | 0.008659 | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
- signrawtransacti... | equal(len( | tx.vout), 1)
assert_equal(
bytes_to_hex_str(tx.serialize()),
self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}]),
)
# Two outputs
tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid'... |
CI-WATER/django-tethys_wps | tethys_wps/views.py | Python | bsd-2-clause | 1,115 | 0.000897 | from inspect import getmembers
from django.shortcuts import render
from utilities import get_wps_service_engine, list_wps_service_engines, abstract_is_link
def home(request):
"""
Home page for Tethys WPS tool. Lists all the WPS services that are linked.
"""
wps_services = list_wps_service_engines()
... | """
View that lists the processes for a given service.
"""
wps = get_wps_service_engine(service)
context = {'wps': wps,
'service': service}
return render(request, 'tethys_wps/service.html', context)
def process(request, service, identifier):
"""
View that displays a det... | ntext = {'process': wps_process,
'service': service,
'is_link': abstract_is_link(wps_process)}
return render(request, 'tethys_wps/process.html', context)
|
kiith-sa/QGIS | tests/src/python/test_qgscomposereffects.py | Python | gpl-2.0 | 3,073 | 0.004557 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsComposerEffects.
.. note:: 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 2 of the License, or
(at your option) any later ver | sion.
"""
__author__ = '(C) 2012 by Dr. Horst Düster / Dr. Marco Hugent | obler'
__date__ = '20/08/2012'
__copyright__ = 'Copyright 2012, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import qgis
from PyQt4.QtCore import QFileInfo
from PyQt4.QtXml import QDomDocument
from PyQt4.QtGui import (QPainter, QColor)
fro... |
mikhtonyuk/rxpython | concurrent/futures/cooperative/ensure_exception_handled.py | Python | mit | 3,261 | 0 | import traceback
class EnsureExceptionHandledGuard:
"""Helper for ensuring that Future's exceptions were | handled.
This solves a nasty problem with Futures and Tasks that have an
exception set: if nobody asks for the exception, the exception is
never logged. This violates the Zen of Python: 'Errors should
never pass silently. Unless explicitly silenced.'
However, we don't want to log the exception a... | as
set_exception() is called: if the calling code is written
properly, it will get the exception and handle it properly. But
we *do* want to log it if result() or exception() was never called
-- otherwise developers waste a lot of time wondering why their
buggy code fails silently.
An earlier... |
robertsj/poropy | pyqtgraph/examples/exampleLoaderTemplate.py | Python | mit | 2,302 | 0.002172 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... | , _fromUtf8("1"))
self.exampleTree.header().setVisible(False)
self.v | erticalLayout.addWidget(self.exampleTree)
self.loadBtn = QtGui.QPushButton(self.layoutWidget)
self.loadBtn.setObjectName(_fromUtf8("loadBtn"))
self.verticalLayout.addWidget(self.loadBtn)
self.codeView = QtGui.QTextBrowser(self.splitter)
font = QtGui.QFont()
font.setFamily... |
asleao/sistema-cotacao | project/cotacao/migrations/0004_auto_20170322_0818.py | Python | gpl-3.0 | 665 | 0.001504 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-22 11:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migrati | on):
dependencies = [
('cotacao', '0003_auto_20170312_2049'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='pedido',
),
| migrations.AddField(
model_name='pedido',
name='itens',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='itens', to='cotacao.Item'),
),
]
|
windflyer/apport | apport_python_hook.py | Python | gpl-2.0 | 7,544 | 0.001723 | '''Python sys.excepthook hook to generate apport crash dumps.'''
# Copyright (c) 2006 - 2009 Canonical Ltd.
# Authors: Robert Collins <robert@ubuntu.com>
# Martin Pitt <martin.pitt@ubuntu.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Publ... | sErrorAnalys | is'] += ' %s (%s is %srunning)' % (
service, exe, ('' if running else 'not '))
def install():
'''Install the python apport hook.'''
sys.excepthook = apport_excepthook
|
streema/deployer | deployer/tasks/virtualenv.py | Python | mit | 576 | 0.003472 | from fabric.api import run
from fabric.decorators import with_settings
from fabric.colors import green, yellow
from deployer.tasks.requirements import install_requirements
@with_settings(warn_only=True)
def setup_virtualenv(python_version='', app_name='', app_dir='', repo_url=''):
print(green("Set | ting up virtualenv on {}".format(app_dir)))
print(green('Creating virtualenv'))
if run("pyenv virtualenv {0} {1}-{0}".format(python_version, app_name)).failed:
print(yellow("Virtualenv already exists"))
install_requirements(app_name, python_ver | sion)
|
evereux/flicket | application/flicket/views/release.py | Python | mit | 2,064 | 0.002907 | #! usr/bin/python3
# -*- coding: utf-8 -*-
#
# Flicket - copyright Paul Bourne: evereux@gmail.com
import datetime
from flask import redirect, url_for, flash, g
from flask_babel import gettext
from flask_login import login_required
from . import flicket_bp
from application import app, db
from application.flicket.mode... | release/<int:ticket_id>/', methods=['GET', 'POST'])
@login_required
def release(ticket_id=False):
if ticket_id:
ticket = FlicketTicket.query.filter_by(id=ticket_id).first()
# is ticket assigned.
if not ticket.assigned:
flash(gettext('Ticket has not been assigned'), category='w... | ket is owned by user or user is admin
if (ticket.assigned.id != g.user.id) and (not g.user.is_admin):
flash(gettext('You can not release a ticket you are not working on.'), category='warning')
return redirect(url_for('flicket_bp.ticket_view', ticket_id=ticket_id))
# set status t... |
Azure/azure-sdk-for-python | sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_peering_management_client.py | Python | mit | 6,754 | 0.002813 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: The Azure subscription ID.
:type subscription_id: str
:param str base_url: Service URL
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: Optional[str]... | tion(credential, subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._serialize.client_side_v... |
engineerapart/TheRemoteFreelancer | docs/scripts/download_favicons.py | Python | unlicense | 964 | 0.001037 | #!python3
"""
This script downloads the favicons
Usage:
python3 update_alexa path/to/data.csv
"""
import os
import requests
favicon_path = os.path.join(os.path.dirname(__file__), "..", "icons")
def download_favicons(links):
for link in links:
netloc = link['netloc']
url = 'http://' + netloc... | new_favicon_path = os.path.join(favicon_path, netloc + ".ico")
if not os.path.exists(new_favicon_path):
try:
print(url)
response = requests.get(
"https://realfavicongenerator.p.rapidapi.com/favicon/icon",
params={ | 'platform': 'desktop', "site": url},
headers={'X-Mashape-Key': os.environ.get("mashape_key")}
)
except:
pass
else:
if response:
with open(new_favicon_path, 'wb') as f:
f.write(response... |
rbuffat/pyidf | tests/test_outputcontrolilluminancemapstyle.py | Python | apache-2.0 | 1,023 | 0.002933 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.daylighting import OutputControlIlluminanceMapStyle
log = logging.getLogger(__name__)
class TestOutputControlIlluminanceMapStyle(unittest.TestCase):
def setUp(self):
... | idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(l | ine.strip())
idf2 = IDF(self.path)
self.assertEqual(idf2.outputcontrolilluminancemapstyles[0].column_separator, var_column_separator) |
mtils/ems | ems/qt4/itemmodel/columnsectionmapper.py | Python | mit | 3,948 | 0.008359 | '''
Created on 24.03.2011
@author: michi
'''
from PyQt4.QtGui import QItemDelegate
from sqlalchemy import Table
from sqlalchemy.sql import Alias,Select
from ems import qt4
class ColumnSectionMapper(object):
def __init__(self,alchemySelect=None, parent=None):
self.__columnConfigs = []
self.__colu... | if delegate is not None:
delegate.paint(painter, option, index)
else:
QItemDelegate.paint(self, painter, option, index)
def createEditor(self, p | arent, option, index):
delegate = self.getDelegate(index)
if delegate is not None:
return delegate.createEditor(parent, option, index)
else:
return QItemDelegate.createEditor(self, parent, option,
index)
def setEditorDat... |
citrix-openstack-build/sahara | sahara/tests/unit/service/edp/test_job_manager.py | Python | apache-2.0 | 20,947 | 0 | # Copyright (c) 2013 Mirantis 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 law or agreed to in writ... | somedir", job, libs_subdir=True)
remote_instance.execute_command.assert_called_with(
"mkdir -p /s | omedir/libs")
expected = ["/somedir/" + n for n in main_names]
expected += ["/somedir/libs/" + n for n in lib_names]
self.assertEqual(paths, expected)
for path in paths:
remote_instance.write_file_to.assert_any_call(path, "data")
@mock.patch('sahara.conductor.API.job_bin... |
mokuki082/EggDrop | code/build/bdist.macosx-10.6-intel/python3.4-standalone/app/temp/pygame/font.py | Python | gpl-3.0 | 393 | 0.005089 |
def __load():
import imp, os, sys
ext = 'pygame/font.so'
for path in sys.path:
if not path.endswith('lib-dynl | oad'):
continue
ext_path = os.path.join(path, ext)
if os.path.exists(ext_path):
mod = imp.load_dynamic(__name__, ext_path)
break
else:
raise ImportError(repr( | ext) + " not found")
__load()
del __load
|
cheery/lever | runtime/evaluator/optable.py | Python | mit | 1,719 | 0.001163 | import re
source = [
('assert', 0x00, False, 'vreg'),
('raise', 0x05, False, 'vreg'),
('constant', 0x10, True, 'constant'),
('list', 0x20, True, 'vreg*'),
('move', 0x30, False, 'vreg vreg'),
('call', 0x40, True, 'vreg vreg*'),
('not', 0x41, True, 'vreg'),
('con... | ),
]
enc = {}
dec = {}
names = {}
for opname, | opcode, has_result, form in source:
assert opcode not in dec, opcode
pattern = re.split(r"\s+", form.rstrip('*'))
if form.endswith('*'):
variadic = pattern.pop()
else:
variadic = None
enc[opname] = opcode, has_result, pattern, variadic
dec[opcode] = opname, has_result, pattern, ... |
ScreamingUdder/mantid | Framework/PythonInterface/test/python/mantid/api/SpectrumInfoTest.py | Python | gpl-3.0 | 788 | 0.005076 | from __future__ import (absolute_import, division, print_function)
import unittest
from testhelpers import WorkspaceCreationHelper
class SpectrumInfoTest(unittest.TestCase):
_ws = None
def setUp(self):
if self.__class__._ws is None:
self.__class__._ws = WorkspaceCreationHelper.create2DWo... | rtEquals(info.hasDetectors(1), True)
def test_isMasked(self):
info = self._ws.spectrumInfo()
self.assertEquals(info.isMasked(1), False)
if __ | name__ == '__main__':
unittest.main()
|
TheRedLady/codebook | codebook/profiles/restapi/serializers.py | Python | gpl-3.0 | 4,811 | 0.001663 | from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from ..models import MyUser, Profile
from ..utils import perform_reputation_check
class CreateUserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'}
... | ue)
reputation = serializers.CharField(max_length=8, read_only=True)
follows = FollowSerializer(read_only=True, many=True)
url = serializers.HyperlinkedIdentityField(view_name='profiles:profile-detail')
questions_count = serializers.SerializerMethodField()
answers_count = serializers.Seriali | zerMethodField()
followed_by = serializers.SerializerMethodField()
class Meta:
model = Profile
fields = [
'url',
'user',
'reputation',
'follows',
'questions_count',
'answers_count',
'followed_by'
]
... |
Evidlo/django-notifications | notifications/tests/urls.py | Python | bsd-3-clause | 544 | 0 | # -*- coding: utf-8 -*-
from django.conf.urls import include, url |
from django.contrib import admin
from django.contrib.auth.views import login
import notifications.urls
import notifications.tests.views
urlpatterns = [
url(r'^login/$', login, name='login'), # needed for Django 1.6 tests
url(r'^admin/', include(admin.site.urls)),
url(r'^test_make/', notifications.tests.... | ude(notifications.urls, namespace='notifications')),
]
|
davidxmoody/diary | tests/filler_text.py | Python | mit | 20,162 | 0.002579 | import random
filler_text = '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate vel... | uptate dolore culpa ipsum labore in undefined voluptate cupidatat amet, sed in aliquip dolor tempor dolore in Ut dolor amet, eiusmod cupidatat in aliqua. ullamco incididunt aute Excepteur ad ullamco sit amet, mollit ex officia Duis.
Ex irure labore dolor aute reprehenderit ullamco elit, sit consectetur aliqua. non cons... | ulpa magna do irure aute tempor quis incididunt cupidatat co |
cmgrote/tapiriik | tapiriik/services/fit.py | Python | apache-2.0 | 22,972 | 0.030167 | from datetime import datetime, timedelta
from .interchange import WaypointType, ActivityStatisticUnit, ActivityType, LapIntensity, LapTriggerMethod
from .devices import DeviceIdentifier, DeviceIdentifierType
import struct
import sys
import pytz
class FITFileType:
Activity = 4 # The only one we care about now.
class ... | SessionEnd = 7
FitnessEquipment = 8
class FIT | ActivityType:
GENERIC = 0
RUNNING = 1
CYCLING = 2
TRANSITION = 3
FITNESS_EQUIPMENT = 4
SWIMMING = 5
WALKING = 6
ALL = 254
class FITMessageDataType:
def __init__(self, name, typeField, size, packFormat, invalid, formatter=None):
self.Name = name
self.TypeField = typeField
self.Size = size
self.PackForm... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_10_01/operations/_virtual_network_peerings_operations.py | Python | mit | 22,805 | 0.004955 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | alizer.
"""
models = _models
def __init__(self, client, config, serializer, | deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _delete_initial(
self,
resource_group_name, # type: str
virtual_network_name, # type: str
virtual_network_peering_name, # ... |
josquindebaz/P2Qt | p2gui.py | Python | lgpl-3.0 | 106,057 | 0.009045 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from PySide import QtCore
from PySide import QtGui
from PySide import QtWebKit
import sys
import re
import datetime
import os
import time
import subprocess
import threading
import atexit
import webbrowser
import functools
import operator
import Viewer
import Controller
cla... | changed)
self.NOT2.depI.listw.currentItemChanged.connect(self.cdepI_changed)
self.NOT2.depII.listw.currentItemChanged.connect(self.cdepII_changed)
self.NOT2.depI.deselected.connect(lam | bda: self.NOT2.depII.listw.clear())
self.NOT2.dep0.deselected.connect(lambda: [self.NOT2.depI.listw.clear(),
self.NOT2.depII.listw.clear()])
#TODO add those below
for i in range(7,12):
self.NOT2.sort_command.model().item(i).setEnabled(False)
##### Tab for synta... |
lenn0x/Milo-Tracing-Framework | src/py/examples/helloworld/HelloWorld.py | Python | apache-2.0 | 5,966 | 0.015924 | #
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
from thrift.protocol import fastbinary
exce... | t()
result.success = self._handler.ping(args.name)
oprot.writeMessageBegin("ping", TMessageType.REPLY, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
# HELPER FUNCTIONS AND STRUCTURES
class ping_args:
"""
Attributes:
- name
"""
thrift_spec = (
None, # 0
... | .__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
... |
NitishT/minio-py | minio/error.py | Python | apache-2.0 | 23,884 | 0.003601 | # -*- coding: utf-8 -*-
# Minio Python Library for Amazon S3 Compatible Cloud Storage,
# (C) 2015, 2016, 2017 Minio, 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.ap... | attribute.text
elif attribute.tag == 'Key':
self.object_name = attribute.text
elif attribute.tag == 'Message':
self.message = attribute.text
elif attribute.tag == 'RequestId':
self.request_id = attribute.text
elif attribute.... | _set_amz_headers()
def _set_error_response_without_body(self, bucket_name=None):
"""
Sets all the error response fields from response headers.
"""
if self._response.status == 404:
if bucket_name:
if self.object_name:
self.code = 'NoSuc... |
kobotoolbox/kpi | kobo/settings/testing.py | Python | agpl-3.0 | 664 | 0.001506 | # coding: utf-8
from mongomock import MongoClient as MockMongoClient
from .base import *
# For tests, don't use KoBoCAT's DB
DATABASES = {
'default': dj_database_url.config(default='sqlite:///%s/db.sqlite3' % BASE_DIR),
}
DATABASE_ROUTERS = ['kpi.db_routers.TestingDat | abaseRouter']
TESTING = True
# Decrease prod value to speed-up tests
SUBMISSION_LIST_LIMIT = 100
ENV = 'testing'
# Run all Celery tasks synchronously during testing
CELERY_TASK_ALWAYS_EAGER = True
MONGO_CONNECTION_URL = 'mongodb://fakehost/formhub_te | st'
MONGO_CONNECTION = MockMongoClient(
MONGO_CONNECTION_URL, j=True, tz_aware=True)
MONGO_DB = MONGO_CONNECTION['formhub_test']
|
pklaus/netio230a | setup.py | Python | gpl-3.0 | 1,135 | 0.026432 | # -*- coding: utf-8 -*-
"""
Copyright (c) 2015, Philipp Klaus. All rights reserved.
License: GPLv3
"""
from distutils.core import setup
setup(name='netio230a',
version = '1.1.9',
description = 'Python package to control the Koukaam NETIO-230A',
long_description = 'Python software to access the Kou... | :: Python :: 2',
'Programming L | anguage :: Python :: 3',
]
)
|
SpiNNakerManchester/SpiNNer | spinner/proxy.py | Python | gpl-2.0 | 8,272 | 0.040015 | r"""A proxy enabling multiple wiring guide instances to interact with the same
SpiNNaker boards.
A very simple protocol is used between the client and server. Clients may send
the following new-line delimited commands to the server:
* ``VERSION,[versionstring]\n`` The server will disconnect any client with an
incom... | (or is invalid) the
# connection is dropped.
try:
while b"\n" in data:
line, _, data = data.part | ition(b"\n")
logging.debug("Handling command {} from {}".format(line, sock))
cmd, _, args = line.partition(b",")
# If an unrecognised command arrives, this lookup will fail and get
# caught by the exception handler, printing an error and disconnecting
# the client.
{
b"VERSION": s... |
eeucalyptus/eeDA | app/graphics/textrenderer.py | Python | apache-2.0 | 3,090 | 0.009385 | from . import Renderer
from PIL import Image, ImageFont, ImageQt, ImageDraw
from PyQt5 import QtGui
'''
Renders a single line of text at a given position.
'''
class TextRenderer(Renderer):
MSFACTOR = 8
def __init__(self, gl, text, pos, size = 64):
super().__init__(gl)
self.text = te... | olCallList()
def genSymbolCallList(self):
genList = self.gl.glGenLists(1)
try:
font = ImageFont.truetype('resources/interface/Roboto.ttf', self.fSize * self.MSFACTOR)
except OSError:
print("Font n | ot found, loading failsafe.")
font = ImageFont.truetype('arial.ttf', self.fSize * self.MSFACTOR)
# works on Windows; may still fail on Linux and OSX. Documentation unclear.
textSize = font.getsize(self.text)
border = 5
image = Image.new("RGBA", (textSize[0] + 2*border,... |
NeCTAR-RC/horizon | openstack_dashboard/api/_nova.py | Python | apache-2.0 | 5,498 | 0 | # 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
# d... | ]
else:
try:
image = glance.image_get(self.request, self.image['id'])
self.image['name'] = image.name
return image.name
except (glance_exceptions.ClientException,
horizon_exceptions.ServiceCatalogException):
... | return None
@property
def internal_name(self):
return getattr(self, 'OS-EXT-SRV-ATTR:instance_name', "")
@property
def availability_zone(self):
return getattr(self, 'OS-EXT-AZ:availability_zone', "")
@property
def host_server(self):
return getattr(self, 'OS-EXT... |
RedHatInsights/insights-core | insights/parsers/tests/test_ls_var_cache_pulp.py | Python | apache-2.0 | 1,314 | 0.003805 | import doctest
from insights.parsers import ls_var_cache_pulp
from insights.parsers.ls_var_cache_pulp import LsVarCachePulp
from insights.tests import context_wrap
LS_VAR_CACHE_PULP = """
total 0
drwxrwxr-x. 5 48 1000 216 Jan 21 12:56 .
drwxr-xr-x. 10 0 0 121 Jan 20 13:57 ..
lrwxrwxrwx. 1 0 0 19 Jan 21 12:... | -202.gsslab.pnq2.redhat.com
drwxr-xr-x. 2 48 48 6 Jan 20 14:03 resource_manager@dhcp130-202.gsslab.pnq2.redhat.com
"""
def test_ls_var_cache_pulp():
ls_var_cache_pulp = LsVarCachePulp(context_wrap(LS_VAR_CACHE_PULP, path="insights_commands/ls_-lan_.var.cache.pulp"))
assert ls_var_cache_pulp.files_of('/va... | em['link']
def test_ls_var_lib_mongodb_doc_examples():
env = {
'ls_var_cache_pulp': LsVarCachePulp(context_wrap(LS_VAR_CACHE_PULP, path="insights_commands/ls_-lan_.var.cache.pulp")),
}
failed, total = doctest.testmod(ls_var_cache_pulp, globs=env)
assert failed == 0
|
pcmoritz/ray-1 | python/ray/tune/tests/test_integration_mlflow.py | Python | apache-2.0 | 11,695 | 0 | import os
import unittest
from collections import namedtuple
from unittest.mock import patch
from ray.tune.function_runner import wrap_function
from ray.tune.integration.mlflow import MLflowLoggerCallback, MLflowLogger, \
mlflow_mixin, MLflowTrainableMixin
class MockTrial(
namedtuple("MockTrial",
... | LOW_EXPERIMENT_NAME" in os.environ:
del os.environ["MLFLOW_EXPERIMENT_NAME"]
if "MLFLOW_EXPERIMENT_ID" in os.environ:
del os.environ["MLFLOW | _EXPERIMENT_ID"]
class MLflowTest(unittest.TestCase):
@patch("mlflow.tracking.MlflowClient", MockMlflowClient)
def testMlFlowLoggerCallbackConfig(self):
# Explicitly pass in all args.
logger = MLflowLoggerCallback(
tracking_uri="test1",
registry_uri="test2",
... |
scholer/pptx-downsizer | pptx_downsizer/__main__.py | Python | gpl-3.0 | 170 | 0.005882 |
# __main__.py is used when a package is executed as a module, i.e.: `python -m pptx_downs | izer`
if __name__ == '__main__':
from .pptx_downsizer impor | t cli
cli()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.