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 |
|---|---|---|---|---|---|---|---|---|
rdobson/xva-tools | pyxva/cmd/tests/test_xva.py | Python | gpl-3.0 | 924 | 0 | import unittest
import os
from mock import MagicMock, patch
| from pyxva.cmd import xva
class TestXVAUpdate(unittest.TestCase):
| OVA_XML = "data/ova.xml"
@patch("pyxva.cmd.xva.extract_xva")
def setUp(self, mock_extract):
ova_xml_path = "%s/%s" % (
os.path.dirname(os.path.realpath(__file__)),
self.OVA_XML
)
with open(ova_xml_path, 'r') as fh:
ova_data = fh.read()
mtar = MagicMock()
mock_extract.return_value = (mtar, ova_data)
self.xva = xva.open_xva(mtar)
def test_update_product_version(self):
self.xva.set_version("product_version", "5.5")
vrec = self.xva.version()
self.assertEqual(vrec["product_version"], "5.5")
def test_update_xapi_minor(self):
self.xva.set_version("xapi_minor", "2.3")
vrec = self.xva.version()
self.assertEqual(vrec["xapi_minor"], "2.3")
|
hosiet/ustcbbs-archiver | exec.py | Python | mit | 125 | 0.008403 | #!/usr/bin/env python3
# 作者:hosiet
import os
import sys
| import sqlite3
import config
import reques | ts
import urllib
|
jimklo/LRSignature | src/setup.py | Python | apache-2.0 | 1,114 | 0.007181 | '''
Copyright 2011 SRI International
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed 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.
Created on May 11, 2011
@author: jklo
'''
from | setuptools import setup, find_packages
setup(
name='LRSignature',
version='0.1.14',
author='Jim Klo',
author_email="jim.klo@sri.com",
url = "https://github.com/jimklo/LRSignature",
description='Learning Registry resource data digital signature management',
packages=find_packages(),
long_description=open('README.txt').read(),
install_requires = ["argparse","python-gnupg>=0.3.0",'nose==1.2.0'],
test_suite = 'nose.collector',
license='Apache 2.0 License'
)
|
renoirb/browsercompat | webplatformcompat/serializers.py | Python | mpl-2.0 | 17,212 | 0 | # -*- coding: utf-8 -*-
"""API Serializers"""
from collections import OrderedDict
from django.db.models import CharField
from django.contrib.auth.models import User
from rest_framework.serializers import (
CurrentUserDefa | ult, DateTimeField, IntegerField,
ModelSerializer, SerializerMethodField, ValidationError)
from sortedm2m.fields import SortedManyToManyField
from . import fields
from .drf_fields import (
CurrentHistoryField, HistoricalObjectField, HistoryField,
MPTTRelationField, OptionalCharField, OptionalIntegerField,
PrimaryKeyRelatedField, TranslatedTextField)
from .history import Changeset
from .mode | ls import (
Browser, Feature, Maturity, Section, Specification, Support, Version)
from .validators import VersionAndStatusValidator
def omit_some(source_list, *omitted):
"""Return a list with some items omitted"""
for item in omitted:
assert item in source_list, '%r not in %r' % (item, source_list)
return [x for x in source_list if x not in omitted]
#
# "Regular" Serializers
#
class WriteRestrictedMixin(object):
def get_fields(self):
"""Add read_only flag for write-restricted fields"""
fields = super(WriteRestrictedMixin, self).get_fields()
view = self.context.get('view', None)
if view and view.action in ('list', 'create'):
update_only_fields = getattr(self.Meta, 'update_only_fields', [])
for field_name in update_only_fields:
fields[field_name].read_only = True
if view and view.action in ('update', 'partial_update'):
write_once_fields = getattr(self.Meta, 'write_once_fields', [])
for field_name in write_once_fields:
fields[field_name].read_only = True
return fields
class FieldMapMixin(object):
"""Automatically handle fields used by this project"""
serializer_field_mapping = ModelSerializer.serializer_field_mapping
serializer_field_mapping[fields.TranslatedField] = TranslatedTextField
serializer_field_mapping[CharField] = OptionalCharField
serializer_field_mapping[SortedManyToManyField] = PrimaryKeyRelatedField
serializer_related_field = PrimaryKeyRelatedField
def build_standard_field(self, field_name, model_field):
field_class, field_kwargs = super(
FieldMapMixin, self).build_standard_field(
field_name, model_field)
if isinstance(model_field, fields.TranslatedField):
if not (model_field.blank or model_field.null):
field_kwargs['required'] = True
if model_field.allow_canonical:
field_kwargs['allow_canonical'] = True
return field_class, field_kwargs
class HistoricalModelSerializer(
WriteRestrictedMixin, FieldMapMixin, ModelSerializer):
"""Model serializer with history manager"""
def build_property_field(self, field_name, model_class):
"""Handle history field.
The history field is a list of PKs for all the history records.
"""
assert field_name == 'history'
field_kwargs = {'many': True, 'read_only': True}
return HistoryField, field_kwargs
def build_unknown_field(self, field_name, model_class):
"""Handle history_current field.
history_current returns the PK of the most recent history record.
It is treated as read-only unless it is an update view.
"""
assert field_name == 'history_current'
view = self.context.get('view', None)
read_only = view and view.action in ('list', 'create')
field_args = {'read_only': read_only}
return CurrentHistoryField, field_args
def to_internal_value(self, data):
"""If history_current in data, load historical data into instance"""
if data and 'history_current' in data:
history_id = int(data['history_current'])
current_history = self.instance.history.all()[0]
if current_history.history_id != history_id:
try:
historical = self.instance.history.get(
history_id=history_id).instance
except self.instance.history.model.DoesNotExist:
err = 'Invalid history ID for this object'
raise ValidationError({'history_current': [err]})
else:
for field in historical._meta.fields:
attname = field.attname
hist_value = getattr(historical, attname)
data[attname] = hist_value
return super(HistoricalModelSerializer, self).to_internal_value(data)
class BrowserSerializer(HistoricalModelSerializer):
"""Browser Serializer"""
def update(self, instance, validated_data):
versions = validated_data.pop('versions', None)
instance = super(BrowserSerializer, self).update(
instance, validated_data)
if versions:
v_pks = [v.pk for v in versions]
current_order = instance.get_version_order()
if v_pks != current_order:
instance.set_version_order(v_pks)
return instance
class Meta:
model = Browser
fields = (
'id', 'slug', 'name', 'note', 'history', 'history_current',
'versions')
update_only_fields = (
'history', 'history_current', 'versions')
write_once_fields = ('slug',)
class FeatureSerializer(HistoricalModelSerializer):
"""Feature Serializer"""
children = MPTTRelationField(many=True, read_only=True)
class Meta:
model = Feature
fields = (
'id', 'slug', 'mdn_uri', 'experimental', 'standardized',
'stable', 'obsolete', 'name',
'sections', 'supports', 'parent', 'children',
'history_current', 'history')
read_only_fields = ('supports',)
class MaturitySerializer(HistoricalModelSerializer):
"""Specification Maturity Serializer"""
class Meta:
model = Maturity
fields = (
'id', 'slug', 'name', 'specifications',
'history_current', 'history')
read_only_fields = ('specifications',)
class SectionSerializer(HistoricalModelSerializer):
"""Specification Section Serializer"""
class Meta:
model = Section
fields = (
'id', 'number', 'name', 'subpath', 'note', 'specification',
'features', 'history_current', 'history')
extra_kwargs = {
'features': {
'default': []
}
}
class SpecificationSerializer(HistoricalModelSerializer):
"""Specification Serializer"""
def update(self, instance, validated_data):
sections = validated_data.pop('sections', None)
instance = super(SpecificationSerializer, self).update(
instance, validated_data)
if sections:
s_pks = [s.pk for s in sections]
current_order = instance.get_section_order()
if s_pks != current_order:
instance.set_section_order(s_pks)
return instance
class Meta:
model = Specification
fields = (
'id', 'slug', 'mdn_key', 'name', 'uri', 'maturity', 'sections',
'history_current', 'history')
extra_kwargs = {
'sections': {
'default': []
}
}
class SupportSerializer(HistoricalModelSerializer):
"""Support Serializer"""
class Meta:
model = Support
fields = (
'id', 'version', 'feature', 'support', 'prefix',
'prefix_mandatory', 'alternate_name', 'alternate_mandatory',
'requires_config', 'default_config', 'protected', 'note',
'history_current', 'history')
class VersionSerializer(HistoricalModelSerializer):
"""Browser Version Serializer"""
order = IntegerField(read_only=True, source='_order')
class Meta:
model = Version
fields = (
'id', 'browser', 'version', 'release_day', 'retirement_day',
'status', 'release_notes_uri', 'note', 'order |
zestrada/nova-cs498cc | nova/db/sqlalchemy/migrate_repo/versions/175_add_project_user_id_to_volume_usage_cache.py | Python | apache-2.0 | 1,735 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed 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.
from sqlalchemy import MetaData, Integer, String, Table, Column
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
# Allow the instance_id to be stored as a uuid, add columns for project_id
# and tenant_id.
volume_usage_cache = Table('volume_usage_cache', meta, autoload=True)
volume_usage_cache.drop_column('instance_id')
| instance_id = Column('instance_uuid', String(36))
pr | oject_id = Column('project_id', String(36))
user_id = Column('user_id', String(36))
volume_usage_cache.create_column(instance_id)
volume_usage_cache.create_column(project_id)
volume_usage_cache.create_column(user_id)
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
volume_usage_cache = Table('volume_usage_cache', meta, autoload=True)
volume_usage_cache.drop_column('instance_uuid')
volume_usage_cache.drop_column('user_id')
volume_usage_cache.drop_column('project_id')
instance_id = Column('instance_id', Integer)
volume_usage_cache.create_column(instance_id)
|
bregman-arie/ansible | lib/ansible/modules/network/eos/eos_banner.py | Python | gpl-3.0 | 6,270 | 0.001276 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = """
---
module: eos_banner
version_added: "2.3"
author: "Peter Sprygada (@privateip)"
short_description: Manage multiline banners on Arista EOS devices
description:
- This will configure both login and motd banners on remote devices
running Arista EOS. It allows playbooks to add or remote
banner text from the active running configuration.
extends_documentation_fragment: eos
notes:
- Tested against EOS 4.15
options:
banner:
description:
- Specifies which banner that should be
configured on the remote device.
required: true
choices: ['login', 'motd']
text:
description:
- The banner text that should be
present in the remote device running configuration. This argument
accepts a multiline string. Requires I(state=present).
state:
description:
- Specifies whether or not the configuration is
present in the current devices active running configuration.
default: present
choices: ['present', 'absent']
"""
EXAMPLES = """
- name: configure the login banner
eos_banner:
banner: login
text: |
this is my login banner
that contains a multiline
string
state: present
- name: remove the motd banner
eos_banner:
banner: motd
state: absent
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device
returned: always
type: list
sample:
- banner login
- this is my login banner
- that contains a multiline
- string
- EOF
session_name:
description: The EOS config session name used to load the configuration
returned: if changes
type: str
sample: ansible_1479315771
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.eos.eos import load_config, run_commands
from ansible.module_utils.network.eos.eos import eos_argument_spec, check_args
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_text
def map_obj_to_commands(updates, module):
commands = list()
want, have = updates
state = module.params['state']
if state == 'absent' and have.get('text'):
if isinstance(have['text'], str):
commands.append('no banner %s' % module.params['banner'])
elif have['text'].get('loginBanner') or have['text'].get('motd'):
commands.append({'cmd': 'no banner %s' % module.params['banner']})
elif state == 'present':
if isinstance(have['text'], string_types):
if want['text'] != have['text']:
commands.append('banner %s' % module.params['banner'])
commands.extend(want['text'].strip().split('\n'))
commands.append('EOF')
else:
have_text = have['text'].get('loginBanner') or have['text'].get('motd')
if have_text:
have_text = have_text.strip()
if to_text(want['text']) != have_text or not have_text:
# For EAPI we need to construct a dict with cmd/input
# key/values for the banner
commands.append({'cmd': 'banner %s' % module.params['banner'],
'input': want['text'].strip('\n')})
return commands
def map_config_to_obj(module):
output = run_commands(module, ['show banner %s' % module.params['banner']])
obj = {'banner': module.params['banner'], 'state': 'absent'}
if output:
if module.params['transport'] == 'eapi':
# On EAPI we need to extract the banner text from dict key
# 'loginBanner'
| if module.params['banner'] == 'login':
banner_response_key = 'loginBanner'
else:
banner_response_key = 'motd'
if isinstance(output[0], dict) and banner_respo | nse_key in output[0].keys():
obj['text'] = output[0]
else:
obj['text'] = output[0]
obj['state'] = 'present'
return obj
def map_params_to_obj(module):
text = module.params['text']
if text:
text = str(text).strip()
return {
'banner': module.params['banner'],
'text': text,
'state': module.params['state']
}
def main():
""" main entry point for module execution
"""
argument_spec = dict(
banner=dict(required=True, choices=['login', 'motd']),
text=dict(),
state=dict(default='present', choices=['present', 'absent'])
)
argument_spec.update(eos_argument_spec)
required_if = [('state', 'present', ('text',))]
module = AnsibleModule(argument_spec=argument_spec,
required_if=required_if,
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
result = {'changed': False}
if warnings:
result['warnings'] = warnings
want = map_params_to_obj(module)
have = map_config_to_obj(module)
commands = map_obj_to_commands((want, have), module)
result['commands'] = commands
if commands:
commit = not module.check_mode
response = load_config(module, commands, commit=commit)
if response.get('diff') and module._diff:
result['diff'] = {'prepared': response.get('diff')}
result['session_name'] = response.get('session')
result['changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main()
|
expectocode/Telethon | telethon_generator/parsers/tlobject/tlobject.py | Python | mit | 5,137 | 0 | import re
import struct
import zlib
from ...utils import snake_to_camel_case
# https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62
WHITELISTED_MISMATCHING_IDS = {
# 0 represents any layer
0: {'channel', # Since layer 77, there seems to be no going back...
'ipPortSecret', 'accessPointRule', 'help.configSimple'}
}
class TLObject:
def __init__(self, fullname, object_id, args, result,
is_function, usability, friendly, layer):
"""
Initializes a new TLObject, given its properties.
:param fullname: The fullname of the TL object (namespace.name)
The namespace can be omitted.
:param object_id: The hexadecimal string representing the object ID
:param args: The arguments, if any, of the TL object
:param result: The result type of the TL object
:param is_function: Is the object a function or a type?
:param usability: The usability for this method.
:param friendly: A tuple (namespace, friendly method name) if known.
:param layer: The layer this TLObject belongs to.
"""
# The name can or not have a namespace
self.fullname = fullname
if '.' in fullname:
self.namespace, self.name = fullname.split('.', maxsplit=1)
else:
self.namespace, self.name = None, fullname
self.args = args
self.result = result
self.is_function = is_function
self.usability = usability
self.friendly = friendly
self.id = None
if object_id is None:
self.id = self.infer_id()
else:
self.id = int(object_id, base=16)
whitelist = WHITELISTED_MISMATCHING_IDS[0] |\
WHITELISTED_MISMATCHING_IDS.get(layer, set())
if self.fullname not in whitelist:
assert self.id == self.infer_id(),\
'Invalid inferred ID for ' + repr(self)
self.class_name = snake_to_camel_case(
self.name, suffix='Request' if self.is_function else '')
self.real_args = list(a for a in self.sorted_args() if not
(a.flag_indicator or a.generic_definition))
@property
def innermost_result(self):
index = self.result.find('<')
if index == -1:
return self.result
else:
return self.result[index + 1:-1]
def sorted_args(self):
"""Returns the arguments properly sorted and ready to plug-in
into a Python's method header (i.e., flags and those which
can be inferred will go last so they can default =None)
"""
return sorted(self.args,
key=lambda x: x.is_flag or x.can_be_inferred)
def __repr__(self, ignore_id=False):
if self.id is None or ignore_id:
hex_id = ''
else:
hex_id = '#{:08x}'.format(self.id)
if self.args:
args = | ' ' + ' '.join([repr(arg) for arg in self.args])
else:
args = ''
return '{}{}{} = {}'.format(self.fu | llname, hex_id, args, self.result)
def infer_id(self):
representation = self.__repr__(ignore_id=True)
representation = representation\
.replace(':bytes ', ':string ')\
.replace('?bytes ', '?string ')\
.replace('<', ' ').replace('>', '')\
.replace('{', '').replace('}', '')
representation = re.sub(
r' \w+:flags\.\d+\?true',
r'',
representation
)
return zlib.crc32(representation.encode('ascii'))
def to_dict(self):
return {
'id':
str(struct.unpack('i', struct.pack('I', self.id))[0]),
'method' if self.is_function else 'predicate':
self.fullname,
'params':
[x.to_dict() for x in self.args if not x.generic_definition],
'type':
self.result
}
def is_good_example(self):
return not self.class_name.endswith('Empty')
def as_example(self, f, indent=0):
f.write('functions' if self.is_function else 'types')
if self.namespace:
f.write('.')
f.write(self.namespace)
f.write('.')
f.write(self.class_name)
f.write('(')
args = [arg for arg in self.real_args if not arg.omit_example()]
if not args:
f.write(')')
return
f.write('\n')
indent += 1
remaining = len(args)
for arg in args:
remaining -= 1
f.write(' ' * indent)
f.write(arg.name)
f.write('=')
if arg.is_vector:
f.write('[')
arg.as_example(f, indent)
if arg.is_vector:
f.write(']')
if remaining:
f.write(',')
f.write('\n')
indent -= 1
f.write(' ' * indent)
f.write(')')
|
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/lepl/lexer/lines/monitor.py | Python | agpl-3.0 | 3,018 | 0.001988 |
# The contents of this file are subject to the Mozilla Public License
# (MPL) Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and
# limitations under the License.
#
# The Original Code is LEPL (http://www.acooke.org/lepl)
# The Initial Developer of the Original Code is Andrew Cooke.
# Portions created by the Initial Developer are Copyright (C) 2009-2010
# Andrew Cooke (andrew@acooke.org). All Rights Reserved.
#
# Alternatively, the contents of this file may be used under the terms
# of the LGPL license (the GNU Lesser General Public License,
# http://www.gnu.org/licenses/lgpl.html), in which case the provisions
# of the LGPL License are applicable instead of those above.
#
# If you wish to allow use of your version of this file only under the
# terms of the LGPL License and not to allow others to use your version
# of this file under the MPL, indicate your decision b | y deleting the
# provisions above and replace them with the notice and other provisions
# required by the LGPL License. If you do not delete the provisions
# above, a recipient may use your version of this file under either the
# MPL or the LGPL License.
'''
Support the stack-scoped tracking of indent level blocks.
'''
from lepl.core.monitor import ActiveMonitor
from lepl.support.state import State
from lepl.support.lib import LogMixin, fmt
class BlockMonitor(ActiveMon | itor, LogMixin):
'''
This tracks the current indent level (in number of spaces). It is
read by `Line` and updated by `Block`.
'''
def __init__(self, start=0):
'''
start is the initial indent (in spaces).
'''
super(BlockMonitor, self).__init__()
self.__stack = [start]
self.__state = State.singleton()
def push_level(self, level):
'''
Add a new indent level.
'''
self.__stack.append(level)
self.__state[BlockMonitor] = level
self._debug(fmt('Indent -> {0:d}', level))
def pop_level(self):
'''
Drop one level.
'''
self.__stack.pop()
if not self.__stack:
raise OffsideError('Closed an unopened indent.')
self.__state[BlockMonitor] = self.indent
self._debug(fmt('Indent <- {0:d}', self.indent))
@property
def indent(self):
'''
The current indent value (number of spaces).
'''
return self.__stack[-1]
def block_monitor(start=0):
'''
Add an extra lambda for the standard monitor interface.
'''
return lambda: BlockMonitor(start)
class OffsideError(Exception):
'''
The exception raised by problems when parsing whitespace significant
code.
'''
|
elaeon/dsignature | creacion_firma/migrations/0011_auto_20150323_1736.py | Python | gpl-3.0 | 461 | 0 | # -*- codi | ng: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('creacion_firma', '0010_userdocumentsign_fecha'),
]
operations = [
migrations.AlterField(
model_name='userdocumentsign',
name='fecha',
field=models.DateField(auto_ | now_add=True),
preserve_default=True,
),
]
|
sffjunkie/home-assistant | homeassistant/components/hvac/__init__.py | Python | mit | 14,456 | 0 | """
Provides functionality to interact with hvacs.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/hvac/
"""
import logging
import os
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.config import load_yaml_config_file
import homeassistant.util as util
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.temperature import convert
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa
from homeassistant.components import zwave
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_ON, STATE_OFF, STATE_UNKNOWN,
TEMP_CELCIUS)
DOMAIN = "hvac"
ENTITY_ID_FORMAT = DOMAIN + ".{}"
SCAN_INTERVAL = 60
SERVICE_SET_AWAY_MODE = "set_away_mode"
SERVICE_SET_AUX_HEAT = "set_aux_heat"
SERVICE_SET_TEMPERATURE = "set_temperature"
SERVICE_SET_FAN_MODE = "set_fan_mode"
SERVICE_SET_OPERATION_MODE = "set_operation_mode"
SERVICE_SET_SWING_MODE = "set_swing_mode"
SERVICE_SET_HUMIDITY = "set_humidity"
STATE_HEAT = "heat"
STATE_COOL = "cool"
STATE_IDLE = "idle"
STATE_AUTO = "auto"
STATE_DRY = "dry"
STATE_FAN_ONLY = "fan_only"
ATTR_CURRENT_TEMPERATURE = "current_temperature"
ATTR_MAX_TEMP = "max_temp"
ATTR_MIN_TEMP = "min_temp"
ATTR_AWAY_MODE = "away_mode"
ATTR_AUX_HEAT = "aux_heat"
ATTR_FAN_MODE = "fan_mode"
ATTR_FAN_LIST = "fan_list"
ATTR_CURRENT_HUMIDITY = "current_humidity"
ATTR_HUMIDITY = "humidity"
ATTR_MAX_HUMIDITY = "max_humidity"
ATTR_MIN_HUMIDITY = "min_humidity"
ATTR_OPERATION_MODE = "operation_mode"
ATTR_OPERATION_LIST = "operation_list"
ATTR_SWING_MODE = "swing_mode"
ATTR_SWING_LIST = "swing_list"
_LOGGER = logging.getLogger(__name__)
DISCOVERY_PLATFORMS = {
zwave.DISCOVER_HVAC: 'zwave'
}
def set_away_mode(hass | , away_mode, entity_id=None):
"""Turn all or specified | hvac away mode on."""
data = {
ATTR_AWAY_MODE: away_mode
}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_AWAY_MODE, data)
def set_aux_heat(hass, aux_heat, entity_id=None):
"""Turn all or specified hvac auxillary heater on."""
data = {
ATTR_AUX_HEAT: aux_heat
}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_AUX_HEAT, data)
def set_temperature(hass, temperature, entity_id=None):
"""Set new target temperature."""
data = {ATTR_TEMPERATURE: temperature}
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_TEMPERATURE, data)
def set_humidity(hass, humidity, entity_id=None):
"""Set new target humidity."""
data = {ATTR_HUMIDITY: humidity}
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_HUMIDITY, data)
def set_fan_mode(hass, fan, entity_id=None):
"""Turn all or specified hvac fan mode on."""
data = {ATTR_FAN_MODE: fan}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_FAN_MODE, data)
def set_operation_mode(hass, operation_mode, entity_id=None):
"""Set new target operation mode."""
data = {ATTR_OPERATION_MODE: operation_mode}
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_OPERATION_MODE, data)
def set_swing_mode(hass, swing_mode, entity_id=None):
"""Set new target swing mode."""
data = {ATTR_SWING_MODE: swing_mode}
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_SWING_MODE, data)
# pylint: disable=too-many-branches
def setup(hass, config):
"""Setup hvacs."""
component = EntityComponent(_LOGGER, DOMAIN, hass,
SCAN_INTERVAL, DISCOVERY_PLATFORMS)
component.setup(config)
descriptions = load_yaml_config_file(
os.path.join(os.path.dirname(__file__), 'services.yaml'))
def away_mode_set_service(service):
"""Set away mode on target hvacs."""
target_hvacs = component.extract_from_service(service)
away_mode = service.data.get(ATTR_AWAY_MODE)
if away_mode is None:
_LOGGER.error(
"Received call to %s without attribute %s",
SERVICE_SET_AWAY_MODE, ATTR_AWAY_MODE)
return
for hvac in target_hvacs:
if away_mode:
hvac.turn_away_mode_on()
else:
hvac.turn_away_mode_off()
if hvac.should_poll:
hvac.update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_SET_AWAY_MODE, away_mode_set_service,
descriptions.get(SERVICE_SET_AWAY_MODE))
def aux_heat_set_service(service):
"""Set auxillary heater on target hvacs."""
target_hvacs = component.extract_from_service(service)
aux_heat = service.data.get(ATTR_AUX_HEAT)
if aux_heat is None:
_LOGGER.error(
"Received call to %s without attribute %s",
SERVICE_SET_AUX_HEAT, ATTR_AUX_HEAT)
return
for hvac in target_hvacs:
if aux_heat:
hvac.turn_aux_heat_on()
else:
hvac.turn_aux_heat_off()
if hvac.should_poll:
hvac.update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_SET_AUX_HEAT, aux_heat_set_service,
descriptions.get(SERVICE_SET_AUX_HEAT))
def temperature_set_service(service):
"""Set temperature on the target hvacs."""
target_hvacs = component.extract_from_service(service)
temperature = util.convert(
service.data.get(ATTR_TEMPERATURE), float)
if temperature is None:
_LOGGER.error(
"Received call to %s without attribute %s",
SERVICE_SET_TEMPERATURE, ATTR_TEMPERATURE)
return
for hvac in target_hvacs:
hvac.set_temperature(convert(
temperature, hass.config.temperature_unit,
hvac.unit_of_measurement))
if hvac.should_poll:
hvac.update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_SET_TEMPERATURE, temperature_set_service,
descriptions.get(SERVICE_SET_TEMPERATURE))
def humidity_set_service(service):
"""Set humidity on the target hvacs."""
target_hvacs = component.extract_from_service(service)
humidity = service.data.get(ATTR_HUMIDITY)
if humidity is None:
_LOGGER.error(
"Received call to %s without attribute %s",
SERVICE_SET_HUMIDITY, ATTR_HUMIDITY)
return
for hvac in target_hvacs:
hvac.set_humidity(humidity)
if hvac.should_poll:
hvac.update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_SET_HUMIDITY, humidity_set_service,
descriptions.get(SERVICE_SET_HUMIDITY))
def fan_mode_set_service(service):
"""Set fan mode on target hvacs."""
target_hvacs = component.extract_from_service(service)
fan = service.data.get(ATTR_FAN_MODE)
if fan is None:
_LOGGER.error(
"Received call to %s without attribute %s",
SERVICE_SET_FAN_MODE, ATTR_FAN_MODE)
return
for hvac in target_hvacs:
hvac.set_fan_mode(fan)
if hvac.should_poll:
hvac.update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_SET_FAN_MODE, fan_mode_set_service,
descriptions.get(SERVICE_SET_FAN_MODE))
def operation_set_service(service):
"""Set operating mode on the target hvacs."""
target_hvacs = component.extract_from_service(service)
operation_mode = service.data.get(ATTR_OPERATION_MODE)
if operation_mode is None:
_LOGGER.error(
"Received call to %s without attribute %s",
SERVICE_SET_OPERATION_MODE, ATTR_OPERATION_MODE)
|
google/pymql | emql/adapters/search.py | Python | apache-2.0 | 5,119 | 0.001563 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed 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.
from itertools import izip, chain
from mw.emql.adapter import Adapter
from mw.emql.emql import id_guid, formatted_id_guid, MQL_LIMIT
class search_adapter(Adapter):
def pre(self, tid, graph, mql, me, control, parent, params, api_keys):
constraints = params.get('constraints')
params = params.get('query')
if params is None:
if constraints is not None:
for operator, _params in constraints:
if operator == '~=':
params = _params
break
if isinstance(params, dict) and params.get('query') is None:
if constraints is not None:
for operator, _params in constraints:
if operator == '~=':
params['query'] = _params
break
if isinstance(params, list):
if params:
params = params[0]
else:
params = None
if isinstance(params, (str, unicode)):
params = { 'query': params }
elif params is None or params.get('query') is None:
raise ValueError, 'no query'
args = {}
result = {}
for arg, value in params.iteritems():
if arg.endswith('|='):
name = str(arg[:-2])
else:
name = str(arg)
if name in ('query', 'prefix', 'prefixed',
'type', 'type_strict', 'domain', 'domain_strict',
'type_exclude', 'type_exclude_strict',
'domain_exclude', 'domain_exclude_strict',
'limit', 'denylist', 'related', 'property',
'mql_filter', 'geo_filter', 'as_of_time', 'timeout'):
args[name] = value
elif name != 'score':
result[name] = value
for arg, value in parent.iteritems():
if arg.endswith('|='):
name = str(arg[:-2])
else:
name = str(arg)
if name not in args:
if name == 'limit':
args[name] = value
elif name == 'type' and isinstance(value, basestring):
args['type_strict'] = 'any'
| args[name] = value
if 'limit' not in args:
args['limit'] = MQL_LIMIT # plug-in default MQL limit
if 'score' in params:
matches = me.get_session().relevance_query(tid, format='ac', **args)
guids = ['#' + match['guid'] for match in matches]
else | :
matches = me.get_session().relevance_query(tid, format='guids', **args)
guids = ['#' + guid for guid in matches]
if guids:
result['guid|='] = guids
else:
result['guid|='] = ['#00000000000000000000000000000000']
if 'score' in params:
result[':extras'] = {
"fetch-data": dict((match['guid'], match['score'])
for match in matches)
}
return result
def fetch(self, tid, graph, mql, me, control, args, params, api_keys):
constraints = params.get('constraints')
scores = params.get(':extras', {}).get('fetch-data')
params = params.get('query')
was_list = False
if isinstance(params, list):
if params:
params = params[0]
was_list = True
else:
params = None
if params is None:
if constraints is not None:
for operator, _params in constraints:
if operator == '~=':
params = _params
break
if isinstance(params, (str, unicode)):
results = dict((mqlres['guid'], params) for mqlres in args)
else:
if scores is not None:
for mqlres in args:
mqlres['score'] = scores[mqlres['guid'][1:]]
if 'guid' in params:
fn = dict.get
else:
fn = dict.pop
results = {}
for mqlres in args:
mqlres['query'] = params['query']
results[fn(mqlres, 'guid')] = [mqlres] if was_list else mqlres
return results
def help(self, tid, graph, mql, me, control, params):
from docs import search_adapter_help
return 'text/x-rst;', search_adapter_help
|
SkiftCreative/docker-gunicorn-examples | flask/app/app.py | Python | mit | 319 | 0 | from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return 'Flask is running on gunicorn!'
@app.route('/data')
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
ret | urn jsonify(data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port | =5000)
|
ClearCorp-dev/odoo-costa-rica | l10n_cr_hr_ins_csv_generator/__openerp__.py | Python | agpl-3.0 | 1,898 | 0.007376 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GN | U Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
######################################## | ######################################
{
"name" : 'Costa Rica INS csv Generator',
"version" : '1.0',
"author" : 'ClearCorp',
'complexity': 'normal',
"description": """
Module build for the generation of custom files to upload information to the INS systems
""",
"category": 'Human Resources',
"sequence": 4,
"website" : "http://clearcorp.co.cr",
"images" : [],
"icon" : False,
"depends" : [
'hr_payroll',
],
"data" : [
'wizard/l10n_cr_hr_ins_csv_generator_wizard_view.xml',
'wizard/l10n_cr_hr_ins_csv_generator_wizard_menu.xml',
'view/l10n_cr_hr_ins_csv_generator_view.xml',
],
"init_xml" : [],
"demo_xml" : [],
"update_xml" : [],
"test" : [],
"auto_install": False,
"application": False,
"installable": True,
'license': 'AGPL-3',
} |
rmyers/dtrove | dtrove/views.py | Python | mit | 3,803 | 0 |
import json
import logging
import uuid
from django.core.cache import caches
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
CACHE = caches['default']
LOG = logging.getLogger()
SERVICE_CATALOG = {
"access": {
"serviceCatalog": [
{
"endpoints": [
{
"publicURL": "http://localhost:8000/osnova/",
"region": "IAD",
"tenantId": "12345",
},
],
"name": "cloudServersOpenStack",
"type": "compute"
}
],
"token": {
"expires": "2012-04-13T13:15:00.000-05:00",
"id": "aaaaa-bbbbb-ccccc-dddd"
},
"user": {
"RAX-AUTH:defaultRegion": "DFW",
"id": "161418",
"name": "demoauthor",
"roles": [
{
"description": "User Admin Role.",
"id": "3",
"name": "identity:user-admin"
}
]
}
}
}
KEYPAIR = {
"keypair": {
"fingerprint": "1e:2c:9b:56:79:4b:45:77:f9:ca:7a:98:2c:b0:d5:3c",
"name": "keypair-dab428fe-6186-4a14-b3de-92131f76cd39",
"public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQsdHw== FAKE",
"user_id": "fake"
}
}
@csrf_exempt
def fake_os_auth(request, path):
LOG.error(request.POST)
return HttpResponse(json.dumps(SERVICE_CATALOG),
content_type="application/json")
@csrf_exempt
def fake_os_nova(request, path):
if 'keypair' in path:
return HttpResponse(json.dumps(KEYPAIR),
content_type="application/json")
if 'servers' in path:
if request.method == 'POST':
server_id = str(uuid.uuid4())
server = {
"server": {
"security_groups": | [],
"OS-DCF:diskConfig": "MANUAL",
"id": ser | ver_id,
"links": [],
"adminPass": "aabbccddeeff"
}
}
return HttpResponse(json.dumps(server),
content_type="application/json")
elif request.method == 'GET':
_, server_id = path.split('/')
key = 'fake_server:%s' % server_id
# Make it appear to be building
progress = CACHE.get(key, 0)
if progress == 0:
CACHE.set(key, 0)
if progress < 100:
progress = CACHE.incr(key, 10)
status = 'BUILD'
else:
progress = 100
status = 'ACTIVE'
server = {
"server": {
"accessIPv4": "10.0.0.3",
"addresses": {},
"created": "2012-08-20T21:11:09Z",
"flavor": {
"id": "1",
"links": []
},
"hostId": "36",
"id": server_id,
"image": {
"id": "70a599e0-31e7-49b7-b260-868f441e862b",
"links": []
},
"links": [],
"metadata": {},
"name": "new-server-test",
"progress": progress,
"status": status,
"tenant_id": "openstack",
"updated": "2012-08-20T21:11:09Z",
"user_id": "fake"
}
}
return HttpResponse(json.dumps(server),
content_type="application/json")
|
jpmunic/udest | watson_examples/personality_insights_v3.py | Python | mit | 669 | 0.001495 | import | json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV3
"""
The example returns a JSON response whose content is the same as that in
../resource | s/personality-v3-expect2.txt
"""
personality_insights = PersonalityInsightsV3(
version='2016-10-20',
username='YOUR SERVICE USERNAME',
password='YOUR SERVICE PASSWORD')
with open(join(dirname(__file__), '../resources/personality-v3.json')) as profile_json:
profile = personality_insights.profile(
profile_json.read(), content_type='application/json',
raw_scores=True, consumption_preferences=True)
print(json.dumps(profile, indent=2))
|
lotube/lotube | lotube/users/views_api_xml.py | Python | mit | 223 | 0 | from core.mixins import XMLFromJSONView
from .view | s_api_json import UserListJSON, UserDetailJSON
class UserListXML(XMLFromJSONView, UserListJSON):
pass
class UserDetailXML(XMLFromJSONView, UserDetailJSON):
| pass
|
gpotter2/scapy | scapy/contrib/automotive/scanner/executor.py | Python | gpl-2.0 | 12,631 | 0 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Nils Weiss <nils@we155.de>
# This program is published under a GPLv2 license
# scapy.contrib.description = AutomotiveTestCaseExecutor base class
# scapy.contrib.status = library
import abc
import time
from itertools import product
from scapy.compat import Any, Union, List, Optional, \
Dict, Callable, Type
from scapy.contrib.automotive.scanner.graph import Graph
from scapy.error import Scapy_Exception, log_interactive
from scapy.utils import make_lined_table, SingleConversationSocket
import scapy.modules.six as six
from scapy.contrib.automotive.ecu import EcuState, EcuResponse, Ecu
from scapy.contrib.automotive.scanner.configuration import \
AutomotiveTestCaseExecutorConfiguration
from scapy.contrib.automotive.scanner.test_case import AutomotiveTestCaseABC, \
_SocketUnion, _CleanupCallable, StateGenerator, TestCaseGenerator
@six.add_metaclass(abc.ABCMeta)
class AutomotiveTestCaseExecutor:
"""
Base class for different automotive scanners. This class handles
the connection to a scan target, ensures the execution of all it's
test cases, and stores the system state machine
"""
@property
def __initial_ecu_state(self):
# type: () -> EcuState
return EcuState(session=1)
def __init__(
self,
socket, # type: _SocketUnion
reset_handler=None, # type: Optional[Callable[[], None]]
reconnect_handler=None, # type: Optional[Callable[[], _SocketUnion]] # noqa: E501
test_cases=None, # type: Optional[List[Union[AutomotiveTestCaseABC, Type[AutomotiveTestCaseABC]]]] # noqa: E501
**kwargs # type: Optional[Dict[str, Any]]
): # type: (...) -> None
# The TesterPresentSender can interfere with a test_case, since a
# target may only allow one request at a time.
# The SingleConversationSocket prevents interleaving requests.
if not isinstance(socket, SingleConversationSocket):
self.socket = SingleConversationSocket(socket)
else:
self.socket = socket
self.target_state = self.__initial_ecu_state
self.reset_handler = reset_handler
self.reconnect_handler = reconnect_handler
self.cleanup_functions = list() # type: List[_CleanupCallable]
self.configuration = AutomotiveTestCaseExecutorConfiguration(
test_cases or self.default_test_case_clss, **kwargs)
self.configuration.state_graph.add_edge(
(self.__initial_ecu_state, self.__initial_ecu_state))
def __reduce__(self): # type: ignore
f, t, d = super(AutomotiveTestCaseExecutor, self).__reduce__() # type: ignore # noqa: E501
try:
del d["socket"]
except KeyError:
pass
try:
del d["reset_handler"]
except KeyError:
pass
try:
del d["reconnect_handler"]
except KeyError:
pass
return f, t, d
@property
@abc.abstractmethod
def default_test_case_clss(self):
# type: () -> List[Type[AutomotiveTestCaseABC]]
raise NotImplementedError()
@property
def state_graph(self):
# type: () -> Graph
return self.configuration.state_graph
@property
def state_paths(self):
# type: () -> List[List[EcuState]]
"""
Returns all state paths. A path is represented by a list of EcuState
objects.
:return: A list of paths.
"""
paths = [Graph.dijkstra(self.state_graph, self.__initial_ecu_state, s)
for s in self.state_graph.nodes
if s != self.__initial_ecu_state]
return sorted(
[p for p in paths if p is not None] + [[self.__initial_ecu_state]],
key=lambda x: x[-1])
@property
def final_states(self):
# type: () -> List[EcuState]
"""
Returns a list with all final states. A final state is the last
state of a path.
:return:
"""
return [p[-1] for p in self.state_paths]
@property
def scan_completed(self):
# type: () -> bool
return all(t.has_completed(s) for t, s in
product(self.configuration.test_cases, self.final_states))
def reset_target(self):
# type: () -> None
log_interactive.info("[i] Target reset")
if self.reset_handler:
self.reset_handler()
self.target_state = self.__initial_ecu_state
def reconnect(self):
# type: () -> None
if self.reconnect_handler:
try:
self.socket.close()
except Exception as e:
log_interactive.debug(
"[i] Exception '%s' during socket.close", e)
log_interactive.info("[i] Target reconnect")
socket = self.reconnect_handler()
if not isinstance(socket, SingleConversationSocket):
self.socket = SingleConversationSocket(socket)
else:
self.socket = socket
def execute_test_case(self, test_case):
# type: (AutomotiveTestCaseABC) -> None
"""
This function ensures the correct execution of a testcase, including
the pre_execute, execute and post_execute.
Finally the testcase is asked if a new edge or a new testcase was
generated.
:param test_case: A test case to be executed
:return: None
"""
test_case.pre_execute(
self.socket, self.target_state, self.configuration)
try:
test_case_kwargs = self.configuration[test_case.__class__.__name__]
except KeyError:
test_case_kwargs = dict()
log_interactive.debug("[i] Execute test_case %s with args %s",
test_case.__class__.__name__, test_case_kwargs)
test_case.execute(self.socket, self.target_state, **test_case_kwargs)
test_case.post_execute(
self.socket, self.target_state, self.configuration)
if isinstance(test_case, StateGenerator):
edge = test_case.get_new_edge(self.socket, self.configuration)
if edge:
log_interactive.debug("Edge found %s", edge)
tf = test_case.get_transition_function(self.socket, edge)
se | lf.stat | e_graph.add_edge(edge, tf)
if isinstance(test_case, TestCaseGenerator):
new_test_case = test_case.get_generated_test_case()
if new_test_case:
log_interactive.debug("Testcase generated %s", new_test_case)
self.configuration.add_test_case(new_test_case)
def scan(self, timeout=None):
# type: (Optional[int]) -> None
"""
Executes all testcases for a given time.
:param timeout: Time for execution.
:return: None
"""
kill_time = time.time() + (timeout or 0xffffffff)
while kill_time > time.time():
test_case_executed = False
log_interactive.debug("[i] Scan paths %s", self.state_paths)
for p, test_case in product(
self.state_paths, self.configuration.test_cases):
log_interactive.info("[i] Scan path %s", p)
terminate = kill_time < time.time()
if terminate:
log_interactive.debug(
"[-] Execution time exceeded. Terminating scan!")
break
final_state = p[-1]
if test_case.has_completed(final_state):
log_interactive.debug("[+] State %s for %s completed",
repr(final_state), test_case)
continue
try:
if not self.enter_state_path(p):
log_interactive.error(
"[-] Error entering path %s", p)
continue
log_interactive.info(
"[i] Execute %s for p |
dennyreiter/pypints | taps/forms.py | Python | gpl-3.0 | 1,775 | 0.006761 | from django import forms
from django.db.models import Q
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Button, Submit, MultiField
from crispy_forms.bootstrap import FormActions, InlineRadios
#from beers.models import Beer
from .models import Tap
from kegs.models import Keg
from beers.models import Beer
class TapListForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TapListForm, self).__init__(*args, **kwargs)
#self.fields['keg'].queryset = Keg.objects.exclude(kegstatus__in=('SERVING','NEEDS_PARTS','NEEDS_REPAIRS','NEEDS_CLEANING'))
self.fields['keg'].queryset = Keg.objects.fil | ter(Q(active=True),
Q(pk=self.instance.keg_id) | ~Q(kegstatus__in=('SERVING',' | NEEDS_PARTS','NEEDS_REPAIRS','NEEDS_CLEANING'))
)
self.fields['beer'].queryset = Beer.objects.filter(active=True)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-6'
self.helper.layout = Layout(
Field('number', readonly="readonly"),
Field('active',),
InlineRadios('tap_type'),
Field('beer',),
Field('keg',),
MultiField("Gravities",
Field('og_actual',),
Field('fg_actual',),
),
Field('srm_actual',),
Field('ibu_actual',),
FormActions(
Submit('save', 'Save changes'),
Button('cancel', 'Cancel'),
)
)
class Meta:
model = Tap
|
magfest/ubersystem | alembic/versions/771555241255_initial_migration.py | Python | agpl-3.0 | 3,407 | 0.012328 | """Initial migration
Revision ID: 771555241255
Revises: 73b22ccbe472
Create Date: 2017-04-24 09:15:59.549855
"""
# revision identifiers, used by Alembic.
revision = '771555241255'
down_revision = '73b22ccbe472'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
import residue
try:
is_sqlite = op.get_context().dialect.name == 'sqlite'
except:
is_sqlite = False
if is_sqlite:
op.get_context().connection.execute('PRAGMA foreign_keys=ON;')
utcnow_server_default = "(datetime('now', 'utc'))"
else:
utcnow_server_default = "timezone('utc', current_timestamp)"
def sqlite_column_reflect_listener(inspector, table, column_info):
"""Adds parenthesis around SQLite datetime defaults for utcnow."""
if column_info['default'] == "datetime('now', 'utc')":
column_info['default'] = utcnow_server_default
sqlite_reflect_kwargs = {
'listeners': [('column_reflect', sqlite_column_reflect_listener)]
}
def upgrade():
op.create_table('room',
sa.Column('id', residue.UUID(), nullable=False),
sa.Column('notes', sa.Unicode(), server_default='', nullable=False),
sa.Column('message', sa.Unicode(), server_default='', nullable=False),
sa.Column('locked_in', sa.Boolean(), server_default='False', nullable=False),
sa.Column('nights', sa.Unicode(), server_default='', nullable=False),
sa.Column('created', residue.UTCDateTime(), server_default=sa.text(utcnow_server_default), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_room'))
)
op.create_table('hotel_requests',
sa.Column('id', residue.UUID(), nullable=False),
sa.Column('attendee_id', residue.UUID(), nullable=False),
sa.Column('nights', sa.Unicode(), server_default='', nullable=False),
sa.Column('wanted_roommates', sa.Unicode(), server_default='', nullable=False),
sa.Column('unwanted_roommates', sa.Unicode(), server_default='', nullable=False),
sa.Column('special_needs', sa.Unicode(), server_default='', nullable=False),
sa.Column('approved', sa.Boolean(), server_default='False', nullable=False),
sa.ForeignKeyConstraint(['attendee_id'], ['attendee.id'], name=op.f('fk_hotel_ | requests_attendee_id_attendee')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_hotel_requests')),
sa.UniqueConstraint('attendee_id', name=op.f('uq_hotel_requests_attendee_id'))
)
op.create_table('room_assignment',
sa.Column('id', residue.UUID(), nullable=False),
sa.Column('room_id', residue.UUID(), nullable=False),
sa.Column('attendee_id', residue.UUID(), nullable=False),
sa.ForeignKeyConstraint(['attendee_id'], ['attendee.id'], name=op.f('fk_room_ass | ignment_attendee_id_attendee')),
sa.ForeignKeyConstraint(['room_id'], ['room.id'], name=op.f('fk_room_assignment_room_id_room')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_room_assignment'))
)
if is_sqlite:
with op.batch_alter_table('attendee', reflect_kwargs=sqlite_reflect_kwargs) as batch_op:
batch_op.add_column(sa.Column('hotel_eligible', sa.Boolean(), server_default='False', nullable=False))
else:
op.add_column('attendee', sa.Column('hotel_eligible', sa.Boolean(), server_default='False', nullable=False))
def downgrade():
op.drop_column('attendee', 'hotel_eligible')
op.drop_table('room_assignment')
op.drop_table('hotel_requests')
op.drop_table('room')
|
bane138/nonhumanuser | nonhumanuser/admin.py | Python | mit | 103 | 0.019417 | admin.a | utodiscover()
flatpages.register()
urlpatterns += [ url(r'^admin/', include(admin.site. | urls)), ] |
ty-a/pytybot | tybot.py | Python | gpl-3.0 | 15,523 | 0.051601 | ##########################################################################
# PyTyBot - A MediaWiki wrapper for use on wikis.
# Copyright (C) 2012 TyA <tya.wiki@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT 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, see <http://www.gnu.org/licenses/>.
##########################################################################
import json
import requests
class tybot(object):
def __init__(self,username,password,wiki):
self.username = username
self.password = password
self.wiki = wiki
self.session = requests.Session()
self.session.headers.update({"User-Agent": 'compressbot by @tya. Contact on Slack for issues/concerns.'})
self.login(self.username,self.password)
self.tokens = self.getTokens()
def change_wiki(self, wiki):
"""
Changes the internal wiki variable to let us edit multiple wikis without
making multiple objects. Does not relogin.
:param wiki(str): The new wiki URL
:returns none:
"""
self.wiki = wiki
def postToWikiaApi(self,data):
"""
POSTS content to the Wikia API in the json format
:param data (dict): A dict of what is being posted.
:returns: The response from the API
"""
response = self.session.post(self.wiki + "/wikia.php", data=data);
response = json.loads(response.text)
return response
def postToWiki(self,data,sessionheaders=None):
"""
POSTs content to the wiki's API in json format
:param data (dict): An dict of what is being posted.
:returns: the response from the API
"""
response = self.session.post(self.wiki + "/api.php", data=data, headers=sessionheaders);
response = json.loads(response.text)
return response
def login(self,username,password):
"""
Logins into the wiki via API
:param username (str): The username of the user
:param password (str): The user's password
:returns: boolean based on success
"""
data = {
"action":"login",
"lgname":username,
"lgpassword":password,
"format":"json"
}
response = self.postToWiki(data)
logintoken = response["login"]["token"]
data = {
"action":"login",
"lgname":username,
"lgpassword":password,
"lgtoken":logintoken,
"format":"json"
}
response = self.postToWiki(data)
if response["login"]["result"] == "Sucess":
return True
else:
print(response["login"]["result"])
return False
def getGroups(self,user):
"""
Gets the usergroup a user is in
:param user (str): The user to get the string for
:returns: dict of groups
"""
data = {
"action":"query",
"list":"users",
"ususers":user,
"usprop":"groups",
"format":"json"
}
response = self.postToWiki(data)
try:
groups = tuple(response["query"]["users"][0]["groups"])
except:
groups = ('*')
return groups
def getTokens(self):
"""
Gets the tokens required to perform many actions
:param none: (uses the username provided when making tybot object)
:returns: dict of tokens
"""
groups = self.getGroups(self.username)
if "sysop" in groups:
data = {
"action":"query",
"prop":"info",
"intoken":"delete|edit|protect|block|unblock|watch",
"titles":"Main Page",
"format":"json"
}
else:
data = {
"action":"query",
"prop":"info",
"intoken":"edit|watch",
"titles":"Main Page",
"format":"json"
}
response = self.postToWiki(data)
response = list(response["query"]["pages"].values())
if "sysop" in groups:
data = {
"action":"query",
"list":"deletedrevs",
"drprop":"token",
"format":"json"
}
for intoken in response:
tokens = {
"edit":intoken["edittoken"],
"delete":intoken["deletetoken"],
"protect":intoken["protecttoken"],
"unblock":intoken["unblocktoken"],
"block":intoken["blocktoken"],
"watch":intoken["watchtoken"]
}
response = self.postToWiki(data)
response = response["query"]["deletedrevs"]
for intoken in response:
tokens["undelete"] = intoken["token"]
else:
for intoken in response:
tokens = {
"edit":intoken["edittoken"],
"watch":intoken["watchtoken"]
}
return tokens
def get_page_content(self,page):
"""
Gets the current content of a page on the wiki.
:param page (str): The page to get the content of.
:returns: string with the page content or '' if page does not exist
"""
data = {
"action":"query",
"prop":"revisions",
"rvprop":"content",
"titles":page,
"format":"json"
}
response = self.postToWiki(data)
response = list(response["query"]["pages"].values())
for page in response:
try:
content = page['revisions'][0]["*"]
except:
content = ""
return content
def edit(self,page,content,summary='',bot=1):
"""
Makes the actual edit to the page
:param page (str): The page to edit
:param content (str): What to put on the page
:param summary (str): The edit summary (Default: '')
:param bot (bool): Mark the edit as a bot or not (Default: 1)
:returns: boolean based on success
"""
data = {
"action":"edit",
"title":page,
"summary":summary,
"text":content,
"bot":bot,
"token":self.tokens["edit"],
"format":"json"
}
response = self.postToWiki(data)
try:
print(response["error"]["info"])
return False
except:
return True
def delete(self,page, summary=''):
"""
Deletes pages via the API
:param page (str): The page to delete
:param summary (str): The deletion summary (Default:'')
:returns: boolean based on success
"""
data = {
"action":"delete",
"token":self.tokens["delete"],
"title":page,
"summary":summary,
"format":"json"
}
response = self.postToWiki(data)
try:
print(response["error"]["info"])
return False
except:
return True
def undelete(self,page,summary=''):
"""
Undeletes pages via the API
:param page (str): The page to undelete
:param summary (str): The undeletin summary (Default: '')
:returns: boolean based on success
"""
data = {
"action":"undelete",
"title":page,
"reason":summary,
| "format":"json",
"token":self.tokens["undelete"]
}
response = self.postToWiki(data)
try:
print(response["error"]["code"])
return False
except:
return True
def block(self,target,summary='',expiry="infinite"):
"""
| Blocks users via the API
:param target (str): The user to block
:param summary (str): The block summary
:param expiry (str): Expiry timestamp or relative time. (Default: infinite)
:returns: boolean based on success
"""
data = {
"action":"block",
"user":target,
"reason":summary,
"expiry":expiry,
"token":self.tokens["block"],
"format":"json"
}
response = self.postToWiki(data)
try:
print(response["error"]["code"])
return False
except:
return True
def unblock(self,target,summary=''):
"""
Unblocks users via the API
:param target (str): The user to unblock
:param reason (str): The unblock reason
:returns: boolean based on success
"""
data = {
"action":"unblock",
"user":target,
"reason":summary,
"token":self.tokens["unblock"],
"format":"json"
}
response = self.postToWiki(data)
try:
print(response["error"]["code"])
return False
except:
return True
def get_category_members(self,category,limit="max"):
"""
Get members of a category
:param category (str): The category to get pages from (Add Category: prefix!)
:param limit (int): How many pages to get back. (Default "max - 500 for normal users, 5000 for users with APIhighlimits)
:returns: list of page titles
"""
cmcontinue = ''
pages = []
if limit != "max":
data = {
"acti |
willemneal/Docky | lib/pygments/tests/test_cmdline.py | Python | mit | 8,892 | 0.000337 | # -*- coding: utf-8 -*-
"""
Command line test
~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import print_function
import io
import os
import re
import sys
import tempfile
import unittest
import support
from pygments import cmdline, highlight
from pygments.util import BytesIO, StringIO
TESTFILE, TESTDIR = support.location(__file__)
TESTCODE = '''\
def func(args):
pass
'''
def run_cmdline(*args, **kwds):
saved_stdin = sys.stdin
saved_stdout = sys.stdout
saved_stderr = sys.stderr
if sys.version_info > (3,):
stdin_buffer = BytesIO()
stdout_buffer = BytesIO()
stderr_buffer = BytesIO()
new_stdin = sys.stdin = io.TextIOWrapper(stdin_buffer, 'utf-8')
new_stdout = sys.stdout = io.TextIOWrapper(stdout_buffer, 'utf-8')
new_stderr = sys.stderr = io.TextIOWrapper(stderr_buffer, 'utf-8')
else:
stdin_buffer = new_stdin = sys.stdin = StringIO()
stdout_buffer = new_stdout = sys.stdout = StringIO()
stderr_buffer = new_stderr = sys.stderr = StringIO()
new_stdin.write(kwds.get('stdin', ''))
new_stdin.seek(0, 0)
try:
ret = cmdline.main(['pygmentize'] + list(args))
finally:
sys.stdin = saved_stdin
sys.stdout = saved_stdout
sys.stderr = saved_stderr
new_stdout.flush()
new_stderr.flush()
out, err = stdout_buffer.getvalue().decode('utf-8'), \
stderr_buffer.getvalue().decode('utf-8')
return (ret, out, err)
class CmdLineTest(unittest.TestCase):
def check_success(self, *cmdline, **kwds):
code, out, err = run_cmdline(*cmdline, **kwds)
self.assertEqual(code, 0)
self.assertEqual(err, '')
return out
def check_failure(self, *cmdline, **kwds):
expected_code = kwds.pop('code', 1)
code, out, err = run_cmdline(*cmdline, **kwds)
self.assertEqual(code, expected_code)
self.assertEqual(out, '')
return err
def test_normal(self):
# test that cmdline gives the same output as library api
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
filename = TESTFILE
with open(filename, 'rb') as fp:
code = fp.read()
output = highlight(code, PythonLexer(), HtmlFormatter())
o = self.check_success('-lpython', '-fhtml', filename)
self.assertEqual(o, output)
def test_stdin(self):
o = self.check_success('-lpython', '-fhtml', stdin=TESTCODE)
o = re.sub('<[^>]*>', '', o)
# rstrip is necessary since HTML inserts a \n after the last </div>
self.assertEqual(o.rstrip(), TESTCODE.rstrip())
# guess if no lexer given
o = self.check_success('-fhtml', stdin=TESTCODE)
o = re.sub('<[^>]*>', '', o)
# rstrip is necessary since HTML inserts a \n after the last </div>
self.assertEqual(o.rstrip(), TESTCODE.rstrip())
def test_outfile(self):
# test that output file works with and without encoding
fd, name = tempfile.mkstemp()
os.close(fd)
for opts in [['-fhtml', '-o', name, TESTFILE],
['-flatex', '-o', name, TESTFILE],
['-fhtml', '-o', name, '-O', 'encoding=utf-8', TESTFILE]]:
try:
self.check_success(*opts)
finally:
os.unlink(name)
def test_stream_opt(self):
o = self.check_success('-lpython', '-s', '-fterminal', stdin=TESTCODE)
o = re.sub(r'\x1b\[.*?m', '', o)
self.assertEqual(o.replace('\r\n', '\n'), TESTCODE)
def test_h_opt(self):
o = self.check_success('-h')
self.assertTrue('Usage:' in o)
def test_L_opt(self):
o = self.check_success('-L')
self.assertTrue('Lexers' in o and 'Formatters' in o and
'Filters' in o and 'Styles' in o)
o = self.check_success('-L', 'lexer')
self.assertTrue('Lexers' in o and 'Formatters' not in o)
self.check_success('-L', 'lexers')
def test_O_opt(self):
filename = TESTFILE
o = self.check_success('-Ofull=1,linenos=true,foo=bar',
'-fhtml', filename)
self.assertTrue('<html' in o)
self.assertTrue('class="linenos"' in o)
# "foobar" is invalid for a bool option
e = self.check_failure('-Ostripnl=foobar', TESTFILE)
self.assertTrue('Error: Invalid value' in e)
e = self.check_failure('-Ostripnl=foobar', '-lpy')
self.assertTrue('Error: Invalid value' in e)
def test_P_opt(self):
filename = TESTFILE
o = self.check_success('-Pfull', '-Ptitle=foo, bar=baz=,',
'-fhtml', filename)
self.assertTrue('<titl | e>foo, bar=baz=,</title>' in o)
def test_F_opt(self):
filename = TESTFILE
o = self.check_success('-Fhighlight:tokentype=Name.Blubb,'
| 'names=TESTFILE filename',
'-fhtml', filename)
self.assertTrue('<span class="n-Blubb' in o)
def test_H_opt(self):
o = self.check_success('-H', 'formatter', 'html')
self.assertTrue('HTML' in o)
o = self.check_success('-H', 'lexer', 'python')
self.assertTrue('Python' in o)
o = self.check_success('-H', 'filter', 'raiseonerror')
self.assertTrue('raiseonerror', o)
e = self.check_failure('-H', 'lexer', 'foobar')
self.assertTrue('not found' in e)
def test_S_opt(self):
o = self.check_success('-S', 'default', '-f', 'html', '-O', 'linenos=1')
lines = o.splitlines()
for line in lines:
# every line is for a token class
parts = line.split()
self.assertTrue(parts[0].startswith('.'))
self.assertTrue(parts[1] == '{')
if parts[0] != '.hll':
self.assertTrue(parts[-4] == '}')
self.assertTrue(parts[-3] == '/*')
self.assertTrue(parts[-1] == '*/')
self.check_failure('-S', 'default', '-f', 'foobar')
def test_N_opt(self):
o = self.check_success('-N', 'test.py')
self.assertEqual('python', o.strip())
o = self.check_success('-N', 'test.unknown')
self.assertEqual('text', o.strip())
def test_invalid_opts(self):
for opts in [
('-X',),
('-L', '-lpy'),
('-L', '-fhtml'),
('-L', '-Ox'),
('-S', 'default', '-l', 'py', '-f', 'html'),
('-S', 'default'),
('-a', 'arg'),
('-H',),
(TESTFILE, TESTFILE),
('-H', 'formatter'),
('-H', 'foo', 'bar'),
('-s',),
('-s', TESTFILE),
]:
self.check_failure(*opts, code=2)
def test_errors(self):
# input file not found
e = self.check_failure('-lpython', 'nonexistent.py')
self.assertTrue('Error: cannot read infile' in e)
self.assertTrue('nonexistent.py' in e)
# lexer not found
e = self.check_failure('-lfooo', TESTFILE)
self.assertTrue('Error: no lexer for alias' in e)
# formatter not found
e = self.check_failure('-lpython', '-ffoo', TESTFILE)
self.assertTrue('Error: no formatter found for name' in e)
# formatter for outfile not found
e = self.check_failure('-ofoo.foo', TESTFILE)
self.assertTrue('Error: no formatter found for file name' in e)
# output file not writable
e = self.check_failure('-o', os.path.join('nonexistent', 'dir', 'out.html'),
'-lpython', TESTFILE)
self.assertTrue('Error: cannot open outfile' in e)
self.assertTrue('out.html' in e)
# unknown filter
e = self.check_failure('-F', 'foo', TESTFILE)
self.assertTrue('Error: filter \'foo\' not found' in e)
def test_exception(self):
cmdline.highlight = None # override callable to provoke TypeError
try:
|
nyuphys/DataMaster | example/lab.py | Python | mit | 2,511 | 0.008761 | # -*- coding: utf-8 -*-
#############################################################
# 1. Imports
#############################################################
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#############################################################
# 2. General Functions
#############################################################
def lsq(x, y):
assert len(x) == len(y), 'Array dimensions do not match'
n = float(len(x)) # Don't lose precision with int * float multiplication
# compute covariance matrix and correlation coefficient of data
cov = np.cov(x, y)
varx = cov[0][0]
vary = cov[1][1]
sxy = cov[0][1]
r = sxy / (np.sqrt(vary) * np.sqrt(varx))
# lambda expression for a line
# dummy parameter array of [1, 1]
f = lambda x, *p: p[0]*x + p[1]
pars = [1, 1]
pvals, pcov = curve_fit(f, x, y, p0=pars)
m, b = pvals
sm = np.sqrt(pcov[0, 0])
sb = np.sqrt(pcov[1, 1])
sy = np.sqrt(vary)
# y = mx + b; r is correlation
return m, b, sy, sm, sb, r
#############################################################
# 3. Data & Globals
#############################################################
current = np.array([5.372, 10.024, 14.975, 20.482, 24.878, 30.105]) * 1e-3 # mA
voltage = np.array([0.503, 1.043, 1.526, 2.034, 2.521, 3.018]) # V
# The multimeter tends to have a variable uncertainty, so these arrays is needed
dI = np.array([0.001, 0.002, 0.002, 0.001, 0.001, 0.003]) * 1e-3
dV = np.array([0.002, 0.001, 0.003, 0.001, 0.001, 0.002])
#############################################################
# 4. Lab-Specific Functions
#############################################################
def plot_line():
# Least-squares linear regression for y = mx + b
m, b, sy, sm, sb, r = lsq(current * 1e3, voltage) # We want to plot in mA
# You will NEED to call this for each plot so that you don't have multiple plots
# overlaid on each other
plt.figure()
# Range upon which we want to plot the line
| x = np.linspace(5, 31, 1000)
plt.plot(x, m*x + b, 'c--')
plt.errorbar(x=(current * 1e3), y=voltage, xerr=(dI * 1e3), yerr=dV, fmt='r.', ecolor='k', a | lpha=0.5)
plt.xlabel('Current ($mA$)')
plt.ylabel('Voltage ($V$)')
def get_resistance():
m, b, sy, sm, sb, r = lsq(current, voltage)
# Resistance is the slope m; its uncertainty sm is already computed by lsq()
return (m, sm)
|
maxpumperla/elephas | tests/mllib/test_adapter.py | Python | mit | 570 | 0 | import numpy as np
from elephas.mllib.adapter import *
from pyspark.mllib.linalg import Matrices, Vectors
def test_to_matrix():
x = np.ones((4, 2))
mat = to_matrix(x)
assert mat.numRows == 4
assert mat.numCols == 2
def test_from_matrix():
mat = M | atrices.dense(1, 2, [13, 37])
x = from_matrix(mat)
assert x.shape == (1, 2)
| def test_from_vector():
x = np.ones((3,))
vector = to_vector(x)
assert len(vector) == 3
def test_to_vector():
vector = Vectors.dense([4, 2])
x = from_vector(vector)
assert x.shape == (2,)
|
lafranceinsoumise/api-django | agir/api/test_runner.py | Python | agpl-3.0 | 1,140 | 0 | import shutil
import tempfile
from django.test import override_settings
from django.test.runner import DiscoverRunner
from .celery import app
class TempMediaMixin(object):
"Mixin to create MEDIA_ROOT in temp and tear down when complete."
def setup_test_environment(self):
"Create temp directory and update MEDIA_ROOT and default storage."
super(TempMediaMixin, self).setup_test_environment()
self._temp_media = tempfile.mkdtemp( | )
self.media_settings_overrider = override_settings(
MEDIA_ROOT=self._temp_media,
DEFAULT_FILE_STORAGE="django.core.files.storage.FileSystemS | torage",
)
self.media_settings_overrider.enable()
def teardown_test_environment(self):
"Delete temp storage."
super(TempMediaMixin, self).teardown_test_environment()
shutil.rmtree(self._temp_media, ignore_errors=True)
self.media_settings_overrider.disable()
class TestRunner(TempMediaMixin, DiscoverRunner):
def setup_test_environment(self, **kwargs):
super().setup_test_environment(**kwargs)
app.conf.task_always_eager = True
|
proevo/pythondotorg | nominations/forms.py | Python | apache-2.0 | 1,948 | 0.002567 | from django import forms
from django.utils.safestring import mark_safe
from markupfield.widgets import MarkupTextarea
from .models import Nomination
class NominationForm(forms.ModelForm):
class Meta:
| model = Nomination
fields = (
"name",
"email",
"previous_board_service",
"employer",
"other_affiliations",
"nomination_statement",
)
widgets = {
"nomination_statement": MarkupTextarea()
} # , "self_nomination": forms.CheckboxInput()}
| help_texts = {
"name": "Name of the person you are nominating.",
"email": "Email address for the person you are nominating.",
"previous_board_service": "Has the person previously served on the PSF Board? If so what year(s)? Otherwise 'New board member'.",
"employer": "Nominee's current employer.",
"other_affiliations": "Any other relevant affiliations the Nominee has.",
"nomination_statement": "Markdown syntax supported.",
}
class NominationCreateForm(NominationForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super(NominationCreateForm, self).__init__(*args, **kwargs)
self_nomination = forms.BooleanField(
required=False,
help_text="If you are nominating yourself, we will automatically associate the nomination with your python.org user.",
)
def clean_self_nomination(self):
data = self.cleaned_data["self_nomination"]
if data:
if not self.request.user.first_name or not self.request.user.last_name:
raise forms.ValidationError(
mark_safe(
'You must set your First and Last name in your <a href="/users/edit/">User Profile</a> to self nominate.'
)
)
return data
|
goedzo/PokemonGo-Bot | pokemongo_bot/cell_workers/heal_pokemon.py | Python | mit | 11,496 | 0.002001 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from datetime import datetime, timedelta
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot import inventory
from pokemongo_bot.item_list import Item
from pokemongo_bot.human_behaviour import sleep, action_delay
class HealPokemon(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
def __init__(self, bot, config):
super(HealPokemon, self).__init__(bot, config)
self.bot = bot
self.config = config
self.enabled = self.config.get("enabled", False)
self.revive_pokemon = self.config.get("revive", True)
self.heal_pokemon = self.config.get("heal", True)
self.next_update = None
self.to_heal = []
self.warned_about_no_revives = False
self.warned_about_no_potions = False
def work(self):
if not self.enabled:
return WorkerResult.SUCCESS
# Check for pokemon to heal or revive
to_revive = []
self.to_heal = []
pokemons = inventory.pokemons().all()
pokemons.sort(key=lambda p: p.hp)
for pokemon in pokemons:
if pokemon.hp < 1.0:
self.logger.info("Dead: %s (%s CP| %s/%s )" % (pokemon.name, pokemon.cp, pokemon.hp, pokemon.hp_max))
to_revive += [pokemon]
elif pokemon.hp < pokemon.hp_max:
self.logger.info("Heal: %s (%s CP| %s/%s )" % (pokemon.name, pokemon.cp, pokemon.hp, pokemon.hp_max))
self.to_heal += [pokemon]
if len(self.to_heal) == 0 and len(to_revive) == 0:
if self._should_print:
self.next_update = datetime.now() + timedelta(seconds=120)
#self.logger.info("No pokemon to heal or revive")
return WorkerResult.SUCCESS
# Okay, start reviving pokemons
# Check revives and potions
revives = inventory.items().get(Item.ITEM_REVIVE.value).count
max_revives = inventory.items().get(Item.ITEM_MAX_REVIVE.value).count
normal = inventory.items().get(Item.ITEM_POTION.value).count
super_p = inventory.items().get(Item.ITEM_SUPER_POTION.value).count
hyper = inventory.items().get(Item.ITEM_HYPER_POTION.value).count
max_p = inventory.items().get(Item.ITEM_MAX_POTION.value).count
self.logger.info("Healing %s pokemon" % len(self.to_heal))
self.logger.info("Reviving %s pokemon" % len(to_revive))
if self.revive_pokemon:
if len(to_revive) > 0 and revives == 0 and max_revives == 0:
if not self.warned_about_no_revives:
self.logger.info("No revives left! Can't revive %s pokemons." % len(to_revive))
self.warned_about_no_revives = True
elif len(to_revive) > 0:
self.logger.info("Reviving %s pokemon..." % len(to_revive))
self.warned_about_no_revives = False
for pokemon in to_revive:
self._revive_pokemon(pokemon)
if self.heal_pokemon:
if len(self.to_heal) > 0 and (normal + super_p + hyper + max_p) == 0:
if not self.warned_about_no_potions:
self.logger.info("No potions left! Can't heal %s pokemon" % len(self.to_heal))
self.warned_about_no_potions = True
elif len(self.to_heal) > 0:
self.logger.info("Healing %s pokemon" % len(self.to_heal))
self.warned_about_no_potions = False
for pokemon in self.to_heal:
self._heal_pokemon(pokemon)
if self._should_print:
self.next_update = datetime.now() + timedelta(seconds=120)
self.logger.info("Done healing/reviving pokemon")
def _revive_pokemon(self, pokemon):
item = Item.ITEM_REVIVE.value
amount = inventory.items().get(item).count
if amount == 0:
self.logger.info("No normal revives left, using MAX revive!")
item = Item.ITEM_MAX_REVIVE.value
amount = inventory.items().get(item).count
if amount > 0:
response_dict_revive = self.bot.api.use_item_revive(item_id=item, pokemon_id=pokemon.unique_id)
action_delay(2, 3)
if response_dict_revive:
result = response_dict_revive.get('responses', {}).get('USE_ITEM_REVIVE', {}).get('result', 0)
revive_item = inventory.items().get(item)
# Remove the revive from the iventory
revive_item.remove(1)
if result is 1: # Request success
self.emit_event(
'revived_pokemon',
formatted='Revived {name}.',
data={
| 'name': pokemon.name
}
)
if item == Item.ITEM_REVIVE.value:
pokemon.hp = int(pokemon.hp_max / 2)
| self.to_heal.append(pokemon)
else:
# Set pokemon as revived
pokemon.hp = pokemon.hp_max
return True
else:
self.emit_event(
'revived_pokemon',
level='error',
formatted='Failed to revive {name}!',
data={
'name': pokemon.name
}
)
return False
def _heal_pokemon(self, pokemon):
if pokemon.hp == 0:
self.logger.info("Can't heal a dead %s" % pokemon.name)
return False
# normal = inventory.items().get(Item.ITEM_POTION.value).count
# super_p = inventory.items().get(Item.ITEM_SUPER_POTION.value).count
# hyper = inventory.items().get(Item.ITEM_HYPER_POTION.value).count
max_p = inventory.items().get(Item.ITEM_MAX_POTION.value).count
# Figure out how much healing needs to be done.
def hp_to_restore(pokemon):
pokemon = inventory.pokemons().get_from_unique_id(pokemon.unique_id)
return pokemon.hp_max - pokemon.hp
if hp_to_restore(pokemon) > 200 and max_p > 0:
# We should use a MAX Potion
self._use_potion(Item.ITEM_MAX_POTION.value, pokemon)
pokemon.hp = pokemon.hp_max
return True
# Okay, now we see to heal as effective as possible
potions = [103, 102, 101]
heals = [200, 50, 20]
for item_id, max_heal in zip(potions, heals):
if inventory.items().get(item_id).count > 0:
while hp_to_restore(pokemon) > max_heal:
if inventory.items().get(item_id).count == 0:
break
action_delay(2, 3)
# More than 200 to restore, use a hyper first
if self._use_potion(item_id, pokemon):
pokemon.hp += max_heal
if pokemon.hp > pokemon.hp_max:
pokemon.hp = pokemon.hp_max
else:
break
# return WorkerResult.ERROR
# Now we use the least
potion_id = 101 # Normals first
while hp_to_restore(pokemon) > 0:
action_delay(2, 4)
if inventory.items().get(potion_id).count > 0:
if potion_id == 104:
self.logger.info("Using MAX potion to heal a %s" % pokemon.name)
if self._use_potion(potion_id, pokemon):
if potion_id == 104:
pokemon.hp = pokemon.hp_max
else:
pokemon.hp += heals[potion_id - 101]
if pokemon.hp > pokemon.hp_max:
pokemon.hp = pokemon.hp_max
else:
if potion_id < 104:
self.logger.info("Failed with potion %s |
nwjs/nw.js | test/sanity/issue5730-add-node-in-permissions/test.py | Python | mit | 1,183 | 0.002536 | import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
testdir = os.path.dirname(os.path.abspath(__file__))
chrome_options.add_argument('nwapp=' + testdir)
driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options)
driver.implicitly_wait(3)
try:
print driver.current_url
ret1 = ''
ret2 = ''
timeout = 10
while timeout > 0:
try:
ret2 = driver.find_element_by_id('request2').get_attribute('innerHTML')
ret1 = driver.find_element_by_id('request1').get_attribute('innerHTML')
if (ret2 != ''):
print 'show webview delayed valu | e'
prin | t ret2
print 'show request normatl value'
print ret1
break
except selenium.common.exceptions.NoSuchElementException:
pass
time.sleep(1)
timeout = timeout - 1
if timeout <= 0:
raise Exception('Timeout when waiting for element' + elem_id)
assert('onRequest' in ret2)
assert('onRequest' in ret1)
finally:
driver.quit()
|
leppa/home-assistant | homeassistant/components/axis/camera.py | Python | apache-2.0 | 3,117 | 0 | """Support for Axis camera streaming."""
from homeassistant.components.camera import SUPPORT_STREAM
from homeassistant.components.mjpeg.camera import (
CONF_MJPEG_URL,
CONF_STILL_IMAGE_URL,
MjpegCamera,
filter_urllib3_logging,
)
from homeassistant.const import (
CONF_AUTHENTICATION,
CONF_DEVICE,
CONF_HOST,
CONF_MAC,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
HTTP_DIGEST_AUTHENTICATION,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .axis_base import AxisEntityBase
from .const import DOMAIN as AXIS_DOMAIN
AXIS_IMAGE = "http://{}:{}/axis-cgi/jpg/image.cgi"
AXIS_VIDEO = "http://{}:{}/axis-cgi/mjpg/video.cgi"
AXIS_STREAM = "rtsp://{}:{}@{}/axis-media/media.amp?videocodec=h264"
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Axis camera video stream."""
filter_urllib3_logging()
serial_number = config_entry.data[CONF_MAC]
device = hass.data[AXIS_DOMAIN][serial_number]
config = {
CONF_NAME: config_entry.data[CONF_NAME],
CONF_ | USERNAME: config_entry.data[CONF_DEVICE][CONF_USERNAME],
CONF_PASSWORD: config_entry.data[CONF_DEVICE][CONF_PASSWORD],
CONF_MJPEG_URL: AXIS_VID | EO.format(
config_entry.data[CONF_DEVICE][CONF_HOST],
config_entry.data[CONF_DEVICE][CONF_PORT],
),
CONF_STILL_IMAGE_URL: AXIS_IMAGE.format(
config_entry.data[CONF_DEVICE][CONF_HOST],
config_entry.data[CONF_DEVICE][CONF_PORT],
),
CONF_AUTHENTICATION: HTTP_DIGEST_AUTHENTICATION,
}
async_add_entities([AxisCamera(config, device)])
class AxisCamera(AxisEntityBase, MjpegCamera):
"""Representation of a Axis camera."""
def __init__(self, config, device):
"""Initialize Axis Communications camera component."""
AxisEntityBase.__init__(self, device)
MjpegCamera.__init__(self, config)
async def async_added_to_hass(self):
"""Subscribe camera events."""
self.unsub_dispatcher.append(
async_dispatcher_connect(
self.hass, self.device.event_new_address, self._new_address
)
)
await super().async_added_to_hass()
@property
def supported_features(self):
"""Return supported features."""
return SUPPORT_STREAM
async def stream_source(self):
"""Return the stream source."""
return AXIS_STREAM.format(
self.device.config_entry.data[CONF_DEVICE][CONF_USERNAME],
self.device.config_entry.data[CONF_DEVICE][CONF_PASSWORD],
self.device.host,
)
def _new_address(self):
"""Set new device address for video stream."""
port = self.device.config_entry.data[CONF_DEVICE][CONF_PORT]
self._mjpeg_url = AXIS_VIDEO.format(self.device.host, port)
self._still_image_url = AXIS_IMAGE.format(self.device.host, port)
@property
def unique_id(self):
"""Return a unique identifier for this device."""
return f"{self.device.serial}-camera"
|
ISISComputingGroup/EPICS-inst_servers | BlockServer/test_modules/test_active_config_holder.py | Python | bsd-3-clause | 26,201 | 0.002901 | # This file is part of the ISIS IBEX application.
# Copyright (C) 2012-2016 Science & Technology Facilities Council.
# All rights reserved.
#
# This program is distributed in the hope that it will be useful.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v1.0 which accompanies this distribution.
# EXCEPT AS EXPRESSLY SET FORTH IN THE ECLIPSE PUBLIC LICENSE V1.0, THE PROGRAM
# AND ACCOMPANYING MATERIALS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND. See the Eclipse Public License v1.0 for more details.
#
# You should have received a copy of the Eclipse Public License v1.0
# along with this program; if not, you can obtain a copy from
# https://www.eclipse.org/org/documents/epl-v10.php or
# http://opensource.org/licenses/eclipse-1.0.php
import unittest
import json
import os
from mock import Mock
from parameterized import parameterized
from BlockServer.config.block import Block
from BlockServer.config.configuration import Configuration
from BlockServer.config.ioc import IOC
from BlockServer.core.active_config_holder import (ActiveConfigHolder, _blocks_changed, _blocks_changed_in_config,
_compare_ioc_properties)
from BlockServer.mocks.mock_ioc_control import MockIocControl
from BlockServer.core.macros import MACROS
from BlockServer.mocks.mock_file_manager import MockConfigurationFileManager
from BlockServer.test_modules.helpers import modify_active
from server_common.constants import IS_LINUX
CONFIG_PATH = "./test_configs/"
BASE_PATH = "./example_base/"
# Helper methods
def quick_block_to_json(name, pv, group, local=True):
return {
'name': name,
'pv': pv,
'group': group,
'local': local
}
def add_basic_blocks_and_iocs(config_holder):
config_holder.add_block(quick_block_to_json("TESTBLOCK1", "PV1", "GROUP1", True))
config_holder.add_block(quick_block_to_json("TESTBLOCK2", "PV2", "GROUP2", True))
config_holder.add_block(quick_block_to_json("TESTBLOCK3", "PV3", "GROUP2", True))
config_holder.add_block(quick_block_to_json("TESTBLOCK4", "PV4", "NONE", True))
config_holder._add_ioc("SIMPLE1")
config_holder._add_ioc("SIMPLE2")
def get_groups_and_blocks(jsondata):
return json.loads(jsondata)
def create_grouping(groups):
return json.dumps([{"name": group, "blocks": blocks} for group, blocks in groups.items()])
def create_dummy_component():
config = Configuration(MACROS)
config.add_block("COMPBLOCK1", "PV1", "GROUP1", True)
config.add_block("COMPBLOCK2", "PV2", "COMPGROUP", True)
config.add_ioc("COMPSIMPLE1")
config.is_component = True
return config
# Note that the ActiveConfigServerManager contains an instance of the Configuration class and hands a lot of
# work off to this object. Rather than testing whether the functionality in the configuration class works
# correctly (e.g. by checking that a block has been edited properly after calling configuration.edit_block),
# we should instead test that ActiveConfigServerManager passes the correct parameters | to the Configuration object.
# We are testing that ActiveConfigServerManager correctly interfaces with Configuration, not testing the
# functionality of Configuration, which is done in Configuration's own suite of tests.
class TestActiveConfigHolderSequence(unittest.TestCase):
def setUp(self):
# Note: All configurations are saved in memory
self.mock_arc | hive = Mock()
self.mock_archive.update_archiver = Mock()
self.mock_file_manager = MockConfigurationFileManager()
self.active_config_holder = self.create_active_config_holder()
def create_active_config_holder(self):
config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "settings")
return ActiveConfigHolder(MACROS, self.mock_archive, self.mock_file_manager, MockIocControl(""), config_dir)
def test_add_ioc(self):
config_holder = self.active_config_holder
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder._add_ioc("SIMPLE1")
config_holder._add_ioc("SIMPLE2")
iocs = config_holder.get_ioc_names()
self.assertTrue("SIMPLE1" in iocs)
self.assertTrue("SIMPLE2" in iocs)
@unittest.skipIf(IS_LINUX, "Unable to save config on Linux")
def test_save_config(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
try:
config_holder.save_active("TEST_CONFIG")
except Exception as e:
self.fail(f"test_save_config raised Exception unexpectedly: {e}")
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_load_config(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_CONFIG")
config_holder.clear_config()
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 0)
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder.load_active("TEST_CONFIG")
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 4)
self.assertTrue('TESTBLOCK1' in blocks)
self.assertTrue('TESTBLOCK2' in blocks)
self.assertTrue('TESTBLOCK3' in blocks)
self.assertTrue('TESTBLOCK4' in blocks)
iocs = config_holder.get_ioc_names()
self.assertTrue("SIMPLE1" in iocs)
self.assertTrue("SIMPLE2" in iocs)
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_GIVEN_load_config_WHEN_load_config_again_THEN_no_ioc_changes(self):
# This test is checking that a load will correctly cache the IOCs that are running so that a comparison will
# return no change
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_CONFIG")
config_holder.clear_config()
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 0)
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder.load_active("TEST_CONFIG")
config_holder.load_active("TEST_CONFIG")
iocs_to_start, iocs_to_restart, iocs_to_stop = config_holder.iocs_changed()
self.assertEqual(len(iocs_to_start), 0)
self.assertEqual(len(iocs_to_restart), 0)
self.assertEqual(len(iocs_to_stop), 0)
def test_load_notexistant_config(self):
config_holder = self.active_config_holder
self.assertRaises(IOError, lambda: config_holder.load_active("DOES_NOT_EXIST"))
def test_save_as_component(self):
config_holder = self.active_config_holder
try:
config_holder.save_active("TEST_CONFIG1", as_comp=True)
except Exception as e:
self.fail(f"test_save_as_component raised Exception unexpectedly: {e}")
@unittest.skipIf(IS_LINUX, "Unable to save config on Linux")
def test_save_config_for_component(self):
config_holder = self.active_config_holder
config_holder.save_active("TEST_CONFIG1", as_comp=True)
try:
config_holder.save_active("TEST_CONFIG1")
except Exception as e:
self.fail(f"test_save_config_for_component raised Exception unexpectedly: {e}")
def test_load_component_fails(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_COMPONENT", as_comp=True)
config_holder.clear_config()
self.assertRaises(IOError, lambda: config_holder.load_active("TEST_COMPONENT"))
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_load_last_config(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active |
QiJune/Paddle | python/paddle/fluid/tests/unittests/testsuite.py | Python | apache-2.0 | 7,265 | 0.000275 | # Copyright (c) 2018 PaddlePaddle 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 law or | agreed to in writing, software
# distributed under the License is distributed 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.
from __futur | e__ import print_function
import numpy as np
import paddle.fluid.core as core
from paddle.fluid.op import Operator
def create_op(scope, op_type, inputs, outputs, attrs):
kwargs = dict()
op_maker = core.op_proto_and_checker_maker
op_role_attr_name = op_maker.kOpRoleAttrName()
if op_role_attr_name not in attrs:
attrs[op_role_attr_name] = int(op_maker.OpRole.Forward)
def __create_var__(name, var_name):
scope.var(var_name).get_tensor()
kwargs[name].append(var_name)
for in_name, in_dup in Operator.get_op_inputs(op_type):
if in_name in inputs:
kwargs[in_name] = []
if in_dup:
sub_in = inputs[in_name]
for item in sub_in:
sub_in_name, _ = item[0], item[1]
__create_var__(in_name, sub_in_name)
else:
__create_var__(in_name, in_name)
for out_name, out_dup in Operator.get_op_outputs(op_type):
if out_name in outputs:
kwargs[out_name] = []
if out_dup:
sub_out = outputs[out_name]
for item in sub_out:
sub_out_name, _ = item[0], item[1]
__create_var__(out_name, sub_out_name)
else:
__create_var__(out_name, out_name)
for attr_name in Operator.get_op_attr_names(op_type):
if attr_name in attrs:
kwargs[attr_name] = attrs[attr_name]
return Operator(op_type, **kwargs)
def set_input(scope, op, inputs, place):
def np_value_to_fluid_value(input):
if input.dtype == np.float16:
input = input.view(np.uint16)
return input
def __set_input__(var_name, var):
if isinstance(var, tuple) or isinstance(var, np.ndarray):
tensor = scope.find_var(var_name).get_tensor()
if isinstance(var, tuple):
tensor.set_recursive_sequence_lengths(var[1])
var = var[0]
tensor._set_dims(var.shape)
tensor.set(np_value_to_fluid_value(var), place)
elif isinstance(var, float):
scope.find_var(var_name).set_float(var)
elif isinstance(var, int):
scope.find_var(var_name).set_int(var)
for in_name, in_dup in Operator.get_op_inputs(op.type()):
if in_name in inputs:
if in_dup:
sub_in = inputs[in_name]
for item in sub_in:
sub_in_name, sub_in_val = item[0], item[1]
__set_input__(sub_in_name, sub_in_val)
else:
__set_input__(in_name, inputs[in_name])
def append_input_output(block, op_proto, np_list, is_input, dtype):
'''Insert VarDesc and generate Python variable instance'''
proto_list = op_proto.inputs if is_input else op_proto.outputs
def create_var(block, name, np_list, var_proto):
dtype = None
shape = None
lod_level = None
if name not in np_list:
assert var_proto.intermediate, "{} not found".format(name)
else:
# inferece the dtype from numpy value.
np_value = np_list[name]
if isinstance(np_value, tuple):
dtype = np_value[0].dtype
# output shape, lod should be infered from input.
if is_input:
shape = list(np_value[0].shape)
lod_level = len(np_value[1])
else:
dtype = np_value.dtype
if is_input:
shape = list(np_value.shape)
lod_level = 0
# NOTE(dzhwinter): type hacking
# numpy float16 is binded to paddle::platform::float16
# in tensor_py.h via the help of uint16 datatype. Because
# the internal memory representation of float16 is
# actually uint16_t in paddle. So we use np.uint16 in numpy for
# raw memory, it can pass through the pybind. So in the testcase,
# we feed data use data.view(uint16), but the dtype is float16 in fact.
# The data.view(uint16) means do not cast the data type, but process data as the uint16
if dtype == np.uint16:
dtype = np.float16
return block.create_var(
dtype=dtype, shape=shape, lod_level=lod_level, name=name)
var_dict = {}
for var_proto in proto_list:
var_name = str(var_proto.name)
if is_input:
if (var_name not in np_list) and var_proto.dispensable:
continue
assert (var_name in np_list) or (var_proto.dispensable), \
"Missing {} as input".format(var_name)
if var_proto.duplicable:
assert isinstance(np_list[var_name], list), \
"Duplicable {} should be set as list".format(var_name)
var_list = []
for (name, np_value) in np_list[var_name]:
var_list.append(
create_var(block, name, {name: np_value}, var_proto))
var_dict[var_name] = var_list
else:
var_dict[var_name] = create_var(block, var_name, np_list, var_proto)
return var_dict
def append_loss_ops(block, output_names):
mean_inputs = list(map(block.var, output_names))
if len(mean_inputs) == 1:
loss = block.create_var(dtype=mean_inputs[0].dtype, shape=[1])
op = block.append_op(
inputs={"X": mean_inputs}, outputs={"Out": loss}, type='mean')
op.desc.infer_var_type(block.desc)
op.desc.infer_shape(block.desc)
else:
avg_sum = []
for cur_loss in mean_inputs:
cur_avg_loss = block.create_var(dtype=cur_loss.dtype, shape=[1])
op = block.append_op(
inputs={"X": [cur_loss]},
outputs={"Out": [cur_avg_loss]},
type="mean")
op.desc.infer_var_type(block.desc)
op.desc.infer_shape(block.desc)
avg_sum.append(cur_avg_loss)
loss_sum = block.create_var(dtype=avg_sum[0].dtype, shape=[1])
op_sum = block.append_op(
inputs={"X": avg_sum}, outputs={"Out": loss_sum}, type='sum')
op_sum.desc.infer_var_type(block.desc)
op_sum.desc.infer_shape(block.desc)
loss = block.create_var(dtype=loss_sum.dtype, shape=[1])
op_loss = block.append_op(
inputs={"X": loss_sum},
outputs={"Out": loss},
type='scale',
attrs={'scale': 1.0 / float(len(avg_sum))})
op_loss.desc.infer_var_type(block.desc)
op_loss.desc.infer_shape(block.desc)
return loss
|
robinson96/GRAPE | vine/updateView.py | Python | bsd-3-clause | 20,286 | 0.007691 | import os
import shutil
import addSubproject
import option
import utility
import grapeGit as git
import grapeConfig
import grapeMenu
import checkout
# update your custom sparse checkout view
class UpdateView(option.Option):
"""
grape uv - Updates your active submodules and ensures you are on a consistent branch throughout your project.
Usage: grape-uv [-f ] [--checkSubprojects] [-b] [--skipSubmodules] [--allSubmodules]
[--skipNestedSubprojects] [--allNestedSubprojects] [--sync=<bool>]
[--add=<addedSubmoduleOrSubproject>...] [--rm=<removedSubmoduleOrSubproject>...]
Options:
-f Force removal of subprojects currently in your view that are taken out of the view as a
result to this call to uv.
--checkSubprojects Checks for branch model consistency across your submodules and subprojects, but does
not go through the 'which submodules do you want' script.
-b Automatically creates subproject branches that should be there according to your branching
model.
--allSubmodules Automatically add all submodules to your workspace.
--allNestedSubprojects Automatically add all nested subprojects to your workspace.
--sync=<bool> Take extra steps to ensure the branch you're on is up to date with origin,
either by pushing or pulling the remote tracking branch.
This will also checkout the public branch in a headless state prior to offering to create
a new branch (in repositories where the current | branch does not exist).
[default: .grapeconfig.post-checkout.syncWithOrigin]
--add=<project> Submodule or subproject to add to the workspace. Can be defined multiple t | imes.
--remove=<project> Submodule or subproject to remove from the workspace. Can be defined multiple times.
"""
def __init__(self):
super(UpdateView, self).__init__()
self._key = "uv"
self._section = "Workspace"
self._pushBranch = False
self._skipPush = False
def description(self):
return "Update the view of your current working tree"
@staticmethod
def defineActiveSubmodules(projectType="submodule"):
"""
Queries the user for the submodules (projectType == "submodule") or nested subprojects
(projectType == "nested subproject") they would like to activate.
"""
if projectType == "submodule":
allSubprojects = git.getAllSubmodules()
activeSubprojects = git.getActiveSubmodules()
if projectType == "nested subproject":
config = grapeConfig.grapeConfig()
allSubprojectNames = config.getAllNestedSubprojects()
allSubprojects = []
for project in allSubprojectNames:
allSubprojects.append(config.get("nested-%s" % project, "prefix"))
activeSubprojects = grapeConfig.GrapeConfigParser.getAllActiveNestedSubprojectPrefixes()
toplevelDirs = {}
toplevelActiveDirs = {}
toplevelSubs = []
for sub in allSubprojects:
# we are taking advantage of the fact that branchPrefixes are the same as directory prefixes for local
# top-level dirs.
prefix = git.branchPrefix(sub)
if sub != prefix:
toplevelDirs[prefix] = []
toplevelActiveDirs[prefix] = []
for sub in allSubprojects:
prefix = git.branchPrefix(sub)
if sub != prefix:
toplevelDirs[prefix].append(sub)
else:
toplevelSubs.append(sub)
for sub in activeSubprojects:
prefix = git.branchPrefix(sub)
if sub != prefix:
toplevelActiveDirs[prefix].append(sub)
included = {}
for directory, subprojects in toplevelDirs.items():
activeDir = toplevelActiveDirs[directory]
if len(activeDir) == 0:
defaultValue = "none"
elif set(activeDir) == set(subprojects):
defaultValue = "all"
else:
defaultValue = "some"
opt = utility.userInput("Would you like all, some, or none of the %ss in %s?" % (projectType,directory),
default=defaultValue)
if opt.lower()[0] == "a":
for subproject in subprojects:
included[subproject] = True
if opt.lower()[0] == "n":
for subproject in subprojects:
included[subproject] = False
if opt.lower()[0] == "s":
for subproject in subprojects:
included[subproject] = utility.userInput("Would you like %s %s? [y/n]" % (projectType, subproject),
'y' if (subproject in activeSubprojects) else 'n')
for subproject in toplevelSubs:
included[subproject] = utility.userInput("Would you like %s %s? [y/n]" % (projectType, subproject),
'y' if (subproject in activeSubprojects) else 'n')
return included
@staticmethod
def defineActiveNestedSubprojects():
"""
Queries the user for the nested subprojects they would like to activate.
"""
return UpdateView.defineActiveSubmodules(projectType="nested subproject")
def execute(self, args):
sync = args["--sync"].lower().strip()
sync = sync == "true" or sync == "yes"
args["--sync"] = sync
config = grapeConfig.grapeConfig()
origwd = os.getcwd()
wsDir = utility.workspaceDir()
os.chdir(wsDir)
base = git.baseDir()
if base == "":
return False
hasSubmodules = len(git.getAllSubmodules()) > 0 and not args["--skipSubmodules"]
includedSubmodules = {}
includedNestedSubprojectPrefixes = {}
allSubmodules = git.getAllSubmodules()
allNestedSubprojects = config.getAllNestedSubprojects()
addedSubmodules = []
addedNestedSubprojects = []
addedProjects = args["--add"]
notFound = []
for proj in addedProjects:
if proj in allSubmodules:
addedSubmodules.append(proj)
elif proj in allNestedSubprojects:
addedNestedSubprojects.append(proj)
else:
notFound.append(proj)
rmSubmodules = []
rmNestedSubprojects = []
rmProjects = args["--rm"]
for proj in rmProjects:
if proj in allSubmodules:
rmSubmodules.append(proj)
elif proj in allNestedSubprojects:
rmNestedSubprojects.append(proj)
else:
notFound.append(proj)
if notFound:
utility.printMsg("\"%s\" not found in submodules %s \nor\n nested subprojects %s" % (",".join(notFound),",".join(allSubmodules),",".join(allNestedSubprojects)))
return False
if not args["--checkSubprojects"]:
# get submodules to update
if hasSubmodules:
if args["--allSubmodules"]:
includedSubmodules = {sub:True for sub in allSubmodules}
elif args["--add"] or args["--rm"]:
includedSubmodules = {sub:True for sub in git.getActiveSubmodules()}
includedSubmodules.update({sub:True for sub in addedSubmodules})
includedSubmodules.update({sub:False for sub in rmSubmodules})
else:
includedSubmodules = self.defineActiveSubmodules()
# get subprojects to update
if not args["--skipNestedSubprojects"]:
nestedPrefixLo |
Symmetry-Innovations-Pty-Ltd/Python-2.7-for-QNX6.5.0-x86 | usr/pkg/lib/python2.7/collections.py | Python | mit | 25,363 | 0.002287 | __all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict']
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
# They should however be considered an integral part of collections.py.
from _abcoll import *
import _abcoll
__all__ += _abcoll.__all__
from _collections import deque, defaultdict
from operator import itemgetter as _itemgetter
from keyword import iskeyword as _iskeyword
import sys as _sys
import heapq as _heapq
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
################################################################################
### OrderedDict
################################################################################
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[PREV]
last[NEXT] = root[PREV] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
def __delitem__(self, key, PREV=0, NEXT=1, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
| # Deleting an existing item uses self.__map to find th | e link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
NEXT, KEY = 1, 2
root = self.__root
curr = root[NEXT]
while curr is not root:
yield curr[KEY]
curr = curr[NEXT]
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
PREV, KEY = 0, 2
root = self.__root
curr = root[PREV]
while curr is not root:
yield curr[KEY]
curr = curr[PREV]
def clear(self):
'od.clear() -> None. Remove all items from od.'
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
dict.clear(self)
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self]
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) pairs in od'
for k in self:
yield (k, self[k])
update = MutableMapping.update
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
key = next(reversed(self) if last else iter(self))
value = self.pop(key)
return key, value
def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key]
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
'od.__ne__(y) <==> od!=y'
return not self == other
# -- the following methods support python 3.x style dictionary views --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
################################################################################
### namedtuple
################################################################################
def namedtuple(typename |
ARM-software/lisa | lisa/tests/staging/utilclamp.py | Python | apache-2.0 | 14,119 | 0.000425 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2020, Arm Limited and contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed 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 functools
from operator import itemgetter
import numpy as np
import pandas as pd
import holoviews as hv
from lisa.analysis.freq | uency import Frequency | Analysis
from lisa.analysis.load_tracking import LoadTrackingAnalysis
from lisa.datautils import df_refit_index
from lisa.pelt import PELT_SCALE
from lisa.tests.base import ResultBundle, TestBundle, RTATestBundle, TestMetric
from lisa.wlgen.rta import RTAPhase, PeriodicWload
from lisa.notebook import plot_signal
class UtilClamp(RTATestBundle, TestBundle):
"""
Validate that UtilClamp min values are honoured properly by the kernel.
The test is split into 8 phases. For each phase, a UtilClamp value is set
for a task, whose duty cycle would generate a lower utilization. Then the
actual capacity, allocated to the task during its activation is checked.
The 8 phases UtilClamp values are picked to cover the entire SoC's CPU
scale. (usually between 0 and 1024)
.. code-block:: text
|<-- band 0 -->|<-- band 1 -->|<-- band 2 -->|<-- ...
capacities: 0 | 128 | 256 512
| |
--------------------|--------------|-------------------------------
phase 1: uclamp_val |
|
-----------------------------------|-------------------------------
phase 2: uclamp_val
...
phase 8:
"""
NR_PHASES = 8
CAPACITY_MARGIN = 0.8 # kernel task placement a 80% capacity margin
@classmethod
def check_from_target(cls, target):
super().check_from_target(target)
kconfig = target.plat_info['kernel']['config']
if not kconfig.get('UCLAMP_TASK'):
ResultBundle.raise_skip("The target's kernel needs CONFIG_UCLAMP_TASK=y kconfig enabled")
@classmethod
def _collect_capacities(cls, plat_info):
"""
Returns, for each CPU a mapping frequency / capacity:
dict(cpu, dict(freq, capacity))
where capacity = max_cpu_capacity * freq / max_cpu_frequency.
"""
max_capacities = plat_info['cpu-capacities']['rtapp']
return {
cpu: {
freq: int(max_capacities[cpu] * freq / max(freqs))
for freq in freqs
}
for cpu, freqs in plat_info['freqs'].items()
}
@classmethod
def _collect_capacities_flatten(cls, plat_info):
capacities = [
capa
for freq_capas in cls._collect_capacities(plat_info).values()
for capa in freq_capas.values()
]
# Remove the duplicates from the list
return sorted(set(capacities))
@classmethod
def _get_bands(cls, capacities):
bands = list(zip(capacities, capacities[1:]))
# Only keep a number of bands
nr_bands = cls.NR_PHASES
if len(bands) > nr_bands:
# Pick the bands covering the widest range of util, since they
# are easier to test
bands = sorted(
bands,
key=lambda band: band[1] - band[0],
reverse=True
)
bands = bands[:nr_bands]
bands = sorted(bands, key=itemgetter(0))
return bands
@classmethod
def _get_phases(cls, plat_info):
"""
Returns a list of phases. Each phase being described by a tuple:
(uclamp_val, util)
"""
capacities = cls._collect_capacities_flatten(plat_info)
bands = cls._get_bands(capacities)
def band_mid(band):
return int((band[1] + band[0]) / 2)
def make_phase(band):
uclamp = band_mid(band)
util = uclamp / 2
name = f'uclamp-{uclamp}'
return (name, (uclamp, util))
return dict(map(make_phase, bands))
@classmethod
def _get_rtapp_profile(cls, plat_info):
periods = [
RTAPhase(
prop_name=name,
prop_wload=PeriodicWload(
duty_cycle_pct=(util / PELT_SCALE) * 100, # util to pct
duration=5,
period=cls.TASK_PERIOD,
),
prop_uclamp=(uclamp_val, uclamp_val),
prop_meta={'uclamp_val': uclamp_val},
)
for name, (uclamp_val, util) in cls._get_phases(plat_info).items()
]
return {'task': functools.reduce(lambda a, b: a + b, periods)}
def _get_trace_df(self):
task = self.rtapp_task_ids_map['task'][0]
# There is no CPU selection when we're going back from preemption.
# Setting preempted_value=1 ensures that it won't count as a new
# activation.
df = self.trace.ana.tasks.df_task_activation(task,
preempted_value=1)
df = df_refit_index(df, window=self.trace.window)
df = df[['active', 'cpu']]
df['activation_start'] = df['active'] == 1
df_freq = self.trace.ana.frequency.df_cpus_frequency()
df_freq = df_freq[['cpu', 'frequency']]
df_freq = df_freq.pivot(index=None, columns='cpu', values='frequency')
df_freq.reset_index(inplace=True)
df_freq.set_index('Time', inplace=True)
df = df.merge(df_freq, how='outer', left_index=True, right_index=True)
# Merge with df_freq will bring NaN in the activation column. We do not
# want to ffill() them.
df['activation_start'].fillna(value=False, inplace=True)
# Ensures that frequency values are propogated through the entire
# DataFrame, as it is possible that no frequency event occur
# during a phase.
df.ffill(inplace=True)
return df
def _get_phases_df(self):
task = self.rtapp_task_ids_map['task'][0]
df = self.trace.ana.rta.df_phases(task, wlgen_profile=self.rtapp_profile)
df = df.copy()
df = df[df['properties'].apply(lambda props: props['meta']['from_test'])]
df.reset_index(inplace=True)
df.rename(columns={'index': 'start'}, inplace=True)
df['end'] = df['start'].shift(-1)
df['uclamp_val'] = df['properties'].apply(lambda row: row['meta']['uclamp_val'])
return df
def _for_each_phase(self, callback):
df_phases = self._get_phases_df()
df_trace = self._get_trace_df()
def parse_phase(phase):
start = phase['start']
end = phase['end']
df = df_trace
# During a phase change, rt-app will wakeup and then change
# UtilClamp value will be changed. We then need to wait for the
# second wakeup for the kernel to apply the most recently set
# UtilClamp value.
start = df[(df.index >= start) &
(df['active'] == 1)].first_valid_index()
end = end if not np.isnan(end) else df.last_valid_index()
if (start > end):
raise ValueError('Phase ends before it has even started')
df = df_trace[start:end].copy()
return callback(df, phase)
return df_phases.apply(parse_phase, axis=1)
def _plot_phases(self, test, failures, signal=None):
task, = self.rtapp_task_ids
ana = self.trace.ana(
task=task,
tasks=[task],
)
figs = [
(
ana.tasks.plot_tasks_activation(
|
noironetworks/neutron | neutron/tests/unit/objects/test_subnet.py | Python | apache-2.0 | 10,392 | 0.000289 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed 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 mock
from neutron_lib import context
from oslo_utils import uuidutils
from neutron.db import rbac_db_models
from neutron.objects import base as obj_base
from neutron.objects.db import api as obj_db_api
from neutron.objects import network as net_obj
from neutron.objects import rbac_db
from neutron.objects import subnet
from neutron.tests.unit.objects import test_base as obj_test_base
from neutron.tests.unit import testlib_api
class IPAllocationPoolObjectIfaceTestCase(
obj_test_base.BaseObjectIfaceTestCase):
_test_class = subnet.IPAllocationPool
class IPAllocationPoolDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
testlib_api.SqlTestCase):
_test_class = subnet.IPAllocationPool
def setUp(self):
super(IPAllocationPoolDbObjectTestCase, self).setUp()
self.update_obj_fields(
{'subnet_id': lambda: self._create_test_subnet_id()})
class DNSNameServerObjectIfaceTestCase(obj_test_base.BaseObjectIfaceTestCase):
_test_class = subnet.DNSNameServer
def setUp(self):
super(DNSNameServerObjectIfaceTestCase, self).setUp()
self.pager_map[self._test_class.obj_name()] = (
obj_base.Pager(sorts=[('order', True)]))
class DNSNameServerDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
testlib_api.SqlTestCase):
_test_class = subnet.DNSNameServer
def setUp(self):
super(DNSNameServerDbObjectTestCase, self).setUp()
self._subnet_id = self._create_test_subnet_id()
self.update_obj_fields({'subnet_id': self._subnet_id})
def _create_dnsnameservers(self):
for obj in self.obj_fields:
dns = self._make_object(obj)
dns.create()
def test_get_objects_sort_by_order_asc(self):
self._create_dnsnameservers()
objs = self._test_class.get_objects(self.context)
fields_sorted = sorted([obj['order'] for obj in self.obj_fields])
self.assertEqual(fields_sorted, [obj.order for obj in objs])
def test_get_objects_sort_by_order_desc(self):
self._create_dnsnameservers()
pager = obj_base.Pager(sorts=[('order', False)])
objs = self._test_class.get_objects(self.context, _pager=pager,
subnet_id=self._subnet_id)
fields_sorted = sorted([obj['order'] for obj in self.obj_fields],
reverse=True)
self.assertEqual(fields_sorted, [obj.order for obj in objs])
def test_get_objects_sort_by_address_asc_using_pager(self):
self._create_dnsnameservers()
pager = obj_base.Pager(sorts=[('address', True)])
objs = self._test_class.get_objects(self.context, _pager=pager)
fields_sorted = sorted([obj['address'] for obj in self.obj_fields])
self.assertEqual(fields_sorted, [obj.address for obj in objs])
class RouteObjectIfaceTestCase(obj_test_base.BaseObjectIfaceTestCase):
_test_class = subnet.Route
class RouteDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
testlib_api.SqlTestCase):
_test_class = subnet.Route
def setUp(self):
super(RouteDbObjectTestCase, self).setUp()
self.update_obj_fields(
{'subnet_id': lambda: self._create_test_subnet_id()})
class SubnetServiceTypeObjectIfaceTestCase(
obj_test_base.BaseObjectIfaceTestCase):
_test_class = subnet.SubnetServiceType
class SubnetServiceTypeDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
testlib_api.SqlTestCase):
_test_class = subnet.SubnetServiceType
def setUp(self):
super(SubnetServiceTypeDbObjectTestCa | se, self).setUp()
self.update_obj_fields(
{'subnet_id': lambda: self._create_test_subnet_id()})
class SubnetObjectIfaceTest | Case(obj_test_base.BaseObjectIfaceTestCase):
_test_class = subnet.Subnet
def setUp(self):
super(SubnetObjectIfaceTestCase, self).setUp()
self.pager_map[subnet.DNSNameServer.obj_name()] = (
obj_base.Pager(sorts=[('order', True)]))
# Base class will mock those out only when rbac_db_model is set for the
# object. Since subnets don't have their own models but only derive
# shared value from networks, we need to unconditionally mock those
# entry points out here, otherwise they will trigger database access,
# which is not allowed in 'Iface' test classes.
mock.patch.object(
rbac_db.RbacNeutronDbObjectMixin,
'is_shared_with_tenant', return_value=False).start()
mock.patch.object(
rbac_db.RbacNeutronDbObjectMixin,
'get_shared_with_tenant').start()
class SubnetDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
testlib_api.SqlTestCase):
_test_class = subnet.Subnet
CORE_PLUGIN = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2'
def setUp(self):
super(SubnetDbObjectTestCase, self).setUp()
# set up plugin because some models used here require a plugin
# (specifically, rbac models and their get_valid_actions validators)
self.setup_coreplugin(self.CORE_PLUGIN)
network_id = self._create_test_network_id()
self.update_obj_fields(
{'network_id': network_id,
'segment_id': lambda: self._create_test_segment_id(network_id)})
def test_get_dns_nameservers_in_order(self):
obj = self._make_object(self.obj_fields[0])
obj.create()
dns_nameservers = [(2, '1.2.3.4'), (1, '5.6.7.8'), (4, '7.7.7.7')]
for order, address in dns_nameservers:
dns = subnet.DNSNameServer(self.context, order=order,
address=address,
subnet_id=obj.id)
dns.create()
new = self._test_class.get_object(self.context, id=obj.id)
self.assertEqual(1, new.dns_nameservers[0].order)
self.assertEqual(2, new.dns_nameservers[1].order)
self.assertEqual(4, new.dns_nameservers[-1].order)
def _create_shared_network_rbac_entry(self, network):
attrs = {
'object_id': network['id'],
'target_tenant': '*',
'action': rbac_db_models.ACCESS_SHARED
}
obj_db_api.create_object(net_obj.NetworkRBAC, self.context, attrs)
def test_get_subnet_shared_true(self):
network = self._create_test_network()
self._create_shared_network_rbac_entry(network)
subnet_data = dict(self.obj_fields[0])
subnet_data['network_id'] = network['id']
obj = self._make_object(subnet_data)
# check if shared will be load by 'obj_load_attr' and using extra query
# by RbacNeutronDbObjectMixin get_shared_with_tenant
self.assertTrue(obj.shared)
obj.create()
# here the shared should be load by is_network_shared
self.assertTrue(obj.shared)
new = self._test_class.get_object(self.context,
**obj._get_composite_keys())
# again, the shared should be load by is_network_shared
self.assertTrue(new.shared)
def test_filter_by_shared(self):
network = self._create_test_network()
self._create_shared_network_rbac_entry(network)
subnet_data = dict(self.obj_fields[0])
subnet_data['network_id'] = network['id']
obj = self._make_object(subnet_data)
obj.create()
result = self._test_class.get_objects(self.context, |
poiesisconsulting/openerp-restaurant | epn/epn.py | Python | agpl-3.0 | 2,129 | 0.008455 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
import openerp
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools.translate import _
_logger = | logging.getLogger(__name__)
class epn_pos_statements(osv.osv):
_inherit = 'account.bank.statement.line'
_columns = {
'signature': fields.binary("Signature",help="This signature provided with the payment"),
'epn_info': fields.text('EPN Credit-Card Info', help="EPN Credit-Card Payment Information"),
| }
class epn_pos_order(osv.osv):
_inherit = 'pos.order'
def _payment_fields(self,ui_paymentline):
fields = super(epn_pos_order,self)._payment_fields(ui_paymentline)
fields['signature'] = ui_paymentline.get('signature',False)
fields['epn_info'] = ui_paymentline.get('epn_info','')
print 'payment_fields',fields
return fields
def _payment_fields2(self,fields):
fields2 = super(epn_pos_order,self)._payment_fields2(fields)
fields2['signature'] = fields.get('signature',False)
fields2['epn_info'] = fields.get('epn_info','')
print 'payment_fields2',fields
return fields2
|
RoyalTS/econ-python-environment | .mywaflib/waflib/Tools/c_preproc.py | Python | bsd-3-clause | 27,412 | 0.03524 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
"""
C/C++ preprocessor for finding dependencies
Reasons for using the Waf preprocessor by default
#. Some c/c++ extensions (Qt) require a custom preprocessor for obtaining the dependencies (.moc files)
#. Not all compilers provide .d files for obtaining the dependencies (portability)
#. A naive file scanner will not catch the constructs such as "#include foo()"
#. A naive file scanner will catch unnecessary dependencies (change an unused header -> recompile everything)
Regarding the speed concerns:
* the preprocessing is performed only when files must be compiled
* the macros are evaluated only for #if/#elif/#include
* system headers are not scanned by default
Now if you do not want the Waf preprocessor, the tool +gccdeps* uses the .d files produced
during the compilation to track the dependencies (useful when used with the boost libraries).
It only works with gcc >= 4.4 though.
A dumb preprocessor is also available in the tool *c_dumbpreproc*
"""
# TODO: more varargs, pragma once
import re, string, traceback
from waflib import Logs, Utils, Errors
from waflib.Logs import debug, error
class PreprocError(Errors.WafError):
pass
POPFILE = '-'
"Constant representing a special token used in :py:meth:`waflib.Tools.c_preproc.c_parser.start` iteration to switch to a header read previously"
recursion_limit = 150
"Limit on the amount of files to read in the dependency scanner"
go_absolute = False
"Set to True to track headers on files in /usr/include, else absolute paths are ignored (but it becomes very slow)"
standard_includes = ['/usr/include']
if Utils.is_win32:
standard_includes = []
use_trigraphs = 0
"""Apply trigraph rules (False by default)"""
strict_quotes = 0
"""Reserve the "#include <>" quotes for system includes (do not search for those includes). False by default."""
g_optrans = {
'not':'!',
'and':'&&',
'bitand':'&',
'and_eq':'&=',
'or':'||',
'bitor':'|',
'or_eq':'|=',
'xor':'^',
'xor_eq':'^=',
'compl':'~',
}
"""Operators such as and/or/xor for c++. Set an empty dict to disable."""
# ignore #warning and #error
re_lines = re.compile(
'^[ \t]*(#|%:)[ \t]*(ifdef|ifndef|if|else|elif|endif|include|import|define|undef|pragma)[ \t]*(.*)\r*$',
re.IGNORECASE | re.MULTILINE)
"""Match #include lines"""
re_mac = re.compile("^[a-zA-Z_]\w*")
"""Match macro definitions"""
re_fun = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*[(]')
"""Match macro functions"""
re_pragma_once = re.compile('^\s*once\s*', re.IGNORECASE)
"""Match #pragma once statements"""
re_nl = re.compile('\\\\\r*\n', re.MULTILINE)
"""Match newlines"""
re_cpp = re.compile(r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE )
"""Filter C/C++ comments"""
trig_def = [('??'+a, b) for a, b in zip("=-/!'()<>", r'#~\|^[]{}')]
"""Trigraph definitions"""
chr_esc = {'0':0, 'a':7, 'b':8, 't':9, 'n':10, 'f':11, 'v':12, 'r':13, '\\':92, "'":39}
"""Escape chara | cters"""
NUM | = 'i'
"""Number token"""
OP = 'O'
"""Operator token"""
IDENT = 'T'
"""Identifier token"""
STR = 's'
"""String token"""
CHAR = 'c'
"""Character token"""
tok_types = [NUM, STR, IDENT, OP]
"""Token types"""
exp_types = [
r"""0[xX](?P<hex>[a-fA-F0-9]+)(?P<qual1>[uUlL]*)|L*?'(?P<char>(\\.|[^\\'])+)'|(?P<n1>\d+)[Ee](?P<exp0>[+-]*?\d+)(?P<float0>[fFlL]*)|(?P<n2>\d*\.\d+)([Ee](?P<exp1>[+-]*?\d+))?(?P<float1>[fFlL]*)|(?P<n4>\d+\.\d*)([Ee](?P<exp2>[+-]*?\d+))?(?P<float2>[fFlL]*)|(?P<oct>0*)(?P<n0>\d+)(?P<qual2>[uUlL]*)""",
r'L?"([^"\\]|\\.)*"',
r'[a-zA-Z_]\w*',
r'%:%:|<<=|>>=|\.\.\.|<<|<%|<:|<=|>>|>=|\+\+|\+=|--|->|-=|\*=|/=|%:|%=|%>|==|&&|&=|\|\||\|=|\^=|:>|!=|##|[\(\)\{\}\[\]<>\?\|\^\*\+&=:!#;,%/\-\?\~\.]',
]
"""Expression types"""
re_clexer = re.compile('|'.join(["(?P<%s>%s)" % (name, part) for name, part in zip(tok_types, exp_types)]), re.M)
"""Match expressions into tokens"""
accepted = 'a'
"""Parser state is *accepted*"""
ignored = 'i'
"""Parser state is *ignored*, for example preprocessor lines in an #if 0 block"""
undefined = 'u'
"""Parser state is *undefined* at the moment"""
skipped = 's'
"""Parser state is *skipped*, for example preprocessor lines in a #elif 0 block"""
def repl(m):
"""Replace function used with :py:attr:`waflib.Tools.c_preproc.re_cpp`"""
s = m.group(0)
if s.startswith('/'):
return ' '
return s
def filter_comments(filename):
"""
Filter the comments from a c/h file, and return the preprocessor lines.
The regexps :py:attr:`waflib.Tools.c_preproc.re_cpp`, :py:attr:`waflib.Tools.c_preproc.re_nl` and :py:attr:`waflib.Tools.c_preproc.re_lines` are used internally.
:return: the preprocessor directives as a list of (keyword, line)
:rtype: a list of string pairs
"""
# return a list of tuples : keyword, line
code = Utils.readf(filename)
if use_trigraphs:
for (a, b) in trig_def: code = code.split(a).join(b)
code = re_nl.sub('', code)
code = re_cpp.sub(repl, code)
return [(m.group(2), m.group(3)) for m in re.finditer(re_lines, code)]
prec = {}
"""
Operator precendence rules required for parsing expressions of the form::
#if 1 && 2 != 0
"""
ops = ['* / %', '+ -', '<< >>', '< <= >= >', '== !=', '& | ^', '&& ||', ',']
for x in range(len(ops)):
syms = ops[x]
for u in syms.split():
prec[u] = x
def trimquotes(s):
"""
Remove the single quotes around an expression::
trimquotes("'test'") == "test"
:param s: expression to transform
:type s: string
:rtype: string
"""
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s
def reduce_nums(val_1, val_2, val_op):
"""
Apply arithmetic rules to compute a result
:param val1: input parameter
:type val1: int or string
:param val2: input parameter
:type val2: int or string
:param val_op: C operator in *+*, */*, *-*, etc
:type val_op: string
:rtype: int
"""
#print val_1, val_2, val_op
# now perform the operation, make certain a and b are numeric
try: a = 0 + val_1
except TypeError: a = int(val_1)
try: b = 0 + val_2
except TypeError: b = int(val_2)
d = val_op
if d == '%': c = a%b
elif d=='+': c = a+b
elif d=='-': c = a-b
elif d=='*': c = a*b
elif d=='/': c = a/b
elif d=='^': c = a^b
elif d=='|': c = a|b
elif d=='||': c = int(a or b)
elif d=='&': c = a&b
elif d=='&&': c = int(a and b)
elif d=='==': c = int(a == b)
elif d=='!=': c = int(a != b)
elif d=='<=': c = int(a <= b)
elif d=='<': c = int(a < b)
elif d=='>': c = int(a > b)
elif d=='>=': c = int(a >= b)
elif d=='^': c = int(a^b)
elif d=='<<': c = a<<b
elif d=='>>': c = a>>b
else: c = 0
return c
def get_num(lst):
"""
Try to obtain a number from a list of tokens. The token types are defined in :py:attr:`waflib.Tools.ccroot.tok_types`.
:param lst: list of preprocessor tokens
:type lst: list of tuple (tokentype, value)
:return: a pair containing the number and the rest of the list
:rtype: tuple(value, list)
"""
if not lst: raise PreprocError("empty list for get_num")
(p, v) = lst[0]
if p == OP:
if v == '(':
count_par = 1
i = 1
while i < len(lst):
(p, v) = lst[i]
if p == OP:
if v == ')':
count_par -= 1
if count_par == 0:
break
elif v == '(':
count_par += 1
i += 1
else:
raise PreprocError("rparen expected %r" % lst)
(num, _) = get_term(lst[1:i])
return (num, lst[i+1:])
elif v == '+':
return get_num(lst[1:])
elif v == '-':
num, lst = get_num(lst[1:])
return (reduce_nums('-1', num, '*'), lst)
elif v == '!':
num, lst = get_num(lst[1:])
return (int(not int(num)), lst)
elif v == '~':
num, lst = get_num(lst[1:])
return (~ int(num), lst)
else:
raise PreprocError("Invalid op token %r for get_num" % lst)
elif p == NUM:
return v, lst[1:]
elif p == IDENT:
# all macros should have been replaced, remaining identifiers eval to 0
return 0, lst[1:]
else:
raise PreprocError("Invalid token %r for get_num" % lst)
def get_term(lst):
"""
Evaluate an expression recursively, for example::
1+1+1 -> 2+1 -> 3
:param lst: list of tokens
:type lst: list of tuple(token, value)
:return: the value and the remaining tokens
:rtype: value, list
"" |
divio/django-filer | tests/test_models.py | Python | bsd-3-clause | 12,044 | 0.001744 | import os
from django.conf import settings
from django.core.files import File as DjangoFile
from django.forms.models import modelform_factory
from django.test import TestCase
from tests.helpers import (
create_clipboard_item, create_folder_structure, create_image,
create_superuser,
)
from filer import settings as filer_settings
from filer.models.clipboardmodels import Clipboard
from filer.models.filemodels import File
from filer.models.foldermodels import Folder
from filer.models.mixins import IconsMixin
from filer.settings import FILER_IMAGE_MODEL
from filer.utils.loader import load_model
Image = load_model(FILER_IMAGE_MODEL)
class FilerApiTests(TestCase):
def setUp(self):
self.superuser = create_superuser()
self.client.login(username='admin', password='secret')
self.img = create_image()
self.image_name = 'test_file.jpg'
self.filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, self.image_name)
self.img.save(self.filename, 'JPEG')
def tearDown(self):
self.client.logout()
os.remove(self.filename)
for f in File.objects.all():
f.delete()
def create_filer_image(self):
file_obj = DjangoFile(open(self.filename, 'rb'), name=self.image_name)
image = Image.objects.create(owner=self.superuser,
original_filename=self.image_name,
file=file_obj)
return image
def test_create_folder_structure(self):
create_folder_structure(depth=3, sibling=2, parent=None)
self.assertEqual(Folder.objects.count(), 26)
def test_create_and_delete_image(self):
self.assertEqual(Image.objects.count(), 0)
image = self.create_filer_image()
image.save()
self.assertEqual(Image.objects.count(), 1)
image = Image.objects.all()[0]
image.delete()
self.assertEqual(Image.objects.count(), 0)
def test_upload_image_form(self):
self.assertEqual(Image.objects.count(), 0)
file_obj = DjangoFile(open(self.filename, 'rb'), name=self.image_name)
ImageUploadForm = modelform_factory(Image, fields=('original_filename', 'owner', 'file'))
upoad_image_form = ImageUploadForm({
'original_filename': self.image_name,
'owner': self.superuser.pk
}, {'file': file_obj})
if upoad_image_form.is_valid():
image = upoad_image_form.save() # noqa
self.assertEqual(Image.objects.count(), 1)
def test_create_clipboard_item(self):
image = self.create_filer_image()
image.save()
# Get the clipboard of the current user
clipboard_item = create_clipboard_item(user=self.superuser,
file_obj=image)
clipboard_item.save()
self.assertEqual(Clipboard.objects.count(), 1)
def test_create_icons(self):
image = self.create_filer_image()
image.save()
icons = image.icons
file_basename = os.path.basename(image.file.path)
self.assertEqual(len(icons), len(filer_settings.FILER_ADMIN_ICON_SIZES))
for size in filer_settings.FILER_ADMIN_ICON_SIZES:
self.assertEqual(os.path.basename(icons[size]),
file_basename + '__%sx%s_q85_crop_subsampling-2_upscale.jpg' % (size, size))
def test_access_icons_property(self):
"""Test IconsMixin that calls static on a non-existent file"""
class CustomObj(IconsMixin, object):
_icon = 'custom'
custom_obj = CustomObj()
try:
icons = custom_obj.icons
except Exception as e:
self.fail("'.icons' access raised Exception {0} unexpectedly!".format(e))
self.assertEqual(len(icons), len(filer_settings.FILER_ADMIN_ICON_SIZES))
def test_file_upload_public_destination(self):
"""
Test where an image `is_public` == True is uploaded.
"""
image = self.create_filer_image()
image.is_public = True
image.save()
self.assertTrue(image.file.path.startswith(filer_settings.FILER_PUBLICMEDIA_STORAGE.location))
def test_file_upload_private_destination(self):
"""
Test where an image `is_public` == False is uploaded.
"""
image = self.create_filer_image()
image.is_public = False
image.save()
self.assertTrue(image.file.path.startswith(filer_settings.FILER_PRIVATEMEDIA_STORAGE.location))
def test_file_move_location(self):
"""
Test the method that move a file between filer_public, filer_private
and vice et versa
"""
image = self.create_filer_image()
image.is_public = False
image.save()
self.assertTrue(image.file.path.startswith(filer_settings.FILER_PRIVATEMEDIA_STORAGE.location))
image.is_public = True
image.save()
self.assertTrue(image.file.path.startswith(filer_settings.FILER_PUBLICMEDIA_STORAGE.location))
def test_file_change_upload_to_destination(self):
"""
Test that the file is actualy move from the private to the public
directory when the is_public is checked on an existing private file.
"""
file_obj = DjangoFile(open(self.filename, 'rb'), name=self.image_name)
image = Image.objects.create(owner=self.superuser,
is_public=False,
original_filename=self.image_name,
file=file_obj)
image.save()
self.assertTrue(image.file.path.startswith(filer_settings.FILER_PRIVATEMEDIA_STORAGE.location))
image.is_public = True
image.save()
self.assertTrue(image.file.path.startswith(filer_settings.FILER_PUBLICMEDIA_STORAGE.location))
self.assertEqual(len(image.icons), len(filer_settings.FILER_ADMIN_ICON_SIZES))
image.is_public = False
image.save()
self.assertTrue(image.file.path.startswith(fi | ler_settings.FILER_PRIVATEMEDIA_STORAGE.location))
self.assertEqual(len(image.icons), len(filer_settings.FILER_ADMIN_ICON_SIZES))
def test_deleting_files(self):
# Note: this first test case fails deep inside
# easy-thumbnails thumbnail generation with a segmentation fault
# (which probably indicates a fail inside C extension or reaching
# CPython stack limits) under certain conditions:
# - | if the previous test case had the create_filer_image() call
# - under python 3.x
# - once out of 3-4 runs
# It happens on completely different systems (locally and on Travis).
# Current tearDown() does not help, nor does cleaning up temp directory
# nor django cache.
# So the workaround for now is to run them in a defined order like one
# real test case. We do not care for setUp() or tearDown() between the
# two since there are enough asserts in the code.
self._test_deleting_image_deletes_file_from_filesystem()
self._test_deleting_file_does_not_delete_file_from_filesystem_if_other_references_exist()
def _test_deleting_image_deletes_file_from_filesystem(self):
file_1 = self.create_filer_image()
self.assertTrue(file_1.file.storage.exists(file_1.file.name))
# check if the thumnails exist
thumbnails = [x for x in file_1.file.get_thumbnails()]
for tn in thumbnails:
self.assertTrue(tn.storage.exists(tn.name))
storage, name = file_1.file.storage, file_1.file.name
# delete the file
file_1.delete()
# file should be gone
self.assertFalse(storage.exists(name))
# thumbnails should be gone
for tn in thumbnails:
self.assertFalse(tn.storage.exists(tn.name))
def _test_deleting_file_does_not_delete_file_from_filesystem_if_other_references_exist(self):
file_1 = self.create_filer_image()
# create another file that references the same physical file
file_2 = File.objects.get(pk=file_1.pk)
file_2.pk = None
file_2.id = None
|
blackball/an-test6 | util/imageutils.py | Python | gpl-2.0 | 1,081 | 0.037003 | import numpy
def write_pnm_to(img, f, maxval=255):
if len(img.shape) == 1:
raise 'write_pnm: img is one-dimensional: must be 2 or 3.'
elif len(img.shape) == 2:
#pnmtype = 'G'
pnmcode = 5
(h,w) = img.shape
elif len(img.shape) == 3:
(h,w,planes) = img.shape
#pnmtype = 'P'
pnmcode = 6
if planes != 3:
raise 'write_pnm: img must have 3 planes, not %i' % planes
else:
raise 'write_pnm: img must have <= 3 d | imensions.'
if img.max() > maxval:
print 'write_pnm: Some pixel values are > maxval (%i): clipping them.' % maxval
if img.min() < 0:
print 'write_pnm: Some pixel values are < 0: clipping them.'
cli | pped = img.clip(0, maxval)
maxval = int(maxval)
if maxval > 65535:
raise 'write_pnm: maxval must be <= 65535'
if maxval < 0:
raise 'write_pnm: maxval must be positive'
f.write('P%i %i %i %i ' % (pnmcode, w, h, maxval))
if maxval <= 255:
f.write(img.astype(numpy.uint8).data)
else:
f.write(img.astype(numpy.uint16).data)
def write_pnm(img, filename, maxval=255):
f = open(filename, 'wb')
write_pnm_to(img, f, maxval)
f.close()
|
danielsamuels/working-on | working_on/apps/site/models.py | Python | mit | 205 | 0 | from cms.models import HtmlField
from cms.apps.pages.models import ContentBase
# class Cont | ent(ContentBase):
# content_primary = HtmlField(
# "primary content",
# blank=True
# ) | |
DavidTingley/ephys-processing-pipeline | installation/klustaviewa-0.3.0/klustaviewa/control/tests/test_processor.py | Python | gpl-3.0 | 1,236 | 0.005663 | """Unit tests for controller module."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os
import numpy as np
from klustaviewa.control.processor import Processor
from kwiklib.dataio.tests.mock_data import (setup, teardown,
nspikes, nclusters, nsamples, nchannels, fetdim, TEST_FOLDER)
from kwiklib.dataio import KlustersLoader
from kwiklib.dataio.selection import select, get_indices
from kwiklib.dataio.tools import check_dtype, check_shape, get_array
# -----------------------------------------------------------------------------
# Utility functions
# -----------------------------------------------------------------------------
def load():
# Open the mock data.
dir = TEST_FOLDER
|
xmlfile = os.path.join(dir, 'test.xml')
l = KlustersLoader(filename=xmlfile)
c = Processor(l)
return (l, c)
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
def t | est_processor():
l, p = load()
l.close()
|
vinodc/evernote | src/evernote/edam/notestore/ttypes.py | Python | bsd-2-clause | 89,345 | 0.016095 | #
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
import evernote.edam.userstore.ttypes
import evernote.edam.type.ttypes
import evernote.edam.error.ttypes
import evernote.edam.limits.ttypes
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class SyncState(object):
"""
This structure encapsulates the information about the state of the
user's account for the purpose of "state based" synchronization.
<dl>
<dt>currentTime</dt>
<dd>
The server's current date and time.
</dd>
<dt>fullSyncBefore</dt>
<dd>
The cutoff date and time for client caches to be
updated via incremental synchronization. Any clients that were last
synched with the server before this date/time must do a full resync of all
objects. This cutoff point will change over time as archival data is
deleted or special circumstances on the service require resynchronization.
</dd>
<dt>updateCount</dt>
<dd>
Indicates the total number of transactions that have
been committed within the account. This reflects (for example) the
number of discrete additions or modifications that have been made to
the data in this account (tags, notes, resources, etc.).
This number is the "high water mark" for Update Sequence Numbers (USN)
within the account.
</dd>
<dt>uploaded</dt>
<dd>
The total number of bytes that have been uploaded to
this account in the current monthly period. This can be compared against
Accounting.uploadLimit (from the UserStore) to determine how close the user
is to their monthly upload limit.
This value may not be present if the SyncState has been retrieved by
a caller that only has read access to the account.
</dd>
</dl>
Attributes:
- currentTime
- fullSyncBefore
- updateCount
- uploaded
"""
thrift_spec = (
None, # 0
(1, TType.I64, 'currentTime', None, None, ), # 1
(2, TType.I64, 'fullSyncBefore', None, None, ), # 2
(3, TType.I32, 'updateCount', None, None, ), # 3
(4, TType.I64, 'uploaded', None, None, ), # 4
)
def __init__(self, currentTime=None, fullSyncBefore=None, updateCount=None, uploaded=None,):
self.currentTime = currentTime
self.fullSyncBefore = fullSyncBefore
self.updateCount = updateCount
self.uploaded = uploaded
def read(self, iprot):
if iprot.__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:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I64:
self.currentTime = iprot.readI64();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I64:
self.fullSyncBefore = iprot.readI64();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.I32:
self.updateCount = iprot.readI32();
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.I64:
self.uploaded = iprot.readI64();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('SyncState')
if self.currentTime != None:
oprot.writeFieldBegin('currentTime', TType.I64, 1)
oprot.writeI64(self.currentTime)
oprot.writeFieldEnd()
if self.fullSyncBefore != None:
oprot.writeFieldBegin('fullSyncBefore', TType.I64, 2)
oprot.writeI64(self.fullSyncBefore)
oprot.writeFieldEnd()
if self.updateCount != None:
oprot.writeFieldBegin('updateCount', TType.I32, 3)
oprot.writeI32(self.updateCount)
oprot.writeFieldEnd()
if self.uploaded != None:
oprot.writeFieldBegin('uploaded', TType.I64, 4)
oprot.writeI64(self.uploaded)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class SyncChunk(object):
"""
This structure is given out by the NoteStore when a client asks to
receive the current state of an account. The client asks for the server's
state one chunk at a time in order to allow clients to retrieve the state
of a large account without needing to transfer the entire account in
a single message.
The server always gives SyncChunks using an ascending series of Update
Sequence Numbers (USNs).
<dl>
<dt>currentTime</dt>
<dd>
The server's current date and time.
</dd>
<dt>chunkHighUSN</dt>
<dd>
The highest USN for any of the data objects represented
in this sync chunk. If there are no objects in the chunk, this will not be
set.
</dd>
<dt>updateCount</dt>
<dd>
The total number of updates that have been performed in
the service for this account. This is equal to the highest USN within the
account at the point that this SyncChunk was generated. If updateCount
and chunkHighUSN are identical, that means that this is the last chunk
in the account ... there | is no more recent information.
</dd>
<dt>notes</dt>
<dd>
| If present, this is a list of non-expunged notes that
have a USN in this chunk. This will include notes that are "deleted"
but not expunged (i.e. in the trash). The notes will include their list
of tags and resources, but the resource content and recognition data
will not be supplied.
</dd>
<dt>notebooks</dt>
<dd>
If present, this is a list of non-expunged notebooks that
have a USN in this chunk. This will include notebooks that are "deleted"
but not expunged (i.e. in the trash).
</dd>
<dt>tags</dt>
<dd>
If present, this is a list of the non-expunged tags that have a
USN in this chunk.
</dd>
<dt>searches</dt>
<dd>
If present, this is a list of non-expunged searches that
have a USN in this chunk.
</dd>
<dt>resources</dt>
<dd>
If present, this is a list of the non-expunged resources
that have a USN in this chunk. This will include the metadata for each
resource, but not its binary contents or recognition data, which must be
retrieved separately.
</dd>
<dt>expungedNotes</dt>
<dd>
If present, the GUIDs of all of the notes that were
permanently expunged in this chunk.
</dd>
<dt>expungedNotebooks</dt>
<dd>
If present, the GUIDs of all of the notebooks that
were permanently expunged in this chunk. When a notebook is expunged,
this implies that all of its child notes (and their resources) were
also expunged.
</dd>
<dt>expungedTags</dt>
<dd>
If present, the GUIDs of all of the tags that were
permanently expunged in this chunk.
</dd>
<dt>expungedSearches</dt>
<dd>
If present, the GUIDs of all of the saved searches
that were permanently expunged in this chunk.
</dd>
<dt>linkedNotebooks</dt>
<dd>
If present, this is a list of non-expunged LinkedNotebooks that
have a USN in this chunk.
</dd>
<dt>expungedLinkedNoteboo |
azumimuo/family-xbmc-addon | plugin.video.specto/resources/lib/resolvers/cloudmailru.py | Python | gpl-2.0 | 1,296 | 0.01466 | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can | redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will b | e useful,
but WITHOUT 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, see <http://www.gnu.org/licenses/>.
'''
import re,json,urllib
from resources.lib.libraries import client
def resolve(url):
try:
try:
v = url.split('public')[-1]
r = client.request(url)
r = re.sub(r'[^\x00-\x7F]+', ' ', r)
tok = re.findall('"tokens"\s*:\s*{\s*"download"\s*:\s*"([^"]+)', r)[0]
url = re.findall('"weblink_get"\s*:\s*\[.+?"url"\s*:\s*"([^"]+)', r)[0]
url = '%s%s?key=%s' % (url, v, tok)
print("u",url)
return url
except:
return
except:
return
|
akoskaaa/imfp | imfp/subscriptions/tests/test_models.py | Python | mit | 1,766 | 0.003964 |
from django.test.testcases import TestCase
from mock import patch, Mock
from imfp.subscriptions.models import Subscription
__all__ = ['CreateSubscriptionTestCase', 'RemoveSubscriptionTestCase']
class SubscriptionOperationsTestBase(TestCase):
def setUp(self):
self.mock_event = Mock(id=1)
self.mock_user = Mock(id=1)
self.mock_subscription = Mock(user=self.mock_user, event=self.mock_event)
self.subscription_manager = Subscription.objects
class CreateSubscriptionTestCase(SubscriptionOperationsTestBase):
def test_get_event_returns_none(self):
with patch('imfp.subscriptions.models.get_or_none') as mock_get_or_none:
mock_get_or_none.return_value = None
result = self.subscription_manager.create_subscription(self.m | ock_user.id, self.mock_event.id)
self.assertEquals(result, None)
# TODO figure this out.
#def test_create_subscription_success(self):
# with patch('imfp.subscriptions.models.get_or_none'):
# with patch('imfp.subscriptions.models.create') as mock_create:
# with patch('i | mfp.subscriptions.models.save'):
# mock_create.return_value = self.mock_subscription
# result = self.subscription_manager.create_subscription(self.mock_user.id, self.mock_event.id)
# self.assertNotEquals(result, None)
class RemoveSubscriptionTestCase(SubscriptionOperationsTestBase):
def test_get_event_returns_none(self):
with patch('imfp.subscriptions.models.get_or_none') as mock_get_or_none:
mock_get_or_none.return_value = None
result = self.subscription_manager.remove_subscription(self.mock_user.id, self.mock_event.id)
self.assertEquals(result, False)
|
marianotepper/dask | dask/distributed/scheduler.py | Python | bsd-3-clause | 24,150 | 0.000621 | from __future__ import print_function
import zmq
import socket
import dill
import uuid
from collections import defaultdict
import itertools
from multiprocessing.pool import ThreadPool
import random
from datetime import datetime
from threading import Thread, Lock
from contextlib import contextmanager
import traceback
import sys
from time import sleep
from ..compatibility import Queue, unicode, Empty
try:
import cPickle as pickle
except ImportError:
import pickle
from ..core import get_dependencies, flatten
from .. import core
from ..async import finish_task, start_state_from_dask as dag_state_from_dask
with open('log.scheduler', 'w') as f: # delete file
pass
def log(*args):
with open('log.scheduler', 'a') as f:
print('\n', *args, file=f)
@contextmanager
def logerrors():
try:
yield
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
tb = ''.join(traceback.format_tb(exc_traceback))
log('Error!', str(e))
log('Traceback', str(tb))
raise
class Scheduler(object):
""" Disitributed scheduler for dask computations
Parameters
----------
hostname: string
hostname or IP address of this machine visible to outside world
port_to_workers: int
Port on which to listen to connections from workers
port_to_clients: int
Port on which to listen to connections from clients
bind_to_workers: string
Addresses from which we accept worker connections, defaults to *
bind_to_clients: string
Addresses from which we accept client connections, defaults to *
block: bool
Whether or not to block the process on creation
State
-----
workers - dict
Maps worker identities to information about that worker
who_has - dict
Maps data keys to sets of workers that own that data
worker_has - dict
Maps workers to data that they own
data - dict
Maps data keys to metadata about the computation that produced it
to_workers - zmq.Socket (ROUTER)
Socket to communicate to workers
to_clients - zmq.Socket (ROUTER)
Socket to communicate with users
collections - dict
Dict holding shared collections like bags and arrays
"""
def __init__(self, port_to_workers=None, port_to_clients=None,
bind_to_workers='*', bind_to_clients='*',
hostname=None, block=False):
self.context = zmq.Context()
hostname = hostname or socket.gethostname()
# Bind routers to addresses (and create addresses if necessary)
self.to_workers = self.context.socket(zmq.ROUTER)
if port_to_workers is None:
port_to_workers = self.to_workers.bind_to_random_port('tcp://' + bind_to_workers)
else:
self.to_workers.bind('tcp://%s:%d' % (bind_to_workers, port_to_workers))
self.address_to_workers = ('tcp://%s:%d' % (hostname, port_to_workers)).encode()
self.worker_poller = zmq.Poller()
self.worker_poller.register(self.to_workers, zmq.POLLIN)
self.to_clients = self.context.socket(zmq.ROUTER)
if port_to_clients is None:
port_to_clients = self.to_clients.bind_to_random_port('tcp://' + bind_to_clients)
else:
self.to_clients.bind('tcp://%s:%d' % (bind_to_clients, port_to_clients))
self.address_to_clients = ('tcp://%s:%d' % (hostname, port_to_clients)).encode()
# State about my workers and computed data
self.workers = dict()
self.who_has = defaultdict(set)
self.worker_has = defaultdict(set)
self.available_workers = Queue()
self.data = defaultdict(dict)
self.collections = dict()
self.send_to_workers_queue = Queue()
self.send_to_workers_recv = self.context.socket(zmq.PAIR)
self.send_to_workers_recv.bind('ipc://to-workers-signal')
self.send_to_workers_send = self.context.socket(zmq.PAIR)
self.send_to_workers_send.connect('ipc://to-workers-signal')
self.worker_poller.register(self.send_to_workers_recv, zmq.POLLIN)
self.pool = ThreadPool(100)
self.lock = Lock()
self.status = 'run'
self.queues = dict()
self._schedule_lock = Lock()
# RPC functions that workers and clients can trigger
self.worker_functions = {'register': self._worker_registration,
'status': self._status_to_worker,
'finished-task': self._worker_finished_task,
'setitem-ack': self._setitem_ack,
'getitem-ack': self._getitem_ack}
self.client_functions = {'status': self._status_to_client,
'schedule': self._schedule_from_client,
'set-collection': self._set_collection,
'get-collection' | : self._get_collection,
'close': self._close}
# Away we go!
log(self.address_to_workers, 'Start')
self._listen_to_workers_thread = Thread(target=self._listen_to_workers)
self._listen_to_worker | s_thread.start()
self._listen_to_clients_thread = Thread(target=self._listen_to_clients)
self._listen_to_clients_thread.start()
if block:
self.block()
def _listen_to_workers(self):
""" Event loop: Listen to worker router """
while self.status != 'closed':
try:
socks = dict(self.worker_poller.poll(100))
if not socks:
continue
except zmq.ZMQError:
break
if self.send_to_workers_recv in socks:
self.send_to_workers_recv.recv()
while not self.send_to_workers_queue.empty():
msg = self.send_to_workers_queue.get()
self.to_workers.send_multipart(msg)
if self.to_workers in socks:
address, header, payload = self.to_workers.recv_multipart()
header = pickle.loads(header)
if 'address' not in header:
header['address'] = address
log(self.address_to_workers, 'Receive job from worker', header)
try:
function = self.worker_functions[header['function']]
except KeyError:
log(self.address_to_workers, 'Unknown function', header)
else:
future = self.pool.apply_async(function, args=(header, payload))
def _listen_to_clients(self):
""" Event loop: Listen to client router """
while self.status != 'closed':
try:
if not self.to_clients.poll(100): # is this threadsafe?
continue
except zmq.ZMQError:
break
with self.lock:
address, header, payload = self.to_clients.recv_multipart()
header = pickle.loads(header)
if 'address' not in header:
header['address'] = address
log(self.address_to_clients, 'Receive job from client', header)
try:
function = self.client_functions[header['function']]
except KeyError:
log(self.address_to_clients, 'Unknown function', header)
else:
self.pool.apply_async(function, args=(header, payload))
def block(self):
""" Block until listener threads close
Warning: If some other thread doesn't call `.close()` then, in the
common case you can not easily escape from this.
"""
self._listen_to_workers_thread.join()
self._listen_to_clients_thread.join()
def _worker_registration(self, header, payload):
""" Worker came in, register them """
payload = pickle.loads(payload)
address = header['address']
self.workers[address] = payload
self.available_workers.put(address)
def _worker_finished_task(self, header, payload): |
LaoZhongGu/kbengine | kbe/src/lib/python/Lib/ctypes/test/test_structures.py | Python | lgpl-3.0 | 15,782 | 0.002344 | import unittest
from ctypes import *
from struct import calcsize
import _testcapi
class SubclassesTest(unittest.TestCase):
def test_subclass(self):
class X(Structure):
_fields_ = [("a", c_int)]
class Y(X):
_fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)])
def test_subclass_delayed(self):
class X(Structure):
pass
self.assertEqual(sizeof(X), 0)
X._fields_ = [("a", c_int)]
class Y(X):
pass
self.assertEqual(sizeof(Y), sizeof(X))
Y._fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)])
class StructureTestCase(unittest.TestCase):
formats = {"c": c_char,
"b": c_byte,
"B": c_ubyte,
"h": c_short,
"H": c_ushort,
"i": c_int,
"I": c_uint,
"l": c_long,
"L": c_ulong,
"q": c_longlong,
"Q": c_ulonglong,
"f": c_float,
"d": c_double,
}
def test_simple_structs(self):
for code, tp in self.formats.items():
class X(Structure):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("c%c0%c" % (code, code)), code))
def test_unions(self):
for code, tp in self.formats.items():
class X(Union):
_fields_ = [("x", c_char),
("y", tp)]
self.as | sertEqual((sizeof(X), code),
(calcsize("%c" % (code)), code))
def test_struct_alignment(self):
class X(Structure):
_fields_ = [("x", c_char * 3)]
self.assertEqual(alignment(X), calcsize("s"))
| self.assertEqual(sizeof(X), calcsize("3s"))
class Y(Structure):
_fields_ = [("x", c_char * 3),
("y", c_int)]
self.assertEqual(alignment(Y), calcsize("i"))
self.assertEqual(sizeof(Y), calcsize("3si"))
class SI(Structure):
_fields_ = [("a", X),
("b", Y)]
self.assertEqual(alignment(SI), max(alignment(Y), alignment(X)))
self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
class IS(Structure):
_fields_ = [("b", Y),
("a", X)]
self.assertEqual(alignment(SI), max(alignment(X), alignment(Y)))
self.assertEqual(sizeof(IS), calcsize("3si 3s 0i"))
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), alignment(X))
self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
def test_emtpy(self):
# I had problems with these
#
# Although these are patological cases: Empty Structures!
class X(Structure):
_fields_ = []
class Y(Union):
_fields_ = []
# Is this really the correct alignment, or should it be 0?
self.assertTrue(alignment(X) == alignment(Y) == 1)
self.assertTrue(sizeof(X) == sizeof(Y) == 0)
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), 1)
self.assertEqual(sizeof(XX), 0)
def test_fields(self):
# test the offset and size attributes of Structure/Unoin fields.
class X(Structure):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, sizeof(c_int))
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
class X(Union):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, 0)
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
# XXX Should we check nested data types also?
# offset is always relative to the class...
def test_packed(self):
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 1
self.assertEqual(sizeof(X), 9)
self.assertEqual(X.b.offset, 1)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 2
self.assertEqual(sizeof(X), 10)
self.assertEqual(X.b.offset, 2)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 4
self.assertEqual(sizeof(X), 12)
self.assertEqual(X.b.offset, 4)
import struct
longlong_size = struct.calcsize("q")
longlong_align = struct.calcsize("bq") - longlong_size
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 8
self.assertEqual(sizeof(X), longlong_align + longlong_size)
self.assertEqual(X.b.offset, min(8, longlong_align))
d = {"_fields_": [("a", "b"),
("b", "q")],
"_pack_": -1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
# Issue 15989
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.INT_MAX + 1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.UINT_MAX + 2}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
def test_initializers(self):
class Person(Structure):
_fields_ = [("name", c_char*6),
("age", c_int)]
self.assertRaises(TypeError, Person, 42)
self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
self.assertRaises(TypeError, Person, "Name", "HI")
# short enough
self.assertEqual(Person(b"12345", 5).name, b"12345")
# exact fit
self.assertEqual(Person(b"123456", 5).name, b"123456")
# too long
self.assertRaises(ValueError, Person, b"1234567", 5)
def test_conflicting_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
# conflicting positional and keyword args
self.assertRaises(TypeError, POINT, 2, 3, x=4)
self.assertRaises(TypeError, POINT, 2, 3, y=4)
# too many initializers
self.assertRaises(TypeError, POINT, 2, 3, 4)
def test_keyword_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
pt = POINT(1, 2)
self.assertEqual((pt.x, pt.y), (1, 2))
pt = POINT(y=2, x=1)
self.assertEqual((pt.x, pt.y), (1, 2))
def test_invalid_field_types(self):
class POINT(Structure):
pass
self.assertRaises(TypeError, setattr, POINT, "_fields_" |
slaporte/qualityvis | orange_scripts/project_setup.py | Python | gpl-3.0 | 321 | 0.009346 | """
Load this into a Python Script widget (does not have
to be connected to any other widgets), and set the
project directory to the location of the git repo.
Hit execute and enjoy!
"""
PRO | JECT_DIR = '/home/mahmoud/work/qualityvis'
import sys
sys.path.append(PROJECT_DIR)
sys.path.append(PROJ | ECT_DIR+'/orange_scripts') |
AlexEKoren/grumpy | compiler/block_test.py | Python | apache-2.0 | 10,530 | 0.002757 | # coding=utf-8
# Copyright 2016 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 agreed to in writing, software
# distributed under the License is distributed 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.
"""Tests Package, Block, BlockVisitor and related classes."""
import ast
import textwrap
import unittest
from grumpy.compiler import block
from grumpy.compiler import util
class PackageTest(unittest.TestCase):
def testCreate(self):
package = block.Package('foo/bar/baz')
self.assertEqual(package.name, 'foo/bar/baz')
self.assertEqual(package.alias, 'π_fooΓbarΓbaz')
def testCreateGrump(self):
package = block.Package('foo/bar/baz', 'myalias')
self.assertEqual(package.name, 'foo/bar/baz')
self.assertEqual(package.alias, 'myalias')
class BlockTest(unittest.TestCase):
def testAddImport(self):
module_block = _MakeModuleBlock()
func1_block = block.FunctionBlock(module_block, 'func1', {}, False)
func2_block = block.FunctionBlock(func1_block, 'func2', {}, False)
package = func2_block.add_import('foo/bar')
self.assertEqual(package.name, 'grumpy/lib/foo/bar')
self.assertEqual(package.alias, 'π_grumpyΓlibΓfooΓbar')
self.assertEqual(module_block.imports, {'grumpy/lib/foo/bar': package})
def testAddImportRepeated(self):
b = _MakeModuleBlock()
package = b.add_import('foo')
self.assertEqual(package.name, 'grumpy/lib/foo')
self.assertEqual(package.alias, 'π_grumpyΓlibΓfoo')
self.assertEqual(b.imports, {'grumpy/lib/foo': package})
package2 = b.add_import('foo')
self.assertIs(package, package2)
self.assertEqual(b.imports, {'grumpy/lib/foo': package})
def testLoop(self):
b = _MakeModuleBlock()
loop = b.push_loop()
self.assertEqual(loop, b.top_loop())
inner_loop = b.push_loop()
self.assertEqual(inner_loop, b.top_loop())
b.pop_loop()
self.assertEqual(loop, b.top_loop())
def testResolveName(self):
module_block = _MakeModuleBlock()
block_vars = {'foo': block.Var('foo', block.Var.TYPE_LOCAL)}
func1_block = block.FunctionBlock(module_block, 'func1', block_vars, False)
block_vars = {'bar': block.Var('bar', block.Var.TYPE_LOCAL)}
func2_block = block.FunctionBlock(func1_block, 'func2', block_vars, False)
block_vars = {'case': block.Var('case', block.Var.TYPE_LOCAL)}
keyword_block = block.FunctionBlock(
module_block, 'keyword_func', block_vars, False)
class1_block = block.ClassBlock(module_block, 'Class1', set())
class2_block = block.ClassBlock(func1_block, 'Class2', set())
self.assertRegexpMatches(self._ResolveName(module_block, 'foo'),
r'ResolveGlobal\b.*foo')
self.assertRegexpMatches(self._ResolveName(module_block, 'bar'),
r'ResolveGlobal\b.*bar')
self.assertRegexpMatches(self._ResolveName(module_block, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(func1_block, 'foo'),
| r'CheckLocal\b.*foo')
self.assertRegexpMatches(self._ResolveName(func1_block, 'bar'),
r'ResolveGlobal\b.*bar')
self.assertRegexpMatches(self._ResolveName(func1_bl | ock, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(func2_block, 'foo'),
r'CheckLocal\b.*foo')
self.assertRegexpMatches(self._ResolveName(func2_block, 'bar'),
r'CheckLocal\b.*bar')
self.assertRegexpMatches(self._ResolveName(func2_block, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(class1_block, 'foo'),
r'ResolveClass\(.*, nil, .*foo')
self.assertRegexpMatches(self._ResolveName(class2_block, 'foo'),
r'ResolveClass\(.*, µfoo, .*foo')
self.assertRegexpMatches(self._ResolveName(keyword_block, 'case'),
r'CheckLocal\b.*µcase, "case"')
def _ResolveName(self, b, name):
writer = util.Writer()
b.resolve_name(writer, name)
return writer.out.getvalue()
class BlockVisitorTest(unittest.TestCase):
def testAssignSingle(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo = 3'))
self.assertEqual(visitor.vars.keys(), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def testAssignMultiple(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo = bar = 123'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
def testAssignTuple(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo, bar = "a", "b"'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
def testAssignNested(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo, (bar, baz) = "a", ("b", "c")'))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'baz', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal')
def testAugAssignSingle(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('foo += 3'))
self.assertEqual(visitor.vars.keys(), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def testVisitClassDef(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('class Foo(object): pass'))
self.assertEqual(visitor.vars.keys(), ['Foo'])
self.assertRegexpMatches(visitor.vars['Foo'].init_expr, r'UnboundLocal')
def testExceptHandler(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt(textwrap.dedent("""\
try:
pass
except Exception as foo:
pass
except TypeError as bar:
pass""")))
self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal')
def testFor(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('for i in foo: pass'))
self.assertEqual(visitor.vars.keys(), ['i'])
self.assertRegexpMatches(visitor.vars['i'].init_expr, r'UnboundLocal')
def testFunctionDef(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('def foo(): pass'))
self.assertEqual(visitor.vars.keys(), ['foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
def testImport(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('import foo.bar, baz'))
self.assertEqual(sorted(visitor.vars.keys()), ['baz', 'foo'])
self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal')
def testImportFrom(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseStmt('from foo.bar import baz, qux'))
self.assertEqual(sorted(visitor.vars.keys()), ['baz', 'qux'])
self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal')
self.assertRegexpMatches(visitor.vars['qux'].init_expr, r'UnboundLocal')
def testGlobal(self):
visitor = block.BlockVisitor()
visitor.visit(_ParseSt |
windyer/windyer_blog | windyer_blog/wsgi.py | Python | bsd-3-clause | 395 | 0 | """
WSGI config for mysite project.
It exposes | the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_ | MODULE", "windyer_blog.settings")
application = get_wsgi_application()
|
miguelinux/vbox | src/VBox/Main/webservice/samples/python/clienttest.py | Python | gpl-2.0 | 4,520 | 0.006195 | #!/usr/bin/python
#
# Copyright (C) 2012 Oracle Corporation
#
# This file is part of VirtualBox Open Source Edition (OSE), as
# available from http://www.virtualbox.org. This file is free software;
# you can redistribute it and/or modify it under the terms of the GNU
# General Public License (GPL) as published by the Free Software
# Foundation, in version 2 as it comes in the "COPYING" file of the
# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
#
# Things needed to be set up before running this sample:
# - Install Python and verify it works (2.7.2 will do, 3.x is untested yet)
# - On Windows: Install the PyWin32 extensions for your Python version
# (see http://sourceforge.net/projects/pywin32/)
# - If not already done, set the environment variable "VBOX_INSTALL_PATH"
# to point to your VirtualBox installation directory (which in turn must have
# the "sdk" subfolder")
# - Install the VirtualBox Python bindings by doing a
# "[python] vboxapisetup.py install"
# - Run this sample with "[python] clienttest.py"
import os,sys
import traceback
#
# Converts an enumeration to a printable string.
#
def enumToString(constants, enum, elem):
all = constants.all_values(enum)
for e in all.keys():
if str(elem) == str(all[e]):
return e
return "<unknown>"
def main(argv):
from vboxapi import VirtualBoxManager
# This is a VirtualBox COM/XPCOM API client, no data needed.
wrapper = VirtualBoxManager(None, None)
# Get the VirtualBox manager
mgr = wrapper.mgr
# Get the global VirtualBox object
vbox = wrapper.vbox
print "Running VirtualBox version %s" %(vbox.version)
# Get all constants through the Python wrapper code
vboxConstants = wrapper.constants
# Enumerate all defined machines
for mach in wrapper.getArray(vbox, 'machines'):
try:
# Be prepared for failures - the VM can be inaccessible
vmname = '<inaccessible>'
try:
vmname = mach.name
except Exception, e:
None
vmid = '';
try:
vmid = mach.id
except Exception, e:
None
# Print some basic VM information even if there were errors
print "Machine name: %s [%s]" %(vmname,vmid)
if vmname == '<inaccessible>' or vmid == '':
continue
# Print some basic VM information
print " State: %s" %(enumToString(vboxConstants, "MachineState", mach.state))
print " Session state: %s" %(enumToString(vboxConstants, "SessionState", mach.sessionState))
# Do some stuff which requires a running VM
if mach.state == vboxConstants.MachineState_Running:
# Get the session object
session = mgr.getSessionObject(vbox)
# Lock the current machine (shared mode, since we won't modify the machine)
mach.lockMachine(session, vboxConstants.LockType_Shared)
# Acquire the VM's console and guest object
console = session.console
guest = console.guest
# Retrieve the current Guest Additions runlevel and print
# the installed Guest Additions version
addRunLevel = guest.additionsRunLevel
print " Additions State: %s" %(enumToString(vboxConstants, "AdditionsRunLevelType", addRunLevel))
if addRunLevel != vboxConstants.AdditionsRunLevelType_None:
print " Additions Ver: %s" %(guest.additionsVersion)
# Get the VM's display object
display = console.display
# Get the VM | 's current display resolution + bit depth + position
screenNum = 0 # From first screen
(screenW, screenH, screenBPP, screenX, screenY, _) = display.getScreenResolution(screenNum)
print " Display (%d): %dx%d, %d BPP at %d,%d" %(screenN | um, screenW, screenH, screenBPP, screenX, screenY)
# We're done -- don't forget to unlock the machine!
session.unlockMachine()
except Exception, e:
print "Errror [%s]: %s" %(mach.name, str(e))
traceback.print_exc()
# Call destructor and delete wrapper
del wrapper
if __name__ == '__main__':
main(sys.argv)
|
MyRobotLab/pyrobotlab | home/kwatters/harry/gestures/InMoovApps/Rock_Paper_Scissors/rock.py | Python | apache-2.0 | 1,243 | 0.132743 | def rock():
fullspeed()
i01.moveHead(90,90)
i01.moveArm("left",70,90,80,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.setHeadSpeed(.8,.8)
i01.moveHead(60,107)
i01.moveArm("left",49,90,75,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5) |
i01.moveArm("left",80,90,85,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.setHeadSpeed(.8,.8)
i01.moveHead(60,107)
i01.moveArm("left",49,90,75,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.moveArm("left",9 | 0,90,90,10)
i01.moveArm("right",20,85,10,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.setHeadSpeed(.8,.8)
i01.moveHead(60,107)
i01.moveArm("left",45,90,75,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,80)
i01.moveHand("right",50,90,90,90,100,90) |
nvenayak/impact | impact/core/__init__.py | Python | gpl-3.0 | 276 | 0.007246 | from .TrialIdentifier import *
from .AnalyteData import TimeCourse, TimePoint, Substrate, Product, Biomass, Reporter, FitParameter
from .SingleTrial import SingleTrial
from .ReplicateTri | al import ReplicateT | rial
from .Experiment import Experiment
from .settings import settings |
ctuning/ck-env | soft/plugin.openme.ctuning/customize.py | Python | bsd-3-clause | 2,895 | 0.02418 | #
# Collective Knowledge (individual environment - setup)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
##############################################################################
# setup environment setup
def setup(i):
"""
Input: {
cfg - meta of this soft entry
self_cfg - meta of module soft
ck_kernel - import CK kernel module (to reuse functions)
host_os_uoa - host OS UOA
host_os_uid - host OS UID
host_os_dict - host OS meta
target_os_uoa - target OS UOA
target_os_uid - target OS UID
target_os_dict - target OS meta
target_device_id - target device ID (if via ADB)
tags - list of tags used to search this entry
env - updated environment vars from meta
customize - updated customize vars from meta
deps - resolved dependencies for this soft
interactive - if 'yes', can ask questions, otherwise quiet
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
bat - prepared string for bat file
}
"""
import os
# Get variables
ck=i['ck_kernel']
s=''
iv=i.get('interactive','')
env=i.get('env',{})
cfg=i.get('cfg',{})
deps=i.get('deps',{})
tags=i.get('tags',[])
cus=i.get('customize',{})
target_d=i.get('target_os_dict',{})
win=target_d.get('windows_base','')
remote=target_d.get('remote','')
mingw=target_d.get('mingw','')
tbits=target_d.get('bits','')
envp=cus.get('env_prefix','')
pi=cus.get('path_install','')
host_d=i.get('host_os_dict',{})
sdirs=host_d.get('dir_sep','')
fp=cus.get('full_path','')
if fp!='':
p1=os.path.dirname(fp)
pi=os.path.dirname(p1)
cus['path_lib']=pi+sdirs+'lib'
ep=cus.get('env_prefix','')
if pi!='' and ep!='':
env[ep]=pi
################################################################
| if win=='yes':
if remote=='yes' or mingw=='yes':
dext='.so'
else:
dext='.dll'
else:
dext='.so'
r = ck.access({'action': 'lib_path_export_script', 'module_uoa': | 'os', 'host_os_dict': host_d,
'dynamic_lib_path': cus.get('path_lib','')})
if r['return']>0: return r
s += r['script']
cus['dynamic_plugin']='plugin-openme-ctuning-1.5'+dext
env[envp+'_DYNAMIC_NAME']=cus.get('dynamic_plugin','')
return {'return':0, 'bat':s}
|
jilljenn/tryalgo | tryalgo/eulerian_tour.py | Python | mit | 4,665 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Eulerian cycle
jill-jênn vie et christoph dürr - 2015-2020
"""
import random
from tryalgo.graph import write_graph
# snip{ eulerian_tour_undirected
def eulerian_tour_undirected(graph):
"""Eulerian tour on an undirected graph
:param graph: directed graph in listlist format, cannot be listdict
:assumes: graph is eulerian
:returns: eulerian cycle as a vertex list
:complexity: `O(|V|+|E|)`
"""
P = [] # resulting tour
Q = [0] # vertices to be explored, start at 0
R = [] # path from start node
next_ = [0] * len(graph) # initialize next_ to 0 for each node
seen = [set() for _ in graph] # mark backward arcs
while Q:
start = Q.pop() # explore a cycle from start node
node = start # current node on cycle
while next_[node] < len(graph[node]): # visit all allowable arcs
neighbor = graph[node][next_[node]] # traverse an arc
next_[node] += 1 # mark arc traversed
if neighbor not in seen[node]: # not yet traversed
seen[neighbor].add(node) # mark backward arc
R.append(neighbor) # append to path from start
node = neighbor # move on
while R:
Q.append(R.pop()) # add to Q the discovered cycle R
P.append(start) # resulting path P is extended
return P
# snip}
# snip{ eulerian_tour_directed
def eulerian_tour_directed(graph):
"""Eulerian tour on a directed graph
:param graph: directed graph in listlist format, cannot be listdict
:assumes: graph is eulerian
:returns: eulerian cycle as a vertex list
:complexity: `O(|V|+|E|)`
"""
P = [] # resulting tour
Q = [0] # vertices to be explored, start at 0
R = [] # path from start node
next_ = [0] * len(graph) # initialize next_ to 0 for each node
while Q:
start = Q.pop() # explore a cycle from start node
node = start # current node on cycle
while next_[node] < len(graph[node]): # visit all allowable arcs
neighbor = graph[node][next_[node]] # traverse an arc
next_[node] += 1 # mark arc traversed
R.append(neighbor) # ap | pend to path from start
node = neighbor # move on
while R:
Q.append(R.pop()) # add to Q the discovered cycle R
P.append(start) # resulting path P is extended
return P
# snip}
def write_cycle(filename, graph, cycle, directed):
"""Write an eulerian tour in DOT format
:param filename: the file to be written in DOT format
:param graph: graph in listlist format, cannot be listdict
:param bool direc | ted: describes the graph
:param cycle: tour as a vertex list
:returns: nothing
:complexity: `O(|V|^2 + |E|)`
"""
n = len(graph)
weight = [[float('inf')] * n for _ in range(n)]
for r in range(1, len(cycle)):
weight[cycle[r-1]][cycle[r]] = r
if not directed:
weight[cycle[r]][cycle[r-1]] = r
write_graph(filename, graph, arc_label=weight, directed=directed)
def random_eulerien_graph(n):
"""Generates some random eulerian graph
:param int n: number of vertices
:returns: undirected graph in listlist representation
:complexity: linear
"""
graphe = [[] for _ in range(n)]
for v in range(n - 1):
noeuds = random.sample(range(v + 1, n), random.choice(
range(0 if len(graphe[v]) % 2 == 0 else 1, (n - v), 2)))
graphe[v].extend(noeuds)
for w in graphe[v]:
if w > v:
graphe[w].append(v)
return graphe
def is_eulerian_tour(graph, tour):
"""Eulerian tour on an undirected graph
:param graph: directed graph in listlist format, cannot be listdict
:param tour: vertex list
:returns: test if tour is eulerian
:complexity: `O(|V|*|E|)` under the assumption that
set membership is in constant time
"""
m = len(tour)-1
arcs = set((tour[i], tour[i+1]) for i in range(m))
if len(arcs) != m:
return False
for (u, v) in arcs:
if v not in graph[u]:
return False
return True
|
losalamos/Pavilion | PAV/modules/helperutilities.py | Python | bsd-3-clause | 3,253 | 0.011989 | #!python
# ###################################################################
#
# Disclaimer and Notice of Copyright
# ==================================
#
# Copyright (c) 2015, Los Alamos National Security, LLC
# All rights reserved.
#
# Copyright 2015. Los Alamos National Security, LLC.
# This software was produced under U.S. Government contract
# DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL),
# which is operated by Los Alamos National Security, LLC for
# the U.S. Department of Energy. The U.S. Government has rights
# to use, reproduce, and distribute this software. NEITHER
# THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES
# ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY
# FOR THE USE OF THIS SOFTWARE. If software is modified to
# produce derivative works, such modified software should be
# clearly marked, so as not to confuse it with the version
# available from LANL.
#
# Additionally, redistribution and use in source and binary
# forms, with or without modification, are permitted provided
# that the following conditions are met:
# - Redistributions of source code must retain the
# above copyright notice, this list of conditions
# and the following disclaimer.
# - Redistributions in binary form must reproduce the
# above copyright notice, this list of conditions
# and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# - Neither the name of Los Alamos National Security, LLC,
# Los Alamos National Laboratory, LANL, the U.S. Government,
# nor the names of its contributors may be used to endorse
# or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC
# AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
#
# ###################################################################
import os
# implement linux "which" command
# FWIW, python 3.3 offers shutil.which()
def which(program | ):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
| else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
|
klmitch/glance | glance/common/client.py | Python | apache-2.0 | 23,213 | 0 | # Copyright 2010-2011 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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed 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.
# HTTPSClientAuthConnection code comes courtesy of ActiveState website:
# http://code.activestate.com/recipes/
# 577548-https-httplib-client-connection-with-certificate-v/
import collections
import copy
import errno
import functools
import os
import re
try:
from eventlet.green import socket
from eventlet.green import ssl
except ImportError:
import socket
import ssl
import osprofiler.web
try:
import sendfile # noqa
SENDFILE_SUPPORTED = True
except ImportError:
SENDFILE_SUPPORTED = False
from oslo_log import log as logging
from oslo_utils import encodeutils
import six
from six.moves import http_client
# NOTE(jokke): simplified transition to py3, behaves like py2 xrange
from six.moves import range
import six.moves.urllib.parse as urlparse
from glance.common import auth
from glance.common import exception
from glance.common import utils
from glance.i18n import _
LOG = logging.getLogger(__name__)
# common chunk size for get and put
CHUNKSIZE = 65536
VERSION_REGEX = re.compile(r"/?v[0-9\.]+")
def handle_unauthenticated(func):
"""
Wrap a function to re-authenticate and retry.
"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except exception.NotAuthenticated:
self._authenticate(force_reauth=True)
return func(self, *args, **kwargs)
return wrapped
def handle_redirects(func):
"""
Wrap the _do_request function to handle HTTP redirects.
"""
MAX_REDIRECTS = 5
@functools.wraps(func)
def wrapped(self, method, url, body, headers):
for i in range(MAX_REDIRECTS):
try:
return func(self, method, url, body, headers)
except exception.RedirectException as redirect:
if redirect.url is None:
raise exception.InvalidRedirect()
url = redirect.url
raise exception.MaxRedirectsExceeded(redirects=MAX_REDIRECTS)
return wrapped
class HTTPSClientAuthConnection(http_client.HTTPSConnection):
"""
Class to make a HTTPS connection, with support for
full client-based SSL Authentication
:see http://code.activestate.com/recipes/
577548-https-httplib-client-connection-with-certificate-v/
"""
def __init__(self, host, port, key_file, cert_file,
ca_file, timeout=None, insecure=False):
http_client.HTTPSConnection.__init__(self, host, port,
key_file=key_file,
cert_file=cert_file)
self.key_file = key_file
self.cert_file = cert_file
self.ca_file = ca_file
self.timeout = timeout
self.insecure = insecure
def connect(self):
"""
Connect to a host on a given (SSL) port.
If ca_file is pointing somewhere, use it to check Server Certificate.
Redefined/copied and extended from httplib.py:1105 (Python 2.6.x).
This is needed to pass cert_reqs=ssl.CERT_REQUIRED as parameter to
ssl.wrap_socket(), which forces SSL to check server certificate against
our client certificate.
"""
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
# Check CA file unless 'insecure' is specified
if self.insecure is True:
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
cert_reqs=ssl.CERT_NONE)
else:
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
ca_certs=self.ca_file,
cert_reqs=ssl.CERT_REQUIRED)
class BaseClient(object):
"""A base client class"""
DEFAULT_PORT = 80
DEFAULT_DOC_ROOT = None
# Standard CA file locations for Debian/Ubuntu, RedHat/Fedora,
# Suse, FreeBSD/OpenBSD
DEFAULT_CA_FILE_PATH = ('/etc/ssl/certs/ca-certificates.crt:'
'/etc/pki/tls/certs/ca-bundle.crt:'
'/etc/ssl/ca-bundle.pem:'
'/etc/ssl/cert.pem')
OK_RESPONSE_CODES = (
http_client.OK,
http_client.CREATED,
http_client.ACCEPTED,
http_client.NO_CONTENT,
)
REDIRECT_RESPONSE_CODES = (
http_client.MOVED_PERMANENTLY,
http_client.FOUND,
http_client.SEE_OTHER,
http_client.USE_PROXY,
http_client.TEMPORARY_REDIRECT,
)
def __init__(self, host, port=None, timeout=None, use_ssl=False,
auth_token=None, creds=None, doc_root=None, key_file=None,
cert_file=None, ca_file=None, insecure=False,
configure_via_auth=True):
"""
Creates a new client to some service.
:param host: The host where service resides
:param port: The port where service resides
:param timeout: Connection timeout.
:param use_ssl: Should we use HTTPS?
:param auth_token: The auth token to pass to the server
:param creds: The credentials to pass to the auth plugin
:param doc_root: Prefix for all URLs we request from host
:param key_file: Optional PEM-formatted file that contains the private
key.
If use_ssl is True, and this param is None (the
default), then an environ variable
GLANCE_CLIENT_KEY_FILE is looked for. If no such
environ variable is found, ClientConnectionError
will be raised.
:param cert_file: Optional PEM-formatted certificate chain file.
If use_ssl is True, and this param is None (the
default), then an environ variable
GLANCE_CLIENT_CERT_FILE is looked for. If no such
environ variable is found, ClientConnectionError
will be raised.
:param ca_file: Optional CA cert file to use in SSL connections
If use_ssl is True, and this param is None (the
default), then an environ variable
GLANCE_CLIENT_CA_FILE is looked for.
:param insecure: Optional. If set then the server's certificate
will not be verified.
:param configure_via_auth: Optional. Defaults to True. If set, the
URL returned from the service catalog for the image
endpoint will **override** the URL supplied to in
the host parameter.
""" |
self.host = host
| self.port = port or self.DEFAULT_PORT
self.timeout = timeout
# A value of '0' implies never timeout
if timeout == 0:
self.timeout = None
self.use_ssl = use_ssl
self.auth_token = auth_token
self.creds = creds or {}
self.connection = None
self.configure_via_auth = configure_via_auth
# doc_root can be a nullstring, which is valid, and why we
# cannot simply do doc_root or self.DEFAULT_DOC_ROOT below.
self.doc_root = (doc_root if doc_root is not None
else self.DEFAULT_DOC_ROOT)
self.key_file = key_file
self.cert_file |
wemanuel/smry | smry/server-auth/ls/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/target_https_proxies/describe.py | Python | apache-2.0 | 917 | 0.007634 | # Copyright 2014 Google Inc. All Rights Reserved.
"""Command for describing target HTTP | S proxies."""
from googlecloudsdk.compute.lib import base_classes
class Describe(base_classes.GlobalDescriber):
"""Display detailed information about a target HTTPS proxy."""
@staticmethod
def Args(parser):
cli = Describe.GetCLIGenerator()
base_classes.GlobalDescriber.Args(
parser, 'compute.targetHttpsProxies', cli,
'compute.target-https-proxies')
base_classes.AddFieldsFlag(parser, 'target | HttpsProxies')
@property
def service(self):
return self.compute.targetHttpsProxies
@property
def resource_type(self):
return 'targetHttpsProxies'
Describe.detailed_help = {
'brief': 'Display detailed information about a target HTTPS proxy',
'DESCRIPTION': """\
*{command}* displays all data associated with a target HTTPS proxy
in a project.
""",
}
|
jolene-esposito/osf.io | website/mails.py | Python | apache-2.0 | 7,045 | 0.002413 | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_prefix='confirm', subject="Confirm your email address")
You can then use ``send_mail`` to send the email.
Usage: ::
from website import mails
...
mails.send_mail('foo@bar.com | ', mails.CONFIRM_EMAIL, user=user)
"""
import os
import logging
from mako.lookup import TemplateLookup, Template
from framework.email import tasks
from website import settings
logger = logging.getLogger(__name__)
EMAIL_TEMPLATES_DIR = os.path.join(settings.TEMPLATES_PATH, 'emails')
|
_tpl_lookup = TemplateLookup(
directories=[EMAIL_TEMPLATES_DIR],
)
TXT_EXT = '.txt.mako'
HTML_EXT = '.html.mako'
class Mail(object):
"""An email object.
:param str tpl_prefix: The template name prefix.
:param str subject: The subject of the email.
"""
def __init__(self, tpl_prefix, subject):
self.tpl_prefix = tpl_prefix
self._subject = subject
def html(self, **context):
"""Render the HTML email message."""
tpl_name = self.tpl_prefix + HTML_EXT
return render_message(tpl_name, **context)
def text(self, **context):
"""Render the plaintext email message"""
tpl_name = self.tpl_prefix + TXT_EXT
return render_message(tpl_name, **context)
def subject(self, **context):
return Template(self._subject).render(**context)
def render_message(tpl_name, **context):
"""Render an email message."""
tpl = _tpl_lookup.get_template(tpl_name)
return tpl.render(**context)
def send_mail(to_addr, mail, mimetype='plain', from_addr=None, mailer=None,
username=None, password=None, mail_server=None, callback=None, **context):
"""Send an email from the OSF.
Example: ::
from website import mails
mails.send_email('foo@bar.com', mails.TEST, name="Foo")
:param str to_addr: The recipient's email address
:param Mail mail: The mail object
:param str mimetype: Either 'plain' or 'html'
:param function callback: celery task to execute after send_mail completes
:param **context: Context vars for the message template
.. note:
Uses celery if available
"""
from_addr = from_addr or settings.FROM_EMAIL
mailer = mailer or tasks.send_email
subject = mail.subject(**context)
message = mail.text(**context) if mimetype in ('plain', 'txt') else mail.html(**context)
# Don't use ttls and login in DEBUG_MODE
ttls = login = not settings.DEBUG_MODE
logger.debug('Sending email...')
logger.debug(u'To: {to_addr}\nFrom: {from_addr}\nSubject: {subject}\nMessage: {message}'.format(**locals()))
kwargs = dict(
from_addr=from_addr,
to_addr=to_addr,
subject=subject,
message=message,
mimetype=mimetype,
ttls=ttls,
login=login,
username=username,
password=password,
mail_server=mail_server
)
if settings.USE_CELERY:
return mailer.apply_async(kwargs=kwargs, link=callback)
else:
ret = mailer(**kwargs)
if callback:
callback()
return ret
# Predefined Emails
TEST = Mail('test', subject='A test email to ${name}')
CONFIRM_EMAIL = Mail('confirm', subject='Confirm your email address')
CONFIRM_MERGE = Mail('confirm_merge', subject='Confirm account merge')
REMOVED_EMAIL = Mail('email_removed', subject='Email address removed from your OSF account')
PRIMARY_EMAIL_CHANGED = Mail('primary_email_changed', subject='Primary email changed')
INVITE = Mail('invite', subject='You have been added as a contributor to an OSF project.')
CONTRIBUTOR_ADDED = Mail('contributor_added', subject='You have been added as a contributor to an OSF project.')
FORWARD_INVITE = Mail('forward_invite', subject='Please forward to ${fullname}')
FORWARD_INVITE_REGiSTERED = Mail('forward_invite_registered', subject='Please forward to ${fullname}')
FORGOT_PASSWORD = Mail('forgot_password', subject='Reset Password')
PENDING_VERIFICATION = Mail('pending_invite', subject="Your account is almost ready!")
PENDING_VERIFICATION_REGISTERED = Mail('pending_registered', subject='Received request to be a contributor')
REQUEST_EXPORT = Mail('support_request', subject='[via OSF] Export Request')
REQUEST_DEACTIVATION = Mail('support_request', subject='[via OSF] Deactivation Request')
CONFERENCE_SUBMITTED = Mail(
'conference_submitted',
subject='Project created on Open Science Framework',
)
CONFERENCE_INACTIVE = Mail(
'conference_inactive',
subject='Open Science Framework Error: Conference inactive',
)
CONFERENCE_FAILED = Mail(
'conference_failed',
subject='Open Science Framework Error: No files attached',
)
DIGEST = Mail('digest', subject='OSF Email Digest')
TRANSACTIONAL = Mail('transactional', subject='OSF: ${subject}')
# Retraction related Mail objects
PENDING_RETRACTION_ADMIN = Mail(
'pending_retraction_admin',
subject='Retraction pending for one of your projects.'
)
PENDING_RETRACTION_NON_ADMIN = Mail(
'pending_retraction_non_admin',
subject='Retraction pending for one of your projects.'
)
# Embargo related Mail objects
PENDING_EMBARGO_ADMIN = Mail(
'pending_embargo_admin',
subject='Registration pending for one of your projects.'
)
PENDING_EMBARGO_NON_ADMIN = Mail(
'pending_embargo_non_admin',
subject='Registration pending for one of your projects.'
)
# Registration related Mail Objects
PENDING_REGISTRATION_ADMIN = Mail(
'pending_registration_admin',
subject='Registration pending for one of your projects.'
)
PENDING_REGISTRATION_NON_ADMIN = Mail(
'pending_registration_non_admin',
subject='Registration pending for one of your projects.'
)
FILE_OPERATION_SUCCESS = Mail(
'file_operation_success',
subject='Your ${action} has finished',
)
FILE_OPERATION_FAILED = Mail(
'file_operation_failed',
subject='Your ${action} has failed',
)
UNESCAPE = "<% from website.util.sanitize import unescape_entities %> ${unescape_entities(src.title)}"
PROBLEM_REGISTERING = "Problem registering " + UNESCAPE
ARCHIVE_SIZE_EXCEEDED_DESK = Mail(
'archive_size_exceeded_desk',
subject=PROBLEM_REGISTERING
)
ARCHIVE_SIZE_EXCEEDED_USER = Mail(
'archive_size_exceeded_user',
subject=PROBLEM_REGISTERING
)
ARCHIVE_COPY_ERROR_DESK = Mail(
'archive_copy_error_desk',
subject=PROBLEM_REGISTERING
)
ARCHIVE_COPY_ERROR_USER = Mail(
'archive_copy_error_user',
subject=PROBLEM_REGISTERING
)
ARCHIVE_UNCAUGHT_ERROR_DESK = Mail(
'archive_uncaught_error_desk',
subject=PROBLEM_REGISTERING
)
ARCHIVE_UNCAUGHT_ERROR_USER = Mail(
'archive_uncaught_error_user',
subject=PROBLEM_REGISTERING
)
ARCHIVE_SUCCESS = Mail(
'archive_success',
subject="Registration of " + UNESCAPE + " complete"
)
|
ahu-odoo/odoo | addons/account/partner.py | Python | agpl-3.0 | 15,435 | 0.00596 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from operator import itemgetter
import time
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp import api
class account_fiscal_position(osv.osv):
_name = 'account.fiscal.position'
_description = 'Fiscal Position'
_order = 'sequence'
_columns = {
'sequence': fields.integer('Sequence'),
'name': fields.char('Fiscal Position', required=True),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide a fiscal position without deleting it."),
'company_id': fields.many2one('res.company', 'Company'),
'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping', copy=True),
'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping', copy=True),
'note': fields.text('Notes'),
'auto_apply': fields.boolean('Automatic', help="Apply automatically this fiscal position."),
'vat_required': fields.boolean('VAT required', help="Apply only if partner has a VAT number."),
'country_id': fields.many2one('res.country', 'Countries', help="Apply only if delivery or invoicing country match."),
'country_group_id': fields.many2one('res.country.group', 'Country Group', help="Apply only if delivery or invocing country match the group."),
}
_defaults = {
'active': True,
}
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
if not taxes:
return []
if not fposition_id:
return map(lambda x: x.id, taxes)
result = set()
for t in taxes:
ok = False
for tax in fposition_id.tax_ids:
if tax.tax_src_id.id == t.id:
if tax.tax_dest_id:
result.add(tax.tax_dest_id.id)
ok=True
if not ok:
result.add(t.id)
return list(result)
@api.v8
def map_tax(self, taxes):
result = taxes.browse()
for tax in taxes:
found = False
for t in self.tax_ids:
if t.tax_src_id == tax:
result |= t.tax_dest_id
found = True
if not found:
result |= tax
return result
@api.v7
def map_account(self, cr, uid, fposition_id, account_id, context=None):
if not fposition_id:
return account_id
for pos in fposition_id.account_ids:
if pos.account_src_id.id == account_id:
account_id = pos.account_dest_id.id
break
return account_id
@api.v8
def map_account(self, account):
for pos in self.account_ids:
if pos.account_src_id == account:
return pos.account_dest_id
return account
def get_fiscal_position(self, cr, uid, company_id, partner_id, delivery_id=None, context=None):
if not partner_id:
return False
# This can be easily overriden to apply more complex fiscal rules
part_obj = self.pool['res.partner']
partner = part_obj.browse(cr, uid, partner_id, context=context)
# partner manually set fiscal position always win
if partner.property_account_position:
return partner.property_account_position.id
# if no delivery use invocing
if delivery_id:
delivery = part_obj.browse(cr, uid, delivery_id, context=context)
else:
delivery = partner
domain = [
('auto_apply', '=', True),
'|', ('vat_required', '=', False), ('vat_required', '=', partner.vat_subjected),
'|', ('country_id', '=', None), ('country_id', '=', delivery.country_id.id),
'|', ('country_group_id', '=', None), ('country_group_id.country_ids', '=', delivery.country_id.id)
]
fiscal_position_ids = self.search(cr, uid, domain, context=context)
if fiscal_position_ids:
return fiscal_position_ids[0]
return False
class account_fiscal_position_tax(osv.osv):
_name = 'account.fiscal.position.tax'
_description = 'Taxes Fiscal Position'
_rec_name = 'position_id'
_columns = {
'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
'tax_src_id': fields.many2one('account.tax', 'Tax Source', required=True),
'tax_dest_id': fields.many2one('account.tax', 'Replacement Tax')
}
_sql_constraints = [
('tax_src_dest_uniq',
'unique (position_id,tax_src_id,tax_dest_id)',
'A tax fiscal position could be defined only once time on same taxes.')
]
class account_fiscal_position_account(osv.osv):
_name = 'account.fiscal.position.account'
_description = 'Accounts Fiscal Position'
_rec_name = 'position_id'
_columns = {
'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
}
_sql_constraints = [
('account_src_dest_uniq',
'unique (position_id,account_src_id,account_dest_id)',
'An account fiscal position could be defined only once time on same accounts.')
]
class res_partner(osv.osv):
_name = 'res.partner'
_inherit = 'res.partner'
_description = 'Partner'
def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
ctx = co | ntext.copy()
ctx['all_fiscalyear'] = True
query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
FROM account_move_line l
| LEFT JOIN account_account a ON (l.account_id=a.id)
WHERE a.type IN ('receivable','payable')
AND l.partner_id IN %s
AND l.reconcile_id IS NULL
AND """ + query + """
GROUP BY l.partner_id, a.type
""",
(tuple(ids),))
maps = {'receivable':'credit', 'payable':'debit' }
res = {}
for id in ids:
res[id] = {}.fromkeys(field_names, 0)
for pid,type,val in cr.fetchall():
if val is None: val=0
res[pid][maps[type]] = (type=='receivable') and val or -val
return res
def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
if not args:
return []
having_values = tuple(map(itemgetter(2), args))
where = ' AND '.join(
map(lambda x: '(SUM(bal2) %(operator)s %%s)' % {
'operator':x[1]},args))
query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
cr.execute(('SELECT pid AS partner_id, SUM(bal2) FRO |
kantel/Virtuelle-Wunderkammer | sources/treepy/tree.py | Python | mit | 680 | 0.016176 | import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_c | aption("Fractal Tree")
screen = pygame.display.get_surface()
def drawTree(x1, y1, angle, depth):
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * d | epth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, angle + 20, depth - 1)
def input(event):
if event.type == pygame.QUIT:
exit(0)
drawTree(300, 550, -90, 9)
pygame.display.flip()
while True:
input(pygame.event.wait()) |
yubang/wechat_sdk | wechat_sdk.py | Python | apache-2.0 | 11,004 | 0.00281 | # coding:UTF-8
"""
微信公众号相关操作封装
@author: yubang
@version: 1.0
2016年02月11日
"""
from xml.dom.minidom import Document
import requests
import json
import urllib
import time
request_timeout = 10
def __fetch_url(url, is_get=True, post_data=None):
"""
发送一个GET请求
:param url: 要请求的url
:param is_get: 是否是GET请求
:param post_data: POST数据
:return: 数据, 状态码(0为正确处理数据,-1为微信服务器无法响应,-2为无法处理微信服务器返回的数据)
"""
try:
if is_get:
r = requests.get(url, timeout=request_timeout)
else:
r = requests.post(url, json.dumps(post_data, ensure_ascii=False), timeout=request_timeout)
except Exception:
return None, 0
if r.status_code == 200:
try:
obj = json.loads(r.text)
return obj, 0
except Exception:
return r.text, -2
else:
return None, -1
def __handle_get_data(data, code):
"""
处理请求服务器之后的返回数据
:param data: 经处理成字典的数据
:param code: 状态码
:return:
"""
result = {"code": code, "msg": u"ok", "content": data}
if code == -1:
result['msg'] = u'微信服务器无法响应'
elif code == -2:
result['msg'] = u'无法处理微信服务器返回的数据'
else:
if 'errcode' in result['content'] and result['content']['errcode'] != 0:
result['code'] = result['content']['errcode']
if 'errmsg' in result['content']:
result['msg'] = result['content']['errmsg']
else:
result['msg'] = u'未知错误!'
return result
def __get_data_use_api(target_url, is_get=True, post_data=None):
"""
调用微信API接口
:param target_url: 要请求的url
:param is_get: 是否是GET请求
:param post_data:
:return: POST数据
"""
data, code = __fetch_url(target_url, is_get, post_data)
# 处理数据
result = __handle_get_data(data, code)
return result
def get_access_token(appid, secret):
"""
获取微信access_token,该凭证是微信所有接口所需要的
该接口不提供缓存功能,由于该接口调用次数有限,请自己缓存
:param appid: 公众号appid
:param secret: 公众号secret
:return:
"""
# 请求服务器
target_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid, secret)
result = __get_data_use_api(target_url)
return result
def get_wechat_server_ip(access_token):
"""
获取微信服务器ip
:param access_token: 微信access_token
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=%s' % access_token
result = __get_data_use_api(target_url)
return result
def get_short_url(access_token, source_url): |
"""
将一条长链接转成短链接
:param access_token: 微信access_token
:param source_url: 源网址
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"action": 'long2short', 'long_url': source_url})
return result
def create_short_ticket(access_token, expire_seconds=2592000, scene_id=0):
"""
创建临时二维码
| :param access_token: 微信access_token
:param expire_seconds: 二维码过期时间
:param scene_id: 场景值ID
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"expire_seconds": expire_seconds, "action_info": {"scene": {"scene_id": scene_id}}, "action_name": 'QR_SCENE'})
return result
def create_long_ticket(access_token, scene_id=0, scene_str=None):
"""
创建永久二维码
注意场景id只能选择一种
:param access_token: 微信access_token
:param scene_id: 场景值ID
:param scene_str: 场景值ID(字符串)
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % access_token
if scene_str:
result = __get_data_use_api(target_url, False, {"action_info": {"scene": {"scene_str": scene_str}}, "action_name": 'QR_LIMIT_STR_SCENE'})
else:
result = __get_data_use_api(target_url, False, {"action_info": {"scene": {"scene_id": scene_id}}, "action_name": 'QR_LIMIT_SCENE'})
return result
def get_ticket_url(ticket):
"""
获取二维码地址,注意该接口只返回一个url
:param ticket: 微信二维码ticket
:return:
"""
url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s' % urllib.quote(ticket)
return url
def set_template_industry(access_token, industry_id1, industry_id2):
"""
设置所属行业
行业代码请看:http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html#.E8.AE.BE.E7.BD.AE.E6.89.80.E5.B1.9E.E8.A1.8C.E4.B8.9A
:param access_token: 微信access_token
:param industry_id1: 行业代码1
:param industry_id2: 行业代码2
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"industry_id1": industry_id1, "industry_id2": industry_id2})
return result
def get_template_id(access_token, template_id_short):
"""
获取模板id
:param access_token: 微信access_token
:param template_id_short:模板库中模板的编号
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"template_id_short": template_id_short})
return result
def send_template_message(access_token, template_id, template_data, targer_open_id, target_url):
"""
发送模版消息
:param access_token: 微信access_token
:param template_id: 模板id
:param template_data: 模板数据
:param targer_open_id: 目标用户open_id
:param target_url: 模板消息跳转的url
:return:
"""
api_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % access_token
result = __get_data_use_api(api_url, False, {
"touser": targer_open_id,
"template_id": template_id,
"url": target_url,
"data": template_data
})
return result
def get_all_templates(access_token):
"""
获取所有设置的模板
:param access_token: 微信access_token
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=%s' % access_token
result = __get_data_use_api(target_url)
return result
def send_text_message(access_token, target_open_id, text):
"""
发送文本消息
:param access_token: 微信access_token
:param target_open_id: 目标用户open_id
:param text: 需要发送的文本内容
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"touser": target_open_id, "text": {"content": text.encode("UTF-8")}, "msgtype": 'text'})
return result
def send_media_message(access_token, target_open_id, media_id, media_type):
"""
发送媒体信息
:param access_token: 微信access_token
:param target_open_id: 目标用户open_id
:param media_id: 媒体id
:param media_type: 媒体类型,image,voice
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"touser": target_open_id, media_type: {"media_id": media_id}, "msgtype": media_type})
return result
def update_media(access_token, media_type, media_name, media_data):
"""
上传临时媒体素材
:param access_token: 微信access_token
:param media_type: 媒体类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_data: 媒体数据
:param media_name: 媒体名字
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s' % (access_token, media_type)
try:
r = requests.post(target_url, files={"media": (media_name, media_data)}, timeout=request_timeout)
if r.status_code == 200:
try:
data = json.loads(r.text)
code = 0
except Exception:
data = r.text
code = -2
else:
code = -1
data = None
except Exception:
code = -1
data = None
result = __handle_get_data(data, code)
return result
def create_menu(access_token, menu_data):
"""
创建菜单
:param access_token: 微信access_token
:param menu_data: 菜单数据 |
weidel-p/nest-simulator | pynest/nest/tests/test_glif_cond.py | Python | gpl-2.0 | 7,258 | 0 | # -*- coding: utf-8 -*-
#
# test_glif_cond.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT 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 NEST. If not, see <http://www.gnu.org/licenses/>.
import unittest
import numpy as np
import nest
HAVE_GSL = nest.ll_api.sli_func("statusdict/have_gsl ::")
@unittest.skipIf(not HAVE_GSL, 'GSL is not av | ailable')
class GLIFCONDTestCase(unittest.TestCase):
def setUp(self):
"""
Clean up and initialize NEST before each test.
"""
msd = 123456
self.resol = 0.01
nest.ResetKernel()
N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
pyrngs = [np.random.RandomState(s)
for s in range(msd, msd + N_vp)]
nest.SetKernelStatus({'resolution': self.resol,
| 'grng_seed': msd + N_vp,
'rng_seeds': range(msd + N_vp + 1,
msd + 2 * N_vp + 1)})
def simulate_w_stim(self, model_params):
"""
Runs a one second simulation with different types of input stimulation.
Returns the time-steps, voltages, and collected spike times.
"""
# Create glif model to simulate
nrn = nest.Create("glif_cond", params=model_params)
# Create and connect inputs to glif model
espikes = nest.Create("spike_generator",
params={"spike_times": [10., 100.,
400., 700.]})
ispikes = nest.Create("spike_generator",
params={"spike_times": [15., 99.,
300., 800.]})
pg = nest.Create("poisson_generator",
params={"rate": 1000.,
"start": 200., "stop": 500.})
pn = nest.Create("parrot_neuron")
cg = nest.Create("step_current_generator",
params={"amplitude_values": [100., ],
"amplitude_times": [600., ],
"start": 600., "stop": 900.})
nest.Connect(espikes, nrn, syn_spec={"receptor_type": 1})
nest.Connect(ispikes, nrn, syn_spec={"receptor_type": 2})
nest.Connect(pg, pn)
nest.Connect(pn, nrn, syn_spec={"weight": 22.,
"receptor_type": 1})
nest.Connect(pn, nrn, syn_spec={"weight": 10.,
"receptor_type": 2})
nest.Connect(cg, nrn, syn_spec={"weight": 3.})
# For recording spikes and voltage traces
sd = nest.Create('spike_detector')
nest.Connect(nrn, sd)
mm = nest.Create("multimeter", params={"record_from": ["V_m"],
"interval": self.resol})
nest.Connect(mm, nrn)
nest.Simulate(1000.)
times = nest.GetStatus(mm, 'events')[0]['times']
V_m = nest.GetStatus(mm, 'events')[0]['V_m']
spikes = nest.GetStatus(sd, 'events')[0]['times']
return times, V_m, spikes
def test_lif(self):
"""
Check LIF model
"""
lif_params = {
"spike_dependent_threshold": False,
"after_spike_currents": False,
"adapting_threshold": False,
"V_m": -78.85
}
times, V_m, spikes = self.simulate_w_stim(lif_params)
spikes_expected = [404.74, 449.55, 612.99, 628.73,
644.47, 660.21, 675.95, 691.69,
707.14, 722.88, 738.62, 754.36,
770.10, 785.84, 801.85, 817.76,
833.50, 849.24, 864.98, 880.72,
896.46]
assert(np.allclose(spikes, spikes_expected, atol=1.0e-3))
assert(np.isclose(V_m[0], -78.85))
def test_lif_r(self):
"""
Check LIF_R model
"""
lif_r_params = {
"spike_dependent_threshold": True,
"after_spike_currents": False,
"adapting_threshold": False,
"V_m": -78.85
}
times, V_m, spikes = self.simulate_w_stim(lif_r_params)
expected_spikes = [404.74, 408.79, 449.57, 613.27,
621.06, 629.30, 637.98, 647.10,
656.65, 666.61, 676.96, 687.67,
698.72, 710.07, 721.70, 733.57,
745.65, 757.91, 770.33, 782.88,
795.54, 812.56, 825.10, 837.73,
850.46, 863.27, 876.15, 889.08]
assert(np.allclose(spikes, expected_spikes, atol=1.0e-3))
assert(np.isclose(V_m[0], -78.85))
def test_lif_asc(self):
"""
Check LIF_ASC model
"""
lif_asc_params = {
"spike_dependent_threshold": False,
"after_spike_currents": True,
"adapting_threshold": False,
"V_m": -78.85
}
times, V_m, spikes = self.simulate_w_stim(lif_asc_params)
expected_spikes = [404.74, 449.55, 614.75, 648.01,
684.71, 724.85, 769.23, 821.97,
875.75]
assert(np.allclose(spikes, expected_spikes, atol=1.0e-3))
assert(np.isclose(V_m[0], -78.85))
def test_lif_r_asc(self):
"""
Check LIF_R_ASC model
"""
lif_r_asc_params = {
"spike_dependent_threshold": True,
"after_spike_currents": True,
"adapting_threshold": False,
"V_m": -78.85
}
times, V_m, spikes = self.simulate_w_stim(lif_r_asc_params)
expected_spikes = [404.74, 408.84, 449.58, 616.22, 652.91,
695.32, 744.16, 800.43, 863.59]
assert(np.allclose(spikes, expected_spikes, atol=1.0e-3))
assert(np.isclose(V_m[0], -78.85))
def test_lif_r_asc_a(self):
"""
Check LIF_R_ASC_A model
"""
lif_r_asc_a_params = {
"spike_dependent_threshold": True,
"after_spike_currents": True,
"adapting_threshold": True,
"V_m": -78.85
}
times, V_m, spikes = self.simulate_w_stim(lif_r_asc_a_params)
expected_spikes = [404.76, 408.87, 449.59, 618.95, 670.17,
745.89, 842.89]
assert(np.allclose(spikes, expected_spikes, atol=1.0e-3))
assert(np.isclose(V_m[0], -78.85))
def suite():
return unittest.makeSuite(GLIFCONDTestCase, "test")
def run():
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())
if __name__ == '__main__':
run()
|
Brett-D/cs494program | echoclient.py | Python | gpl-2.0 | 3,368 | 0.058492 | #!/usr/bin/env python
"""
Written by Brett Dunscomb
This is the game client for the game manhunt
The object of the game is to move into the space occupied by the other player
"""
import socket
import select
import sys
import os
import time
data = 'hello'
move = 'up'
host = 'localhost'
port = 50000
size = 1024
#game declerations
boardsize = 4
playerlock = 0
board = [['0']*boardsize for x in range(boardsize)]
#game functions
def printBoard(uboard):
print' ',
for x in range(len(board[1])):
print x,
print
for x, element in enumerate(uboard):
print x, ' '.join(element)
def updateLoc(xpos, ypos):
for x in range(boardsize):
for y in range(boardsize):
board[x][y] = '0'
board[xpos][ypos] = 'X'
os.system('cls' if os.name == 'nt' else 'clear')
printBoard(board)
#game commands
def forward():
try:
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((host,port))
except socket.error, (value,message):
if conn:
conn.close()
print "Could not open socket: " + message
sys.exit(1)
_id = str(conn.getsockname()[1])
return [_id, conn]
def RepresentsInt(s):
try:
s = int(s)
if s > boardsize - 1:
return False
else:
return True
except ValueError:
return False
#network stuff
class Maingame:
def __init__(self):
self.me,self.conn = forward()
self.players = []
self.players_id = []
if __name__ == "__main__":
game = Maingame()
try:
os.system('cls' if os.name == 'nt' else 'clear')
#data = game.conn.recv(size) #set the character name
start = raw_input("Enter your players name")
game.conn.send("c" + start)
#data = game.conn.recv(size) #set the x position
while True:
xpos = raw_input("Enter your x starting position")
cont = RepresentsInt(xpos)
if cont:
break
game.conn.send("]" + xpos)
#data = game.conn.recv(size) #set the y position
while True:
ypos = raw_input("Enter your y starting position")
cont = RepresentsInt(ypos)
if cont:
break
game.conn.send("[" + ypos)
xpos =(int)(xpos)
ypos =(int)(ypos)
start = game.conn.recv(size)
print start
while move.strip() != 'quit':
try:
data = "p" #request connected players
game.conn.send(data)
playerlock = (game.conn.recv(size))
#print playerlock, "bd" #debug message
if playerlock[2] == "1":
print "you found your target and winBD"
game.conn.close()
quit()
elif playerlock[2] =="0":
print "you have been found you looseBD"
| game.conn.close()
quit()
if playerlock[0] == "2" and playerlock[1] == "N":
#data = game.conn.recv(size)
updateLoc(xpos,ypos)
print "two players connected"
move = raw_input("Enter Movement(up,down,left,right,quit):")
game.conn.send("m" + move) #sends movement command
data = game.conn.recv(size)
xpos = (int)(data[0])
ypos = (int)(data[1])
updateLoc(xpos,ypos)
#print data
elif playerlock[1] == "w" or playerlock[0] == "1":
| updateLoc(xpos,ypos)
#print playerlock
print "waiting for player"
time.sleep(1)
except socket.error, (value,message):
if game.conn:
game.conn.close()
print "Server error: " + message
sys.exit(1)
finally:
game.conn.close()
|
Cocosoft/bitcoin | qa/rpc-tests/rpcnamedargs.py | Python | mit | 1,437 | 0.004175 | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_jsonrpc,
start_nodes,
)
class NamedArgumentTest(BitcoinTestFramework):
"""
Test named arguments on RPC calls.
"""
def __init__(self):
super().__init__()
self.setup_clean_chain = False
self.num_nodes = 1
def setup_network(self, split=False):
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir)
self.is_network_split = False
self.sync_all()
def run_test(self):
node = self.nodes[0]
h = node.help(command='getinfo')
assert(h.startswith('getinfo\n'))
assert_raises_jsonrpc(-8, 'Unknown named parameter', node.help, random='getinfo')
h = node.getblockhash(height=0)
node.getblock(blockhash=h)
assert_equal(node.echo(), [])
assert_equal(node.echo(arg0=0,arg9=9), [0] + [None]*8 + [9])
ass | ert_equal(node.echo(arg1=1), [None, 1])
assert_equal(node.echo(arg9=None), [None]*10)
assert_equal(node.echo(arg0=0,ar | g3=3,arg9=9), [0] + [None]*2 + [3] + [None]*5 + [9])
if __name__ == '__main__':
NamedArgumentTest().main()
|
ARudiuk/mne-python | mne/commands/mne_show_fiff.py | Python | bsd-3-clause | 485 | 0 | #!/usr/bin/env python
"""Show the contents of a FIFF file
You can do for example:
$ mne show_fiff test_raw.fif
"""
# Authors : Eric Larson, PhD
import sys
import mne
def run():
parser = mne.command | s.utils.get_optparser(
__file__, usage='mne show_fiff <file>')
options, args = parser.parse_args()
if len(args) != 1:
parser.print_help()
sys.exit(1)
print(mne.io.show_fiff(args[0]))
is_main = (__name__ == '__main__')
if is_main:
run()
| |
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_rich_string03.py | Python | bsd-2-clause | 1,229 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file crea | ted by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'rich_string03.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.e | xp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
italic = workbook.add_format({'italic': 1})
worksheet.write('A1', 'Foo', bold)
worksheet.write('A2', 'Bar', italic)
worksheet.write_rich_string('A3', bold, 'abc', 'defg')
workbook.close()
self.assertExcelEqual()
|
AntSharesSDK/antshares-python | sdk/AntShares/IO/BinaryWriter.py | Python | apache-2.0 | 2,641 | 0.001515 | # -*- coding:utf-8 -*-
"""
Description:
Binary Writer |
Usage:
from AntShares.IO.BinaryWriter import BinaryWriter
"""
import struct
import binascii
class BinaryWriter(object):
"""docstring for BinaryWriter"""
def __init__(self, stream):
super(BinaryWriter, self).__init__()
self.stream = stream
def writeByte(self, value):
self.stream.write(chr(value))
def writeBytes(self, value):
try:
| value = binascii.unhexlify(value)
except TypeError:
pass
self.stream.write(value)
def pack(self, fmt, data):
return self.writeBytes(struct.pack(fmt, data))
def writeChar(self, value):
return self.pack('c', value)
def writeInt8(self, value):
return self.pack('b', value)
def writeUInt8(self, value):
return self.pack('B', value)
def writeBool(self, value):
return self.pack('?', value)
def writeInt16(self, value):
return self.pack('h', value)
def writeUInt16(self, value):
return self.pack('H', value)
def writeInt32(self, value):
return self.pack('i', value)
def writeUInt32(self, value):
return self.pack('I', value)
def writeInt64(self, value):
return self.pack('q', value)
def writeUInt64(self, value):
return self.pack('Q', value)
def writeFloat(self, value):
return self.pack('f', value)
def writeDouble(self, value):
return self.pack('d', value)
def writeVarInt(self, value):
if not isinstance(value ,int):
raise TypeError, '%s not int type.' % value
if value < 0:
raise Exception, '%d too small.' % value
elif value < 0xfd:
return self.writeByte(value)
elif value <= 0xffff:
self.writeByte(0xfd)
return self.writeUInt16(value)
elif value <= 0xFFFFFFFF:
self.writeByte(0xfd)
return self.writeUInt32(value)
else:
self.writeByte(0xff)
return self.writeUInt64(value)
def writeVarBytes(self, value):
length = len(binascii.unhexlify(value))
self.writeVarInt(length)
return self.writeBytes(value)
def writeString(self, value):
length = len(binascii.unhexlify(value))
self.writeUInt8(length)
return self.pack(str(length) + 's', value)
def writeSerializableArray(self, array):
self.writeVarInt(len(array))
for item in array:
item.serialize(self)
def writeFixed8(self, value):
return self.writeBytes(value.getData())
|
simonzhangsm/voltdb | tools/vmc_stats_emulator.py | Python | agpl-3.0 | 4,874 | 0.012926 | #!/usr/bin/env python2.6
# This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the 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 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 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS 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.
import datetime
import httplib2
import json
import random
import threading
import time
#Set these
server="volt4b"
port=8080
sleep_time=5 #Time to sleep between every VMC iteration (VMC delay is 5)
max_err=1 #Max number of errors on any thread before it quits
thr=20 #Concurrent threads of VMC emulation
request_format = "http://%s:%d/api/1.0/?%s"
#These are the requests being made every 5 seconds by VMC in V4.9
#This may change in the future
arguments = [
"Procedure=%40SystemInformation&Parameters=%5B%22OVERVIEW%22%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22MEMORY%22%2C0%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22LATENCY_HISTOGRAM%22%2C0%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22PROCEDUREPROFILE%22%2C0%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22CPU%22%2C0%5D&admin=true",
"Procedure=%40SystemInformation&Parameters=%5B%22DEPLOYMENT%22%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22TABLE%22%2C0%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22MEMORY%22%2C0%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22TABLE%22%2C0%5D&admin=true",
"Procedure=%40Statistics&Parameters=%5B%22PROCEDUREPROFILE%22%2C0%5D&admin=true",
"Procedure=%40SystemCatalog&Parameters=%5B%22TABLES%22%5D&admin=true",
]
HTTP_SUCCESS=200
STATUS_STRINGS = {
"VOLTDB_CONNECTION_LOST": -4,
"VOLTDB_CONNECTION_TIMEOUT": -6,
"VOLTDB_GRACEFUL_FAILURE": -2,
"VOLTDB_OPERATIONAL_FAILURE": -9,
"VOLTDB_RESPONSE_UNKNOWN": -7,
"VOLTDB_SERVER_UNAVAILABLE": -5,
"VOLTDB_SUCCESS": 1,
"VOLTDB_TXN_RESTART": -8,
"VOLTDB_UNEXPECTED_FAILURE": -3,
"VOLTDB_UNINITIALIZED_APP_STATUS_CODE": -128,
"VOLTDB_USER_ABORT": -1,
}
STATUS_CODES = dict((v,k) for k, v in STATUS_STRINGS.iteritems())
pause_on_error=False
def ts():
return datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S,%f')
def push_it(max_errors=1, sleep_time=0):
err_ct = 0
tid = str(threading.current_thread().name)
print ts() + " Starting thread " + tid
i = 1
http = httplib2.Http(cache=None, timeout=15.0)
#while forever
while ( i > 0 ) :
if not i % 100:
print "%s %s Loop Count: %4d" % (ts(), tid, i)
for a in arguments:
url = request_format % (server, port, a)
try:
#http = httplib2.Http(cache=None, timeout=15.0)
response,content = http.request(url, 'GET')
if response['status'] != str(HTTP_SUCCESS) or json.loads(content)['status'] != STATUS_STRINGS['VOLTDB_SUCCESS']:
statusstring = STATUS_CODES.get(json.loa | ds(content)['status'],"Unknown status")
print "%s %s Request# %d - | Error getting %s\n\thttp_status=%s\tresponse=%s" % (ts(), tid, i, a, response['status'], statusstring)
err_ct += 1
except AttributeError:
err_ct += 1
if err_ct >= max_errors:
if pause_on_error:
raw_input("Press any key to continue...")
else:
print "%s: Too many errors - I'm out of here" % tid
return (-1)
time.sleep(sleep_time)
i += 1
threads = []
for i in range(thr):
t = threading.Thread(target=push_it, args=(1,sleep_time))
t.daemon=True
threads.append(t)
for t in threads:
#Don't bunch them all up
time.sleep (random.randint(50,200)/100.0)
t.start()
for t in threads:
t.join()
#TODO: This threading is dodgy and doesn't end gracefully
#and doesn't handle ctrl-c gracefully
|
elbow-jason/flask-meta | flask_meta/appmeta/controllers/form_page.py | Python | mit | 402 | 0.007463 | from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
form_page = Blueprint('form_page', __name__,
template_folder='templat | es')
@form_page.route('/<page>')
def show(page):
try:
form = AppForms.query.filter_by(name=page).first()
return render_template( | 'form.html', form=form)
except TemplateNotFound:
abort(404) |
vied12/superdesk | server/superdesk/media/media_operations.py | Python | agpl-3.0 | 3,953 | 0.000759 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import arrow
import magic
import hashlib
import logging
import requests
from io import BytesIO
from PIL import Image
from flask import json
from .image import get_meta
from .video import get_meta as video_meta
import base64
from superdesk.errors import SuperdeskApiError
logger = logging.getLogger(__name__)
def hash_file(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest()
def get_file_name(file):
return hash_file(file, hashlib.sha256())
def download_file_from_url(url):
rv = requests.get(url, timeout=15)
if rv.status_code not in (200, 201):
raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url)
mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8')
ext = mime.split('/')[1]
name = 'stub.' + ext
return BytesIO(rv.content), name, mime
def download_file_from_encoded_str(encoded_str):
content = encoded_str.split(';base64,')
mime = content[0].split(':')[1]
ext = content[0].split('/')[1]
name = 'web_capture.' + ext
content = base64.b64decode(content[1])
return BytesIO(content), name, mime
def process_file_from_stream(content, content_type=None):
content_type = content_type or content.content_type
content = BytesIO(content.read())
if 'application/' in content_type:
content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8')
content.seek(0)
file_type, ext = content_type.split('/')
try:
metadata = process_file(content, file_type)
except OSError: # error from PIL when image is supposed to be an image but is not.
raise SuperdeskApiError.internalError('Failed to process file')
file_name = get_file_name(content)
content.seek(0)
metadata = encode_metadata(metadata)
metadata.update({'length': json.dumps(len(content.getvalue()))})
return file_name, content_type, metadata
def encode_metadata(metadata):
return dict((k.lower(), json.dumps(v)) for k, v in metadata.items())
def decode_metadata(metadata):
return dict(( | k.lower(), decode_val(v)) for k, v in metadata.items())
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
except (Exception):
return val
def process_file(content, type):
if type == 'image':
| return process_image(content, type)
if type in ('audio', 'video'):
return process_video(content, type)
return {}
def process_video(content, type):
content.seek(0)
meta = video_meta(content)
content.seek(0)
return meta
def process_image(content, type):
content.seek(0)
meta = get_meta(content)
content.seek(0)
return meta
def crop_image(content, file_name, cropping_data):
if cropping_data:
file_ext = os.path.splitext(file_name)[1][1:]
if file_ext in ('JPG', 'jpg'):
file_ext = 'jpeg'
logger.debug('Opened image from stream, going to crop it s')
content.seek(0)
img = Image.open(content)
cropped = img.crop(cropping_data)
logger.debug('Cropped image from stream, going to save it')
try:
out = BytesIO()
cropped.save(out, file_ext)
out.seek(0)
return (True, out)
except Exception as io:
logger.exception(io)
return (False, content)
|
magfest/ubersystem | alembic/versions/53b71e7c45b5_add_fields_for_mivs_show_info_checklist_.py | Python | agpl-3.0 | 1,940 | 0.005155 | """Add fields for MIVS show_info checklist item
Revision ID: 53b71e7c45b5
Revises: ad26fcaafb78
Create Date: 2019-11-25 19:37:15.322579
"""
|
# revision identifiers, used by Alembic.
revision = '53b71e7c45b5'
down_revision = 'ad26fcaafb78'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
try:
is_sqlite = op.get_context().dialect.name == 'sqlite'
except Exception:
is_sqlite = False
if is_sqlite:
op.get_context().connection.execute('PRAGMA foreign_keys=ON;')
utcnow_server_default = "(datetime('now', 'utc'))"
else:
utcnow_server_default = "t | imezone('utc', current_timestamp)"
def sqlite_column_reflect_listener(inspector, table, column_info):
"""Adds parenthesis around SQLite datetime defaults for utcnow."""
if column_info['default'] == "datetime('now', 'utc')":
column_info['default'] = utcnow_server_default
sqlite_reflect_kwargs = {
'listeners': [('column_reflect', sqlite_column_reflect_listener)]
}
# ===========================================================================
# HOWTO: Handle alter statements in SQLite
#
# def upgrade():
# if is_sqlite:
# with op.batch_alter_table('table_name', reflect_kwargs=sqlite_reflect_kwargs) as batch_op:
# batch_op.alter_column('column_name', type_=sa.Unicode(), server_default='', nullable=False)
# else:
# op.alter_column('table_name', 'column_name', type_=sa.Unicode(), server_default='', nullable=False)
#
# ===========================================================================
def upgrade():
op.add_column('indie_studio', sa.Column('contact_phone', sa.Unicode(), server_default='', nullable=False))
op.add_column('indie_studio', sa.Column('show_info_updated', sa.Boolean(), server_default='False', nullable=False))
def downgrade():
op.drop_column('indie_studio', 'show_info_updated')
op.drop_column('indie_studio', 'contact_phone')
|
TylerKirby/cltk | cltk/tests/test_nlp/test_phonology.py | Python | mit | 40,764 | 0.003701 | """Test cltk.phonology."""
__author__ = ['Jack Duff <jmunroeduff@gmail.com>', "Clément Besnier <clemsciences@aol.com>"]
__license__ = 'MIT License. See LICENSE.'
import unicodedata
from cltk.phonology.arabic.romanization import transliterate as AarabicTransliterate
from cltk.phonology.greek import transcription as grc
from cltk.phonology.latin import transcription as lat
from cltk.phonology.middle_high_german import transcription as mhg
from cltk.phonology.middle_english.transcription import Word as word_me
from cltk.phonology.akkadian import stress as AkkadianStress
from cltk.phonology.old_norse import transcription as ont
from cltk.phonology.gothic import transcription as gothic
from cltk.phonology.old_swedish import transcription as old_swedish
from cltk.phonology import utils as ut
from cltk.phonology.syllabify import Syllabifier, Syllable
from cltk.tokenize.word import WordTokenizer
from cltk.corpus.old_norse.syllabifier import invalid_onsets
import unittest
class TestSequenceFunctions(unittest.TestCase):
"""Class for unittest"""
"""Tes | t the Latin Library corpus reader filter"""
@classmethod
def setUpClass(self):
self.greek_transcriber = grc.Transcriber("Attic", "Probert")
s | elf.latin_transcriber = lat.Transcriber("Classical", "Allen")
"""greek.transcription"""
def test_greek_refresh(self):
"""Test the Word class's `_refresh` method in Greek."""
test_word = grc.Word("pʰór.miŋks", grc.GREEK["Attic"]["Probert"])
test_word._refresh()
contexts = [test_word.phones[0].left.ipa,
test_word.phones[1].left.ipa, test_word.phones[1].right.ipa,
test_word.phones[-1].right.ipa]
target = [grc.Phone("#").ipa, grc.Phone("pʰ").ipa,
grc.Phone("r").ipa, grc.Phone("#").ipa]
self.assertEqual(contexts, target)
def test_greek_r_devoice(self):
"""Test the Word class's method `_r_devoice` in Greek."""
condition_1 = grc.Word("rɑ́ks", grc.GREEK["Attic"]["Probert"])
condition_1._refresh()
condition_1._r_devoice()
condition_2 = grc.Word("syrrɑ́ptɔː", grc.GREEK["Attic"]["Probert"])
condition_2._refresh()
condition_2._r_devoice()
outputs = [''.join(p.ipa for p in condition_1.phones),
''.join(p.ipa for p in condition_2.phones)]
target = [unicodedata.normalize('NFC', y) for y in
["r̥ɑ́ks", "syrr̥ɑ́ptɔː"]]
self.assertEqual(outputs, target)
def test_greek_s_voice_assimilation(self):
"""Test the Word class's method `_s_voice_assimilation` in Greek."""
condition = grc.Word("ẹːrgɑsménon", grc.GREEK["Attic"]["Probert"])
condition._refresh()
condition._s_voice_assimilation()
output = ''.join([p.ipa for p in condition.phones])
target = unicodedata.normalize('NFC', "ẹːrgɑzménon")
self.assertEqual(output, target)
def test_greek_nasal_place_assimilation(self):
"""Test the Word method `_nasal_place_assimilation` in Greek."""
condition_1 = grc.Word("pʰórmigks", grc.GREEK["Attic"]["Probert"])
condition_1._refresh()
condition_1._nasal_place_assimilation()
condition_2 = grc.Word("ɑ́ggelos", grc.GREEK["Attic"]["Probert"])
condition_2._refresh()
condition_2._nasal_place_assimilation()
outputs = [''.join([p.ipa for p in condition_1.phones]),
''.join([p.ipa for p in condition_2.phones])]
target = [unicodedata.normalize('NFC', y) for y in
["pʰórmiŋks", "ɑ́ŋgelos"]]
self.assertEqual(outputs, target)
def test_greek_g_nasality_assimilation(self):
"""Test the Word class's `_g_nasality_assimilation` in Greek."""
condition = grc.Word("gignɔ́ːskɔː", grc.GREEK["Attic"]["Probert"])
condition._refresh()
condition._g_nasality_assimilation()
output = ''.join([p.ipa for p in condition.phones])
target = unicodedata.normalize('NFC', "giŋnɔ́ːskɔː")
self.assertEqual(output, target)
def test_greek_alternate(self):
"""Test the Word class's `_alternate` in Greek."""
raw_inputs = ["rɑ́ks", "syrrɑ́ptɔː", "ẹːrgɑsménon",
"pʰórmigks", "ɑ́ggelos", "gignɔ́ːskɔː"]
outputs = []
for i in raw_inputs:
w = grc.Word(i, grc.GREEK["Attic"]["Probert"])
w._alternate()
outputs.append(''.join([p.ipa for p in w.phones]))
target = [unicodedata.normalize('NFC', y) for y in ["r̥ɑ́ks",
"syrr̥ɑ́ptɔː", "ẹːrgɑzménon",
"pʰórmiŋks", "ɑ́ŋgelos", "giŋnɔ́ːskɔː"]]
self.assertEqual(outputs, target)
def test_greek_syllabify(self):
"""Test the Word class's `_syllabify` in Greek."""
raw_inputs = ["lẹ́ːpẹː", "píptɔː", "téknọː", "skɛ̂ːptron"]
outputs = []
for i in raw_inputs:
w = grc.Word(i, grc.GREEK["Attic"]["Probert"])
w._alternate()
outputs.append([''.join([p.ipa for l in n for p in l])
for n in w._syllabify()])
target = [[unicodedata.normalize('NFC', s) for s in y] for y in
[["lẹ́ː", "pẹː"], ["píp", "tɔː"],
["té", "knọː"], ["skɛ̂ːp", "tron"]]]
self.assertEqual(outputs, target)
def test_greek_print_ipa(self):
"""Test the Word class's `_print_ipa` in Greek."""
w = grc.Word("élipe", grc.GREEK["Attic"]["Probert"])
output = [w._print_ipa(True), w._print_ipa(False)]
target = [unicodedata.normalize('NFC', "é.li.pe"),
unicodedata.normalize('NFC', "élipe")]
self.assertEqual(output, target)
def test_greek_parse_diacritics(self):
"""Test the Transcriber class's `_parse_diacritics` in Greek."""
inputs = ["ἄ", "Φ", "ῷ", "ὑ", "ϊ", "ῑ"]
outputs = [self.greek_transcriber._parse_diacritics(char) for char in inputs]
target = [unicodedata.normalize('NFC', c) for c in
["α/" + grc.chars.ACUTE + "//",
"φ///", "ω/" + grc.chars.CIRCUMFLEX + "/"
+ grc.chars.IOTA_SUBSCRIPT + "/", "h///υ///",
"ι//" + grc.chars.DIAERESIS + "/", "ι//" + grc.chars.LONG + "/"]]
self.assertEqual(outputs, target)
def test_greek_prep_text(self):
"""Test the Transcriber class's `_prep_text` in Greek."""
inputs = ["λείπειν", "ὕπνῳ"]
outputs = [self.greek_transcriber._prep_text(w) for w in inputs]
target = [[('λ', '', ''), ('ει', '́', ''), ('π', '', ''),
('ει', '', ''), ('ν', '', '')],
[('h', '', ''), ('υ', '́', ''), ('π', '', ''),
('ν', '', ''), ('ωι', '', '̄')]]
self.assertEqual(outputs, target)
def test_transcriber_probert(self):
"""Test Attic Greek IPA transcription via Probert reconstruction."""
transcriber = self.greek_transcriber.transcribe
transcription = [transcriber(x) for x in
[unicodedata.normalize('NFC', y) for y in
["ῥάξ", "εἰργασμένον", "φόρμιγξ", "γιγνώσκω"]]]
target = [unicodedata.normalize('NFC', y) for y in
["[r̥ɑ́ks]", "[ẹːr.gɑz.mé.non]", "[pʰór.miŋks]", "[giŋ.nɔ́ːs.kɔː]"]]
self.assertEqual(transcription, target)
"""latin.transcription"""
def test_latin_refresh(self):
"""Test the Word class's `_refresh` method in Latin."""
test_word = lat.Word("ɔmn̪ɪs", lat.LATIN["Classical"]["Allen"])
test_word._refresh()
contexts = [test_word.phones[0].left.ipa,
test_word.phones[1].left.ipa, test_word.phones[1].right.ipa,
test_word.phones[-1].right.ipa]
target = [grc.Phone("#").ipa, grc.Phone("ɔ").ipa,
grc.Phone("n̪").ipa, grc.Phone("#").ipa]
self.assertEqual(contexts, target)
def test_latin_j_maker(self):
"""Test the Word class's method `_j_maker` in Latin."" |
myriadrf/pyLMS7002M | pyLMS7002M/__init__.py | Python | apache-2.0 | 115 | 0.043478 | __version_ | _="1.1.0"
from LMS7002_EVB import *
from LimeSDR import *
from LimeSDRMini import *
from QSpark import *
| |
CrashenX/auto-grader | src/auto-grade.py | Python | agpl-3.0 | 9,526 | 0.010708 | #!/usr/bin/env python
# Mininet Automatic Testing Tool (Prototype)
# Copyright (C) 2013 Jesse J. Cook
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from collections import namedtuple
import argparse
import hashlib
import libvirt
import os
import paramiko
import py_compile
import socket
import sys
import time
Environment = namedtuple('Environment', ['dom_name', 'ss_name'])
class GradingException(Exception):
def __init__(self,value):
self.value = "fail:\n%s" % value
def __str__(self):
return str(self.value)
# TODO: reevaluate try except blocks
def parse_prog_input():
desc = "Mininet Testing Tool (Prototype)"
contract = """program contract:
Requires:
- The sandbox environment is setup as described in README.md
- The following paths on the host to be provided and read access granted:
the code that is to be tested
the test suite that is to be run against the code
the guest domain from which the tests will be run
- The following paths on the guest to be provided and r/w access granted:
the destination for the code submission
the destination for the test suite
- The guest domain from which the tests will be run:
to be reachable via the network from the host
to have a client listening over the network (for now, ssh on port 22)
to have sufficent free space on the disk (60%% of allocated suggested)
Guarantees:
- The domain state will be saved in a snapshot
- The following will be installed on the snapshot of the guest:
the code that is to be tested (for now, 1 python file)
the test suite that is to be run (for now, 1 python file)
- The test suite will be run against the code on the guest
- The test results will be presented (for now, printed to stdout)
- A grade will be presented (for now, printed to stdout)
- The domain's state will be revereted to the saved state
- The snapshot will be deleted
"""
frmt = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser( description=desc
, epilog=contract
, formatter_class=frmt
)
parser.add_argument( '--submission'
, dest='code'
, default='sample-submission.py'
, help='code submission to be tested'
)
parser.add_argument( '--submission-dest'
, dest='code_dest'
, default='/home/mininet/pyretic/pyretic/examples/fw.py'
, help='code submission destination within guest'
)
parser.add_argument( '--test-suite'
, dest='test'
, default='sample-test-suite.py'
, help='test suite to test the code submission with'
)
parser.add_argument( '--test-suite-dest'
, dest='test_dest'
, default='/tmp/test-suite.py'
, help='test suite destination within guest'
)
parser.add_argument( '--domain-name'
, dest='domain'
, default='mininet'
, help='libvirt domain to test the code submission on'
)
parser.add_argument( '--hostname'
, | dest='hostname'
, default='mininet'
, help='hostname for the libvirt test domain'
)
return parser.parse_args()
def ssh_connect( hos | tname
, port=22
, username="mininet"
, keyfile="~/.ssh/id_rsa"
):
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect( hostname = hostname
, port = port
, username = username
, key_filename = os.path.expanduser(keyfile)
)
except Exception, e:
print "Connection to host '%s' failed (%s)" % (hostname, str(e))
sys.exit(1)
return ssh
def is_client_up( hostname
, port=22
):
up = False
ssh = ssh_connect(hostname=hostname, port=port)
(stdin, stdout, stderr) = ssh.exec_command("mn --version")
chan = stdout.channel
if 0 == chan.recv_exit_status():
up = True
chan.close()
ssh.close()
return up
def setup_test_env(hostname, domain):
xml = "<domainsnapshot><domain><name>%s</name></domain></domainsnapshot>"
conn = libvirt.open(None)
if conn == None:
print "Failed to open connection to the hypervisor"
sys.exit(1)
try:
dom = conn.lookupByName(domain)
except:
print "Failed to find domain '%s'" % domain
sys.exit(1)
if libvirt.VIR_DOMAIN_SHUTOFF == dom.state()[0]:
print "\n\tDomain is shutdown; starting '%s'" % domain
try:
dom.create()
except:
print "Failed to start domain (%s)" % domain
sys.exit(1)
state = dom.state()[0]
if libvirt.VIR_DOMAIN_RUNNING != state:
print 'Domain (%s) in unsupported state (%s)' % (domain, state)
sys.exit(1)
if not is_client_up(hostname):
print "Unable to reach client on host '%s'" % hostname
sys.exit(1)
try:
ss = dom.snapshotCreateXML(xml % domain, 0)
except:
print "Failed to create snapshot of domain (%s)" % domain
sys.exit(1)
conn.close()
return Environment(dom_name=domain, ss_name=ss.getName())
def teardown_test_env(env):
conn = libvirt.open(None)
if conn == None:
print "Failed to open connection to the hypervisor"
sys.exit(1)
try:
dom = conn.lookupByName(env.dom_name)
except:
print "Failed to find domain '%s'" % env.dom_name
sys.exit(1)
try:
ss = dom.snapshotLookupByName(env.ss_name)
dom.revertToSnapshot(ss)
ss.delete(0)
except:
print "Failed to cleanup snapshot of domain (%s)" % env.dom_name
sys.exit(1)
conn.close()
def sha1sum(path):
bs=65536
f = open(path, 'rb')
buf = f.read(bs)
h = hashlib.sha1()
while len(buf) > 0:
h.update(buf)
buf = f.read(bs)
f.close()
return h.hexdigest()
def push_file(src, tgt, hostname, port=22):
spath = os.path.expanduser(src)
dpath = os.path.expanduser(tgt)
sname = os.path.basename(spath)
chk_path = "/tmp/%s.sha1sum" % sname
f = open(chk_path, 'w')
f.write("%s %s" % (sha1sum(spath), dpath))
f.close()
ssh = ssh_connect(hostname=hostname, port=port)
scp = paramiko.SFTPClient.from_transport(ssh.get_transport())
scp.put(spath, dpath)
scp.put(chk_path, chk_path)
(stdin, stdout, stderr) = ssh.exec_command("sha1sum -c %s" % chk_path)
chan = stdout.channel
if 0 != chan.recv_exit_status():
raise Exception("Integrity checked failed for '%s'" % fpath)
chan.close()
scp.close()
ssh.close()
def test_code(test, hostname, port=22):
ssh = ssh_connect(hostname=hostname, port=port)
(stdin, stdout, stderr) = ssh.exec_command("sudo python -u %s" % test, 0)
chan = stdout.channel
while not chan.exit_status_ready():
time.sleep(.1)
if chan.recv_ready():
sys.stdout.write(chan.re |
aswolf/unbiased-pscale | code/Fei2007_fit.py | Python | mit | 9,689 | 0.023222 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as optimization
from MGD_func import MGD_PowerLaw
#define functions here
def lsqfun(p_eos,volume,temperature,Natom,P):
resid_scl = MGD_PowerLaw(volume, temperature, p_eos,Natom) - P
return resid_scl
def fitfun(p_eos,volume,temperature,Natom,P,error):
| resid_scl = (MGD_PowerLaw(volume, tem | perature, p_eos,Natom) - P)/error
return resid_scl
#V0, gamma0 and theta0 are fixed here.
def lsqfun_Fixed(p_fit, p_fix ,volume,temperature,Natom,P):
pall = [p_fix[0],p_fit[0],p_fit[1],p_fix[1], p_fix[2],p_fit[2]]
resid_scl = MGD_PowerLaw(volume, temperature, pall,Natom) - P
return resid_scl
def lsqfun_Fixedfit(p_fit, p_fix ,volume,temperature,Natom,P,error):
pall = [p_fix[0],p_fit[0],p_fit[1],p_fix[1], p_fix[2],p_fit[2]]
resid_scl = (MGD_PowerLaw(volume, temperature, pall,Natom) - P)/error
return resid_scl
"""
#Au-fitting
Audat = np.loadtxt(fname='Au-Fig-1.md', delimiter='|', skiprows=3)
T_Au = Audat[:,0]
P_Au = Audat[:,1]
V_Au = Audat[:,2]
Natom_Au = 4
plt.plot(P_Au,V_Au,'ro')
plt.xlabel('Pressure[GPa]')
plt.ylabel('Volume[' r'$A^{3}$'']')
plt.show()
#sequence of the p_eos: V0, K0, Kp, theta0, gamma0, q
guess = [67.85,167,6.00,170,2.97,0.6]
popt = optimization.leastsq(lsqfun,guess[:],args=(V_Au,T_Au,Natom_Au,P_Au),full_output = 0)
print popt
#(array([ 71.20655615, 86.21463461, 8.5687309 , 169.99994558, -1.70495262, 0.7049154 ]), 1)
"""
"""
#NaCl-B2-Fig-4_fitting
#we read the text
NaCldat = np.loadtxt(fname='NaCl-B2-Fig-4.md', delimiter='|', skiprows=3)
T_NaCl = NaCldat[:,0]
P_NaCl = NaCldat[:,1]
V_NaCl = NaCldat[:,2]
Natom_NaCl = 4
plt.plot(P_NaCl,V_NaCl,'ro')
plt.xlabel('Pressure[GPa]')
plt.ylabel('Volume[' r'$A^{3}$'']')
plt.show()
#sequence of the p_eos: V0, K0, Kp, theta0, gamma0, q
guess_fix = [41.35,290,1.7]#V0,theta0 and gamma0
guess = [26.86,5.25,0.5]#K0,Kp and q
popt = optimization.leastsq(lsqfun_Fixed,guess[:],args=(guess_fix[:],V_NaCl,T_NaCl,Natom_NaCl,P_NaCl),full_output = 0)
print popt
#(array([ 26.14377661, 5.33390463, 2.07041529]), 1)
"""
"""
#Neon using Au scale
Ne_Audat = np.loadtxt(fname='Neon-Au-Fig-5.md', delimiter='|', skiprows=4)
T_Ne_Au = Ne_Audat[:,0]
P_Ne_Au = Ne_Audat[:,1]
V_Ne_Au = Ne_Audat[:,2]
NatomNe_Au = 4
plt.plot(P_Ne_Au,V_Ne_Au,'ro')
plt.xlabel('Pressure[GPa]')
plt.ylabel('Volume[' r'$A^{3}$'']')
plt.show()
#sequence of the p_eos: V0, K0, Kp, theta0, gamma0, q
guessNe_fix = [88.967,75.1,2.05]#V0,theta0 and gamma0
guessNe = [1.16,8.23,0.6]#K0,Kp and q
popt = optimization.leastsq(lsqfun_Fixed,guessNe[:],args=(guessNe_fix[:],V_Ne_Au,T_Ne_Au,NatomNe_Au,P_Ne_Au),full_output = 0)
print popt
#(array([ 144.64862632, -2.13616756, 9.9976124 ]), 1)
"""
"""
#Neon
Ne_Ptdat = np.loadtxt(fname='Neon-Pt-Fig-5.md', delimiter='|', skiprows=4)
Ne_Audat = np.loadtxt(fname='Neon-Au-Fig-5.md', delimiter='|', skiprows=4)
Hemley_dat = np.loadtxt(fname='Hemley1989-Neon.md', delimiter='|', skiprows=3)
T_Ne = np.concatenate([Ne_Ptdat[:,0], Ne_Audat[:,0],Hemley_dat[:,0]])
P_Ne = np.concatenate([Ne_Ptdat[:,1], Ne_Audat[:,1],Hemley_dat[:,1]])
HemleyV = (Hemley_dat[:,2]**3)
V_Ne = np.concatenate([Ne_Ptdat[:,2], Ne_Audat[:,2],HemleyV])
NatomNe = 4
report = [88.967,1.16,8.23,75.1,2.05,0.6]
FeiPt_residual = lsqfun(report,Ne_Ptdat[:,2],Ne_Ptdat[:,0],NatomNe,Ne_Ptdat[:,1])
FeiPt_errorbar = np.sqrt(sum(FeiPt_residual*FeiPt_residual)/(len(Ne_Ptdat[:,2])-6))
FeiAu_residual = lsqfun(report,Ne_Audat[:,2],Ne_Audat[:,0],NatomNe,Ne_Audat[:,1])
FeiAu_errorbar = np.sqrt(sum(FeiAu_residual*FeiAu_residual)/(len(Ne_Audat[:,2])-6))
Hemley_residual = lsqfun(report,HemleyV,Hemley_dat[:,0],NatomNe,Hemley_dat[:,1])
Hemley_errorbar = np.sqrt(sum(Hemley_residual*Hemley_residual)/(len(Hemley_dat[:,0])-6))
error = np.concatenate([FeiPt_errorbar*np.ones(len(Ne_Ptdat[:,0])), FeiAu_errorbar*np.ones(len(Ne_Audat[:,0])), Hemley_errorbar*np.ones(len(Hemley_dat[:,0]))])
plt.plot(P_Ne,V_Ne,'ro')
plt.xlabel('Pressure[GPa]')
plt.ylabel('Volume[' r'$A^{3}$'']')
plt.show()
#sequence of the p_eos: V0, K0, Kp, theta0, gamma0, q
guessNe_fix = [88.967,75.1,2.05]#V0,theta0 and gamma0
guessNe = [1.16,8.23,0.6]#K0,Kp and q
popt = optimization.leastsq(lsqfun_Fixedfit,guessNe[:],args=(guessNe_fix[:],V_Ne,T_Ne,NatomNe,P_Ne,error),full_output = 1)
#print popt
cov = popt[1]
mean = popt[0]
print mean,cov
V = np.linspace(24,50,100)
a = np.random.multivariate_normal(mean,cov)
para = [guessNe_fix[0], a[0],a[1],guessNe_fix[1],guessNe_fix[2],a[2]]
print para
pressure300 = MGD_PowerLaw(V,300*np.ones(len(V)), para, NatomNe)
pressure1000 = MGD_PowerLaw(V,1000*np.ones(len(V)), para, NatomNe)
pressure2000 = MGD_PowerLaw(V,2000*np.ones(len(V)), para, NatomNe)
plt.figure(facecolor="white")
plt.plot(pressure300,V,label = "300K",color=[0.5,0.5,1])
plt.plot(pressure1000,V,label = "1000K",color=[1,0.5,0.5])
plt.plot(pressure2000,V,label = "2000K",color=[0.5,1,0.5])
for i in range(1,9):
a = np.random.multivariate_normal(mean,cov)
para = [guessNe_fix[0], a[0],a[1],guessNe_fix[1],guessNe_fix[2],a[2]]
#print(a)
#print V
pressure300 = MGD_PowerLaw(V,300*np.ones(len(V)), para, NatomNe)
pressure1000 = MGD_PowerLaw(V,1000*np.ones(len(V)), para, NatomNe)
pressure2000 = MGD_PowerLaw(V,2000*np.ones(len(V)), para, NatomNe)
#print pressure300
#print pressure1700
plt.plot(pressure300,V,'-',color=[0.5,0.5,1])
plt.plot(pressure1000,V,'-',color=[1,0.5,0.5])
plt.plot(pressure2000,V,'-',color=[0.5,1,0.5])
plt.plot(Ne_Ptdat[0:8,1],Ne_Ptdat[0:8,2], 'ob')
plt.plot(Ne_Ptdat[9:14,1],Ne_Ptdat[9:14,2], 'or')
plt.plot(Ne_Audat[:,1],Ne_Audat[:,2], 'ob')
plt.plot(Hemley_dat[:,1],HemleyV, 'ob')
plt.xlabel('Pressure[GPa]',fontsize = 20)
plt.ylabel('Volume[' r'$A^{3}$'']',fontsize = 20)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.legend(prop={'size':15})
#plt.figure(facecolor="white")
plt.title("Uncertainty Interval of Ne from Fei2007[1]",fontsize = 20)
plt.show()
"""
"""
punc = np.sqrt(np.diag(popt[1]))
print "parameter uncert: ", punc
"""
#Pt
Fei_Ptdat = np.loadtxt(fname='Fei2004-Pt.md', delimiter='|', skiprows=3)
Dewaele_Ptdat = np.loadtxt(fname='Dewaele-Pt.md', delimiter='|', skiprows=3)
T_Pt = np.concatenate([Fei_Ptdat[:,0], Dewaele_Ptdat[:,0]])
P_Pt = np.concatenate([Fei_Ptdat[:,1], Dewaele_Ptdat[:,1]])
FeiV = Fei_Ptdat[:,2]**3
DewaeleV = Dewaele_Ptdat[:,2]*4
V_Pt = np.concatenate([FeiV,DewaeleV])
Natom_Pt = 4
#Fei's reported parameters for Pt
fei_report = [60.38, 277,5.08,230,2.72,0.5]
#get residuals here
Dewaele_residual = lsqfun(fei_report,DewaeleV,Dewaele_Ptdat[:,0],Natom_Pt,Dewaele_Ptdat[:,1])
Dewaele_errorbar = np.sqrt(sum(Dewaele_residual*Dewaele_residual)/(len(Dewaele_Ptdat[:,2])-6))
Fei_residual = lsqfun(fei_report,FeiV,Fei_Ptdat[:,0],Natom_Pt,Fei_Ptdat[:,1])
Fei_errorbar = np.sqrt(sum(Fei_residual*Fei_residual)/(len(Fei_Ptdat[:,0])-6))
#print Fei_residual
print Fei_errorbar
error = np.concatenate([Fei_errorbar*np.ones(len(Fei_Ptdat[:,0])), Dewaele_errorbar*np.ones(len(Dewaele_Ptdat[:,2]))])
plt.plot(P_Pt,V_Pt,'ro')
plt.xlabel('Pressure[GPa]')
plt.ylabel('Volume[' r'$A^{3}$'']')
plt.show()
#sequence of the p_eos: V0, K0, Kp, theta0, gamma0, q
guess = [60.38,277,5.08,230,2.72,0.5]
popt = optimization.leastsq(fitfun,guess[:],args=(V_Pt,T_Pt,Natom_Pt,P_Pt,error), ftol = Fei_errorbar,full_output = 1)
#pt,pcov = optimization.curve_fit(curfitfun, V_Pt, P_Pt, p0 = guess, sigma = error)
cov = popt[1]
mean = popt[0]
#mean = pt
#cov = pcov
print mean, cov
#print(np.sqrt(cov[0][0]))
V = np.linspace(47,65,70)
a = np.random.multivariate_normal(mean,cov)
pressure300 = MGD_PowerLaw(V,300*np.ones(len(V)), a, Natom_Pt)
pressure1473 = MGD_PowerLaw(V,1473*np.ones(len(V)), a, Natom_Pt)
pressure1873 = MGD_PowerLaw(V,1873*np.ones(len(V)), a, Natom_Pt)
plt.figure(facecolor="white")
plt.plot(pressure300,V,label = "300K",color=[0.5,0.5,1])
plt.plot(pressure1473,V,label = "1473K", color=[1,0.5,0.5])
plt.plot(pressure1873,V,label = "1873K",color=[0.5,1,0.5])
for i in range(1,9):
a = np.random.multivariate_normal(mean,cov)
pressure300 = MGD_PowerLaw(V,300*np.ones(len(V)), a, Natom_Pt)
pressure1473 = MGD_PowerLaw(V,1473*np.ones(len(V)), a, Natom_Pt)
pressure1873 = MGD_Po |
mwales/education | InteractivePython/asteroids.py | Python | gpl-2.0 | 25,069 | 0.011568 | # program template for Spaceship
import simplegui
import math
import random
# globals for user interface
WIDTH = 800
HEIGHT = 600
score = 0
lives = 3
time = 0
game_mode = 0 # 0 = splash screen, 1 = game mode, 2 = game over
ANGULAR_ACCEL_SCALAR = math.pi / 800.0
ANGULAR_FRICTION = 0.95
LINEAR_ACCEL_SCALAR = 0.25
LINEAR_FRICTION = 0.99
RANDOM_VEL_MAX = 4.0
RANDOM_VEL_MIN = 0.5
RANDOM_ANG_MAX = math.pi / 100.0
BULLET_VEL = 10
SMALL_ROCK_SPEED = 3
class ImageInfo:
def __init__(self, center, size, radius = 0, lifespan = None, animated = False):
self.center = center
self.size = size
self.radius = radius
if lifespan:
self.lifespan = lifespan
else:
self.lifespan = float('inf')
self.animated = animated
def get_center(self):
return self.center
def get_size(self):
return self.size
def get_radius(self):
return self.radius
def get_lifespan(self):
return self.lifespan
def get_animated(self):
return self.animated
# art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim
# debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png
# debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png
debris_info = ImageInfo([320, 240], [640, 480])
debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")
# nebula images - nebula_brown.png, nebula_blue.png
nebula_info = ImageInfo([400, 300], [800, 600])
nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png")
# splash image
splash_info = ImageInfo([200, 150], [400, 300])
splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png")
# ship image
ship_info = ImageInfo([45, 45], [90, 90], 35)
ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")
# missile image - shot1.png, shot2.png, shot3.png
missile_info = ImageInfo([5,5], [10, 10], 3, 75)
missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png")
# asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png
asteroid_info = ImageInfo([45, 45], [90, 90], 40)
asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")
# animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png
explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")
# sound assets purchased from sounddogs.com, please do not redistribute
soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3")
missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3")
missile_sound.set_volume(.5)
ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3")
explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3")
## CC 3.0 sound file by Jesus Lastra, http://opengameart.org/content/8-bit-pickup-1
extra_life_sound = simplegui.load_sound("http://mwales.net/junk/SFX_Pickup_44.mp3")
# helper functions to handle transformations
def angle_to_vector(ang):
return [math.cos(ang), math.sin( | ang)]
def vector_to_angle(v):
return math.atan2(v[0],v[1])
def vector_scale(vec, scale):
return [vec[0] * scale, vec[1] * scale]
def vector_add(vec1, vec2):
return [vec1[0] + vec2[0], vec1[1] + vec2[1]]
def dist(p,q):
return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2)
def smallRockExplode(rockInstance):
# Return an explosion sprite
explodeObj = Sprite(rockInstance.get_position(),
| (0,0),
random.random() * 2 * math.pi,
0,
explosion_image,
explosion_info,
explosion_sound,
relSize = 0.3)
return explodeObj
def rockExplode(rockInstance, deathBullet):
# Return an explosion sprite
explodeObj = Sprite(rockInstance.get_position(),
(0,0),
random.random() * 2 * math.pi,
0,
explosion_image,
explosion_info,
explosion_sound)
# Create 4 smaller rocks that explode away based on angle bullet came in at
bulletAngle = vector_to_angle(deathBullet.get_velocity())
smallRockAngle = bulletAngle + 45.0 / 360.0 * math.pi * 2.0
for i in range(0,4):
smallRockAngle += math.pi / 2.0
smallRockVel = angle_to_vector(smallRockAngle)
smallRockVel = vector_scale(smallRockVel, SMALL_ROCK_SPEED)
smallRockVel = vector_add(smallRockVel, rockInstance.get_velocity())
randomAngVel = random.random() * RANDOM_ANG_MAX * 4.0 - RANDOM_ANG_MAX
smallRock = Sprite(rockInstance.get_position(),
smallRockVel,
random.random() * 2 * math.pi,
randomAngVel,
asteroid_image,
asteroid_info,
relSize = 0.5)
smallRockList.append(smallRock)
return explodeObj
# Ship class
class Ship:
def __init__(self, pos, vel, angle, image, info, bulletTimer):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.thrust = False
self.angle = angle
self.angle_vel = 0
self.angle_acc = 0
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
self.bullet_timer = bulletTimer
self.spawn_bullets = False
self.bullets = []
self.bullet_type = 0
self.weapon_name = {}
self.weapon_name[0] = "Speed Shot"
self.weapon_name[1] = "Spread Shot"
self.weapon_name[2] = "Power Shot"
def get_weapon_name(self):
return self.weapon_name[self.bullet_type]
def draw(self,canvas):
if self.thrust:
canvas.draw_image(self.image,
(self.image_center[0] + self.image_size[0], self.image_center[1]),
self.image_size,
self.pos,
self.image_size,
self.angle)
else:
canvas.draw_image(self.image,
self.image_center,
self.image_size,
self.pos,
self.image_size,
self.angle)
for singleBullets in self.bullets:
singleBullets.draw(canvas)
def update(self):
self.pos = vector_add(self.pos, self.vel)
# Position should wrap around the screen
self.pos = [self.pos[0] % WIDTH, self.pos[1] % HEIGHT]
# Handle ship thrust
if self.thrust:
accel = angle_to_vector(self.angle)
accel = vector_scale(accel, LINEAR_ACCEL_SCALAR)
self.vel = vector_add(self.vel, accel)
# Friction against motion
self.vel = vector_scale(self.vel, LINEAR_FRICTION)
self.angle = self.angle + self.angle_vel
self.angle_vel = self.angle_vel + self.angle_acc
self.angle_vel = self.angle_vel * ANGULAR_FRICTION
oldBullets = [] |
nikitamarchenko/open-kilda | services/topology-engine/queue-engine/tests/smoke-tests/create-multi-path-topology.py | Python | apache-2.0 | 779 | 0 | #!/usr/bin/python
# Copyright 2017 Telstra Open Source
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law | or agreed to in writing, software
# distributed under the License is distributed 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.
#
from clean_topology | import cleanup
from create_topology import create_topo
print "\n -- "
cleanup()
create_topo('multi-path-topology.json')
print "\n -- "
|
tomasstorck/diatomas | blender/asdriver_nofil.py | Python | mit | 1,371 | 0.010941 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Driver for ecoli.py
import os, re, time, subprocess
iterModDiv = 1
dirPathList = ["/home/tomas/documenten/modelling/diatomas_symlink/results/as_low_bridging_seed2"]
for d in dirPathList:
print(time.strftime('%H:%M:%S ') + d)
dAbs = d + "/output"
fileList = [files for files in os.listdir(dAbs) if os.path.splitext(files)[-1]=='.mat']
fileList.sort(reverse=True)
for f in fileList:
###################
# Optional: skip some files manually
if int(re.match('g(\d{4})r(\d{4}).mat',f).group(2)) != 560:
continue
###################
print(time.strftime('%H:%M:%S ') + "\t" + f | )
if not int(re.match('g(\d{4})r(\d{4}).mat',f).group(2))%iterModDiv == 0:
# relaxation iteration (YYYY in filename gXXXXrYYYY.mat) % iterModulusDivider == 0
continue
fAbs = dAbs + "/" + f
callStr = ["blender", "--background", "--python", "as_nofil.py", "--", fAbs] # Call string is with filename
[stdout, _] = subprocess.Popen(callStr, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
| stdout = stdout.decode()
if 'Error' in stdout:
print("#####################################")
print(stdout)
print("#####################################")
|
Polarcraft/KbveBot | commands/help.py | Python | gpl-2.0 | 1,867 | 0.002142 | # Copyright (C) 2013-2015 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Fox Wilson
#
# 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 WITHOUT 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, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from helpers.command import Command, get_commands, get_command, is_registered
@Command('help', ['nick', 'config'])
def cmd(send, msg, args):
"""Gives help.
Syntax: {command} [command]
"""
cmdchar = args['config']['core']['cmdchar']
if msg:
if msg.startswith(cmdchar):
msg = msg[len(cmdchar):]
if len(msg.split()) > 1:
send("One | argument only")
elif not is_registered(msg):
send("Not a module.")
else:
doc = get_command(msg).get_doc()
if doc is None:
send("No documentation found.")
else:
for line in doc.splitlines():
| send(line.format(command=cmdchar + msg))
else:
modules = sorted(get_commands())
cmdlist = (' %s' % cmdchar).join(modules)
send('Commands: %s%s' % (cmdchar, cmdlist), target=args['nick'], ignore_length=True)
send('%shelp <command> for more info on a command.' % cmdchar, target=args['nick'])
|
drcoms/drcom-generic | latest-wired.py | Python | agpl-3.0 | 18,049 | 0.016473 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import struct
import time
import hashlib
import sys
import os
import random
import traceback
# CONFIG
server = "192.168.100.150"
username = ""
password = ""
host_name = "LIYUANYUAN"
host_os = "8089D"
host_ip = "10.30.22.17"
PRIMARY_DNS = "114.114.114.114"
dhcp_server = "0.0.0.0"
mac = 0xb888e3051680
CONTROLCHECKSTATUS = '\x20'
ADAPTERNUM = '\x01'
KEEP_ALIVE_VERSION = '\xdc\x02'
'''
AUTH_VERSION:
unsigned char ClientVerInfoAndInternetMode;
unsigned char DogVersion;
'''
AUTH_VERSION = '\x0a\x00'
IPDOG = '\x01'
ror_version = False
# CONFIG_END
keep_alive1_mod = False #If you have trouble at KEEPALIVE1, turn this value to True
nic_name = '' #Indicate your nic, e.g. 'eth0.2'.nic_name
bind_ip = '0.0.0.0'
class ChallengeException (Exception):
def __init__(self):
pass
class LoginException (Exception):
def __init__(self):
pass
def bind_nic():
try:
import fcntl
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
return get_ip_address(nic_name)
except ImportError as e:
print('Indicate nic feature need to be run under Unix based system.')
return '0.0.0.0'
except IOError as e:
print(nic_name + 'is unacceptable !')
return '0.0.0.0'
finally:
return '0.0.0.0'
if nic_name != '':
bind_ip = bind_nic()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((bind_ip, 61440))
s.settimeout(3)
SALT = ''
IS_TEST = True
# specified fields based on version
CONF = "/etc/drcom.conf"
UNLIMITED_RETRY = True
EXCEPTION = False
DEBUG = False #log saves to file
LOG_PATH = '/var/log/drcom_client.log'
if IS_TEST:
DEBUG = True
LOG_PATH = 'drcom_client.log'
def log(*args, **kwargs):
s = ' '.join(args)
print s
if DEBUG:
with open(LOG_PATH,'a') as f:
f.write(s + '\n')
def challenge(svr,ran):
while True:
t = struct.pack("<H", int(ran)%(0xFFFF))
s.sendto("\x01\x02"+t+"\x09"+"\x00"*15, (svr, 61440))
try:
data, address = s.recvfrom(1024)
log('[challenge] recv',data.encode('hex'))
except:
log('[challenge] timeout, retrying...')
continue
if address == (svr, 61440):
break
else:
continue
log('[DEBUG] challenge:\n' + data.encode('hex'))
if data[0] != '\x02':
raise ChallengeException
log('[challenge] challenge packet sent.')
return data[4:8]
def md5sum(s):
m = hashlib.md5()
m.update(s)
return m.digest()
def dump(n):
s = '%x' % n
if len(s) & 1:
s = '0' + s
return s.decode('hex')
def ror(md5, pwd):
ret = ''
for i in range(len(pwd)):
x = ord(md5[i]) ^ ord(pwd[i])
ret += chr(((x<<3)&0xFF) + (x>>5))
return ret
def gen_crc(data, encrypt_type):
DRCOM_DIAL_EXT_PROTO_CRC_INIT = 20000711
ret = ''
if encrypt_type == 0:
# 加密方式无
return struct.pack('<I',DRCOM_DIAL_EXT_PROTO_CRC_INIT) + struct.pack('<I',126)
elif encrypt_type == 1:
# 加密方式为 md5
foo = hashlib.md5(data).digest()
ret += foo[2]
ret += foo[3]
ret += foo[8]
ret += foo[9]
ret += foo[5]
ret += foo[6]
ret += foo[13]
ret += foo[14]
return ret
elif encrypt_type == 2:
# md4
foo = hashlib.new('md4', data).digest()
ret += foo[1]
ret += foo[2]
ret += foo[8]
ret += foo[9]
ret += foo[4]
ret += foo[5]
ret += foo[11]
ret += foo[12]
return ret
elif encrypt_type == 3:
# sha1
foo = hashlib.sha1(data).digest()
ret += foo[2]
ret += foo[3]
ret += foo[9]
ret += foo[10]
ret += foo[5]
ret += foo[6]
ret += foo[15]
ret += foo[16]
return ret
def keep_alive_package_builder(number,random,tail,type=1,first=False):
data = '\x07'+ chr(number) + '\x28\x00\x0b' + chr(type)
if first :
data += '\x0f\x27'
else:
data += KEEP_ALIVE_VERSION
data += '\x2f\x12' + '\x00' * 6
data += tail
data += '\x00' * 4
#data += struct.pack("!H",0xdc02)
if type == 3:
foo = ''.join([chr(int(i)) for i in host_ip.split('.')]) # host_ip
#CRC
# edited on 2014/5/12, filled zeros to checksum
# crc = packet_CRC(data+foo)
crc = '\x00' * 4
#data += struct.pack("!I",crc) + foo + '\x00' * 8
data += crc + foo + '\x00' * 8
else: #packet type = 1
data += '\x00' * 16
return data
# def packet_CRC(s):
# ret = 0
# for i in re.findall('..', s):
# ret ^= struct.unpack('>h', i)[0]
# ret &= 0xFFFF
# ret = ret * 0x2c7
# return ret
def keep_alive2(*args):
#first keep_alive:
#number = number (mod 7)
#status = 1: first packet user sended
# 2: first packet user recieved
# 3: 2nd packet user sended
# 4: 2nd packet user recieved
# Codes for test
tail = ''
packet = ''
svr = server
ran = random.randint(0,0xFFFF)
ran += random.randint(1,10)
# 2014/10/15 add by latyas, maybe svr sends back a file packet
svr_num = 0
packet = keep_alive_package_builder(svr_num,dump(ran),'\x00'*4,1,True)
while True:
log('[keep-alive2] send1',packet.encode('hex'))
s.sendto( | packet, (svr, 61440))
data, address = s.recvfrom(1024)
log('[keep-alive2] recv1',data.encode('hex'))
if da | ta.startswith('\x07\x00\x28\x00') or data.startswith('\x07' + chr(svr_num) + '\x28\x00'):
break
elif data[0] == '\x07' and data[2] == '\x10':
log('[keep-alive2] recv file, resending..')
svr_num = svr_num + 1
# packet = keep_alive_package_builder(svr_num,dump(ran),'\x00'*4,1, False)
break
else:
log('[keep-alive2] recv1/unexpected',data.encode('hex'))
#log('[keep-alive2] recv1',data.encode('hex'))
ran += random.randint(1,10)
packet = keep_alive_package_builder(svr_num, dump(ran),'\x00'*4,1,False)
log('[keep-alive2] send2',packet.encode('hex'))
s.sendto(packet, (svr, 61440))
while True:
data, address = s.recvfrom(1024)
if data[0] == '\x07':
svr_num = svr_num + 1
break
else:
log('[keep-alive2] recv2/unexpected',data.encode('hex'))
log('[keep-alive2] recv2',data.encode('hex'))
tail = data[16:20]
ran += random.randint(1,10)
packet = keep_alive_package_builder(svr_num,dump(ran),tail,3,False)
log('[keep-alive2] send3',packet.encode('hex'))
s.sendto(packet, (svr, 61440))
while True:
data, address = s.recvfrom(1024)
if data[0] == '\x07':
svr_num = svr_num + 1
break
else:
log('[keep-alive2] recv3/unexpected',data.encode('hex'))
log('[keep-alive2] recv3',data.encode('hex'))
tail = data[16:20]
log("[keep-alive2] keep-alive2 loop was in daemon.")
i = svr_num
while True:
try:
time.sleep(20)
keep_alive1(*args)
ran += random.randint(1,10)
packet = keep_alive_package_builder(i,dump(ran),tail,1,False)
#log('DEBUG: keep_alive2,packet 4\n',packet.encode('hex'))
log('[keep_alive2] send',str(i),packet.encode('hex'))
s.sendto(packet, (svr, 61440))
data, address = s.recvfrom(1024)
log('[keep_alive2] recv',data.encode('hex'))
tail = data[16:20]
#log('DEBUG: keep_alive2,packet 4 return\n',data.encode('hex'))
ran += random.randint(1,10)
packet = keep_alive_package_builder(i+1,dump(ran),tail,3,False)
#log(' |
caio2k/RIDE | src/robotide/lib/robot/libraries/dialogs_jy.py | Python | apache-2.0 | 3,458 | 0 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed 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 time
from java.awt import GridLayout
from java.awt.event import WindowAdapter
from javax.swing import JLabel, JOptionPane, JPanel, JPasswordField, JTextField
from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
YES_NO_OPTION, OK_CANCEL_OPTION, OK_OPTION, DEFAULT_OPTION
class _SwingDialog(object):
def __init__(self, pane):
self._pane = pane
def show(self):
self._show_dialog(self._pane)
return self._get_value(self._pane)
def _show_dialog(self, pane):
dialog = pane.createDialog(None, 'Robot Framework')
dialog.setModal(False)
dialog.setAlwaysOnTop(True)
dialog.addWindowFocusListen | er(pane.focus_listener)
dialog.show()
while dialog.isShowing():
time.sleep(0.2)
dialog.dispose()
def _get_value(self, pane):
value = pane.getInputValue()
return value if value != UNINITIALIZED_VALUE else None
clas | s MessageDialog(_SwingDialog):
def __init__(self, message):
pane = WrappedOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)
_SwingDialog.__init__(self, pane)
class InputDialog(_SwingDialog):
def __init__(self, message, default, hidden=False):
self._input_field = JPasswordField() if hidden else JTextField()
self._input_field.setText(default)
self._input_field.selectAll()
panel = JPanel(layout=GridLayout(2, 1))
panel.add(JLabel(message))
panel.add(self._input_field)
pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
pane.set_focus_listener(self._input_field)
_SwingDialog.__init__(self, pane)
def _get_value(self, pane):
if pane.getValue() != OK_OPTION:
return None
return self._input_field.getText()
class SelectionDialog(_SwingDialog):
def __init__(self, message, options):
pane = WrappedOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
pane.setWantsInput(True)
pane.setSelectionValues(options)
_SwingDialog.__init__(self, pane)
class PassFailDialog(_SwingDialog):
def __init__(self, message):
pane = WrappedOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
None, ['PASS', 'FAIL'], 'PASS')
_SwingDialog.__init__(self, pane)
def _get_value(self, pane):
return pane.getValue() == 'PASS'
class WrappedOptionPane(JOptionPane):
focus_listener = None
def getMaxCharactersPerLineCount(self):
return 120
def set_focus_listener(self, component):
self.focus_listener = WindowFocusListener(component)
class WindowFocusListener(WindowAdapter):
def __init__(self, component):
self.component = component
def windowGainedFocus(self, event):
self.component.requestFocusInWindow()
|
Fenugreek/tamarind | calendar.py | Python | gpl-3.0 | 11,719 | 0.008789 | """
Track valid dates, number of days between them, etc.
"""
import re
import datetime, time
import numpy
from . import logging
def today():
"""Return system date in YYYYMMDD."""
return time.strftime('%Y%m%d')
def decimalize(dates):
"""
Convert '20020930' to 2002.75.
"""
if numpy.isscalar(dates):
date = str(dates)
if not date: return numpy.nan
return float(date[:4]) + (float(date[4:6]) - 1) / 12 + float(date[6:8]) / 31 / 12
results = []
for date in numpy.array(dates).flatten():
date = str(date)
if not date: results.append(numpy.nan)
else: results.append(float(date[:4]) + (float(date[4:6]) - 1) / 12
+ float(date[6:8]) / 31 / 12)
return numpy.array(results).reshape(numpy.shape(dates))
def dt(dates):
"""
Convert '20020930' to datetime.date(2002, 9, 30)
"""
if numpy.isscalar(dates):
date = str(dates)
return datetime.date(int(date[:4]), int(date[4:6]), int(date[6:8]))
results = []
for date in numpy.array(dates).flatten():
date = str(date)
results.append(datetime.date(int(date[:4]), int(date[4:6]), int(date[6:8])))
return numpy.array(results).reshape(numpy.shape(dates))
class Calendar(object):
"""
The calendar object treats dates as 8 character YYYYMMDD strings.
The dates are stored in two object attributes. An ordered numpy array,
obj.dates. And a hash obj.date with the date as the key and the index of the
date in obj.dates as the value.
"""
date_expression = re.compile('^\d{8}$')
def __init__(self, dates_file_or_list, start=None, finish=None,
select_tag=None, skip_tag=None, logger='warning'):
"""
Initialize with dates in dates_file_or_list (one per line if file),
as the valid dates of the calendar.
start, finish:
Limit calendar to dates between these dates.
select_tag, skip_tag:
Split on whitespace each line in dates_file_or_list, which is of the form
'<date> <tag>', and load only dates with or without the given tag respectively.
"""
if start: start = str(start)
if finish: finish = str(finish)
dates_list = dates_file_or_list
if type(dates_list) == str:
file_dates = open(dates_file_or_list)
dates_list = file_dates.readlines()
dates = []
self.date = {}
for count, date in enumerate(dates_list):
tokens = date.split()
date = tokens.pop(0)
if skip_tag and tokens and tokens[0] == skip_tag: continue
if select_tag and (not tokens or tokens[0] != select_tag): continue
match = Calendar.date_expression.match(date)
if not match:
raise ValueError('Bad date in ' + dates_file + ': ' + date)
if start and date < start: continue
if finish and date > finish: break
dates.append(date)
self.date[date] = count
self.dates = numpy.array(dates)
if type(logger) == str:
self.logger = logging.Logger(self.__class__.__name__, logger)
else: self.logger = logger
self.logger.debug('Loaded calendar')
def _date_index(self, date):
"""Returns index of date in self.dates that is closest <= given date."""
index = None
date = str(date)
if date in self.date:
index = self.date[date]
else:
match = Calendar.date_expression.match(date)
if not match: raise ValueError('Bad date: ' + date)
index = numpy.searchsorted(self.dates, date) - 1
if index is None: raise ValueError('Bad date for calendar: ' + date)
return index
def search_date(self, date, offset, clip_old=False, clip_new=False):
"""Returns date offset calendar-days away from given date."""
index = self._date_index(date)
new_index = index + offset
if new_index < 0:
if clip_old:
self.logger.info('Clipping offset date to oldest date in calendar %s %d %s',
date, offset, self.dates[0])
return self.dates[0]
else:
raise IndexError('Date ' + date + ' offset ' + str(offset) +
' outside calendar range.')
elif new_index >= len(self.dates):
if clip_new:
self.logger.info('Clipping offset date to newest date in calendar %s %d %s',
date, offset, self.dates[-1])
return self.dates[-1]
else:
raise IndexError('Date ' + date + ' offset ' + str(offset) +
' outside calendar range.')
else:
return self.dates[new_index]
def next_date(self, date):
"""Returns next date in the calendar that is subsequent to given date."""
return self.search_date(date, 1)
def previous_date(self, date):
"""Returns previous date in the calendar that is earlier than given date."""
return self.search_date(date, -1)
def next_valid(self, date):
"""If given date is in calendar, return it; otherwise return closest
subsequent date in the calendar."""
date = str(date)
if date in self.date: return | date
| else: return self.search_date(date, 1)
def previous_valid(self, date):
"""If given date is in calendar, return it; otherwise return closest
earlier date in the calendar."""
date = str(date)
if date in self.date: return date
else: return self.search_date(date, 0)
def next_valid_close(self, date, time):
"""
Convert date, time strings 'YYYYMMDD', 'HH:MM:SS' to 'YYYYMMDD', such that
the resulting date is the next valid date-time 'YYYYMMDD 16:00:00'.
"""
date = str(date)
if date not in self.date: return self.next_valid(date)
elif time > '15:59:59': return self.next_date(date)
else: return date
def days_between(self, date_older, date_newer):
"""Returns number of days between date_older and date_newer;
returns a negative value if date_older is more recent."""
return self._date_index(date_newer) - self._date_index(date_older)
def dates_between(self, date_older, date_newer):
"""Returns dates >= date_older and < date_newer."""
return self.dates[self.date[self.next_valid(date_older)]:
self.date[self.previous_date(date_newer)] + 1]
def valid_dates_between(self, date_older, date_newer):
"""Returns dates >= date_older and <= date_newer."""
return self.dates[self.date[self.next_valid(date_older)]:
self.date[self.next_date(date_newer)]]
def next_year(self, date, include_current=False):
"""Returns next first-day-of-year in the calendar that is subsequent to
given date. Set include_current flag if you want >= current date."""
date = str(date)
year, month, day = date[:4], date[4:6], date[6:]
current_first_doy = self.next_valid(year + '0101')
if date < current_first_doy or \
(include_current and date == current_first_doy):
return current_first_doy
return self.next_valid(str(int(year)+1) + '0101')
def next_valid_year(self, date):
return self.next_year(date, include_current=True)
def previous_year(self, date, include_current=False):
"""Returns previous first-day-of-year in the calendar that is earlier
than given date. Set include_current flag if you want >= current date."""
date = str(date)
year, month, day = date[:4], date[4:6], date[6:]
current_first_doy = self.next_valid(year + month + '0101')
if date > current_first_doy or \
(include_current and date == current_first_doy):
return |
tboyce1/home-assistant | homeassistant/components/hassio/http.py | Python | apache-2.0 | 4,916 | 0.00061 | """HTTP Support for Hass.io."""
import asyncio
import logging
import os
import re
from typing import Dict, Union
import aiohttp
from aiohttp import web
from aiohttp.hdrs import CONTENT_LENGTH, CONTENT_TYPE
from aiohttp.web_exceptions import HTTPBadGateway
import async_timeout
from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView
from homeassistant.components.onboarding import async_is_onboarded
from homeassistant.const import HTTP_UNAUTHORIZED
from .const import X_HASS_IS_ADMIN, X_HASS_USER_ID, X_HASSIO
_LOGGER = logging.getLogger(__name__)
MAX_UPLOAD_SIZE = 1024 * 1024 * 1024
NO_TIMEOUT = re.compile(
r"^(?:"
r"|homeassistant/update"
r"|hassos/update"
r"|hassos/update/cli"
r"|supervisor/update"
r"|addons/[^/]+/(?:update|install|rebuild)"
r"|snapshots/.+/full"
r"|snapshots/.+/partial"
r"|snapshots/[^/]+/(?:upload|download)"
r")$"
)
NO_AUTH_ONBOARDING = re.compile(
r"^(?:" r"|supervisor/logs" r"|snapshots/[^/]+/.+" r")$"
)
NO_AUTH = re.compile(
r"^(?:" r"|app/.*" r"|addons/[^/]+/logo" r"|addons/[^/]+/icon" r")$"
)
class HassIOView(HomeAssistantView):
"""Hass.io view to handle base part."""
name = "api:hassio"
url = "/api/hassio/{path:.+}"
requires_auth = False
def __init__(self, host: str, websession: aiohttp.ClientSession):
"""Initialize a Hass.io base view."""
self._host = host
self._websession = websession
async def _handle(
self, request: web.Request, path: str
) -> Union[web.Response, web.StreamResponse]:
"""Route data to Hass.io."""
hass = request.app["hass"]
if _need_auth(hass, path) and not request[KEY_AUTHENTICATED]:
return web.Response(status=HTTP_UNAUTHORIZED)
return await self._command_proxy(path, request)
delete = _handle
get = _handle
post = _handle
async def _command_proxy(
self, path: str, request: web.Request
) -> Union[web.Response, web.StreamResponse]:
"""Return a client request with proxy origin for Hass.io supervisor.
This method is a coroutine.
"""
read_timeout = _get_timeout(path)
client_timeout = 10
data = None
headers = _init_header(request)
if path == "snapshots/new/upload":
# We need to reuse the full content type that includes the boundary
headers[
"Content-Type"
] = request._stored_content_type # pylint: disable=protected-access
# Snapshots are big, so we need to adjust the allowed size
request._client_max_size = ( # pylint: disable=protected-access
MAX_UPLOAD_SIZE
)
client_timeout = 300
try:
with async_timeout.timeout(client_timeout):
data = await request.read()
method = getattr(self._websession, request.method.lower())
client = await method(
f"http://{self._host}/{path}",
data=data,
headers=headers,
timeout=read_timeout,
)
# Simple request
if int(client.headers.get(CONTENT_LENGTH, 0)) < 4194000:
# Return Response
body = await clie | nt.read()
return web.Respons | e(
content_type=client.content_type, status=client.status, body=body
)
# Stream response
response = web.StreamResponse(status=client.status, headers=client.headers)
response.content_type = client.content_type
await response.prepare(request)
async for data in client.content.iter_chunked(4096):
await response.write(data)
return response
except aiohttp.ClientError as err:
_LOGGER.error("Client error on api %s request %s", path, err)
except asyncio.TimeoutError:
_LOGGER.error("Client timeout error on API request %s", path)
raise HTTPBadGateway()
def _init_header(request: web.Request) -> Dict[str, str]:
"""Create initial header."""
headers = {
X_HASSIO: os.environ.get("HASSIO_TOKEN", ""),
CONTENT_TYPE: request.content_type,
}
# Add user data
user = request.get("hass_user")
if user is not None:
headers[X_HASS_USER_ID] = request["hass_user"].id
headers[X_HASS_IS_ADMIN] = str(int(request["hass_user"].is_admin))
return headers
def _get_timeout(path: str) -> int:
"""Return timeout for a URL path."""
if NO_TIMEOUT.match(path):
return 0
return 300
def _need_auth(hass, path: str) -> bool:
"""Return if a path need authentication."""
if not async_is_onboarded(hass) and NO_AUTH_ONBOARDING.match(path):
return False
if NO_AUTH.match(path):
return False
return True
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/contrib/localflavor/pe/pe_region.py | Python | bsd-3-clause | 854 | 0 | # -*- coding: utf-8 -*-
"""
A list of Peru regions as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
from __future__ import unicode_literals
REG | ION_CHOICES = (
('AMA', 'Amazonas'),
('ANC', 'Ancash'),
('APU', 'Apurímac'),
('ARE', 'Arequipa'),
('AYA', 'Ayacucho'),
('CAJ', 'Cajamarca'),
('CAL', 'Callao'),
('CUS', 'Cusco'),
('HUV', 'Huancavelica'),
('HUC', 'Huánuco'),
('ICA', 'Ica'),
('JUN', 'Junín'),
('LAL', 'La Libertad'),
('LAM', 'Lambayeque'),
('LIM', 'Lima'),
('LOR', 'Loreto'),
('MDD', 'Madre de Dios'),
('MOQ', 'Moquegua'),
('PAS', 'Pasc | o'),
('PIU', 'Piura'),
('PUN', 'Puno'),
('SAM', 'San Martín'),
('TAC', 'Tacna'),
('TUM', 'Tumbes'),
('UCA', 'Ucayali'),
)
|
meteorfox/PerfKitBenchmarker | perfkitbenchmarker/providers/gcp/gcp_bigtable.py | Python | apache-2.0 | 3,117 | 0.003529 | # Copyright 2016 PerfKitBenchmarker 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 law or agreed to in writing, software
# distributed under the License is distributed 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.
"""Module containing class for GCP's bigtable instances.
Clusters can be created and deleted.
"""
import json
import logging
from perfkitbenchmarker import flags
from perfkitbenchmarker import resource
from perfkitbenchmarker.providers.gcp import util
FLAGS = flags.FLAGS
class GcpBigtableInstance(resource.BaseResource):
"""Object representing a GCP Bigtable Instance.
Attributes:
name: Instance and cluster name.
num_nodes: Number of nodes in the instance's cluster.
project: Enclosing project for the instance.
zone: zone of the instance's cluster.
"""
def __init__(self, name, num_nodes, project, zone):
super(GcpBigtableInstance, self).__init__()
self.num_nodes = num_nodes
self.name = name
self.zone = zone
self.project = project
def _Create(self):
"""Creates the instance."""
cmd = util.GcloudCommand(self, 'beta', 'bigtable', 'instances', 'create',
self.name)
cmd.flags['description'] = 'PkbCreatedCluster'
cmd.flags['cluster'] = self.name
cmd.flags['cluster-num-nodes'] = str(self.num_nodes)
cmd.flags['cluster-zone'] = self.zone
cmd.flags['project'] = self.project
# The zone flag makes this command fail.
cmd.flags['zone'] = []
cmd.Issue()
def _Delete(self):
"""Deletes the instance."""
cmd = util.GcloudCommand(self, 'beta', 'bigtable', 'instances', 'delete',
self.name)
# The zone flag makes this command fail.
cmd.flags['zone'] = []
cmd.Issue()
def _Exists(self):
"""Returns true if the instance exists."""
cmd = util.G | cloudCommand(self, 'beta', 'bigtable', 'instances', 'list')
cmd.flags['format'] = 'json'
cmd.flags['project'] = self.project
# The zone flag makes this command fail.
cmd.flags['zone'] = []
stdout, stderr, retcode = cmd.Issue(suppress_warning=True)
if retcode != 0:
# This is not ideal, as we're returning false not because we know
# t | he table isn't there, but because we can't figure out whether
# it is there. This behavior is consistent without other
# _Exists methods.
logging.error('Unable to list GCP Bigtable instances. Return code %s '
'STDOUT: %s\nSTDERR: %s', retcode, stdout, stderr)
return False
result = json.loads(stdout)
instances = {instance['name'] for instance in result}
full_name = 'projects/{}/instances/{}'.format(self.project, self.name)
return full_name in instances
|
berquist/cclib | cclib/parser/gamessukparser.py | Python | bsd-3-clause | 30,330 | 0.002209 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2020, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Parser for GAMESS-UK output files"""
import re
import numpy
from cclib.parser import logfileparser
from cclib.parser import utils
class GAMESSUK(logfileparser.Logfile):
"""A GAMESS UK log file"""
SCFRMS, SCFMAX, SCFENERGY = list(range(3)) # Used to index self.scftargets[]
def __init__(self, *args, **kwargs):
# Call the __init__ method of the superclass
super(GAMESSUK, self).__init__(logname="GAMESSUK", *args, **kwargs)
def __str__(self):
"""Return a string representation of the object."""
return "GAMESS UK log file %s" % (self.filename)
def __repr__(self):
"""Return a representation of the object."""
return 'GAMESSUK("%s")' % (self.filename)
def normalisesym(self, label):
"""Use standard symmetry labels instead of GAMESS UK labels."""
label = label.replace("''", '"').replace("+", "").replace("-", "")
ans = label[0].upper() + label[1:]
return ans
def before_parsing(self):
# used for determining whether to add a second mosyms, etc.
self.betamosyms = self.betamoenergies = self.betamocoeffs = False
def extract(self, inputfile, line):
"""Extract information from the file object inputfile."""
# Extract the version number and optionally the revision number.
if "version" in line:
search = re.search(r"\sversion\s*(\d\.\d)", line)
if search:
package_version = search.groups()[0]
self.metadata["package_version"] = package_version
self.metadata["legacy_package_version"] = package_version
if "Revision" in line:
revision = line.split()[1]
package_version = self.metadata.get("package_version")
if package_version:
self.metadata["package_version"] = "{}+{}".format(
package_version, revision
)
if line[1:22] == "total number of atoms":
natom = int(line.split()[-1])
self.set_attribute('natom', natom)
if line[3:44] == "convergence threshold in optimization run":
# Assuming that this is only found in the case of OPTXYZ
# (i.e. an optimization in Cartesian coordinates)
self.geotargets = [float(line.split()[-2])]
if line[32:61] == "largest component of gradient":
# This is the geotarget in the case of OPTXYZ
if not hasattr(self, "geovalues"):
self.geovalues = []
self.geovalues.append([float(line.split()[4])])
if line[37:49] == "convergence?":
# Get the geovalues and geotargets for OPTIMIZE
if not hasattr(self, "geovalues"):
self.geovalues = []
self.geotargets = []
geotargets = []
geovalues = []
for i in range(4):
temp = line.split()
geovalues.append(float(temp[2]))
if not self.geotargets:
geotargets.append(float(temp[-2]))
line = next(inputfile)
self.geovalues.append(geovalues)
if not self.geotargets:
self.geotargets = geotargets
# This is the only place coordinates are printed in single point calculations. Note that
# in the following fragment, the basis set selection is not always printed:
#
# ******************
# molecular geometry
# ******************
#
# *********************** | *****************
# * basis selected is sto sto3g *
# ****************************************
#
# *******************************************************************************
# * *
# * atom | atomic coordinates number of *
# * charge x y z shells *
# * *
# *******************************************************************************
# * *
# * *
# * c 6.0 0.0000000 -2.6361501 0.0000000 2 *
# * 1s 2sp *
# * *
# * *
# * c 6.0 0.0000000 2.6361501 0.0000000 2 *
# * 1s 2sp *
# * *
# ...
#
if line.strip() == "molecular geometry":
self.updateprogress(inputfile, "Coordinates")
self.skip_lines(inputfile, ['s', 'b', 's'])
line = next(inputfile)
if "basis selected is" in line:
self.skip_lines(inputfile, ['s', 'b', 's', 's'])
self.skip_lines(inputfile, ['header1', 'header2', 's', 's'])
atomnos = []
atomcoords = []
line = next(inputfile)
while line.strip():
line = next(inputfile)
if line.strip()[1:10].strip() and list(set(line.strip())) != ['*']:
atomcoords.append([utils.convertor(float(x), "bohr", "Angstrom") for x in line.split()[3:6]])
atomnos.append(int(round(float(line.split()[2]))))
if not hasattr(self, "atomcoords"):
self.atomcoords = []
self.atomcoords.append(atomcoords)
self.set_attribute('atomnos', atomnos)
# Each step of a geometry optimization will also print the coordinates:
#
# search 0
# *******************
# point 0 nuclear coordinates
# *******************
#
# x y z chg tag
# ============================================================
# 0.0000000 -2.6361501 0.0000000 6.00 c
# 0.0000000 2.6361501 0.0000000 6.00 c
# ..
#
if line[40:59] == "nuclear coordinates":
self.updateprogress(inputfile, "Coordinates")
# We need not remember the first geometry in geometry optimizations, as this will
# be already parsed from the "molecular geometry" section (see above).
if not hasattr(self, 'firstnuccoords') or self.firstnuccoords:
self.firstnuccoords = False
return
self.skip_lines(inputfile, ['s', 'b', 'colname', 'e'])
atomcoords = []
atomnos = []
line = next(inputfile)
while list(set(line.strip())) != ['=']:
cols = line.split()
atomcoords.append([utils.convertor(float(x), "bohr", "Angstrom") for x in cols[0:3]])
atomnos.append(int(float(cols[3])))
line = next(inputfile)
if not hasattr(self, "atomcoords"):
self.atomcoords = []
self.atomcoords.append(atomcoords)
self.set_attribute('atomnos |
pystruct/pystruct | setup.py | Python | bsd-2-clause | 1,928 | 0 | from setuptools import setup
from setuptools.extension import Extension
import numpy as np
import os
if os.path.exists('MANIFEST'):
os.remove('MANIFEST')
include_dirs = [np.get_include()]
setup(name="pystruct",
version="0.3.2",
install_requires=["ad3", "numpy"],
packages=['pystruct', 'pystruct.learners', 'pystruct.inference',
'pystruct.models', 'pystruct.utils', 'pystruct.datasets',
'pystruct.tests', 'pystruct.tests.test_learners',
'pystruct.tests.test_models', 'pystruct.tests.test_inference',
'pystruct.tests.test_utils'],
include_package_data=True,
description="Structured Learning and Prediction in Python",
author="Andreas Mueller",
author_email="t3kcit@gmail.com",
url="http://pystruct.github.io",
license="BSD 2-clause",
use_2to3=True,
ext_modules=[Extension("pystruct.models.utils", ["src/utils.c"],
include_dirs=include_dirs),
Extension("pystruct.inference._viterbi",
["pystruct/inference/_viterbi.c"],
include_dirs=include_dirs)],
classifiers=['Intended Audience :: Science/Research', |
'Intended Audience :: Developers',
'License :: OSI Approved',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
| 'Operating System :: Unix',
'Operating System :: MacOS',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
],
)
|
nesdis/djongo | tests/django_tests/tests/v21/tests/context_processors/urls.py | Python | agpl-3.0 | 173 | 0 | from django.conf.urls import url
from . impo | rt views
urlpatterns = [
url(r'^request_att | rs/$', views.request_processor),
url(r'^debug/$', views.debug_processor),
]
|
cheddarfinancial/quarry-platform | chassis/database.py | Python | bsd-3-clause | 7,076 | 0.006218 | # Standard Library
import datetime
import json
# Third Party
import mixingboard
from sqlalchemy import create_engine, types, event, exc, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool import Pool
# Local
user_db_conf = mixingboard.getConf('user_db')
engine = create_engine('mysql+pymysql://%s:%s@%s:%s/%s' % (
user_db_conf['user'],
user_db_conf['password'],
user_db_conf['host'],
user_db_conf.get('port', 3306),
user_db_conf['database']
), pool_recycle=3600)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
# catch disconnects before they fuck things up
@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except:
# raise DisconnectionError - pool will try
# connecting again up to three times before raising.
raise exc.DisconnectionError()
cursor.close()
Base = declarative_base()
Base.query = db_session.query_property()
def toDict(self):
fields = {}
for field in [x for x in dir(self) if not x.startswith('_') and x not in {'metadata','query'} and x not in self.__serialize_exclude__]:
val = self.__getattribute__(field)
if not hasattr(val, '__call__'):
if isinstance(val, datetime.datetime):
val = val.isoformat()
elif isinstance(val, Base):
# AVOID CIRCULAR REFERENCES DEAR GOD
val = getattr(self, field).dict()
fields[field] = val
return fields
Base.dict = toDict
Base.__serialize_exclude__ = set()
Base.__serialize_include__ = set()
def init_db():
# import all models before you call this
from models.account import Account
from models.datajob import DataJob
from models.job import Job
from m | odels.jobhistory import JobHistory
from models.notification import Notification
from models.query import Query
from models.rawdataset impor | t RawDataset
from models.user import User
from models.workflow import Workflow
from models.token import Token
Base.metadata.create_all(bind=engine)
##
# Json TYPE BECAUSE SQLALCHEMY IS RETARDED
##
class JsonEncodedObj(types.TypeDecorator):
"""Represents an immutable structure as a json-encoded string."""
impl = Text
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
class MutationObj(Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, dict) and not isinstance(value, MutationDict):
return MutationDict.coerce(key, value)
if isinstance(value, list) and not isinstance(value, MutationList):
return MutationList.coerce(key, value)
return value
@classmethod
def _listen_on_attribute(cls, attribute, coerce, parent_cls):
key = attribute.key
if parent_cls is not attribute.class_:
return
# rely on "propagate" here
parent_cls = attribute.class_
def load(state, *args):
val = state.dict.get(key, None)
if coerce:
val = cls.coerce(key, val)
state.dict[key] = val
if isinstance(val, cls):
val._parents[state.obj()] = key
def set(target, value, oldvalue, initiator):
if not isinstance(value, cls):
value = cls.coerce(key, value)
if isinstance(value, cls):
value._parents[target.obj()] = key
if isinstance(oldvalue, cls):
oldvalue._parents.pop(target.obj(), None)
return value
def pickle(state, state_dict):
val = state.dict.get(key, None)
if isinstance(val, cls):
if 'ext.mutable.values' not in state_dict:
state_dict['ext.mutable.values'] = []
state_dict['ext.mutable.values'].append(val)
def unpickle(state, state_dict):
if 'ext.mutable.values' in state_dict:
for val in state_dict['ext.mutable.values']:
val._parents[state.obj()] = key
event.listen(parent_cls, 'load', load, raw=True, propagate=True)
event.listen(parent_cls, 'refresh', load, raw=True, propagate=True)
event.listen(attribute, 'set', set, raw=True, retval=True, propagate=True)
event.listen(parent_cls, 'pickle', pickle, raw=True, propagate=True)
event.listen(parent_cls, 'unpickle', unpickle, raw=True, propagate=True)
class MutationDict(MutationObj, dict):
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to MutationDict"""
self = MutationDict((k,MutationObj.coerce(key,v)) for (k,v) in value.items())
self._key = key
return self
def __setitem__(self, key, value):
dict.__setitem__(self, key, MutationObj.coerce(self._key, value))
self.changed()
def __delitem__(self, key):
dict.__delitem__(self, key)
self.changed()
class MutationList(MutationObj, list):
@classmethod
def coerce(cls, key, value):
"""Convert plain list to MutationList"""
self = MutationList((MutationObj.coerce(key, v) for v in value))
self._key = key
return self
def __setitem__(self, idx, value):
list.__setitem__(self, idx, MutationObj.coerce(self._key, value))
self.changed()
def __setslice__(self, start, stop, values):
list.__setslice__(self, start, stop, (MutationObj.coerce(self._key, v) for v in values))
self.changed()
def __delitem__(self, idx):
list.__delitem__(self, idx)
self.changed()
def __delslice__(self, start, stop):
list.__delslice__(self, start, stop)
self.changed()
def append(self, value):
list.append(self, MutationObj.coerce(self._key, value))
self.changed()
def insert(self, idx, value):
list.insert(self, idx, MutationObj.coerce(self._key, value))
self.changed()
def extend(self, values):
list.extend(self, (MutationObj.coerce(self._key, v) for v in values))
self.changed()
def pop(self, *args, **kw):
value = list.pop(self, *args, **kw)
self.changed()
return value
def remove(self, value):
list.remove(self, value)
self.changed()
def JsonType():
return MutationObj.as_mutable(JsonEncodedObj)
|
veltzer/demos-python | src/examples/short/gzip/same_content_different_files.py | Python | gpl-3.0 | 1,827 | 0.001095 | #!/usr/bin/env python
"""
This example shows that two activations of the gzip library to compress files
actually produce files with different md5 signatures.
The reason for this is the filename, date and compression levels.
You can control this by uding the GzipFil | e object which has more
parameters. This is not yet demonstrated in this demo.
References:
- http://stackoverflow.com/questions/28213912/python-md5-hashes-of-same-gzipped-file-are-inconsistent
"""
import gzip
import hashlib
f_name = '/etc/passwd'
output_template = '/tmp/test{}.gz'
def digest(filename: str) -> str:
md5 = hashlib.md5()
with open(filename | , 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
return md5.hexdigest()
block_size = 4096
print("The default way - non identical outputs")
for x in range(0, 3):
input_handle = open(f_name, 'rb')
output_filename = output_template.format(x)
my_zip = gzip.open(output_filename, 'wb')
try:
for chunk in iter(lambda: input_handle.read(block_size), b''):
my_zip.write(chunk)
finally:
input_handle.close()
my_zip.close()
print(digest(output_filename))
print("The right way to get identical outputs")
for x in range(3, 6):
input_handle = open(f_name, 'rb')
output_filename = output_template.format(x)
my_zip = gzip.GzipFile(
filename='', # do not emit filename into the output gzip file
mode='wb',
fileobj=open(output_filename, 'wb'),
mtime=0, # do not emit modification time information into the output gzip file
)
try:
for chunk in iter(lambda: input_handle.read(block_size), b''):
my_zip.write(chunk)
finally:
input_handle.close()
my_zip.close()
print(digest(output_filename))
|
KiChjang/servo | tests/wpt/web-platform-tests/service-workers/service-worker/resources/fetch-access-control.py | Python | mpl-2.0 | 5,045 | 0.006343 | import base64
import json
import os
import six
from wptserve.utils import isomorphic_decode, isomorphic_encode
def decodebytes(s):
if six.PY3:
return base64.decodebytes(six.ensure_binary(s))
return base64.decodestring(s)
def main(request, response):
headers = []
headers.append((b'X-ServiceWorker-ServerHeader', b'SetInTheServer'))
if b"ACAOrigin" in request.GET:
for item in request.GET[b"ACAOrigin"].split(b","):
headers.append((b"Access-Control-Allow-Origin", item))
for suffix in [b"Headers", b"Methods", b"Credentials"]:
query = b"ACA%s" % suffix
header = b"Access-Control-Allow-%s" % suffix
if query in request.GET:
headers.append((header, re | quest.GET[query]))
if b"ACEHeaders" in request.GET:
headers.append((b"Access-Control-Expose-Headers", request.GET[b"ACEHeaders"]))
if (b"Auth" in reques | t.GET and not request.auth.username) or b"AuthFail" in request.GET:
status = 401
headers.append((b'WWW-Authenticate', b'Basic realm="Restricted"'))
body = b'Authentication canceled'
return status, headers, body
if b"PNGIMAGE" in request.GET:
headers.append((b"Content-Type", b"image/png"))
body = decodebytes(b"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1B"
b"AACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAAhSURBVDhPY3wro/KfgQLABKXJBqMG"
b"jBoAAqMGDLwBDAwAEsoCTFWunmQAAAAASUVORK5CYII=")
return headers, body
if b"VIDEO" in request.GET:
headers.append((b"Content-Type", b"video/webm"))
body = open(os.path.join(request.doc_root, u"media", u"movie_5.ogv"), "rb").read()
length = len(body)
# If "PartialContent" is specified, the requestor wants to test range
# requests. For the initial request, respond with "206 Partial Content"
# and don't send the entire content. Then expect subsequent requests to
# have a "Range" header with a byte range. Respond with that range.
if b"PartialContent" in request.GET:
if length < 1:
return 500, headers, b"file is too small for range requests"
start = 0
end = length - 1
if b"Range" in request.headers:
range_header = request.headers[b"Range"]
prefix = b"bytes="
split_header = range_header[len(prefix):].split(b"-")
# The first request might be "bytes=0-". We want to force a range
# request, so just return the first byte.
if split_header[0] == b"0" and split_header[1] == b"":
end = start
# Otherwise, it is a range request. Respect the values sent.
if split_header[0] != b"":
start = int(split_header[0])
if split_header[1] != b"":
end = int(split_header[1])
else:
# The request doesn't have a range. Force a range request by
# returning the first byte.
end = start
headers.append((b"Accept-Ranges", b"bytes"))
headers.append((b"Content-Length", isomorphic_encode(str(end -start + 1))))
headers.append((b"Content-Range", b"bytes %d-%d/%d" % (start, end, length)))
chunk = body[start:(end + 1)]
return 206, headers, chunk
return headers, body
username = request.auth.username if request.auth.username else b"undefined"
password = request.auth.password if request.auth.username else b"undefined"
cookie = request.cookies[b'cookie'].value if b'cookie' in request.cookies else b"undefined"
files = []
for key, values in request.POST.items():
assert len(values) == 1
value = values[0]
if not hasattr(value, u"file"):
continue
data = value.file.read()
files.append({u"key": isomorphic_decode(key),
u"name": value.file.name,
u"type": value.type,
u"error": 0, #TODO,
u"size": len(data),
u"content": data})
get_data = {isomorphic_decode(key):isomorphic_decode(request.GET[key]) for key, value in request.GET.items()}
post_data = {isomorphic_decode(key):isomorphic_decode(request.POST[key]) for key, value in request.POST.items()
if not hasattr(request.POST[key], u"file")}
headers_data = {isomorphic_decode(key):isomorphic_decode(request.headers[key]) for key, value in request.headers.items()}
data = {u"jsonpResult": u"success",
u"method": request.method,
u"headers": headers_data,
u"body": isomorphic_decode(request.body),
u"files": files,
u"GET": get_data,
u"POST": post_data,
u"username": isomorphic_decode(username),
u"password": isomorphic_decode(password),
u"cookie": isomorphic_decode(cookie)}
return headers, u"report( %s )" % json.dumps(data)
|
nanocell/lsync | python/boto/auth.py | Python | gpl-3.0 | 24,702 | 0.000648 | # Copyright 2010 Google Inc.
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2011, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
"""
Handles authentication required to AWS and GS
"""
import base64
import boto
import boto.auth_handler
import boto.exception
import boto.plugin
import boto.utils
import hmac
import sys
import urllib
import time
import datetime
import copy
from email.utils import formatdate
from boto.auth_handler import AuthHandler
from boto.exception import BotoClientError
#
# the following is necessary because of the incompatibilities
# between Python 2.4, 2.5, and 2.6 as well as the fact that some
# people running 2.4 have installed hashlib as a separate module
# this fix was provided by boto user mccormix.
# see: http://code.google.com/p/boto/issues/detail?id=172
# for more details.
#
try:
from hashlib import sha1 as sha
from hashlib import sha256 as sha256
if sys.version[:3] == "2.4":
# we are using an hmac that expects a .new() method.
class Faker:
def __init__(self, which):
self.which = which
self.digest_size = self.which().digest_size
def new(self, *args, **kwargs):
return self.which(*args, **kwargs)
sha = Faker(sha)
sha256 = Faker(sha256)
except ImportError:
import sha
sha256 = None
class HmacKeys(object):
"""Key based Auth handler helper."""
def __init__(self, host, config, provider):
if provider.access_key is None or provider.secret_key is None:
raise boto.auth_handler.NotReadyToAuthenticate()
self.host = host
self.update_provider(provider)
def update_provider(self, provider):
self._provider = provider
self._hmac = hmac.new(self._provider.secret_key, digestmod=sha)
if sha256:
self._hmac_256 = hmac.new(self._provider.secret_key,
digestmod=sha256)
else:
self._hmac_256 = None
def algorithm(self):
if self._hmac_256:
return 'HmacSHA256'
else:
return 'HmacSHA1'
def _get_hmac(self):
if self._hmac_256:
digestmod = sha256
else:
digestmod = sha
return hmac.new(self._provider.secret_key,
digestmod=digestmod)
def sign_string(self, string_to_sign):
new_hmac = self._get_hmac()
new_hmac.update(string_to_sign)
return base64.encodestring(new_hmac.digest()).strip()
def __getstate__(self):
pickled_dict = copy.copy(self.__dict__)
del pickled_dict['_hmac']
del pickled_dict['_hmac_256']
return pickled_dict
def __setstate__(self, dct):
self.__dict__ = dct
self.update_provider(self._provider)
class AnonAuthHandler(AuthHandler, HmacKeys):
"""
Implements Anonymous requests.
"""
capability = ['anon']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
def add_auth(self, http_request, **kwargs):
pass
class HmacAuthV1Handler(AuthHandler, HmacKeys):
""" Implements the HMAC request signing used by S3 and GS."""
capability = ['hmac-v1', 's3']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
self._hmac_256 = None
def update_provider(self, provider):
super(HmacAuthV1Handler, self).update_provider(provider)
self._hmac_256 = None
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
method = http_request.method
auth_path = http_request.auth_path
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
if self._provider.security_token:
key = self._provider.security_token_header
headers[key] = self._provider.security_token
string_to_sign = boto.utils.canonical_string(method, auth_path,
headers, None,
self._provider)
boto.log.debug('StringToSign:\n%s' % string_to_sign)
b64_hmac = self.sign_string(string_to_sign)
auth_hdr = self._provider.auth_header
headers['Authorization'] = ("%s %s:%s" %
(auth_hdr,
self._provider. | access_key, b64_hmac))
class HmacAuthV2Handler(AuthHandler, HmacKeys):
"""
Implements the simplified HMAC authorization used by CloudFront.
"""
capability = ['hmac-v2', 'cloudfront']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
self._hmac_256 = None
def update_provider(self, | provider):
super(HmacAuthV2Handler, self).update_provider(provider)
self._hmac_256 = None
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
b64_hmac = self.sign_string(headers['Date'])
auth_hdr = self._provider.auth_header
headers['Authorization'] = ("%s %s:%s" %
(auth_hdr,
self._provider.access_key, b64_hmac))
class HmacAuthV3Handler(AuthHandler, HmacKeys):
"""Implements the new Version 3 HMAC authorization used by Route53."""
capability = ['hmac-v3', 'route53', 'ses']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
if self._provider.security_token:
key = self._provider.security_token_header
headers[key] = self._provider.security_token
b64_hmac = self.sign_string(headers['Date'])
s = "AWS3-HTTPS AWSAccessKeyId=%s," % self._provider.access_key
s += "Algorithm=%s,Signature=%s" % (self.algorithm(), b64_hmac)
headers['X-Amzn-Authorization'] = s
class HmacAuthV3HTTPHandler(AuthHandler, HmacKeys):
"""
Implements the new Version 3 HMAC authorization used by DynamoDB.
"""
capability = ['hmac-v3-http']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
def headers_to_sign(self, http_request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
headers_to_sign = {}
headers_to_sign = {'Host': self.host}
for name, value in http_request.headers.items():
lname = name.lower()
if lname.startswith('x-amz'):
|
stepanvanecek/failover_test_framework | source/infrastructure/main.py | Python | gpl-3.0 | 2,430 | 0.003704 | #!/usr/bin/python
import os
import sys
import commentjson
import time
import json
import datetime
from parse_input import check_config_struc | ture
from build_nova import build_infrastructure, wait_for_spawn
from url_requests import test_infrastructure
import subprocess
### MAIN
| if __name__ == "__main__":
if len(sys.argv) > 4:
configFile = sys.argv[4]
else:
print "No config file specified. Using 'config_example.json'"
configFile = 'config_example.json'
try:
with open(sys.argv[3] + "/config_files/" + configFile) as json_data_file:
try:
configData = commentjson.load(json_data_file)
except ValueError:
print "Wrong data format. Should be json."
exit(1)
except commentjson.JSONLibraryException:
print "Wrong data format. Should be json."
exit(1)
except IOError:
print "File not found/permission was denied."
exit(1)
configData['creds']['os_password'] = sys.argv[1]
configData['framework_dir'] = sys.argv[3]
print "Checking JSON structure..."
if check_config_structure(configData) == -1:
print "problem reading config file"
exit(1)
configData['launch_time'] = datetime.datetime.now().strftime('%Y/%m/%d-%H:%M:%S')
print "Building the infrastructure..."
if build_infrastructure(configData) == -1:
print "problem building the infrastructure"
exit(1)
if wait_for_spawn(configData) == -1:
print "machines didn't spawn properly"
exit(1)
raw_input("Press Enter once the HA installation is ready:")
print "Sending test request to ensure the operability."
if test_infrastructure(configData) == -1:
print "Infrastructure not built properly"
#erase built VMs
configData['creds']['os_password'] = ""
with open(sys.argv[2], 'w') as outfile:
json.dump(configData, outfile)
exit(1)
print " Request received."
print "---"
time.sleep(5)
#configData['test_url']['full_url'] = "87.190.239.41" #TODO zakomentovat
configData['creds']['os_password'] = ""
#TODO perform always, even after an exception
with open( sys.argv[2], 'w') as outfile:
json.dump(configData, outfile)
print "Testing availability of a service " + configData['test_url']['full_url']
exit(10) # OK
|
dotKom/onlineweb4 | apps/profiles/appconfig.py | Python | mit | 333 | 0 | from django.apps import AppConfig
class ProfilesConfig(AppConfig):
name = 'apps.profiles'
verbose_name = | 'Profiles'
def ready(self):
super(ProfilesConfig, self).ready()
from reversion import revisions as reversion
from apps.profiles.model | s import Privacy
reversion.register(Privacy)
|
levilucio/SyVOLT | UMLRT2Kiltera_MM/PortConnector.py | Python | mit | 3,839 | 0.029435 | """
__PortConnector.py_____________________________________________________
Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY)
Author: gehan
Modified: Sat Aug 30 18:23:4 | 0 2014
_______________________________________________________________________
"""
fro | m ASGNode import *
from ATOM3Type import *
from ATOM3String import *
from graph_PortConnector import *
class PortConnector(ASGNode, ATOM3Type):
def __init__(self, parent = None):
ASGNode.__init__(self)
ATOM3Type.__init__(self)
self.superTypes = ['NamedElement', 'MetaModelElement_S']
self.graphClass_ = graph_PortConnector
self.isGraphObjectVisual = True
if(hasattr(self, '_setHierarchicalLink')):
self._setHierarchicalLink(False)
if(hasattr(self, '_setHierarchicalNode')):
self._setHierarchicalNode(False)
self.parent = parent
self.cardinality=ATOM3String('1', 20)
self.cardinality=ATOM3String('1', 20)
self.cardinality=ATOM3String('1', 20)
self.classtype=ATOM3String('t_', 20)
self.classtype=ATOM3String('t_', 20)
self.classtype=ATOM3String('t_', 20)
self.name=ATOM3String('s_', 20)
self.name=ATOM3String('s_', 20)
self.name=ATOM3String('s_', 20)
self.generatedAttributes = {'cardinality': ('ATOM3String', ),
'cardinality': ('ATOM3String', ),
'cardinality': ('ATOM3String', ),
'classtype': ('ATOM3String', ),
'classtype': ('ATOM3String', ),
'classtype': ('ATOM3String', ),
'name': ('ATOM3String', ),
'name': ('ATOM3String', ),
'name': ('ATOM3String', ) }
self.realOrder = ['cardinality','cardinality','cardinality','classtype','classtype','classtype','name','name','name']
self.directEditing = [1,1,1,1,1,1,1,1,1]
def clone(self):
cloneObject = PortConnector( self.parent )
for atr in self.realOrder:
cloneObject.setAttrValue(atr, self.getAttrValue(atr).clone() )
ASGNode.cloneActions(self, cloneObject)
return cloneObject
def copy(self, other):
ATOM3Type.copy(self, other)
for atr in self.realOrder:
self.setAttrValue(atr, other.getAttrValue(atr) )
ASGNode.copy(self, other)
def preCondition (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.preCondition(actionID, params)
else: return None
def postCondition (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.postCondition(actionID, params)
else: return None
def preAction (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.preAction(actionID, params)
else: return None
def postAction (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.postAction(actionID, params)
else: return None
def QOCA(self, params):
"""
QOCA Constraint Template
NOTE: DO NOT select a POST/PRE action trigger
Constraints will be added/removed in a logical manner by other mechanisms.
"""
return # <---- Remove this to use QOCA
""" Get the high level constraint helper and solver """
from Qoca.atom3constraints.OffsetConstraints import OffsetConstraints
oc = OffsetConstraints(self.parent.qocaSolver)
"""
Example constraint, see Kernel/QOCA/atom3constraints/OffsetConstraints.py
For more types of constraints
"""
oc.fixedWidth(self.graphObject_, self.graphObject_.sizeX)
oc.fixedHeight(self.graphObject_, self.graphObject_.sizeY)
|
DronMDF/laweb | lawe/migrations/0007_auto_20170423_1937.py | Python | apache-2.0 | 1,029 | 0.029258 | # -*- coding: u | tf-8 -*-
# Generated by Django 1.10 on 2017-04-23 19:37
''' Миграция '''
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
''' Добавляем опциональные поля '''
dependencies = [
('lawe', '0006_remove_account_unit'),
]
operations = [
migrations.AlterField(
model_name='account',
name='group',
field=models.CharField(blank=True, max_ | length=200, verbose_name='Основная группа'),
),
migrations.AlterField(
model_name='account',
name='name',
field=models.CharField(blank=True, max_length=200, verbose_name='Название'),
),
migrations.AlterField(
model_name='account',
name='subgroup',
field=models.CharField(blank=True, max_length=200, verbose_name='Подгруппа'),
),
migrations.AlterField(
model_name='transaction',
name='description',
field=models.CharField(blank=True, max_length=200, verbose_name='Описание'),
),
]
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractBLNovelObsession.py | Python | bsd-3-clause | 854 | 0.0363 | def extractBLNovelObsession(item):
"""
'BL Novel Obsession'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Feng | Mang' in item['tags']:
return buildReleaseMessageWithType(item, 'Feng Mang', vol, chp, frag=frag, postfix=postfix)
tagmap = [
('Deceive', 'Deceive', 'translated'),
('Feng Mang', 'Feng Mang', 'translated'),
('15P 7H 6SM', '15P 7H 6SM', 'translated'),
('goldenassistant', 'Golden Assistant', 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return b | uildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
wcmitchell/insights-core | insights/combiners/tests/test_user_namespaces.py | Python | apache-2.0 | 4,522 | 0 | from ..user_namespaces import UserNamespaces
from ...parsers.cmdline import CmdLine
from ...parsers.grub_conf import Grub2Config
from ...tests import context_wrap
ENABLE_TOK_A = '''
user_namespaces.enable=1
'''.strip() # noqa
ENABLE_TOK_B = '''
user-namespaces.enable=1
'''.strip() # noqa
CMDLINE = '''
BOOT_IMAGE=/vmlinuz-3.10.0-514.6.1.el7.x86_64 root=/dev/mapper/rhel-root ro crashkernel=auto rd.lvm.lv=rhel/root rd.lvm.lv=rhel/swap {0}
'''.strip() # noqa
GRUB2_CONF = '''
### BEGIN /etc/grub.d/10_linux ###
menuentry 'Red Hat Enterprise Linux Server (3.10.0-514.16.1.el7.x86_64) 7.3 (Maipo)' --class red --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-514.el7.x86_64-advanced-9727cab4-12c2-41a8-9527-9644df34e586' {{
load_video
set gfxpayload=keep
insmod gzio
insmod part_gpt
insmod xfs
set root='hd0,gpt2'
if [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 d80fa96c-ffa1-4894-9282-aeda37f0befe
else
search --no-floppy --fs-uuid --set=root d80fa96c-ffa1-4894-9282-aeda37f0befe
fi
linuxefi /vmlinuz-3.10.0-514.16.1.el7.x86_64 root=/dev/mapper/rhel-root ro rd.luks.uuid=luks-a40b320e-0711-4cd6-8f9e-ce32810e2a79 rd.lvm.lv=rhel/root rd.lvm.lv=rhel/swap rhgb quiet LANG=en_US.UTF-8 {0}
initrdefi /initramfs-3.10.0-514.16.1.el7.x86_64.img
}}
menuentry 'Red Hat Enterprise Linux Server (3.10.0-514.10.2.e | l7.x86_64) 7.3 (Maipo)' --class red --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-514.el7.x86_64-advanced-9727cab4-12c2-41a8-9527-9644df34e586' {{
load_video
set gfxpayload=keep
insmod gzio
insmod part_gpt
insmod xfs
set root='hd0,gpt2'
if | [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 d80fa96c-ffa1-4894-9282-aeda37f0befe
else
search --no-floppy --fs-uuid --set=root d80fa96c-ffa1-4894-9282-aeda37f0befe
fi
linuxefi /vmlinuz-3.10.0-514.10.2.el7.x86_64 root=/dev/mapper/rhel-root ro rd.luks.uuid=luks-a40b320e-0711-4cd6-8f9e-ce32810e2a79 rd.lvm.lv=rhel/root rd.lvm.lv=rhel/swap rhgb quiet LANG=en_US.UTF-8 {1}
initrdefi /initramfs-3.10.0-514.10.2.el7.x86_64.img
}}
''' # noqa
MENUENTRY_0 = '''
'Red Hat Enterprise Linux Server (3.10.0-514.16.1.el7.x86_64) 7.3 (Maipo)' --class red --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-514.el7.x86_64-advanced-9727cab4-12c2-41a8-9527-9644df34e586'
'''.strip() # noqa
MENUENTRY_1 = '''
'Red Hat Enterprise Linux Server (3.10.0-514.10.2.el7.x86_64) 7.3 (Maipo)' --class red --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-514.el7.x86_64-advanced-9727cab4-12c2-41a8-9527-9644df34e586'
'''.strip() # noqa
CASES = [
# noqa
# |-- provided --| |---- expected results ---|
# ((cmdline, grub), (enabled, enabled_configs))
# Not enabled, no grub data
((CMDLINE.format(''), None), (False, [])),
# Not enabled, not enabled in grub
((CMDLINE.format(''), GRUB2_CONF.format('', '')), (False, [])),
# Not enabled, but enabled in menuentry 1
((CMDLINE.format(''), GRUB2_CONF.format('', ENABLE_TOK_A)),
(False, [MENUENTRY_1])),
# Enabled, no grub data
((CMDLINE.format(ENABLE_TOK_A), None), (True, [])),
# Enabled, but not enabled in grub
((CMDLINE.format(ENABLE_TOK_A), GRUB2_CONF.format('', '')),
(True, [])),
# Enabled, enabled in menuentry 0
((CMDLINE.format(ENABLE_TOK_A), GRUB2_CONF.format(ENABLE_TOK_A, '')),
(True, [MENUENTRY_0])),
# Dash syntax, rather than underscore
((CMDLINE.format(ENABLE_TOK_B), GRUB2_CONF.format(ENABLE_TOK_B, '')),
(True, [MENUENTRY_0]))
]
def test_integration():
for case in CASES:
context = {}
context[CmdLine] = CmdLine(context_wrap(case[0][0]))
if case[0][1] is not None:
context[Grub2Config] = Grub2Config(context_wrap(case[0][1]))
un = UserNamespaces(context.get(CmdLine), context.get(Grub2Config))
assert un.enabled() == case[1][0]
assert un.enabled_configs() == case[1][1]
|
cmtm/networkx | networkx/algorithms/shortest_paths/tests/test_astar.py | Python | bsd-3-clause | 5,022 | 0 | from nose.tools import assert_equal
from nose.tools import assert_raises
from nose.tools import raises
from math import sqrt
from random import random, choice
import networkx as nx
from networkx.utils import pairwise
def dist(a, b):
"""Returns the Euclidean distance between points `a` and `b`."""
return sqrt(sum((x1 - x2) ** 2 for x1, x2 in zip(a, b)))
class TestAStar:
def setUp(self):
edges = [('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1), ('u', 'x', 2),
('v', 'y', 1), ('x', 'u', 3), ('x', 'v', 5), ('x', 'y', 2),
('y', 's', 7), ('y', 'v', 6)]
self.XG = nx.DiGraph()
self.XG.add_weighted_edges_from(edges)
def test_random_graph(self):
"""Tests that the A* shortest path agrees with Dijkstra's
shortest path for a random graph.
"""
G = nx.Graph()
points = [(random(), random()) for _ in range(100)]
# Build a path from points[0] to points[-1] to be sure it exists
for p1, p2 in pairwise(points):
G.add_edge(p1, p2, weight=dist(p1, p2))
# Add other random edges
for _ in range(100):
p1, p2 = choice(points), choice(points)
G.add_edge(p1, p2, weight=dist(p1, p2))
path = nx.astar_path(G, points[0], points[-1], dist)
assert_equal(path, nx.dijkstra_path(G, points[0], points[-1]))
def test_astar_directed(self):
assert_equal(nx.astar_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v'])
assert_equal(nx.astar_path_length(self.XG, 's', 'v'), 9)
def test_astar_multigraph(self):
G = nx.MultiDiGraph(self.XG)
assert_raises(nx.NetworkXNotImplemented, nx.astar_path, G, 's', 'v')
assert_raises(nx.NetworkXNotImplemented, nx.astar_path_length,
G, 's', 'v')
def test_astar_undirected(self):
GG = self.XG.to_undirected()
# make sure we get lower weight
# to_undirected might choose either edge with weight 2 or weight 3
GG['u']['x']['weight'] = 2
GG['y']['v']['weight'] = 2
assert_equal(nx.astar_path(GG, 's', 'v'), ['s', 'x', 'u', 'v'])
assert_equal(nx.astar_path_length(GG, 's', 'v'), 8)
def test_astar_directed2(self):
XG2 = nx.DiGraph()
edges = [(1, 4, 1), (4, 5, 1), (5, 6, 1), (6, 3, 1), (1, 3, 50),
(1, 2, 100), (2, 3, 100)]
XG2.add_weighted_edges_from(edges)
assert_equal(nx.astar_path(XG2, 1, 3), [1, 4, 5, 6, 3])
def test_astar_undirected2(self):
XG3 = nx.Graph()
edges = [(0, 1, 2), (1, 2, 12), (2, 3, 1), (3, 4, 5), (4, 5, 1),
(5, 0, 10)]
XG3.add_weighted_edges_from(edges)
assert_equal(nx.astar_path(XG3, 0, 3), [0, 1, 2, 3])
assert_equal(nx.astar_path_length(XG3, 0, 3), 15)
def test_astar_undirected3(self):
XG4 = nx.Graph()
edges = [(0, 1, 2), (1, 2, 2), (2, 3, 1), (3, 4, 1), (4, 5, 1),
(5, 6, 1), (6, 7, 1), (7, 0, 1)]
XG4.add_weighted_edges_from(edges)
assert_equal(nx.astar_path(XG4, 0, 2), [0, 1, 2])
assert_equal(nx.astar_path_length(XG4, 0, 2), 4)
# >>> MXG4=NX.MultiGraph(XG4)
# >>> MXG4.add_edge(0,1,3)
# >>> NX.dijkstra_path(MXG4,0,2)
# [0, 1, 2]
def test_astar_w1(self):
G = nx.DiGraph()
G.add_edges_from([('s', 'u'), ('s', 'x'), ('u', 'v'), ('u', 'x'),
('v', 'y'), ('x', 'u'), ('x', 'w'), ('w', 'v'),
('x', 'y'), ('y', 's'), ('y', 'v')])
assert_equal(nx.astar_path(G, 's', 'v'), ['s', 'u', 'v'])
assert_equal(nx.astar_path_length(G, 's', 'v'), 2)
@raises(nx.NodeNotFound)
def test_astar_nopath(self):
nx.astar_path(self.XG, 's', 'moon')
def test_cycle(self):
C = nx.cycle_graph(7)
assert_equal(nx.astar_path(C, 0, 3), [0, 1, 2, 3])
assert_equal(nx.dijkstra_path(C, 0, 4), [0, 6, 5, 4])
def test_unorderable_nodes(self):
"""Tests that A* accomodates nodes that are not orderable.
For more information, see issue #554.
"""
# TODO In Python 3, instances of the `object` class are
# unorderable by default, so we wouldn't need to define our own
# class here, we could just instantiate an instance of the
# `object` class. However, we still support Python 2; when
# support for Pyth | on 2 is | dropped, this test can be simplified
# by replacing `Unorderable()` by `object()`.
class Unorderable(object):
def __le__(self):
raise NotImplemented
def __ge__(self):
raise NotImplemented
# Create the cycle graph on four nodes, with nodes represented
# as (unorderable) Python objects.
nodes = [Unorderable() for n in range(4)]
G = nx.Graph()
G.add_edges_from(pairwise(nodes, cyclic=True))
path = nx.astar_path(G, nodes[0], nodes[2])
assert_equal(len(path), 3)
|
uDeviceX/uDeviceX | pre/uconf/src/uconf.py | Python | gpl-2.0 | 20,089 | 0.0001 | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
if attr == '_OrderedDict__root':
# Work around Python2's OrderedDict weirdness.
raise AttributeError("AttrDict has no attribute %r" % attr)
return self.__getitem__(attr)
def __setitem__(self, name, value):
d = self
if name in d:
otype = type(d[name])
ntype = type(value)
if otype is not ntype:
msg = "cannot set '%s' to '%s', expecting type: '%s', given '%s'" % \
(name, str(value), otype.__name__, ntype.__name__)
raise AttributeError(msg)
super().__setitem__(name, value)
def __setattr__(self, name, value):
self[name] = value
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
| (BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)' | ),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.