prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
"""`Factory of Factories` pattern."""
from dependency_injector import containers, providers
class SqlAlchemyDatabaseService:
def __init__(self, session, base_class):
self.session = session
self.base_class = base_class
class TokensService:
def __init__(self, id_generator, database):
... | ject()
id_generator = object()
class Container(containers.DeclarativeContainer):
database_factory = providers.Factory(
providers.Factory,
SqlAlchemyDatabaseService,
session=session,
)
token_servi | ce = providers.Factory(
TokensService,
id_generator=id_generator,
database=database_factory(base_class=Token),
)
user_service = providers.Factory(
UsersService,
id_generator=id_generator,
database=database_factory(base_class=User),
)
if __name__ == '__main_... |
"""Local Media Source Implementation."""
from __future__ import annotations
import mimetypes
from pathlib import Path
from aiohttp import web
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.media_player.const import MEDIA_CLASS_DIRECTORY
from homeassistant.components.media_p... | web.HTTPNotFound()
media_path = self.source.async_full_path(source_dir_id, location)
# Check that the file exists
if not media_path.is_file():
raise web.HTTPNotFound()
# | Check that it's a media file
mime_type, _ = mimetypes.guess_type(str(media_path))
if not mime_type or mime_type.split("/")[0] not in MEDIA_MIME_TYPES:
raise web.HTTPNotFound()
return web.FileResponse(media_path)
|
import django.dispatch
# Whenever a permission object | is saved, it sends out the signal. This | allows
# models to keep their permissions in sync
permission_changed = django.dispatch.Signal(providing_args=('to_whom', 'to_what')) |
# Copyright 2022 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | _product.setup_cleanup import (
create_bq_dataset,
create_bq_table,
delete_bq_table,
upload_data_to_bq_table,
)
def test_import_products_bq(table_id_prefix):
dataset = "products"
valid_products_table = f"{table_id_prefix}products"
product_schema = "../resources/product_schema.json"
val... | aset, valid_products_table, product_schema)
upload_data_to_bq_table(
dataset, valid_products_table, valid_products_source_file, product_schema
)
output = str(
subprocess.check_output(
f"python import_products_big_query_table.py {dataset} {valid_products_table}",
shel... |
import pytest
from conftest import DeSECAPIV1Client
@pytest.mark.parametrize("init_rrsets", [
{
('www', 'A'): (3600, {'1.2.3.4'}),
('www', 'AAAA'): (3600, {'::1'}),
('one', 'CNAME'): (3600, {'some.example.net.'}) | ,
('other', 'TXT'): (3600, {'"foo" "bar"', '"bar" "foo"'}),
}
])
@pytest.mark.parametrize | ("rrsets", [
{ # create three RRsets
('a' * 63, 'A'): (7000, {'4.3.2.1', '7.6.5.4'}),
('b', 'PTR'): (7000, {'1.foo.bar.com.', '2.bar.foo.net.'}),
('c.' + 'a' * 63, 'MX'): (7000, {'10 mail.something.net.'}),
},
{ # update three RRsets
('www', 'A'): None, # ensure value from... |
'''
t4_adm.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>
This program can be distributed under the terms of the GNU GPLv3.
'''
from __future__ import division, print_function, absolute_import
from s3ql.backends import local
from s3ql.backends.c... | Popen([sys.executable, os.path.join(BA | SEDIR, 'bin', 's3qladm'),
'--quiet', 'passphrase',
self.storage_url ], stdin=subprocess.PIPE)
print(self.passphrase, file=proc.stdin)
print(passphrase_new, file=proc.stdin)
print(passphrase_new, file=proc.stdin)
proc.stdi... |
# -*- coding: utf-8 -*-
from __future__ i | mport unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
def hello_world_view(request):
return HttpResponse("hello world", conten | t_type="text/plain")
|
# -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import contents.models
class Migration(migrations.Migration):
dependencies = [
('contents', '0017_auto_20170329_1504'),
]
operations = [
migrations.AlterField(
model_name='frontpageima... | page_image_path),
),
]
|
# coding: utf-8
#
# This file is part of Progdupeupl.
#
# Progdupeupl is fr | ee software: you | can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Progdupeupl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; withou... |
',
'UCSR1C_UMSEL1': '$C0',
'UCSR1C_UPM1': '$30',
'UCSR1C_USBS1': '$08',
'UCSR1C_UCSZ1': '$06',
'UCSR1C_UCPOL1': '$01',
'UBRR1': '&204',
'SPMCSR': '&87',
'SPMCSR_SPMIE': '$80',
'SPMCSR_RWWSB': '$40',
'SPMCSR_SIGRD': '$20',
'SPMCSR_RWWSRE': '$10',
'SPMCSR_BLBSET': '$08',
'SPMCSR_PGWRT':... | 01',
'UERST': '&234',
'UERST_EPRST': '$7F',
'UENUM': '&233',
'UEINTX': '&232',
'UEINTX_FIFOCON': '$80',
'UEINTX_NAKINI': '$40',
'UEINTX_RWAL': '$20',
'UEINTX_NAKO | UTI': '$10',
'UEINTX_RXSTPI': '$08',
'UEINTX_RXOUTI': '$04',
'UEINTX_STALLEDI': '$02',
'UEINTX_TXINI': '$01',
'UDMFN': '&230',
'UDMFN_FNCERR': '$10',
'UDFNUM': '&228',
'UDADDR': '&227',
'UDADDR_ADDEN': ' |
op is None:
io_loop = IOLoop.current()
request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout,
validate_cert=kwargs.get("validate_cert", True))
request = httpclient._RequestProxy(request, options)
conn = WebSocketClientConnection(io_loop, request)
... | kwargs.get("ssl_options"))
self.bind(port,
kwargs.get("address", ''),
kwargs.get("family", socket.AF_UNSPEC),
kwargs.get("backlog", 128))
self.ws_url = ws_url
self.ws_options = kwargs.get("ws_option... | self.ws_conn = None
self._address_list = []
@property
def address_list(self):
return self._address_list
def handle_stream(self, stream, address):
"""
Handle a new client connection with a proxy over websocket
"""
logger.info("Got connection from %s on %s... |
hon.ops import array_ops
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.training import monitored_session
from tensorflow.python.training import session_run_hook
from tensorflow.python.util import nest
class ModeKeys(object):
"""Standard names for model modes.
The following ... | For `mode == ModeKeys.TRAIN`: required fields are `loss` and `train_op`.
* For `mode == ModeKeys.EVAL`: required field is `loss`.
* For `mode == ModeKeys.PREDICT`: required fie | lds are `predictions`.
model_fn can populate all arguments independent of mode. In this case, some
arguments will be ignored by `Estimator`. E.g. `train_op` will be ignored
in eval and infer modes. Example:
```python
def my_model_fn(mode, features, labels):
predictions = ...
loss = ...... |
import logging
from airflow.contrib.hooks.bigquery_hook import BigQueryHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class BigQueryOperator(BaseOperator):
"""
Executes BigQuery SQL queries in a specific BigQuery database
"""
template_fields = ('bql', 'destinatio... | For this to work, the service account making the request must have domain-wide delegation enabled.
:typ | e delegate_to: string
"""
super(BigQueryOperator, self).__init__(*args, **kwargs)
self.bql = bql
self.destination_dataset_table = destination_dataset_table
self.write_disposition = write_disposition
self.bigquery_conn_id = bigquery_conn_id
self.delegate_to = deleg... |
on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess, time, sys
import json
import datetime
from optparse import OptionParser
SKIP_TEST="-DskipTests... | er(parsed_args.is_server_debug)
if retcode != 0: sys.exit(retcode)
retcode = start_dependant_services()
if retcode != 0: sys.exit(retcode)
if parsed_args.is_install_agent:
retcode = install_ambari_agent()
if retcode != 0: sys.exit(retcode)
retcode = configure_ambari_agent()
if retcode != 0: sys.exit(ret... | if retcode != 0: sys.exit(retcode)
retcode = create_cluster()
if retcode != 0: sys.exit(retcode)
end = datetime.datetime.utcnow()
print ""
print "Duration: " + str((end-start).seconds) + " seconds"
print "Parameters: " + str(sys.argv |
#!/usr/bin/env python
from setuptools import setup, find_packages
with open('pypd/version.py') as version_file:
exec(compile(version_file.read(), version_file.name, 'exec'))
options = {
'name': 'pypd',
'version': _ | _version__,
'packages': find_packages(),
'scripts': [],
'description': 'A python client for PagerDuty API',
'author': 'JD Cumpson',
'author_email': 'jdc@pagerduty.com',
'maintainer_email': 'jdc@pagerduty.com',
'license': 'MIT',
'url': 'https://github.com/PagerDuty/pypd',
'download_ur... | :: Python',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
'install_requires': ['ujson', 'requests'],
'tests_require': [],
'cmdclass': {}
}
setup(**options)
|
import unittest
from autosklearn.pipeline.components.classification.extra_trees import \
ExtraTreesClassifier
from autosklearn.pipeline.util import _test_classifier, \
_test_classifier_iterative_fit, _test_classifier_predict_proba
import numpy as np
import sklearn.metrics
import sklearn.ensemble
class Extra... | _test_classifier(ExtraTreesClassifier, make_binary=True)
self.assertAlmostEqual(1,
sklearn.metrics.accuracy_score(targets,
predictions))
def test_default_configuration_multilabel(self):
... | 060428849902536,
sklearn.metrics.average_precision_score(
targets, predictions))
def test_default_configuration_predict_proba_multilabel(self):
for i in range(10):
predictions, targets = \
_test_classifier... |
ath import exists
from shutil import rmtree
from whoosh import fields, index, qparser, store, writing
class TestIndexing(unittest.TestCase):
def make_index(self, dirname, schema):
if not exists(dirname):
mkdir(dirname)
st = store.FileStorage(dirname)
ix = index.Index(st, schema... | ency("content", u"bravo"), 2) |
self.assertEqual(tr.frequency("content", u"bravo"), 5)
self.assertEqual(tr.doc_frequency("content", u"echo"), 2)
self.assertEqual(tr.frequency("content", u"echo"), 2)
self.assertEqual(tr.doc_frequency("content", u"alfa"), 1)
self.assertEqual(tr.frequency("content", u"alfa"), 1)
... |
from django.conf import settings
from datetime import timedelta
# Endpoint settings
OAI_BASE_URL="http"
if settings.HTTPS == "on":
OAI_BASE_URL="https"
OAI_BASE_URL=OAI_B | ASE_URL+"://"+settings.SITE_NAME
REPOSITORY_NAME = settings.PLATFORM_NAME
ADMIN_EMAIL = settings.TECH_SUPPORT_EMAIL
OAI_ENDPOINT_NAME = 'oai'
RESULTS_LIMIT = 100
RESUMPTION_TOKEN_VALIDITY = timedelta(hours=6)
METADATA_FORMAT = 'oai_dc'
OWN_SET_PREFIX = s | ettings.PLATFORM_NAME
DISABLE_PRINT_OWN_SET_PREFIX= True
RESUMPTION_TOKEN_SALT = 'change_me' # salt used to generate resumption tokens
if hasattr(settings, 'OAI_SETTINGS'):
OAI_ENDPOINT_NAME = settings.OAI_SETTINGS.get('OAI_ENDPOINT_NAME')
RESULTS_LIMIT = settings.OAI_SETTINGS.get('RESULTS_LIMIT') or RESULTS_L... |
from djoser.conf import s | ettings
__all__ = ['settings']
def get_user_email(user):
email_field_name = get_user_email_field_name(user)
return getattr(user, email_field_name, None)
def get_user_email_field_name(user):
re | turn user.get_email_field_name()
|
from tr | ackers import *
| |
# -*- coding: utf-8 -*-
# This file is part of emesene.
#
# emesene 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 version.
#
#... | u.list._on_contact_change_something(*args)
def _on_status_change_succeed(self, stat):
"""
This is called when status is successfully changed
"""
if stat not in status.ALL or stat == -1:
return
self.setIcon(QtGui.QIcon(
gu | i.theme.image_theme.status_icons_panel[stat]))
def hide(self):
self.unsubscribe()
QtGui.QSystemTrayIcon.setVisible(self, False)
def unsubscribe(self):
self.disconnect_signals()
if self.menu:
self.menu.unsubscribe()
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. | 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozi | lla.org/MPL/2.0/.
import datetime
import pytz
def now():
return datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
|
import smbus
from time import sleep
def delay(time):
sleep(time/1000.0)
def delayMicroseconds(time):
sleep(time/1000000.0)
from hd44780 import HD44780
class Screen(HD44780):
"""A driver for MCP23008-based I2C LCD backpacks. The one tested had "WIDE.HK" written on it."""
def __init__(self, bus=1, ad... | lf.setMCPreg(0x0a, data)
data ^= 0x80
delayMicroseconds(1.0)
self.setMCPreg(0x0a, data)
data ^= 0x80
delayMicro | seconds(1.0)
self.setMCPreg(0x0a, data)
delay(1.0)
def setMCPreg(self, reg, val):
"""Sets the MCP23017 register."""
self.bus.write_byte_data(self.addr, reg, val)
if __name__ == "__main__":
screen = Screen(bus=1, addr=0x27, cols=16, rows=2, debug=True, autoscroll=False)... |
# Copyright (c) 2014 Intel Corporation
#
# 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 ... | g as logging
from blazar import exceptions
from blazar.i18n import _
LOG = logging.getLogger(__name__)
class BlazarDBException(exceptions.BlazarException):
msg_fmt = _('An unknown database exception occurred')
class BlazarDBDuplicateEntry(BlazarDBException):
msg_fmt = _('Duplicate entry for %(columns)s i... | msg_fmt = _('%(query_filter)s is invalid')
class BlazarDBInvalidFilterOperator(BlazarDBException):
msg_fmt = _('%(filter_operator)s is invalid')
class BlazarDBExtraCapabilitiesNotEnabled(BlazarDBException):
msq_fmt = _('%(resource_type)s does not have extra capabilities enabled.')
class BlazarDBInvalid... |
from urlparse import urljoin
from os.path import dirname, basename
from xml.etree import ElementTree
from mimetypes import guess_type
from StringIO import StringIO
import requests
def update_print(apibase, password, print_id, progress):
"""
"""
params = {'id': print_id}
data = dict(progress=progress,... | mimetype=(guess_type(file_path)[0] or '')))
res = requests.get(urljoin(apibase, '/append.php'), params=params, headers=dict(Accept='application/paperwalking+xml'))
form = ElementTree.parse(StringIO(res.text)).g | etroot()
if form.tag == 'form':
form_action = form.attrib['action']
inputs = form.findall('.//input')
fields = {}
files = {}
for input in inputs:
if input.attrib['type'] != 'file' and 'name' in input.attrib:
fields[input.att... |
# Copyright 2016 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 applicable ... | ges(image, (output_height, output_width))
# Resize and crop if needed.
resized_image = tf.image.resize_image_with_crop_or_pad(image,
output_width,
output_height)
tf.summary.image('res | ized_image', tf.expand_dims(resized_image, 0))
# Subtract off the mean and divide by the variance of the pixels.
return tf.image.per_image_standardization(resized_image)
def preprocess_image(image, output_height, output_width, is_training=False):
"""Preprocesses the given image.
Args:
image: A `Tensor` ... |
#!/usr/bin/env python
import time
from ni | cfit.aio import Application
async def _main(args):
print(args)
print("Sleeping 2...")
time.sleep(2)
print("Sleeping 0...")
return 0
def atexit():
print("atexit")
app = Application(_main, atexit=atexit)
app | .arg_parser.add_argument("--example", help="Example cli")
app.run()
assert not"will not execute"
|
from compare import expect
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import Client
from django.core.management import call_command
import sys
from tardis.tardis_portal.models import \
Experiment, Dataset, Dataset_File, ExperimentACL, License, UserProfile... | l_description='CC BY 2.5 AU',
allows_distribution=True)
license_.save()
return license_
def _create_test_experiment(user, license_):
experiment = Experiment(title='Norwegian Blue',
description='Parrot + 40kV',
created_by=user)
... | iment.save()
experiment.author_experiment_set.create(order=0,
author="John Cleese",
url="http://nla.gov.au/nla.party-1")
experiment.author_experiment_set.create(order=1,
author="Mi... |
import subprocess
from pkg_resources import resource_filename
def playit(file):
"""
Function used to play a sound file
"""
filepath = resource_filename(__name__, 'sou | nd/' + file)
subprocess.Popen(["pa | play", filepath])
|
"""revert: add plugin event acl to the admin backend
Revision ID: 97e2d9949db
Revises: 1e5140290977
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '97e2d9949db'
down_revision = '1e5140290977'
POLICY_NAME = 'wazo_default_admin_policy'
ACL_TEMPLATES = ['events... | _templates(conn, ACL_TEMPLATES)
if acl_template_ | ids:
policy_uuid = _get_policy_uuid(conn, POLICY_NAME)
delete_query = policy_template.delete().where(
sa.sql.and_(
policy_template.c.policy_uuid == policy_uuid,
policy_template.c.template_id.in_(acl_template_ids),
)
)
op.execute(del... |
from . import minic_ast
class PrettyGenerator(object | ):
def __init__(self):
# Statements start with indentation of self.indent_level spaces, using
# the _make_indent method
#
self.indent_level = 0
def _make_indent(self):
return ' ' * self.indent_level
def visit(self, node):
method = 'visit_' + node.__class__._... | ne:
return ''
else:
return ''.join(self.visit(c) for c_name, c in node.children())
|
from node_view import NodeGraphView
from node_scene import NodeGraphScene
from items.node_item import NodeIt | em
from items.connection_item import Connectio | nItem
from items.connector_item import BaseConnectorItem, IOConnectorItem, InputConnectorItem, OutputConnectorItem
import node_utils |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.mo | dels import F, Func, Value
class AlphabeticalPaginationMixin(object):
alphabetical_pagination_field = 'name'
def get_alphabetical_pagination_field(self):
return self.alphabetical_pagination_field
def get_selected_letter(self):
return self.request.GET.get('letter', 'a' | )
def get_base_queryset(self):
"""
Queryset before applying pagination filters.
"""
qs = super(AlphabeticalPaginationMixin, self).get_queryset().exclude(
**{self.get_alphabetical_pagination_field(): ''}
)
return qs
def get_queryset(self):
qs ... |
"""add graphql ACL to users
Revision ID: 2d4882d39dbb
Revises: c4d0e9ec46a9
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d4882d39dbb'
down_revision = 'dc2848563b53'
POLICY_NAME = 'wazo_default_user_policy'
ACL_TEMPLATES = ['dird.graphql.me']
policy_tabl... | able.c.name == policy_name
)
for policy in conn.execute(policy_query).fetchall():
return policy[0]
def _insert_acl_ | template(conn, acl_templates):
acl_template_ids = []
for acl_template in acl_templates:
acl_template_id = _find_acl_template(conn, acl_template)
if not acl_template_id:
query = (
acl_template_table.insert()
.returning(acl_template_table.c.id)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ndvi_test.py
#
# Copyright 2015 rob <rob@Novu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General P | ublic License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WI | THOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation,... |
lt behavior; C(no) does not install recommended packages. Suggested packages are never installed.
required: false
default: yes
choices: [ "yes", "no" ]
force:
description:
- If C(yes), force installs/removes.
required: false
default: "no"
choices: [ "yes", "no" ]
upgrade:
descr... | ion)
def package_status(m, pkgname, version, cache, state):
try:
# get the package from the cache, as well as the
# the low-level apt_pkg.Package object which contains
# state fields not directly acc | cesible from the
# higher-level apt.package.Package object.
pkg = cache[pkgname]
ll_pkg = cache._cache[pkgname] # the low-level package object
except KeyError:
if state == 'install':
try:
if cache.get_providing_packages(pkgname):
return... |
#!/usr/bin/env python
###############################################################################
# $Id: gdal2grd.py 27044 2014-03-16 23:41:27Z rouault $
#
# Project: GDAL Python samples
# Purpose: Script to write | out ASCII GRD rasters (used in Golden Software
# Surfer)
# from any source supported by GDAL.
# Author: Andrey Kiselev, dron@remotesensing.org
#
###############################################################################
# Copyright (c) | 2003, Andrey Kiselev <dron@remotesensing.org>
# Copyright (c) 2009, Even Rouault <even dot rouault at mines-paris dot org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restricti... |
ename)
return
else:
model.api.devlog("loading file %s" % filename)
infilepath = os.path.join(self._path, filename)
host_dict = {}
try:
with open(infilepath) as infile:
host_dict = json.load(infile)
except Exceptio... | of created workspaces to be able to load them
"""
def __ | init__(self, model_controller, plugin_controller):
self.active_workspace = None
self._couchAvailable = False
self.report_manager = ReportManager(10, plugin_controller)
self.couchdbmanager = PersistenceManagerFa... |
ll always eat "
"the data away from the other."
)
read_all = "Read as many bytes as are currently available"
read_some = "Read exactly this number of bytes:"
read_time = "and wait this maximum number of milliseconds for them:"
import wx
import threading
import win... | port,
baudrate=baudrate,
bytesize=(5, 6, 7, 8)[bytesize],
stopbits=(1, 2)[stopbits],
parity=('N', | 'O', 'E')[parity],
xonxoff=xonxoff,
rtscts=rtscts,
)
except:
self.serial = None
raise self.Exceptions.SerialOpenFailed
self.serial.timeout = 1.0
self.serial.setRTS()
if generateEvents:
self.decoder ... |
ngs_override)s
'''
SCRIPT_TEMPLATES = {
'wsgi': easy_install.script_header + '''
%(relative_paths_setup)s
import sys
sys.path[0:0] = [
%(path)s,
]
%(initialization)s
import os
try:
from django.core.wsgi import get_wsgi_application
IS_14_PLUS = True
except ImportError:
from django.core.handlers... | )
self.working_set = egg.working_set(self.eggs)
def setup_secret(self):
secret_file = os.path.join(
self.buildout['buildout']['directory'],
self.secret_cfg
)
if os.path.isfile(secret_file):
stream | = open(secret_file, 'rb')
data = stream.read().decode('utf-8').strip()
stream.close()
self.logger.debug("Read secret: %s" % data)
else:
stream = open(secret_file, 'wb')
chars = u'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
data = u'... |
from distutils.core import setup
setup(
name = 'mirobot',
packages = ['mirobot'],
version = '1.0.3',
description = 'A Python library to control Mirobot (http://mirobot.io)',
author = 'Ben Pirt',
author_email = 'ben@pirt.co.uk',
url = 'https://github.com/mirobot/mirobot-py',
download_url = 'https://githu... |
keywords = ['robotics', 'control', 'mirobot'],
classifiers = ['Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ' | Topic :: Education', 'License :: OSI Approved :: MIT License'],
install_requires=[
"websocket-client",
],
)
|
"""Base rop | e package
This package contains rope core modules that are used by other modules
and packages.
"""
__all__ = ["project", " | libutils", "exceptions"]
|
import scipy.sparse as ss
import warnings
warnings.simplefilter('ignore', ss.SparseEfficiencyWarning)
from sparray import FlatSparray
class Operations(object):
params = [['FlatSparray', 'csr_matrix']]
param_names = ['arr_type']
def setup(self, arr_type):
mat = ss.rand(3000, 4000, density=0.1, format='csr'... | arr[:,273]
def time_diagonal(self, arr_type):
self.arr.diagonal()
class Imp | ureOperations(object):
params = [['FlatSparray', 'csr_matrix']]
param_names = ['arr_type']
number = 1 # make sure we re-run setup() before each timing
def setup(self, arr_type):
mat = ss.rand(3000, 4000, density=0.1, format='csr')
if arr_type == 'FlatSparray':
self.arr = FlatSparray.from_spmatri... |
from pyspark import SparkConf, SparkContext
from jsonrpc.authproxy import AuthServiceProxy
import json
import sys
#This is batch processing of bitcoind (locally run bitcoin daemon)
#RPC (Remote Procedure Call) block's json stored
#in HDFS. Currently 187,990 blocks' json representation is
#stored in HDFS. The HDFS file... | tput.key.class": "org.apache.hadoop.hbase.io.ImmutableBytesWritable",
"mapreduce.job.output.value.class": "org.apache.hadoop.io.Writable"}
keyConv = "org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter"
valueConv = "org.apache.spark.examples.pythonconverters.StringList... | ily=tx_fee_col,column_name = tx_fee, column_value=x
#datamap = tx_fee_rdd.map(lambda x: ("tx_fee",x) )
#( rowkey , [ row key , column family , column name , value ] )
datamap = tx_fee_rdd.map(lambda x: (str(x[0]),
[str(x[0]),"tx_fee_col","tx_fee",str(x[1])])
... |
# encoding: utf-8
"""Provides collection of events emitters"""
import time
from . import EndPoint
def container_count(host_fqdn, docker_client, statistics):
"""
Emit events providing:
- number of containers
- number of running containers
- number of crashed containers
:param host_fqdn:... | all on https://docs.docker.com/reference/api/docker_remote_api_v1.17/#get-container-stats-based-on-resource-usage
:return: list of dicts providing additional events to push to Zabbix.
Each dict is composed of 4 keys:
- hostname
- timestamp
- key
- value
"""
running = 0
... | status = container['Status']
if status.startswith('Up'):
running += 1
elif not status.startswith('Exited (0)'):
crashed += 1
data = {
'all': len(containers),
'running': running,
'crashed': crashed,
}
return [
{
'hostname': '... |
# From Python 3.6 func | tools.py
# Bug was in detecting "nonlocal" access
def not_bug():
cache_token = 5
def register():
nonlocal cache_token
return ca | che_token == 5
return register()
assert not_bug()
|
# codi | ng: utf-8
from flask import Blueprint
__author__ = 'Jux.Liu'
user = Blueprint('user', __name__)
from . | import views
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import apps
from django.forms import widgets
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from cmsplugin_cascade.fields ... | al='',
label=_("Link Target"),
help_text=_("Open Link in other target.")
),
PartialFormField('title',
widgets.T | extInput(),
label=_("Title"),
help_text=_("Link's Title")
),
)
html_tag_attributes = {'title': 'title', 'target': 'target'}
# map field from glossary to these form fields
glossary_field_map = {'link': ('link_type', 'cms_page', 'ext_url', 'mail_to',)}
@classmethod
... |
__all__ = ['scraper', 'local_scraper', 'pw_scraper', 'uflix_scraper', 'watchseries_scraper', 'movie25_scraper', 'merdb_scraper', '2movies_scraper', 'icefilms_scraper',
'movieshd_scraper', 'yifytv_scraper', 'viooz_scraper', 'filmstreaming_scraper', 'myvideolinks_scraper', 'filmikz_scraper', 'clickplay_scraper... | ath, 'r') as f:
xml = f.read()
except:
raise
new_settings = []
cat_count = 1
old_xml = xml
classes = scraper.Scraper.__class__.__subclasses__(scraper.Scraper)
for cls in sorted(classes, key=lambda x: x.get_name().upper()):
new_settings += cls.get_settings()
... | ew_settings:
xml = update_xml(xml, new_settings, cat_count)
if xml != old_xml:
try:
with open(full_path, 'w') as f:
f.write(xml)
except:
raise
else:
log_utils.log('No Settings Update Needed', xbmc.LOGDEBUG)
update_settings()
|
x")
self.similarity = similarity
if 'gap_open' not in self.similarity:
raise ValueError(
"No gap_open open penalty in alignment scoring matrix.")
if 'gap_extend' not in self.similarity:
raise ValueError(
"No gap_open extend penalty in alig... | 1, j - 1, "mismatch", None))
i -= 1
j -= 1
elif self.matrix[i, j]['trace'] == Aligner._INS:
pos_1 = 0 if (i - 1) < 0 else (i - 1)
tracebac | k.append((pos_1, j - 1, "insertion", 1))
j -= 1
elif self.matrix[i, j]['trace'] == Aligner._DEL:
pos_2 = 0 if (j - 1) < 0 else (j - 1)
traceback.append((i - 1, pos_2, "deletion", 1))
i -= 1
elif self.matrix[i, j]['trace'] == Aligner... |
#!/usr/bin/env python
from distutils.core import setup, run_setup, Command
import zmq.auth
import shutil
import os
OSAD2_PATH = os.path.dirname(os.path.realpath(__file__))
OSAD2_SERVER_CERTS_DIR = "/etc/rhn/osad2-server/certs/"
OSAD2_SERVER_PUB_KEY = os.path.join(OSAD2_SERVER_CERTS_DIR, "public_keys/server.key")
OSA... | _SERVER_CERTS_DIR, "private_keys")
shutil.move(pk_file, pk_dst)
shutil.move(sk_file, sk_dst)
pk_dst = os.path.join(pk_dst, name + ".key")
sk_dst = os.path.join(sk_dst, name + ".key_secret")
print pk_dst
print sk_dst
return pk_dst, sk_dst
class CreateServerCo... | r_options = []
def initialize_options(self):
self.name = None
def finalize_options(self):
assert os.path.isdir(OSAD2_SERVER_CERTS_DIR), \
'Certificates storage dir doesn\'t exist: %s' % OSAD2_SERVER_CERTS_DIR
server_keyfile = os.path.join(OSAD2_SERVER_CERTS_DIR, 'private_key... |
import pylab as pl
import scipy as sp
from serpentine import *
from elements import *
import visualize
class AtfExt :
def __init__(self) :
print 'AtfExt:__init__'
# set twiss parameters
mytwiss = Twiss()
mytw | iss.betax = 6.85338806855804
mytwiss.alphax = 1.11230788371885
mytwiss.etax = 3.89188697330735e-012
mytwiss.etaxp = 63.1945125619190e-015
mytwiss.betay = 2.94129410712918
mytwiss.alphay = -1.91105724003646
mytwiss.etay = 0
mytwiss.etayp = 0
mytwiss... | sigP = 1.03999991965541e-003
mytwiss.pz_cor = 0
# load beam line
self.atfFull = Serpentine(line='newATF2lat.aml',twiss=mytwiss)
self.atfExt = Serpentine(line=beamline.Line(self.atfFull.beamline[947:]),twiss=mytwiss)
# zero zero cors
self.atfExt.beamline.ZeroC... |
port noPadding
from binascii import a2b_hex
import unittest
class Rijndael_TestVectors(unittest.TestCase):
""" Test Rijndael algorithm using know values."""
def testGladman_dev_vec(self):
""" All 25 combinations of block and key size.
These test vectors were generated by Dr B... | 370734',
ct = '231d844639b31b412211cfe93712b880')
| RijndaelTestVec( i = 'dev_vec.txt 16 byte block, 24 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da5',
pt = '3243f6a8885a308d313198a2e0370734',
ct = 'f9fb29aefc384a250340d833b87ebc00')
RijndaelTestVec( i = 'dev... |
# 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 not u... | ule, "SHORT_HELP")
if hasattr(module, "USAGE"):
self.USAGE = getattr(module, "USAGE")
self.settings = settings
self.config = config
def __autocomplete__(self, command, current_word, argv):
# pylint: disable=unused-variable,unused-argument,
# attribute-defined-ou... | # <command>
comp_words = list(self.COMMANDS.keys())
comp_words = cli.util.completions(comp_words, current_word, argv)
if comp_words is not None:
return (option, comp_words)
# <args>...
comp_words = self.__autocomplete__(argv[0], current_word, argv[1:])
... |
"""
Django settings for dts_test_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... | T_APPS if app not in SHARED_APPS]
ROOT_URLCONF = 'dts_test_project.urls'
WSGI_APPLICATION = 'dts_test_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django_tenants. | postgresql_backend',
'NAME': 'dts_test_project',
'USER': 'postgres',
'PASSWORD': os.environ.get('DATABASE_PASSWORD', 'root'),
'HOST': os.environ.get('DATABASE_HOST', 'localhost'),
'PORT': '',
}
}
DATABASE_ROUTERS = (
'django_tenants.routers.TenantSyncRouter',
)
MIDDLEWA... |
#! /usr/bin/env python3
import argparse
import logging
import os
from utils import run
logging.basicConfig(level=logging.INFO)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('dist_dir')
parser.add_argument('version')
| return parser.parse_args()
args = parse_args()
DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(DIR)
DIST_DIR = os.path.abspath(args.dist_dir)
DRIVE_C = os.p | ath.join(DIST_DIR, 'drive_c')
WINE_RN_DIR = os.path.join(DRIVE_C, 'rednotebook')
WINE_RN_WIN_DIR = os.path.join(WINE_RN_DIR, 'win')
os.environ['WINEPREFIX'] = DIST_DIR
ISCC = os.path.join(DRIVE_C, 'Program Files (x86)', 'Inno Setup 5', 'ISCC.exe')
VERSION_PARAM = '/dREDNOTEBOOK_VERSION=%s' % args.version
run(['wine', ... |
from django.contrib import admin
from common.admin import AutoUserMixin
from licenses.models import License
class LicenseAdmin(AutoUserMixin, admin.ModelAdmin):
fieldsets = [
(None, {
'fields': ['added', 'name', 'url', 'creative_commons',
| 'cc_attribution', 'cc_noncommercial',
'cc_no_deriv', 'cc_share_alike']
}),
]
# fields
readonly_fields = ['added']
list_display = ['name', 'url']
# field display
list_filter = ['name', 'added']
search_fields = ['name', 'url']
admin.si... | ister(License, LicenseAdmin)
|
.dot(V_uM.T.conj(), V_uM)
U_ow, U_lw, U_Ml = get_rot(F_MM, V_oM, Nw - No)
self.U_nw = np.vstack((U_ow, dots(V_uM, U_Ml, U_lw)))
# stop here ?? XXX
self.S_ww = self.rotate_matrix(np.ones(1))
if ortho:
lowdin(self.U_nw, self.S_ww)
self.S_ww = np.identity(Nw... | __init__(self, V_n | M, S_MM, No, lcaoindices=None):
Nw = V_nM.shape[1]
assert No <= Nw
self.V_oM, V_uM = V_nM[:No], V_nM[No:]
F_MM = S_MM - np.dot(self.V_oM.T.conj(), self.V_oM)
U_ow, U_lw, U_Ml = get_rot(F_MM, self.V_oM, Nw - No)
self.U_Mw = np.dot(U_Ml, U_lw)
self.U_ow = U... |
import unittest, uuid
from nixie.core import Nixie, KeyError
class NixieErrorsTestCase(unittest.TestCase):
def test_read_mi | ssing(self):
nx = Nixie()
self.assertIsNone(nx.read('missing'))
def test_update_m | issing(self):
nx = Nixie()
with self.assertRaises(KeyError):
nx.update('missing')
def test_update_with_wrong_value(self):
nx = Nixie()
key = nx.create()
with self.assertRaises(ValueError):
nx.update(key, 'a')
def test_delete_missing(self):
nx = Nixie()
with self.assertRaise... |
from django.shortcuts import render_to_resp | onse
from django.core.context_processors import csrf
from django.conf import settings
def my_render(request, template, context={}):
context.update(csrf(request))
context['STATIC_URL'] = settings.STATIC_URL
context['flash'] = request.get_flash()
context['user'] = request.user
context['user_perfil']... | |
# -*- coding: utf-8 -*-
from django import forms
from cmskit.articles.models import Index, Article
from cms.plugin_pool import plugin_pool
from cms.plugins.text.widgets.wymeditor_widget import WYMEditor
from cms.plugins.text.settings import USE_TINYMCE
def get_editor_widget():
"""
Returns the Django form Widg... | for page in self.fields['page'].querys | et:
choices.append(
(page.id, ''.join(['- '*page.level, page.__unicode__()]))
)
self.fields['page'].choices = choices
class ArticleForm(forms.ModelForm):
body = forms.CharField(widget=get_editor_widget())
class Meta:
model = Art... |
et ips that aren't the loopback
unwrap00 = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1]
# ???
unwrap01 = [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]
... | o signal that we are alive
"""
# send the terminal some information about ourselves
# TODO: Report any calibrations that we have
hello = {'pilot':self.name, 'ip':self.ip, 'state':self.state}
self.node.send(self.parentid, 'HANDSHAKE', value=hello)
def update_state(self):
... | will handle any
future requests.
"""
self.node.send(self.parentid, 'STATE', self.state, flags={'NOLOG':True})
def l_start(self, value):
"""
Start running a task.
Get the task object by using `value['task_type']` to select from
:data:`.tasks.TASK_LIST` , then... |
# -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2014 - 2016
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | and
# retrieving the next value from there and then subtracting one.
# __reduce__ returns the factory ('count') and the argument tuple
# containing the initial value (advanced with each call to next())
# pylint: disable = no-member
return _gen_id.__self__.__reduce__()[1][0] - 1
class Job(object... | lf, job_id, desc, group, locks, importance, not_before,
extra, predecessors, attempts):
"""
Initialization
:Parameters:
`job_id` : ``int``
Job ID
`desc` : `TodoDescription`
Job description
`group` : ``str``
Job... |
from builtins import str
from builtins import object
import smtplib
import email.utils
from biomaj.workflow import Workflow
import lo | gging
import sys
if sys.version < '3':
from emai | l.MIMEText import MIMEText
else:
from email.mime.text import MIMEText
class Notify(object):
"""
Send notifications
"""
@staticmethod
def notifyBankAction(bank):
if not bank.config.get('mail.smtp.host') or bank.session is None:
logging.info('Notify:none')
return... |
from __future__ import print_function
import os
twyg = ximport('twyg')
# reload(twyg)
datafiles = list(filelist( os.path.abspath('example-data')))
datafile = choice(datafiles)
configs | = [ 'boxes', 'bubbles', 'edge', 'flowchart', 'hive', 'ios', 'jellyfish',
'junction1', 'junction2', 'modern', 'nazca', 'rounded', 'square',
'synapse', 'tron']
colorschemes = [ 'aqua', 'azure', 'bordeaux', 'clay', 'cmyk', 'cobalt', 'colors21',
'crayons', 'earth', 'forest', 'grape... | ,
'mango', 'mellow', 'merlot', 'milkshake', 'mint-gray', 'mint', 'moon',
'mustard', 'neo', 'orbit', 'pastels', 'quartz', 'salmon', 'tentacle',
'terracotta', 'turquoise', 'violet']
config = choice(configs)
colorscheme = choice(colorschemes)
margins = ['10%', '5%']
pr... |
"clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
@attr.s(init=False, eq=False, order=False, hash=False, repr=False)
class C1Bare(object):
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
... | elf, a):
super(C, self).__init__()
C(field=1)
@attr.s(getstate_setstate=True)
class C2(object):
x = attr.ib()
@attr.s(slots=True, getstate_setstate=True)
class C2Slots(object):
| x = attr.ib()
class TestPickle(object):
@pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL))
def test_pickleable_by_default(self, protocol):
"""
If nothing else is passed, slotted classes can be pickled and
unpickled with all supported protocols.
"""
i... |
# 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 is distributed in the hope that it will be useful,
# but... | RANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Plac... | ort create_engine
from sqlalchemy.orm import sessionmaker
from daklib.database.all import Base
Session = sessionmaker()
@pytest.fixture(scope='session')
def engine():
engine = create_engine('sqlite://', echo=True)
Base.metadata.create_all(engine)
return engine
@pytest.yield_fixture
def session(engine... |
in the provenance
doc_id = provenance[0].get('document', {}).get('@id')
if doc_id:
title = self.doc.documents.get(doc_id, {}).get('title')
if title:
provenance[0]['document']['title'] = title
annotations = {'found_by': relation.get('r... | the negation
# under annotations, just in case it's needed
annotations['negated_texts'] = negations
# If that fails, we can still get the text of the relation
if text is None:
text = _sanitize(relation.get('text'))
| ev = Evidence(source_api='eidos', text=text, annotations=annotations,
context=context, epistemics=epistemics)
return ev
@staticmethod
def get_negation(event):
"""Return negation attached to an event.
Example: "states": [{"@type": "State", "type": "NEGATION",... |
.
def create_uuid():
return str(uuid.uuid4().int)
##
# GID is a tuple:
# (uuid, urn, public_key)
#
# UUID is a unique identifier and is created by the python uuid module
# (or the utility function create_uuid() in gid.py).
#
# HRN is a human readable name. It is a dotted form similar to a backward domain
# ... | N %s isn't in the namespace for parent HRN %s" % (self.get_hrn(), self.parent.get_hrn()))
# Parent must also be an authority (of some type) to sign a GID
# There are multiple types of authority - accept them all here
if not self.parent.get_type().find('authority') == 0:
... | ype()))
# Then recurse up the chain - ensure the parent is a trusted
# root or is in the namespace of a trusted root
self.parent.verify_chain(trusted_certs)
else:
# make sure that the trusted root's hrn is a prefix of the child's
trusted_gid = GID(str... |
"""
Django settings for DocumentsFlow project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
imp... | s://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_... | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.dj... |
# -*- coding: utf-8
from __future__ import absolute_import, unicode_literals
import django
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "o0fy)a6pmew*fe9b+^wf)96)2j8)%6oz555d7by7_(*i!b8wj8"
DATABASES = {
"default": {
"ENGINE": "django.db.backe... | ngo.contrib.messages",
"lock_tokens.apps.LockTokensConfig",
"tests",
]
SITE_ID = 1
STATIC_URL = '/static/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contri... | "django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
else:
MIDDLEWARE_CLASSES = (
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.mes... |
rvice not in sd.services
def test_unregisteringAnythingElseFails(sd):
item = 34
try:
sd.unregister(item)
except TypeError:
assert True
assert item not in sd.services
def test_unregisteringWhenRunningThrowsError(dns_sd, sd):
service = dns_sd.Service()
def dummy():
p... | ces
def test_discoverableRemvoingAnythingElseFails(dns_sd):
discoverable = dns_sd.ServiceContainer()
item = object( | )
try:
discoverable.remove_service(item)
assert False
except TypeError:
assert True
assert item not in discoverable.services
|
from discord. | ext import commands
class Github:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def permrole(self, ctx, argument:str):
await self.b | ot.say(';py for perm in discord.utils.get(ctx.message.server.roles, name="{}").permissions: print(perm)'.format(argument))
def setup(bot):
bot.add_cog(Github(bot))
|
from .command_line_mix | ins import CommandLineMixins
from .module import Module
from .console_app import ConsoleApp
__all__ = ['CommandLineMixins', 'Module' | , 'ConsoleApp'] |
# | -*- coding: utf-8 -*-
'''Caution:
For Python 2.7, `__init__.py` file in folder | s is nessary.
'''
|
# Copyright 2015 Nicta
#
# 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, softwa... | ote_host_scripts_dir = 'clusterous'
remote_host_key_file = 'key.pem'
remote_host_vars_file = 'vars.yml'
container_id_script_file = 'container_id.sh'
mesos_port = 5050
marathon_port = 8080
central_logging_port = 8 | 081
nat_ssh_port_forwarding = 22000
# How many seconds to wait for all Marathon applications to reach "started" state
# Currently 30 minutes
app_launch_start_timeout = 1800
app_destroy_timeout = 60
def get_script(filename):
"""
Takes script relative filename, returns absolute path
Assumes this file is in... |
tion
"""
result = {}
# Process the property to list hook by
if list_by == 'priority':
if show_info:
def _append_hook(d, priority, name, path):
# Use the priority as key and a dict of hooks names
# with their info as value
value = { 'p... | ing
| ask_string = _value_for_locale(arg['ask'])
# Append extra strings
if 'choices' in arg:
ask_string += ' ({:s})'.format('|'.join(arg['choices']))
if 'default' in arg:
ask_string += ' (default: {:s})'.format(arg[... |
import sys # this allows you to read the user input from keyboard also called "stdin"
import classOne # This imports all the classOne functions
import classTwo # This imports all the classTwo functions
import classThree # This imports all the classThree functions
import classFour # This imports all the classFour fun... | adline().strip())
if (usersClass < 1 or usersClass > MAX_CLASS) :
p | rint("No Quiz available for Class " + str(usersClass))
return False
else :
return usersClass
except :
print("Exception")
return False
if __name__ == '__main__':
while(True) :
usersClass = getUsersClass()
if (usersClass != False) :
bre... |
self.setAccess(queryLoadUserData.value(queryLoadUserData.record().indexOf("access")))
def setAccess(self,access):
self.access = access
def setName(self,name):
self.name = name
def getUsername(self):
return self.username.lower()
def getAccess(self):
... | e(queryLoadAccessTable.record().index | Of("name")),
'access': queryLoadAccessTable.value(queryLoadAccessTable.record().indexOf("bezeichnung"))}
results.append(list)
return results
def deleteUser(self):
sql = "DELETE FROM public.postnas_search_access_control WHERE lower(username) = :username"
... |
from behave import given, when, then
from slackrest.app import SlackrestApp
from slackrest.command import Visibility, Method
import json
class GiveMeAReply:
pattern = '!givemeareply'
url_format = '/reply'
visibility = Visibility.Any
body = None
method = Method.GET
class GiveMeANotification:
... | t, channel_id):
event = conte | xt.slack_events.await_event(event_type='message')
assert event['message']['channel'] == channel_id
@then(u'I should get a message containing "{msg}"')
def step_impl(context, msg):
event = context.slack_events.await_event(event_type='message')
print("Got message containing '{}'".format(event['message']['te... |
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 out
# serve to show the default.
import os
import sys
import django
import getpaid
sys.path.appe... |
sys.path.insert(0, os.path.abspath("../example"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")
django.setup()
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use o... | ---------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx_rtd_theme",
... |
# Script loads 3d data from text file (after Gwyddion text importing of AFM file)
import re
import numpy as np
def ReadData(file_name):
'''
Load 3d data array from a text file. The text file is imported from Gwyddion (free SPM data analysis software).
Parameters
----------
file_name : str
... | ers)
pixel_height : float
Height of one pixel (in meters)
height_unit : float
Measurement unit coefficient (in unit/meter)
'''
comments = [] # List of comments in text file
f = open(file_name)
for line in f:
if line.startswith('#'):
comments.append(... | ssion for image size searching
width_match = re.search(rex, comments[1])
height_match = re.search(rex, comments[2])
if (width_match.group(2) == 'µm') and (height_match.group(2) == 'µm'):
width_unit = 1e-6
height_unit = 1e-6
else:
raise ValueError("Attention! The measurement ... |
# -------------------------------- Database models----------------------------------------------------------------------
import sys, os
import sqlalchemy
from sqlalchemy import create_engine
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import secrets
import settings
MY... | ram session: session object
:return:
"""
session.add(obj)
@classmethod
def commit_session(cls, session):
"""
commit to session
:param session:
:return:
"""
session.commit()
@classmethod
def delete_from_session(cls, session, obj):
... | (obj)
@classmethod
def rollback_session(cls, session):
"""
rollback the current session
:param session:
:return:
"""
session.rollback()
@classmethod
def close_session(cls, session):
"""
close the current session
:param session:
... |
"""Module for parsing and testing package version predicate strings.
"""
import re
import distutils.version
import operator
re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)",
re.ASCII)
# (package) (rest)
re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
r... | zed list: 'bar (12.21)'
"""
def __init__(self, versionPredicateStr):
"""Parse a version predicate string.
"""
# Fields:
# name: package name
# pred: list of (comparison string, StrictVersion)
versionPredicateStr = versionPredicateStr.strip()
... | tr:
raise ValueError("empty package restriction")
match = re_validPackage.match(versionPredicateStr)
if not match:
raise ValueError("bad package name in %r" % versionPredicateStr)
self.name, paren = match.groups()
paren = paren.strip()
if paren:
... |
ort ckan.model as model
from ckanext.archiver.model import init_tables
init_tables(model.meta.engine)
self.log.info('Archiver tables are initialized')
elif cmd == 'migrate-archive-dirs':
self.migrate_archive_dirs()
elif cmd == 'migrate':
self.m... | e: %d', len(resources))
if not (packages or resources) | :
self.log.error('No datasets or resources to process')
sys.exit(1)
self.log.info('Queue: %s', self.options.queue)
for package in packages:
if p.toolkit.check_ckan_version(max_version='2.2.99'):
# earlier CKANs had ResourceGroup
pkg_re... |
from common import bounty, peers, settings
from common.safeprint import safeprint
from multiprocessing import Queue, Value
from time import sleep, time
import pickle
def sync():
from multiprocessing import Manager
man = Manager()
items = {'config': man.dict(),
'peerList': man.list(),
... | tyList'].extend(bounty.bountyList)
safeprint(items)
peers.sync(items)
return items
def initParallels():
queue = Queue()
live = Value('b', True)
ear = peers.listener(settings.config['port'], settings.config['outbound'], queue, live, settings.config['server'])
ear.daemon = True
ear.items... | ear.start()
mouth = peers.propagator(settings.config['port'] + 1, live)
mouth.daemon = True
mouth.items = ear.items
mouth.start()
feedback = []
stamp = time()
while queue.empty():
if time() - 15 > stamp:
break
global ext_ip, ext_port
ext_ip = ""
ext_port =... |
()[old] = type(native_str(old),
(_Deprecated,),
{"old": old, "new": new})
class AdminLoginInterfaceSelectorMiddleware(object):
"""
Checks for a POST from the admin login view and if authentication is
successful and the "site" interface is selected, redir... | self, request, view_func, view_args, view_kwargs):
login_type = request.POST.get("mezzanine_login_interface")
if login_type and not request.user.is_authenticated():
response = view_func(request, *view_args, **view_kwargs)
if request.user.is_authenticated():
if log... | next = request.get_full_path()
username = request.user.get_username()
if (username == DEFAULT_USERNAME and
request.user.check_password(DEFAULT_PASSWORD)):
error(request, mark_safe(_(
"Your account ... |
re
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefi... | g"]
| if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
else:
# exception #1
rendered = "0.p... |
# Utility functions for Ope | nMORA scripts
#
# Part of OpenMora - https://github.com/OpenMORA
import os, sys, string
import platform
import yaml
def get_mora_paths():
""" Returns a list of paths with MORA modules, from the env var MORA_PATH
"""
if not 'MORA_PATH' in os.environ:
print('**ERROR** Environment variable MORA_PATH not set')
sys... | viron['MORA_PATH'];
if platform.system()=="Windows":
sPathDelim = ";"
else:
sPathDelim = ":"
morabase_dir="";
return sMoraPaths.split(sPathDelim)
def get_morabase_dir():
""" Returns the path of "mora-base" pkg
"""
mora_paths = get_mora_paths() # Get env vars
for p in mora_paths:
tstPath = os.path.no... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from foo_receiver import FooReceiver
from foo_listener_bf import FooListenerBfHelper
from PyCFFIlib_cffi import ffi, lib
import gc
class FooListenerBfImpl:
def delete_fl_in_fl(self):
print ("Not to b... | 2 = None
gc.collect()
fr = None
gc.c | ollect()
assert 0 == len(FooListenerBfHelper.c_data_set)
|
# Tests for source4/libnet/py_net_dckeytab.c
#
# Copyright (C) David Mulder <dmulder@suse.com> 2018
#
# 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 yo... | (keytab=self.ktfile, principal=self.principal)
assert os.path.exists(self.ktfile), 'keytab was not created'
with open_bytes(self.ktfile) as bytes_kt:
result = ''
for c in bytes_kt.read():
| if c in string.printable:
result += c
principal_parts = self.principal.split('@')
assert principal_parts[0] in result and \
principal_parts[1] in result, \
'Principal not found in generated keytab'
|
self.subscribe(method='self.get_names')
other_ws._send(method='self.change_name_then_error')
self.assert_incoming()
def test_triggered_error(self):
with self.open_ws() as other_ws:
self.subscribe(method='self.get_names')
self.names.append(object())
... | ' + uuid4().hex)
self.ws._send(method='crud.update', client=client, params=self.models(*models))
self.assert_incoming(client=client)
def test_read(self):
self.read('User')
self.assert_no_response()
def test_triggered_read(self):
self.read('User')
self.update('Us... | ssert_no_response()
def test_triggered_error(self):
self.mr.update_error = True
with self.open_ws() as other_ws:
other_ws._send(method='crud.read', client='other_tte', params=self.models('User'))
self.assert_incoming(other_ws, client='other_tte')
self.update('Use... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
""" astropy.cosmology contains classes and functions for cosmological
distance measures and other cosmology-related calculations.
See the `Astropy | documentation
<https://docs.astropy.org/en/latest/cosmology/index.html>`_ for more
detailed usage examples and references.
"""
from . import core, flrw, funcs, parameter, units, utils
from . import io # needed before 'realizations' # isort: split
from . import realizations
from .core import | *
from .flrw import *
from .funcs import *
from .parameter import *
from .realizations import *
from .utils import *
__all__ = (core.__all__ + flrw.__all__ # cosmology classes
+ realizations.__all__ # instances thereof
+ funcs.__all__ + parameter.__all__ + utils.__all__) # util... |
()
aset1 = amcattest.create_test_set(4, project=project)
aset2 = amcattest.create_test_set(5, project=project)
aset3 = amcattest.create_test_set(0)
# Creates a codingjob for each articleset, as handle_split should account
# for "codedarticlesets" as well.
cj1 = amcattest... | self.assertTrue(f.is_valid())
handle_split(f, project, article, Sentence.objects.none())
self.assertTrue(article in aset2.articles.all())
# Test remove_from_sets
f = form(dict(remove_from_sets=[aset1.id]))
self.assertTrue(f.is_valid())
handle_split(f, project, article, S... | ssertTrue(article not in aset1.articles.all())
# Test remove_from_all_sets
aset1.add_articles([article])
aset2.add_articles([article])
aset3.add_articles([article])
f = form(dict(remove_from_all_sets=True))
self.assertTrue(f.is_valid())
handle_split(f, project, ... |
import logging
from discord.ext import commands
from bot.cooldowns import CooldownMapping, Cooldown
from bot.globals import Auth
from utils.utilities import is_owner, check_blacklist, no_dm
terminal = logging.getLogger('terminal')
def command(*args, **attrs):
if 'cls' not in attrs:
attrs['cls'] = Comma... | add_command(result)
return result
return decorator
def command(self, *args, **kwargs):
def decorator(func):
if 'owner_only' not in kwargs:
kwargs['owner_only'] = self | .owner_only
kwargs.setdefault('parent', self)
result = command(*args, **kwargs)(func)
self.add_command(result)
return result
return decorator
|
#!/usr/bin/python
################################################################################
# Bus Supervisor Interface
#
# - interfaces to the MCP23017 and PCF8574 IO expander chips
#
# The logic for this was ported from Dr Scott M. Baker's project:
# http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor
#
... | _i2cAddr8
if _i2cAddr8 is None:
baseAddr = 0x21
self.data = 0
self.dataControl = 0
self.dataAddress = 0
self.ardy = _ardy
self.cpuIoData = MCP23017_IOExpander16( _ardy, baseAddr + 0 )
self.cpuControl = PCF8574_IOExpander8( _ardy, baseAddr + 1 )
self.cpuAddre | ss = MCP23017_IOExpander16( _ardy, baseAddr + 2 )
self.ClearAllExpanders()
def ClearAllExpaners( self ):
# clear data register
self.cpuIoData.DirectionA( IODIRA, IOALLINPUT )
self.cpuIoData.SetA( 0x00 )
self.cpuIoData.DirectionB( IODIRA, IOALLINPUT )
self.cpuIoData.SetB( 0x00 )
# clear control registe... |
import sys, os
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from random import randint
import tempfile
def glm_gamma_offset_mojo():
train = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip"))
y = "DPROS"
x = ["AGE","RACE","CAPSULE","DCAPS... | dir, MOJONAME) # load model and perform predict
h2o.download_csv(pred_h2o, os.path.join(tmpdir, "h2oPred.csv"))
print("Comparing mojo predict and h2o predict...")
pyunit_utils.compare_frames_local(pred_h2o, pred_mojo, 0.1, tol=1e-10) # compare mojo and model predict
if __name__ == "__main__":
pyunit_u... | test(glm_gamma_offset_mojo)
else:
glm_gamma_offset_mojo()
|
#!/usr/bin/env python
import os
import sy | s
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "timberwyck.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Dev")
from configurations.man | agement import execute_from_command_line
execute_from_command_line(sys.argv)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko
import threading
import sys
import re
import time
import os
def start_shell(h, u, p):
ssh = | paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(h, 22, u, p)
| s = ssh.invoke_shell()
w = threading.Thread(target=write_chanel, args=(s, ))
# r = threading.Thread(target=read_chanel, args=(s, ))
w.setDaemon(True)
w.start()
# w.start()
read_chanel(s)
# w.join()
try:
s.close()
ssh.close()
except:
pass
def read_ch... |
#!/usr/bin/python3
import sys, subprocess
def main(argv=None):
if argv is None:
argv = sys.argv
experiments = {
1 : ('Continuous', 'COPD'),
2 : ('Binary', ' COPD'),
3 : ('Continuous', 'EmphysemaExtentLung'),
4 : ('Binary', 'EmphysemaExtentLung'),
}
try:
... | csv',
}
instances = '../../Data/Training/Instances.csv'
bagMembership = '../../Data/Training/BagMembership.csv'
modelPattern = "Out/Training/MaxIterati | ons1000/%s_%s_k%s_1.model"
numberOfClusters = ['5', '10', '20', ]#'15', '20', ]#'25', '30']
params = {
'histograms' : '24',
}
for k in numberOfClusters:
out = 'Out/Training/MaxIterations1000/%s_%s_k%s_' % (experiment + (k,))
cmd = [
prog,
"--instances", i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.