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 |
|---|---|---|---|---|---|---|---|---|
policycompass/policycompass-services | apps/metricsmanager/signals.py | Python | agpl-3.0 | 1,207 | 0.002486 | """
This creates Django signals that automatically update the elastic search Index
When an item is created, a signal is thrown that runs the create / upd | ate index API of the Search Manager
When an item is deleted, a signal is thrown that executes the delete index API of the Search Manager
This way the Policy compass database and Elastic search index remains synced.
"""
from django.db.models.signals i | mport post_save, post_delete
from django.dispatch import receiver
from .models import Metric
from apps.searchmanager.signalhandlers import search_index_update, search_index_delete
from apps.datasetmanager import internal_api
@receiver(post_save, sender=Metric)
def update_document_on_search_service(sender, **kwargs):
if not kwargs.get('raw', False):
instance = kwargs['instance']
search_index_update('metric', instance.id)
@receiver(post_delete, sender=Metric)
def delete_document_on_search_service(sender, **kwargs):
instance = kwargs['instance']
search_index_delete('metric', instance.id)
@receiver(post_delete, sender=Metric)
def remove_metric_link_from_datasets(sender, **kwargs):
instance = kwargs['instance']
internal_api.remove_metric_link(instance.id)
|
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/masked/ipaddrctrl.py | Python | mit | 8,362 | 0.013155 | #----------------------------------------------------------------------------
# Name: masked.ipaddrctrl.py
# Authors: Will Sadkin
# Email: wsadkin@nameconnector.com
# Created: 02/11/2003
# Copyright: (c) 2003 by Will Sadkin, 2003
# RCS-ID: $Id$
# License: wxWidgets license
#----------------------------------------------------------------------------
# NOTE:
# Masked.IpAddrCtrl is a minor modification to masked.TextCtrl, that is
# specifically tailored for entering IP addresses. It allows for
# right-insert fields and provides an accessor to obtain the entered
# address with extra whitespace removed.
#
#----------------------------------------------------------------------------
"""
Provides a smart text input control that understands the structure and
limits of IP Addresses, and allows automatic field navigation as the
user hits '.' when typing.
"""
import wx, types, string
from wx.lib.masked import BaseMaskedTextCtrl
# jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
# be a good place to implement the 2.3 logger class
from wx.tools.dbg import Logger
##dbg = Logger()
##dbg(enable=0)
class IpAddrCtrlAccessorsMixin:
"""
Defines IpAddrCtrl's list of attributes having their own
Get/Set functions, exposing only those that make sense for
an IP address control.
"""
exposed_basectrl_params = (
'fields',
'retainFieldValidation',
'formatcodes',
'fillChar',
'defaultValue',
'description',
'useFixedWidthFont',
'signedForegroundColour',
'emptyBackgroundColour',
'validBackgroundColour',
'invalidBackgroundColour',
'emptyInvalid',
'validFunc',
'validRequired',
)
for param in exposed_basectrl_params:
propname = param[0].upper() + param[1:]
exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
if param.find('Colour') != -1:
# add non-british spellings, for backward-compatibility
propname.replace('Colour', 'Color')
exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):
"""
This class is a particular type of MaskedTextCtrl that accepts
and understands the semantics of IP addresses, reformats input
as you move from field to field, and accepts '.' as a navigation
character, so that typing an IP address can be done naturally.
"""
def __init__( self, parent, id=-1, value = '',
pos = wx.DefaultPosition,
size = wx.DefaultSize,
style = wx.TE_PROCESS_TAB,
validator = wx.DefaultValidator,
name = 'IpAddrCtrl',
setupEventHandling = True, ## setup event handling by default
**kwargs):
if not kwargs.has_key('mask'):
kwargs['mask'] = mask = "###.###.###.###"
if not kwargs.has_key('formatcodes'):
kwargs['formatcodes'] = 'F_Sr<>'
if not kwargs.has_key('validRegex'):
kwargs['validRegex'] = "( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}"
BaseMaskedTextCtrl.__init__(
self, parent, id=id, value = value,
pos=pos, size=size,
style = style,
validator = validator,
name = name,
setupEventHandling = setupEventHandling,
**kwargs)
# set up individual field parameters as well:
field_params = {}
field_params['validRegex'] = "( | \d| \d |\d | \d\d|\d\d |\d \d|(1\d\d|2[0-4]\d|25[0-5]))"
# require "valid" string; this prevents entry of any value > 255, but allows
# intermediate constructions; overall control validation requires well-formatted value.
field_params['formatcodes'] = 'V'
if field_params:
for i in self._field_indices:
self.SetFieldParameters(i, **field_params)
# This makes '.' act like tab:
self._AddNavKey('.', handler=self.OnDot)
self._AddNavKey('>', handler=self.OnDot) # for "shift-."
def OnDot(self, event):
"""
Defines what action t | o take when the '.' character is typed in the
control. | By default, the current field is right-justified, and the
cursor is placed in the next field.
"""
## dbg('IpAddrCtrl::OnDot', indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
oldvalue = self.GetValue()
edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
if not event.ShiftDown():
if pos > edit_start and pos < edit_end:
# clip data in field to the right of pos, if adjusting fields
# when not at delimeter; (assumption == they hit '.')
newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]
self._SetValue(newvalue)
self._SetInsertionPoint(pos)
## dbg(indent=0)
return self._OnChangeField(event)
def GetAddress(self):
"""
Returns the control value, with any spaces removed.
"""
value = BaseMaskedTextCtrl.GetValue(self)
return value.replace(' ','') # remove spaces from the value
def _OnCtrl_S(self, event):
## dbg("IpAddrCtrl::_OnCtrl_S")
if self._demo:
print "value:", self.GetAddress()
return False
def SetValue(self, value):
"""
Takes a string value, validates it for a valid IP address,
splits it into an array of 4 fields, justifies it
appropriately, and inserts it into the control.
Invalid values will raise a ValueError exception.
"""
## dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)
if type(value) not in (types.StringType, types.UnicodeType):
## dbg(indent=0)
raise ValueError('%s must be a string', str(value))
bValid = True # assume True
parts = value.split('.')
if len(parts) != 4:
bValid = False
else:
for i in range(4):
part = parts[i]
if not 0 <= len(part) <= 3:
bValid = False
break
elif part.strip(): # non-empty part
try:
j = string.atoi(part)
if not 0 <= j <= 255:
bValid = False
break
else:
parts[i] = '%3d' % j
except:
bValid = False
break
else:
# allow empty sections for SetValue (will result in "invalid" value,
# but this may be useful for initializing the control:
parts[i] = ' ' # convert empty field to 3-char length
if not bValid:
## dbg(indent=0)
raise ValueError('value (%s) must be a string of form n.n.n.n where n is empty or in range 0-255' % str(value))
else:
## dbg('parts:', parts)
value = string.join(parts, '.')
BaseMaskedTextCtrl.SetValue(self, value)
## dbg(indent=0)
__i=0
## CHANGELOG:
## ====================
## Version 1.2
## 1. Fixed bugs involving missing imports now that these classes are in
## their own module.
## 2. Added doc strings for ePyDoc.
## 3. Renamed helper functions, vars et |
ekivemark/bofhirdev | accounts/admin.py | Python | gpl-2.0 | 4,321 | 0.000694 | from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
# Register your models here.
from accounts.models import (User,
ValidSMSCode,
# Application,
Crosswalk)
# TODO: Fix Admin Panels - Bootstrap Layout is not fully functional
# TODO: Add Admin Breadcrumbs?
# TODO: Allow record to be added to empty database
# Account
class UserCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label='Password',
widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation',
widget=forms.PasswordInput,
help_text="<br/>Enter your password again to confirm.")
class Meta:
model = User
fields = ('user', 'email', 'first_name', 'last_name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""
A form for updating users. Includes all the fields on
the user, but replaces the password field with admin
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('user', 'email', 'password', 'first_name', 'last_name',
'is_active', 'is_admin', 'is_staff', 'notify_activity')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class UserAdmin(UserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('user', 'email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('user', 'email', 'password')}),
('Personal info', {'fields': ('first_name',
'last_name',
'mobile',
'carrier',
'mfa',
'notify_activity')}),
(
'Permissions', {'fields': ('is_admin', 'is_active', 'is_staff',)}),
)
# TODO: Need to make phone number formatting more user friendly
# Currently requires +Country code
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when cr | eating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('user', 'email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# class ApplicationAdmin(admin.ModelAdmin):
# """
# Tailor the Application page in the main Admi | n module
# """
# # DONE: Add Admin view for applications
# list_display = ('name', 'user')
# admin.site.register(Account)
admin.site.register(User, UserAdmin)
# admin.site.register(Application, ApplicationAdmin)
# admin.site.register(ApplicationKey)
admin.site.register(ValidSMSCode)
admin.site.register(Crosswalk)
admin.site.unregister(Group)
|
khrapovs/multivol | setup.py | Python | mit | 1,004 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as file:
long_description = file.read()
setup(name='multivol',
version='1.0',
description=('Multivariate (co)variance'),
long_description=long_description,
author='Stanislav Khrapov',
license='MIT',
author_email='khrapovs@gmail.com',
url='https://github.com/khrapovs/multivol',
packages=find_packages(),
keywords=['volatility', 'multivariate', 'covariance', 'dynamics',
'estimation', 'simulation'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Financial and Insurance Industry',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Pyth | on :: 3. | 3',
'Programming Language :: Python :: 3.4',
],
)
|
dl1ksv/gnuradio | gr-utils/modtool/core/rm.py | Python | gpl-3.0 | 9,217 | 0.001844 | #
# Copyright 2013, 2018-2020 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
""" Remove blocks module """
import os
import re
import sys
import glob
import logging
from ..tools import remove_pattern_from_file, CMakeFileEditor, CPPFileEditor, get_block_names
from .base import ModTool, ModToolException
logger = logging.getLogger(__name__)
class ModToolRemove(ModTool):
""" Remove block (delete files and remove Makefile entries) """
name = 'remove'
description = 'Remove a block from a module.'
def __init__(self, blockname=None, **kwargs):
ModTool.__init__(self, blockname, **kwargs)
self.info['pattern'] = blockname
def validate(self):
""" Validates the arguments """
ModTool._validate(self)
if not self.info['pattern'] or self.info['pattern'].isspace():
raise ModToolException("Incorrect blockname (Regex)!")
def run(self):
""" Go, go, go! """
# This portion will be covered by the CLI
if not self.cli:
self.validate()
else:
from ..cli import cli_input
def _remove_cc_test_case(filename=None, ed=None):
""" Special function that removes the occurrences of a qa*.cc file
from the CMakeLists.txt. """
modname_ = self.info['modname']
if filename[:2] != 'qa':
return
if self.info['version'] == '37':
(base, ext) = os.path.splitext(filename)
if ext == '.h':
remove_pattern_from_file(self._file['qalib'],
fr'^#include "{filename}"\s*$')
remove_pattern_from_file(self._file['qalib'],
fr'^\s*s->addTest\(gr::{modname_}::{base}::suite\(\)\);\s*$'
)
self.scm.mark_file_updated(self._file['qalib'])
elif ext == '.cc':
ed.remove_value('list',
r'\$\{CMAKE_CURRENT_SOURCE_DIR\}/%s' % filename,
to_ignore_start=f'APPEND test_{modname_}_sources')
self.scm.mark_file_updated(ed.filename)
elif self.info['version'] in ['38', '310']:
(base, ext) = os.path.splitext(filename)
if ext == '.cc':
ed.remove_value(
'list', filename,
to_ignore_start=f'APPEND test_{modname_}_sources')
self.scm.mark_file_updated(ed.filename)
else:
filebase = os.path.splitext(filename)[0]
ed.delete_entry('add_executable', filebase)
ed.delete_entry('target_link_libraries', filebase)
ed.delete_entry('GR_ADD_TEST', filebase)
ed.remove_double_newlines()
self.scm.mark_file_updated(ed.filename)
def _remove_py_test_case(filename=None, ed=None):
""" Special function that removes the occurrences of a qa*.{cc,h} file
from the CMakeLists.txt and the qa_$modname.cc. """
if filename[:2] != 'qa':
return
filebase = os.path.splitext(filename)[0]
ed.delete_entry('GR_ADD_TEST', filebase)
ed.remove_double_newlines()
# Go, go, go!
if not self.skip_subdirs['python']:
py_files_deleted = self._run_subdir(self.info['pydir'], ('*.py',), ('GR_PYTHON_INSTALL',),
cmakeedit_func=_remove_py_test_case)
for f in py_files_deleted:
remove_pattern_from_file(
self._file['pyinit'], fr'.*import\s+{f[:-3]}.*')
remove_pattern_from_file(
self._file['pyinit'], fr'.*from\s+{f[:-3]}\s+import.*\n')
pb_files_deleted = self._run_subdir(os.path.join(
self.info['pydir'], 'bindings'), ('*.cc',), ('list',))
pbdoc_files_deleted = self._run_subdir(os.path.join(
self.info['pydir'], 'bindings', 'docstrings'), ('*.h',), ('',))
# Update python_bindings.cc
blocknames_to_delete = []
if self.info['blockname']:
# A complete block name was given
blocknames_to_delete.append(self.info['blockname'])
elif self.info['pattern']:
# A regex resembling one or several blocks were given
blocknames_to_delete = get_block_names(
self.info['pattern'], self.info['modname'])
else:
raise ModToolException("No block name or regex was specified!")
for blockname in blocknames_to_delete:
ed = CPPFileEditor(self._file['ccpybind'])
ed.remove_value('// BINDING_FUNCTION_PROTOTYPES(', '// ) END BINDING_FUNCTION_PROTOTYPES',
'void bind_' + blockname + '(py::module& m);')
ed.remove_value('// BINDING_FUNCTION_CALLS(', '// ) END BINDING_FUNCTION_CALLS',
'bind_' + blocknam | e + '(m);')
ed.write()
if not self.skip_subdirs['lib']:
self._run_subdir('lib', ('*.cc', '*.h'), ('add_library', 'list'),
cmakeedit_func=_remove_cc_test_case)
if not self.skip_subdirs['include']:
incl_files_de | leted = self._run_subdir(
self.info['includedir'], ('*.h',), ('install',))
if not self.skip_subdirs['grc']:
self._run_subdir('grc', ('*.yml',), ('install',))
def _run_subdir(self, path, globs, makefile_vars, cmakeedit_func=None):
""" Delete all files that match a certain pattern in path.
path - The directory in which this will take place
globs - A tuple of standard UNIX globs of files to delete (e.g. *.yml)
makefile_vars - A tuple with a list of CMakeLists.txt-variables which
may contain references to the globbed files
cmakeedit_func - If the CMakeLists.txt needs special editing, use this
"""
if self.cli:
from ..cli import cli_input
# 1. Create a filtered list
files = []
for g in globs:
files = files + sorted(glob.glob(f"{path}/{g}"))
files_filt = []
logger.info(f"Searching for matching files in {path}/:")
if self.info['blockname']:
# Ensure the blockname given is not confused with similarly named blocks
blockname_pattern = ''
if path == self.info['pydir']:
blockname_pattern = f"^(qa_)?{self.info['blockname']}.py$"
elif path == os.path.join(self.info['pydir'], 'bindings'):
blockname_pattern = f"^{self.info['blockname']}_python.cc$"
elif path == os.path.join(self.info['pydir'], 'bindings', 'docstrings'):
blockname_pattern = f"^{self.info['blockname']}_pydoc_template.h$"
elif path == 'lib':
blockname_pattern = f"^{self.info['blockname']}_impl(\\.h|\\.cc)$"
elif path == self.info['includedir']:
blockname_pattern = f"^{self.info['blockname']}.h$"
elif path == 'grc':
blockname_pattern = f"^{self.info['modname']}_{self.info['blockname']}.block.yml$"
for f in files:
if re.search(blockname_pattern, os.path.basename(f)) is not None:
files_filt.append(f)
elif self.info['pattern']:
# A regex resembling one or several blocks were given as stdin
for f in files:
if re.search(self.info['pattern'], os.path.basename(f)) is not None:
files_filt.append(f)
if len(files_filt) == 0:
logger.info("None found.")
return []
# 2. Delete files, Makefile entries and other occurrences
files_deleted = []
yes = self.info['yes']
for f in files_filt:
|
Lilykos/invenio | invenio/testsuite/test_utils_pagination.py | Python | gpl-2.0 | 2,174 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Test unit for the miscutil/paginationutils module.
"""
from invenio.utils.pagination import Pagination
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
class TestPaginationUtils(InvenioTestCase):
"""
PaginationUtils TestSuite.
"""
def test_first_page(self):
page = 1
per_page = 10
total_count = 98
pagination = Pagination(page, per_page, total_count)
self.assertFalse(pagination.has_prev)
self. | assertTrue(pagination.has_next)
self.assertEqual(list(pagination.iter_pages()), [1, 2, 3, None, 10])
def test_last_page(self):
page = 10
per_page = 10
total_count = 98
pagination = Pagination(page, per_page, total_count)
self.assertTrue(pagination.has_prev)
self.assertFalse(pagination.has_next)
self.assertEqual(list(pagination.iter_pages()), [1, None, 9, 10])
def test_middle_page(self):
page = 5
per_page = 10
t | otal_count = 98
pagination = Pagination(page, per_page, total_count)
self.assertTrue(pagination.has_prev)
self.assertTrue(pagination.has_next)
self.assertEqual(list(pagination.iter_pages()),
[1, None, 4, 5, 6, 7, None, 10])
TEST_SUITE = make_test_suite(TestPaginationUtils,)
if __name__ == "__main__":
run_test_suite(TEST_SUITE)
|
sbyount/pynet_test | netmiko_test.py | Python | apache-2.0 | 377 | 0.007958 | #!usr/bin | /env python
from netmiko import ConnectHandler
from getpass import getpass
#passowrd = getpass()
pynet1 = {
'device_type': 'cisco_ios',
'ip': '184.105.247.70',
'username': 'pyclass',
'password': '88newclass'
}
pynet_rtr1 = ConnectHandler(**pynet1) # Pass all args from | the dictionary
outp = pynet_rtr1.send_command('sh ip int br')
print outp
|
jawilson/home-assistant | homeassistant/helpers/debounce.py | Python | apache-2.0 | 3,910 | 0.000512 | """Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
def __init__(
self,
hass: HomeAssistant,
logger: Logger,
*,
cooldown: float,
immediate: bool,
function: Callable[..., Awaitable[Any]] | None = None,
) -> None:
"""Initialize debounce.
immediate: indicate if the function needs to be called right away and
wait <cooldown> until executing next invocation.
function: optional and can be instantiated later.
"""
self.hass = hass
self.logger = logger
self._function = function
self.cooldown = cooldown
self.immediate = immediate
self._timer_task: asyncio.TimerHandle | None = None
self._execute_at_end_of_timer: bool = False
self._execute_lock = asyncio.Lock()
self._job: HassJob | None = None if function is None else HassJob(function)
@property
def function(self) -> Callable[..., Awaitable[Any]] | None:
"""Return the function being wrapped by the Debouncer."""
return self._function
@function.setter
def function(self, function: Callable[..., Awaitable[Any]]) -> None:
"""Update the function being wrapped by the Debouncer."""
self._function = function
if self._job is None or function != self._job.target:
self._job = HassJob(function)
async def async_call(self) -> None:
"""Call the function."""
assert self._job is not None
if self._timer_task:
if not self._execute_at_end_of_timer:
self._execute_at_end_of_timer = True
return
# Locked means a call is in progress. Any call is good, so abort.
if self._execute_lock.locked():
return
if not self.immediate:
self._execute_at_end_of_timer = True
self._schedule_timer()
return
async with self._execute_lock:
# Abort if timer got set while we're waiting for the lock.
if self._timer_task:
return
task = self.hass.async_run_hass_job(self._job)
if task:
await task
self._schedule_timer()
async def _handle_timer_finish(self) -> None:
"""Handle a finished timer."""
assert self._job is not None
self._timer_task = None
if not self._execute_at_end_of_timer:
return
self._execute_at_end_of_timer = False
# Locked means a call is in progress. Any call is good, so abort.
if self._execute_lock.locked():
return
async with self._execute_lock:
# Abo | rt if timer got set while we're waiting for the lock.
| if self._timer_task:
return # type: ignore
try:
task = self.hass.async_run_hass_job(self._job)
if task:
await task
except Exception: # pylint: disable=broad-except
self.logger.exception("Unexpected exception from %s", self.function)
self._schedule_timer()
@callback
def async_cancel(self) -> None:
"""Cancel any scheduled call."""
if self._timer_task:
self._timer_task.cancel()
self._timer_task = None
self._execute_at_end_of_timer = False
@callback
def _schedule_timer(self) -> None:
"""Schedule a timer."""
self._timer_task = self.hass.loop.call_later(
self.cooldown,
lambda: self.hass.async_create_task(self._handle_timer_finish()),
)
|
briancline/softlayer-python | SoftLayer/CLI/vlan/detail.py | Python | mit | 3,145 | 0 | """Get details about a VLAN."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
import click
@click.command()
@click.argument('identifier')
@click.option('--no-vs',
is_flag=True,
help="Hide virtual server listing")
@click.option('--no-hardware',
is_flag=True,
help="Hide hardware listing")
@environment.pass_env
def cli(env, identifier, no_vs, no_hardware):
"""Get details about a VLAN."""
mgr = SoftLayer.NetworkManager(env.client)
vlan_id = helpers.resolve_id(mgr.resolve_vlan_ids, identifier, 'VLAN')
vlan = mgr.get_vlan(vlan_id)
table = formatting.KeyValueTable(['Name', 'Value'])
table.align['Name'] = 'r'
table.align['Value'] = 'l'
table.add_row(['id', vlan['id']])
table.add_row(['number', vlan['vlanNumber']])
table.add_row(['datacenter',
vlan['primaryRouter']['datacenter']['longName']])
t | able.add_row(['primary router',
vlan['primaryRouter']['fullyQualifiedDomainName']])
table.add_row(['firewall',
'Yes' if vlan['firewallInterfaces'] else 'No'])
subnets = []
for subnet in vlan['subnets']:
subnet_table = formatting.KeyValueTable(['Name', 'Value'])
subnet_table.align['Name'] | = 'r'
subnet_table.align['Value'] = 'l'
subnet_table.add_row(['id', subnet['id']])
subnet_table.add_row(['identifier', subnet['networkIdentifier']])
subnet_table.add_row(['netmask', subnet['netmask']])
subnet_table.add_row(['gateway', subnet.get('gateway', '-')])
subnet_table.add_row(['type', subnet['subnetType']])
subnet_table.add_row(['usable ips',
subnet['usableIpAddressCount']])
subnets.append(subnet_table)
table.add_row(['subnets', subnets])
if not no_vs:
if vlan['virtualGuests']:
vs_table = formatting.KeyValueTable(['Hostname',
'Domain',
'IP'])
vs_table.align['Hostname'] = 'r'
vs_table.align['IP'] = 'l'
for vsi in vlan['virtualGuests']:
vs_table.add_row([vsi['hostname'],
vsi['domain'],
vsi.get('primaryIpAddress')])
table.add_row(['vs', vs_table])
else:
table.add_row(['vs', 'none'])
if not no_hardware:
if vlan['hardware']:
hw_table = formatting.Table(['Hostname', 'Domain', 'IP'])
hw_table.align['Hostname'] = 'r'
hw_table.align['IP'] = 'l'
for hardware in vlan['hardware']:
hw_table.add_row([hardware['hostname'],
hardware['domain'],
hardware.get('primaryIpAddress')])
table.add_row(['hardware', hw_table])
else:
table.add_row(['hardware', 'none'])
env.fout(table)
|
knagra/farnsworth | managers/migrations/0001_initial.py | Python | bsd-2-clause | 6,574 | 0.00578 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Announcement',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('body', models.TextField(help_text='The body of the announcement.')),
('post_date', models.DateTimeField(help_text='The date this announcement was posted.', auto_now_add=True)),
('pinned', models.BooleanField(default=False, help_text='Whether this announcment should be pinned permanently.')),
('change_date', models.DateTimeField(help_text='The last time this request was modified.', auto_now_add=True)),
('incumbent', models.ForeignKey(help_text='The incumbent who made this announcement.', to='base.UserProfile')),
],
options={
'ordering': ['-post_date'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Manager',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(help_text='The title of this management position.', unique=True, max_length=255)),
('url_title', models.CharField(help_text='The unique URL key for this manager. Autogenerated from custom interface.', max_length=255)),
('compensation', models.TextField(help_text='The compensation for this manager.', null=True, blank=True)),
('duties', models.TextField(help_text='The duties of this manager.', null=True, blank=True)),
('email', models.EmailField(help_text='The e-mail address of this manager.', max_length=255, null=True, blank=True)),
('president', models.BooleanField(default=False, help_text='Whether this manager has president privileges (edit managers, bylaws, etc.).')),
('workshift_manager', models.BooleanField(default=False, help_text='Whether this manager has workshift manager privileges (assign workshifts, etc.).')),
('active', models.BooleanField(default=True, help_text='Whether this is an active manager position (visible in directory, etc.).')),
('incumbent', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, blank=True, to='base.UserProfile', help_text='The incumbent for this position.', null=True)),
],
options={
},
bases=(models.Model,),
),
migrations.AddField(
model_name='announcement',
name='manager',
field=models.ForeignKey(help_text='The manager who made this announcement.', to='managers.Manager'),
preserve_default=True,
),
migrations.CreateModel(
name='Request',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('body', models.TextField(help_text='The body of this request.')),
('post_date', models.DateTimeField(help_text='The date this request was posted.', auto_now_add=True)),
('change_date', models.DateTimeField(help_text='The last time this request was modified.', auto_now_add=True)),
('filled', models.BooleanField(default=False, help_text='Whether the manager deems this request filled.')),
('closed', models.BooleanField(default=False, help_text='Whether the manager has closed this request.')),
('number_of_responses', models.PositiveSmallIntegerField(default=0, help_text='The number of responses to this request.')),
('owner', models.ForeignKey(help_text='The user who made this request.', to='base.UserProfile')),
('upvotes', models.ManyToManyField(to='base.UserProfile', null=True, blank=True)),
],
options={
'ordering': ['-post_date'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='RequestType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(help_text='Name of the request type.', unique=True, max_length=255)),
('url_name', models.CharField(help_text='Unique URL key for this manager. Autogenerated from custom interface.', unique=True | , max_length=255)),
('enabled', models.BooleanField(default=True, help_text='Whether this type of request i | s currently accepted. Toggle this to off to temporarily disable accepting this type of request.')),
('glyphicon', models.CharField(help_text='Glyphicon for this request type (e.g., cutlery). Check Bootstrap documentation for more info.', max_length=100, null=True, blank=True)),
('managers', models.ManyToManyField(to='managers.Manager')),
],
options={
'ordering': ['name'],
},
bases=(models.Model,),
),
migrations.AddField(
model_name='request',
name='request_type',
field=models.ForeignKey(help_text='The type of request this is.', to='managers.RequestType'),
preserve_default=True,
),
migrations.CreateModel(
name='Response',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('body', models.TextField(help_text='The body of this response.')),
('post_date', models.DateTimeField(help_text='The date this response was posted.', auto_now_add=True)),
('manager', models.BooleanField(default=False, help_text='Whether this is a relevant manager response.')),
('owner', models.ForeignKey(help_text='The user who posted this response.', to='base.UserProfile')),
('request', models.ForeignKey(help_text='The request to which this is a response.', to='managers.Request')),
],
options={
'ordering': ['post_date'],
},
bases=(models.Model,),
),
]
|
bundgus/python-playground | matplotlib-playground/examples/pylab_examples/demo_agg_filter.py | Python | mit | 9,321 | 0.000858 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
def smooth1d(x, window_len):
# copied from http://www.scipy.org/Cookbook/SignalSmooth
s = np.r_[2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]]
w = np.hanning(window_len)
y = np.convolve(w/w.sum(), s, mode='same')
return y[window_len-1:-window_len+1]
def smooth2d(A, sigma=3):
window_len = max(int(sigma), 3)*2 + 1
A1 = np.array([smooth1d(x, window_len) for x in np.asarray(A)])
A2 = np.transpose(A1)
A3 = np.array([smooth1d(x, window_len) for x in A2])
A4 = np.transpose(A3)
return A4
class BaseFilter(object):
def prepare_image(self, src_image, dpi, pad):
ny, nx, depth = src_image.shape
#tgt_image = np.zeros([pad*2+ny, pad*2+nx, depth], dtype="d")
padded_src = np.zeros([pad*2 + ny, pad*2 + nx, depth], dtype="d")
padded_src[pad:-pad, pad:-pad, :] = src_image[:, :, :]
return padded_src # , tgt_image
def get_pad(self, dpi):
return 0
def __call__(self, im, dpi):
pad = self.get_pad(dpi)
padded_src = self.prepare_image(im, dpi, pad)
tgt_image = self.process_image(padded_src, dpi)
return tgt_image, -pad, -pad
class OffsetFilter(BaseFilter):
def __init__(self, offsets=None):
if offsets is None:
self.offsets = (0, 0)
else:
self.offsets = offsets
def get_pad(self, dpi):
return int(max(*self.offsets)/72.*dpi)
def process_image(self, padded_src, dpi):
ox, oy = self.offsets
a1 = np.roll(padded_src, int(ox/72.*dpi), axis=1)
a2 = np.roll(a1, -int(oy/72.*dpi), axis=0)
return a2
class GaussianFilter(BaseFilter):
"simple gauss filter"
def __init__(self, sigma, alpha=0.5, color=None):
self.sigma = sigma
self.alpha = alpha
if color is None:
self.color = (0, 0, 0)
else:
self.color = color
def get_pad(self, dpi):
return int(self.sigma*3/72.*dpi)
def process_image(self, padded_src, dpi):
#offsetx, offsety = int(self.offsets[0]), int(self.offsets[1])
tgt_image = np.zeros_like(padded_src)
aa = smooth2d(padded_src[:, :, -1]*self.alpha,
self.sigma/72.*dpi)
tgt_image[:, :, -1] = aa
tgt_image[:, :, :-1] = self.color
return tgt_image
class DropShadowFilter(BaseFilter):
def __init__(self, sigma, alpha=0.3, color=None, offsets=None):
self.gauss_filter = GaussianFilter(sigma, alpha, color)
self.offset_filter = OffsetFilter(offsets)
def get_pad(self, dpi):
return max(self.gauss_filter.get_pad(dpi),
self.offset_filter.get_pad(dpi))
def process_image(self, padded_src, dpi):
t1 = self.gauss_filter.process_image(padded_src, dpi)
t2 = self.offset_filter.process_image(t1, dpi)
return t2
from matplotlib.colors import LightSource
class LightFilter(BaseFilter):
"simple gauss filter"
def __init__(self, sigma, fraction=0.5):
self.gauss_filter = GaussianFilter(sigma, alpha=1)
self.light_source = LightSource()
self.fraction = fraction
def get_pad(self, dpi):
return self.gauss_filter.get_pad(dpi)
def process_image(self, padded_src, dpi):
t1 = self.gauss_filter.process_image(padded_src, dpi)
elevation = t1[:, :, 3]
rgb = padded_src[:, :, :3]
rgb2 = self.light_source.shade_rgb(rgb, elevation,
fraction=self.fraction)
tgt = np.empty_like(padded_src)
tgt[:, :, :3] = rgb2
tgt[:, :, 3] = padded_src[:, :, 3]
return tgt
class GrowFilter(BaseFilter):
"enlarge the area"
def __init__(self, pixels, color=None):
self.pixels = pixels
if color is None:
self.color = (1, 1, 1)
else:
self.color = color
def __call__(self, im, dpi):
pad = self.pixels
ny, nx, depth = im.shape
new_im = np.empty([pad*2 + ny, pad*2 + nx, depth], dtype="d")
alpha = new_im[:, :, 3]
alpha.fill(0)
alpha[pad:-pad, pad:-pad] = im[:, :, -1]
alpha2 = np.clip(smooth2d(alpha, self.pixels/72.*dpi) * 5, 0, 1)
new_im[:, :, -1] = alpha2
new_im[:, :, :-1] = self.color
offsetx, offsety = -pad, -pad
return new_im, offsetx, offsety
from matplotlib.artist import Artist
class FilteredArtistList(Artist):
"""
A simple container to draw filtered artist.
"""
def __init__(self, artist_list, filter):
self._artist_list = artist_list
self._filter = filter
Artist.__init__(self)
def draw(self, renderer):
renderer.start_rasterizing()
renderer.start_filter()
for a in self._artist_list:
a.draw(renderer)
renderer.stop_fi | lter(self._filter)
| renderer.stop_rasterizing()
import matplotlib.transforms as mtransforms
def filtered_text(ax):
# mostly copied from contour_demo.py
# prepare image
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)
# draw
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
cmap=cm.gray, extent=(-3, 3, -2, 2))
levels = np.arange(-1.2, 1.6, 0.2)
CS = ax.contour(Z, levels,
origin='lower',
linewidths=2,
extent=(-3, 3, -2, 2))
ax.set_aspect("auto")
# contour label
cl = ax.clabel(CS, levels[1::2], # label every second level
inline=1,
fmt='%1.1f',
fontsize=11)
# change clable color to black
from matplotlib.patheffects import Normal
for t in cl:
t.set_color("k")
# to force TextPath (i.e., same font in all backends)
t.set_path_effects([Normal()])
# Add white glows to improve visibility of labels.
white_glows = FilteredArtistList(cl, GrowFilter(3))
ax.add_artist(white_glows)
white_glows.set_zorder(cl[0].get_zorder() - 0.1)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def drop_shadow_line(ax):
# copied from examples/misc/svg_filter_line.py
# draw lines
l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-",
mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
gauss = DropShadowFilter(4)
for l in [l1, l2]:
# draw shadows with same lines with slight offset.
xx = l.get_xdata()
yy = l.get_ydata()
shadow, = ax.plot(xx, yy)
shadow.update_from(l)
# offset transform
ot = mtransforms.offset_copy(l.get_transform(), ax.figure,
x=4.0, y=-6.0, units='points')
shadow.set_transform(ot)
# adjust zorder of the shadow lines so that it is drawn below the
# original lines
shadow.set_zorder(l.get_zorder() - 0.5)
shadow.set_agg_filter(gauss)
shadow.set_rasterized(True) # to support mixed-mode renderers
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def drop_shadow_patches(ax):
# copyed from barchart_demo.py
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
rects1 = ax.bar(ind, menMeans, width, color='r', ec="w", lw=2)
womenMeans = (25, 32, 34, 20, 25)
rects2 = ax.bar(ind + width + 0.1, womenMeans, width, color='y', ec="w", lw=2)
#gauss = GaussianFilter(1.5, offsets=(1,1), )
gauss = DropShadowFilter(5, offsets=(1, 1), )
shadow = FilteredArtistList(rects1 + r |
vmahuli/contrail-controller | src/api-lib/tools/install_venv_common.py | Python | apache-2.0 | 6,620 | 0.000755 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.
"""Provides methods needed by installation script for OpenStack development
virtual environments.
Since this script is used to bootstrap a virtualenv from the system's Python
environment, it should be kept strictly compatible with Python 2.6.
Synced in from openstack-common
"""
from __future__ import print_function
import optparse
import os
import subprocess
import sys
class InstallVenv(object):
def __init__(self, root, venv, requirements,
test_requirements, py_version,
project):
self.root = root
self.venv = venv
self.requirements = requirements
self.test_requirements = test_requirements
self.py_version = py_version
self.project = project
def die(self, message, *args):
print(message % args, file=sys.stderr)
sys.exit(1)
def check_python_version( | self):
if sys.version_info < (2, 6):
self.die("Need Python Version >= 2.6")
def run_command_with_code(self, cmd, redirect_output=True,
check_exit_code=True):
"""Runs a command in an out-of-process shell.
Returns the output of that command. Working directory is self.root.
"""
if redirect | _output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.communicate()[0]
if check_exit_code and proc.returncode != 0:
self.die('Command "%s" failed.\n%s', ' '.join(cmd), output)
return (output, proc.returncode)
def run_command(self, cmd, redirect_output=True, check_exit_code=True):
return self.run_command_with_code(cmd, redirect_output,
check_exit_code)[0]
def get_distro(self):
if (os.path.exists('/etc/fedora-release') or
os.path.exists('/etc/redhat-release')):
return Fedora(
self.root, self.venv, self.requirements,
self.test_requirements, self.py_version, self.project)
else:
return Distro(
self.root, self.venv, self.requirements,
self.test_requirements, self.py_version, self.project)
def check_dependencies(self):
self.get_distro().install_virtualenv()
def create_virtualenv(self, no_site_packages=True):
"""Creates the virtual environment and installs PIP.
Creates the virtual environment and installs PIP only into the
virtual environment.
"""
if not os.path.isdir(self.venv):
print('Creating venv...', end=' ')
if no_site_packages:
self.run_command(['virtualenv', '-q', '--no-site-packages',
self.venv])
else:
self.run_command(['virtualenv', '-q', self.venv])
print('done.')
else:
print("venv already exists...")
pass
def pip_install(self, find_links, *args):
tdir = '/tmp/cache/%s/config_test' %(os.environ.get('USER', 'pip'))
find_links_str = ' '.join('--find-links file://'+x for x in find_links)
cmd_array = ['tools/with_venv.sh',
'python', '.venv/bin/pip', 'install',
'--download-cache=%s' %(tdir),
'--upgrade']
for link in find_links:
cmd_array.extend(['--find-links', 'file://'+link])
self.run_command(cmd_array + list(args),
redirect_output=False)
def install_dependencies(self, find_links):
print('Installing dependencies with pip (this can take a while)...')
# First things first, make sure our venv has the latest pip and
# setuptools and pbr
self.pip_install(find_links, 'pip>=1.4')
self.pip_install(find_links, 'setuptools')
self.pip_install(find_links, 'pbr')
self.pip_install(find_links, '-r', self.requirements, '-r', self.test_requirements, '--pre')
def parse_args(self, argv):
"""Parses command-line arguments."""
parser = optparse.OptionParser()
parser.add_option('-n', '--no-site-packages',
action='store_true',
help="Do not inherit packages from global Python "
"install")
parser.add_option('-f', '--find-links',
action='append',
help="Build generation directory ")
return parser.parse_args(argv[1:])[0]
class Distro(InstallVenv):
def check_cmd(self, cmd):
return bool(self.run_command(['which', cmd],
check_exit_code=False).strip())
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if self.check_cmd('easy_install'):
print('Installing virtualenv via easy_install...', end=' ')
if self.run_command(['easy_install', 'virtualenv']):
print('Succeeded')
return
else:
print('Failed')
self.die('ERROR: virtualenv not found.\n\n%s development'
' requires virtualenv, please install it using your'
' favorite package management tool' % self.project)
class Fedora(Distro):
"""This covers all Fedora-based distributions.
Includes: Fedora, RHEL, CentOS, Scientific Linux
"""
def check_pkg(self, pkg):
return self.run_command_with_code(['rpm', '-q', pkg],
check_exit_code=False)[1] == 0
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if not self.check_pkg('python-virtualenv'):
self.die("Please install 'python-virtualenv'.")
super(Fedora, self).install_virtualenv()
|
Galiaf47/lib3d | convert_obj_three.py | Python | gpl-2.0 | 48,258 | 0.006113 | """Convert Wavefront OBJ / MTL files into Three.js (JSON model version, to be used with ascii / binary loader)
-------------------------
How to use this converter
-------------------------
python convert_obj_three.py -i infile.obj -o outfile.js [-m "morphfiles*.obj"] [-c "morphcolors*.obj"] [-a center|centerxz|top|bottom|none] [-s smooth|flat] [-t ascii|binary] [-d invert|normal] [-b] [-e]
Notes:
- flags
-i infile.obj input OBJ file
-o outfile.js output JS file
-m "morphfiles*.obj" morph OBJ files (can use wildcards, enclosed in quotes multiple patterns separate by space)
-c "morphcolors*.obj" morph colors OBJ files (can use wildcards, enclosed in quotes multiple patterns separate by space)
-a center|centerxz|top|bottom|none model alignment
-s smooth|flat smooth = export vertex normals, flat = no normals (face normals computed in loader)
-t ascii|binary export ascii or binary format (ascii has more features, binary just supports vertices, faces, normals, uvs and materials)
-b bake material colors into face colors
-x 10.0 scale and truncate
-f 2 morph frame sampling step
- by default:
use smooth shading (if there were vertex normals in the original model)
will be in ASCII format
no face colors baking
no scale and truncate
morph frame step = 1 (all files will be processed)
- binary conversion will create two files:
outfile.js (materials)
outfile.bin (binary buffers)
--------------------------------------------------
How to use generated JS file in your HTML document
--------------------------------------------------
<script type="text/javascript" src="Three.js"></script>
...
<script type="text/javascript">
...
// load ascii model
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "Model_ascii.js", createScene );
// load binary model
var binLoader = new THREE.BinaryLoader();
binLoader.load( "Model_bin.js", createScene );
function createScene( geometry, materials ) {
var mesh = new THREE.Mesh( geometry, new THREE.MultiMaterial( materials ) );
}
...
</script>
-------------------------------------
Parsers based on formats descriptions
-------------------------------------
http://en.wikipedia.org/wiki/Obj
http://en.wikipedia.org/wiki/Material_Template_Library
-------------------
Current limitations
-------------------
- for the moment, only diffuse color and texture are used
(will need to extend shaders / renderers / materials in Three)
- texture coordinates can be wrong in canvas renderer
(there is crude normalization, but it doesn't
work for all cases)
- smoothing can be turned on/off only for the whole mesh
----------------------------------------------
How to get proper OBJ + MTL files with Blender
----------------------------------------------
0. Remove default cube (press DEL and ENTER)
1. Import / create model
2. Select all meshes (Select -> Select All by Type -> Mesh)
3. Export to OBJ (File -> Export -> Wavefront .obj)
- enable following options in exporter
Material Groups
Rotate X90
Apply Modifiers
High Quality Normals
Copy Images
Selection Only
Objects as OBJ Objects
UVs
Normals
Materials
- select empty folder
- give your exported file name with "obj" extension
- click on "Export OBJ" button
4. Your model is now all files in this folder (OBJ, MTL, number of images)
- this converter assumes all files staying in the same folder,
(OBJ / MTL files use relative paths)
- for WebGL, textures must be power of 2 sized
------
Author
------
AlteredQualia http://alteredqualia.com
"""
import fileinput
import operator
import random
import os.path
import getopt
import sys
import struct
import math
import glob
# #####################################################
# Configuration
# #####################################################
ALIGN = "none" # center centerxz bottom top none
SHADING = "smooth" # smooth flat
TYPE = "ascii" # ascii binary
TRUNCATE = False
SCALE = 1.0
FRAMESTEP = 1
BAKE_COLORS = False
# default colors for debugging (each material gets one distinct color):
# white, red, green, blue, yellow, cyan, magenta
COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee]
# #####################################################
# Templates
# #####################################################
TEMPLATE_FILE_ASCII = u"""\
{
"metadata" :
{
"formatVersion" : 3.1,
"sourceFile" : "%(fname)s",
"generatedBy" : "OBJConverter",
"vertices" : %(nvertex)d,
"faces" : %(nface)d,
"normals" : %(nnormal)d,
"colors" : %(ncolor)d,
"uvs" : %(nuv)d,
"materials" : %(nmaterial)d
},
"scale" : %(scale)f,
"materials": [%(materials)s],
"vertices": [%(vertices)s],
"morphTargets": [%(morphTargets)s],
"morphColors": [%(morphColors)s],
"normals": [%(normals)s],
"colors": [%(colors)s],
"uvs": [[%(uvs)s]],
"faces": [%(faces)s]
}
"""
TEMPLATE_FILE_BIN = u"""\
{
"metadata" :
{
"formatVersion" : 3.1,
"sourceFile" : "%(fname)s",
"generatedBy" : "OBJConverter",
"vertices" : %(nvertex)d,
"faces" : %(nface)d,
"normals" : %(nnormal)d,
"uvs" : %(nuv)d,
"materials" : %(nmaterial)d
},
"materials": [%(materials)s],
"buffers": "%(buffers)s"
}
"""
TEMPLATE_VERTEX = "%f,%f,%f"
TEMPLATE_VERTEX_TRUNCATE = "%d,%d,%d"
TEMPLATE_N = "%.5g,%.5g,%.5g"
TEMPLATE_UV = "%.5g,%.5g"
TEMPLATE_COLOR = "%.3g,%.3g,%.3g"
TEMPLATE_COLOR_DEC = "%d"
TEMPLATE_MORPH_VERTICES = '\t{ "name": "%s", "vertices": [%s] }'
TEMPLATE_MORPH_COLORS = '\t{ "name": "%s", "colors": [%s] }'
# #####################################################
# Utils
# #####################################################
def file_exists(filename):
"""Return true if file exists and is accessible for reading.
Should be safer than just testing for existence due to links and
permissions magic on Unix filesystems.
@rtype: boolean
"""
try:
f = open(filename, 'r')
f.close()
return True
except IOError:
return False
def get_name(fname):
"""Create model name based of filename ("path/fname.js" -> "fname").
"""
return os.path.splitext(os.path.basename(fname))[0]
def bbox(vertices):
"""Compute bounding box of vertex array.
"""
if l | en(vertices)>0:
minx = maxx = vertices[0][0]
miny = maxy = vertices[0][1]
minz = maxz = vertices[0][2]
for v in vertices[1:]:
| if v[0]<minx:
minx = v[0]
elif v[0]>maxx:
maxx = v[0]
if v[1]<miny:
miny = v[1]
elif v[1]>maxy:
maxy = v[1]
if v[2]<minz:
minz = v[2]
elif v[2]>maxz:
maxz = v[2]
return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] }
else:
return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
def translate(vertices, t):
"""Translate array of vertices by vector t.
"""
for i in xrange(len(vertices)):
vertices[i][0] += t[0]
vertices[i][1] += t[1]
vertices[i][2] += t[2]
def center(vertices):
"""Center model (middle of bounding box).
"""
bb = bbox(vertices)
cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0
cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
translate(vertices, [-cx,-cy,-cz])
def top(vertices):
"""Align top of the model with the floor (Y-axis) and ce |
partofthething/home-assistant | homeassistant/components/airvisual/__init__.py | Python | apache-2.0 | 13,229 | 0.001814 | """The airvisual component."""
import asyncio
from datetime import timedelta
from math import ceil
from pyairvisual import CloudAPI, NodeSamba
from pyairvisual.errors import (
AirVisualError,
InvalidKeyError,
KeyExpiredError,
NodeProError,
)
from homeassistant.config_entries import SOURCE_REAUTH
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_API_KEY,
CONF_IP_ADDRESS,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_PASSWORD,
CONF_SHOW_ON_MAP,
CONF_STATE,
)
from homeassistant.core import callback
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .const import (
CONF_CITY,
CONF_COUNTRY,
CONF_GEOGRAPHIES,
CONF_INTEGRATION_TYPE,
DATA_COORDINATOR,
DOMAIN,
INTEGRATION_TYPE_GEOGRAPHY | _COORDS,
INTEGRATION_TYPE_GEOGRAPHY_NAME,
INTEGRATION_TYPE_NODE_PRO,
LOGGER,
)
PLATFORMS = ["air_quality", "sensor"]
DATA_LISTENER = "listener"
DEFAULT_ATTRIBUTION = "Data provided by Ai | rVisual"
DEFAULT_NODE_PRO_UPDATE_INTERVAL = timedelta(minutes=1)
CONFIG_SCHEMA = cv.deprecated(DOMAIN)
@callback
def async_get_geography_id(geography_dict):
"""Generate a unique ID from a geography dict."""
if not geography_dict:
return
if CONF_CITY in geography_dict:
return ", ".join(
(
geography_dict[CONF_CITY],
geography_dict[CONF_STATE],
geography_dict[CONF_COUNTRY],
)
)
return ", ".join(
(str(geography_dict[CONF_LATITUDE]), str(geography_dict[CONF_LONGITUDE]))
)
@callback
def async_get_cloud_api_update_interval(hass, api_key, num_consumers):
"""Get a leveled scan interval for a particular cloud API key.
This will shift based on the number of active consumers, thus keeping the user
under the monthly API limit.
"""
# Assuming 10,000 calls per month and a "smallest possible month" of 28 days; note
# that we give a buffer of 1500 API calls for any drift, restarts, etc.:
minutes_between_api_calls = ceil(1 / (8500 / 28 / 24 / 60 / num_consumers))
LOGGER.debug(
"Leveling API key usage (%s): %s consumers, %s minutes between updates",
api_key,
num_consumers,
minutes_between_api_calls,
)
return timedelta(minutes=minutes_between_api_calls)
@callback
def async_get_cloud_coordinators_by_api_key(hass, api_key):
"""Get all DataUpdateCoordinator objects related to a particular API key."""
coordinators = []
for entry_id, coordinator in hass.data[DOMAIN][DATA_COORDINATOR].items():
config_entry = hass.config_entries.async_get_entry(entry_id)
if config_entry.data.get(CONF_API_KEY) == api_key:
coordinators.append(coordinator)
return coordinators
@callback
def async_sync_geo_coordinator_update_intervals(hass, api_key):
"""Sync the update interval for geography-based data coordinators (by API key)."""
coordinators = async_get_cloud_coordinators_by_api_key(hass, api_key)
if not coordinators:
return
update_interval = async_get_cloud_api_update_interval(
hass, api_key, len(coordinators)
)
for coordinator in coordinators:
LOGGER.debug(
"Updating interval for coordinator: %s, %s",
coordinator.name,
update_interval,
)
coordinator.update_interval = update_interval
async def async_setup(hass, config):
"""Set up the AirVisual component."""
hass.data[DOMAIN] = {DATA_COORDINATOR: {}, DATA_LISTENER: {}}
return True
@callback
def _standardize_geography_config_entry(hass, config_entry):
"""Ensure that geography config entries have appropriate properties."""
entry_updates = {}
if not config_entry.unique_id:
# If the config entry doesn't already have a unique ID, set one:
entry_updates["unique_id"] = config_entry.data[CONF_API_KEY]
if not config_entry.options:
# If the config entry doesn't already have any options set, set defaults:
entry_updates["options"] = {CONF_SHOW_ON_MAP: True}
if config_entry.data.get(CONF_INTEGRATION_TYPE) not in [
INTEGRATION_TYPE_GEOGRAPHY_COORDS,
INTEGRATION_TYPE_GEOGRAPHY_NAME,
]:
# If the config entry data doesn't contain an integration type that we know
# about, infer it from the data we have:
entry_updates["data"] = {**config_entry.data}
if CONF_CITY in config_entry.data:
entry_updates["data"][
CONF_INTEGRATION_TYPE
] = INTEGRATION_TYPE_GEOGRAPHY_NAME
else:
entry_updates["data"][
CONF_INTEGRATION_TYPE
] = INTEGRATION_TYPE_GEOGRAPHY_COORDS
if not entry_updates:
return
hass.config_entries.async_update_entry(config_entry, **entry_updates)
@callback
def _standardize_node_pro_config_entry(hass, config_entry):
"""Ensure that Node/Pro config entries have appropriate properties."""
entry_updates = {}
if CONF_INTEGRATION_TYPE not in config_entry.data:
# If the config entry data doesn't contain the integration type, add it:
entry_updates["data"] = {
**config_entry.data,
CONF_INTEGRATION_TYPE: INTEGRATION_TYPE_NODE_PRO,
}
if not entry_updates:
return
hass.config_entries.async_update_entry(config_entry, **entry_updates)
async def async_setup_entry(hass, config_entry):
"""Set up AirVisual as config entry."""
if CONF_API_KEY in config_entry.data:
_standardize_geography_config_entry(hass, config_entry)
websession = aiohttp_client.async_get_clientsession(hass)
cloud_api = CloudAPI(config_entry.data[CONF_API_KEY], session=websession)
async def async_update_data():
"""Get new data from the API."""
if CONF_CITY in config_entry.data:
api_coro = cloud_api.air_quality.city(
config_entry.data[CONF_CITY],
config_entry.data[CONF_STATE],
config_entry.data[CONF_COUNTRY],
)
else:
api_coro = cloud_api.air_quality.nearest_city(
config_entry.data[CONF_LATITUDE],
config_entry.data[CONF_LONGITUDE],
)
try:
return await api_coro
except (InvalidKeyError, KeyExpiredError):
matching_flows = [
flow
for flow in hass.config_entries.flow.async_progress()
if flow["context"]["source"] == SOURCE_REAUTH
and flow["context"]["unique_id"] == config_entry.unique_id
]
if not matching_flows:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": SOURCE_REAUTH,
"unique_id": config_entry.unique_id,
},
data=config_entry.data,
)
)
return {}
except AirVisualError as err:
raise UpdateFailed(f"Error while retrieving data: {err}") from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=async_get_geography_id(config_entry.data),
# We give a placeholder update interval in order to create the coordinator;
# then, below, we use the coordinator's presence (along with any other
# coordinators using the same API key) to calculate an actual, leveled
# update interval:
update_interval=timedelta(minutes=5),
update_method=async_update_data,
)
async_sync_geo_coordinator_update_intervals(
hass, config_e |
allenwoods/parasys | debug/__init__.py | Python | mit | 306 | 0 | #! /usr/bin/ | env python
# -*- coding: utf-8 -*-
"""
@file __init__.py.py
@author Allen Woods
@date 2016-08-02
@version 16-8-2 上午8:50 ???
Some other Description
"""
def func():
pass
class Main(object):
def __init__(self):
pass
if __name__ == '__main__ | ':
pass
|
andrius-preimantas/odoo | addons/website/models/website.py | Python | agpl-3.0 | 33,629 | 0.003717 | # -*- coding: utf-8 -*-
import cStringIO
import contextlib
import datetime
import hashlib
import inspect
import itertools
import logging
import math
import mimetypes
import unicodedata
import os
import re
import urlparse
from PIL import Ima | ge
from sys import maxint
import werkzeug
import werkzeug.exceptions
import werkzeug.utils
import werkzeug.wrappers
# optional python-slugify import (https://github.com/un33k/python-slugify)
try:
| import slugify as slugify_lib
except ImportError:
slugify_lib = None
import openerp
from openerp.osv import orm, osv, fields
from openerp.tools import html_escape as escape
from openerp.tools import ustr as ustr
from openerp.tools.safe_eval import safe_eval
from openerp.addons.web.http import request
logger = logging.getLogger(__name__)
def url_for(path_or_uri, lang=None):
if isinstance(path_or_uri, unicode):
path_or_uri = path_or_uri.encode('utf-8')
current_path = request.httprequest.path
if isinstance(current_path, unicode):
current_path = current_path.encode('utf-8')
location = path_or_uri.strip()
force_lang = lang is not None
url = urlparse.urlparse(location)
if request and not url.netloc and not url.scheme and (url.path or force_lang):
location = urlparse.urljoin(current_path, location)
lang = lang or request.context.get('lang')
langs = [lg[0] for lg in request.website.get_languages()]
if (len(langs) > 1 or force_lang) and is_multilang_url(location, langs):
ps = location.split('/')
if ps[1] in langs:
# Replace the language only if we explicitly provide a language to url_for
if force_lang:
ps[1] = lang
# Remove the default language unless it's explicitly provided
elif ps[1] == request.website.default_lang_code:
ps.pop(1)
# Insert the context language or the provided language
elif lang != request.website.default_lang_code or force_lang:
ps.insert(1, lang)
location = '/'.join(ps)
return location.decode('utf-8')
def is_multilang_url(local_url, langs=None):
if not langs:
langs = [lg[0] for lg in request.website.get_languages()]
spath = local_url.split('/')
# if a language is already in the path, remove it
if spath[1] in langs:
spath.pop(1)
local_url = '/'.join(spath)
try:
# Try to match an endpoint in werkzeug's routing table
url = local_url.split('?')
path = url[0]
query_string = url[1] if len(url) > 1 else None
router = request.httprequest.app.get_db_router(request.db).bind('')
func = router.match(path, query_args=query_string)[0]
return func.routing.get('website', False) and func.routing.get('multilang', True)
except Exception:
return False
def slugify(s, max_length=None):
""" Transform a string to a slug that can be used in a url path.
This method will first try to do the job with python-slugify if present.
Otherwise it will process string by stripping leading and ending spaces,
converting unicode chars to ascii, lowering all chars and replacing spaces
and underscore with hyphen "-".
:param s: str
:param max_length: int
:rtype: str
"""
s = ustr(s)
if slugify_lib:
# There are 2 different libraries only python-slugify is supported
try:
return slugify_lib.slugify(s, max_length=max_length)
except TypeError:
pass
uni = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode('ascii')
slug = re.sub('[\W_]', ' ', uni).strip().lower()
slug = re.sub('[-\s]+', '-', slug)
return slug[:max_length]
def slug(value):
if isinstance(value, orm.browse_record):
# [(id, name)] = value.name_get()
id, name = value.id, value[value._rec_name]
else:
# assume name_search result tuple
id, name = value
slugname = slugify(name or '').strip().strip('-')
if not slugname:
return str(id)
return "%s-%d" % (slugname, id)
_UNSLUG_RE = re.compile(r'(?:(\w{1,2}|\w[a-z0-9-_]+?\w)-)?(-?\d+)(?=$|/)', re.I)
def unslug(s):
"""Extract slug and id from a string.
Always return un 2-tuple (str|None, int|None)
"""
m = _UNSLUG_RE.match(s)
if not m:
return None, None
return m.group(1), int(m.group(2))
def urlplus(url, params):
return werkzeug.Href(url)(params or None)
class website(osv.osv):
def _get_menu_website(self, cr, uid, ids, context=None):
# IF a menu is changed, update all websites
return self.search(cr, uid, [], context=context)
def _get_menu(self, cr, uid, ids, name, arg, context=None):
root_domain = [('parent_id', '=', False)]
menus = self.pool.get('website.menu').search(cr, uid, root_domain, order='id', context=context)
menu = menus and menus[0] or False
return dict( map(lambda x: (x, menu), ids) )
_name = "website" # Avoid website.website convention for conciseness (for new api). Got a special authorization from xmo and rco
_description = "Website"
_columns = {
'name': fields.char('Domain'),
'company_id': fields.many2one('res.company', string="Company"),
'language_ids': fields.many2many('res.lang', 'website_lang_rel', 'website_id', 'lang_id', 'Languages'),
'default_lang_id': fields.many2one('res.lang', string="Default language"),
'default_lang_code': fields.related('default_lang_id', 'code', type="char", string="Default language code", store=True),
'social_twitter': fields.char('Twitter Account'),
'social_facebook': fields.char('Facebook Account'),
'social_github': fields.char('GitHub Account'),
'social_linkedin': fields.char('LinkedIn Account'),
'social_youtube': fields.char('Youtube Account'),
'social_googleplus': fields.char('Google+ Account'),
'google_analytics_key': fields.char('Google Analytics Key'),
'user_id': fields.many2one('res.users', string='Public User'),
'partner_id': fields.related('user_id','partner_id', type='many2one', relation='res.partner', string='Public Partner'),
'menu_id': fields.function(_get_menu, relation='website.menu', type='many2one', string='Main Menu',
store= {
'website.menu': (_get_menu_website, ['sequence','parent_id','website_id'], 10)
})
}
_defaults = {
'company_id': lambda self,cr,uid,c: self.pool['ir.model.data'].xmlid_to_res_id(cr, openerp.SUPERUSER_ID, 'base.public_user'),
}
# cf. Wizard hack in website_views.xml
def noop(self, *args, **kwargs):
pass
def write(self, cr, uid, ids, vals, context=None):
self._get_languages.clear_cache(self)
return super(website, self).write(cr, uid, ids, vals, context)
def new_page(self, cr, uid, name, template='website.default_page', ispage=True, context=None):
context = context or {}
imd = self.pool.get('ir.model.data')
view = self.pool.get('ir.ui.view')
template_module, template_name = template.split('.')
# completely arbitrary max_length
page_name = slugify(name, max_length=50)
page_xmlid = "%s.%s" % (template_module, page_name)
try:
# existing page
imd.get_object_reference(cr, uid, template_module, page_name)
except ValueError:
# new page
_, template_id = imd.get_object_reference(cr, uid, template_module, template_name)
page_id = view.copy(cr, uid, template_id, context=context)
page = view.browse(cr, uid, page_id, context=context)
page.write({
'arch': page.arch.replace(template, page_xmlid),
'name': page_name,
'page': ispage,
})
imd.create(cr, uid, {
'name': page_name,
'module': template_module,
'model': 'ir.ui.view',
'res_id': page_id,
'noupdate': True
|
skoobe/riofs | tests/test_amazon.py | Python | gpl-3.0 | 1,249 | 0.001601 | import os
import sys
import shutil
import unittest
import tempfile
import time
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "ms3"))
from ms3.testing import MS3Server
from s3ffs_server import s3ffsServer, wait_until
class AmazonTestCase(unittest.TestCase):
def setUp(self):
self.local = tempfile.mkdtemp()
self.s3ffs = None
# In case there occurs an exception during setUp(), unittest
# doesn't call tearDown(), hence we need to make sure we don't
# leave any server processes running.
try:
self.s3ffs = s3ffsServer("s3ffs-us", mountpoint=self.local).start()
except Exception:
self.tearDown()
| raise
def tearDown(self):
if self.s3ffs:
self.s3ffs.stop()
shutil.rmtree(self.local, True)
def test_mounted(self):
self.assertTrue(os.path.ismount(self.local))
def test_single_file(self):
content = "Hello, world!"
path | = os.path.join(self.local, "file.txt")
with open(path, "w") as f:
f.write(content)
wait_until(os.path.exists, path)
self.assertTrue(open(path).read(), content)
if __name__ == "__main__":
unittest.main()
|
eriol/pywt | pywt/_dwt.py | Python | mit | 9,891 | 0.000303 | import numpy as np
from ._extensions._pywt import Wavelet, Modes, _check_dtype
from ._extensions._dwt import (dwt_single, dwt_axis, idwt_single, idwt_axis,
upcoef as _upcoef, downcoef as _downcoef,
dwt_max_level as _dwt_max_level,
dwt_coeff_len as _dwt_coeff_len)
__all__ = ["dwt", "idwt", "downcoef", "upcoef", "dwt_max_level", "dwt_coeff_len"]
def dwt_max_level(data_len, filter_len):
"""
dwt_max_level(data_len, filter_len)
Compute the maximum useful level of decomposition.
Parameters
----------
data_len : int
Input data length.
filter_len : int
Wavelet filter length.
Returns
-------
max_level : int
Maximum level.
Examples
--------
>>> import pywt
>>> w = pywt.Wavelet('sym5')
>>> pywt.dwt_max_level(data_len=1000, filter_len=w.dec_len)
6
>>> pywt.dwt_max_level(1000, w)
6
"""
if isinstance(filter_len, Wavelet):
filter_len = filter_len.dec_len
return _dwt_max_level(data_len, filter_len)
def dwt_coeff_len(data_len, filter_len, mode):
"""
dwt_coeff_len(data_len, filter_len, mode='symmetric')
Returns length of dwt output for given data length, filter length and mode
Parameters
----------
data_len : int
Data length.
filter_len : int
Filter length.
mode : str, optional (default: 'symmetric')
Signal extension mode, see Modes
Returns
-------
len : int
Length of dwt output.
Notes
-----
For all modes except periodization::
len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2)
for periodization mode ("per")::
len(cA) == len(cD) == ceil(len(data) / 2)
"""
if isinstance(filter_len, Wavelet):
filter_len = filter_len.dec_len
return _dwt_coeff_len(data_len, filter_len, Modes.from_object(mode))
def dwt(data, wavelet, mode='symmetric', axis=-1):
"""
dwt(data, wavelet, mode='symmetric', axis=-1)
Single level Discrete Wavelet Transform.
Parameters
----------
data : array_like
Input signal
wavelet : Wavelet object or name
Wavelet to use
mode : str, optional
Signal extension mode, see Modes
axis: int, optional
Axis over which to compute the DWT. If not given, the
last axis is used.
Returns
-------
(cA, cD) : tuple
Approximation and detail coefficients.
Notes
-----
Length of coefficients arrays depends on the selected mode.
For all modes except periodization:
``len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2)``
For periodization mode ("per"):
``len(cA) == len(cD) == ceil(len(data) / 2)``
Examples
--------
>>> import pywt
>>> (cA, cD) = pywt.dwt([1, 2, 3, 4, 5, 6], 'db1')
>>> cA
array([ 2.12132034, 4.94974747, 7.77817459])
>>> cD
array([-0.70710678, -0.70710678, -0.70710678])
"""
if np.iscomplexobj(data):
data = np.asarray(data)
cA_r, cD_r = dwt(data.real, wavelet, mode, axis)
cA_i, cD_i = dwt(data.imag, wavelet, mode, axis)
return (cA_r + 1j*cA_i, cD_r + 1j*cD_i)
# accept array_like input; make a copy to ensure a contiguous array
dt = _check_dtype(data)
data = np.array(data, dtype=dt)
mode = Modes.from_object(mode)
if not isinstance(wavelet, Wavelet):
wavelet = Wavelet(wavelet)
if axis < 0:
axis = axis + data.ndim
if not 0 <= axis < data.ndim:
raise ValueError("Axis greater than data dimensions")
if data.ndim == 1:
cA, cD = dwt_single(data, wavelet, mode)
# TODO: Check whether this makes a copy
cA, cD = np.asarray(cA, dt), np.asarray(cD, dt)
else:
cA, cD = dwt_axis(data, wavelet, mode, axis=axis)
return (cA, cD)
def idwt(cA, cD, wavelet, mode='symmetric', axis=-1):
"""
idwt(cA, cD, wavelet, mode='symmetric', axis=-1)
Single level Inverse Discrete Wavelet Transform.
Parameters
----------
cA : array_like or None
Approximation coefficients. If None, will be set to array of zeros
with same shape as `cD`.
cD : array_like or None
Detail coefficients. If None, will be set to array of zeros
with same shape as `cA`.
wavelet : Wavelet object or name
Wavelet to use
mode | : str, optional (default: 'symmetric')
Signal extension mode, see Modes
axis: int, optional
Axis over which to compute the inverse DWT. If not given, the
last axis is used.
Returns
---- | ---
rec: array_like
Single level reconstruction of signal from given coefficients.
"""
# TODO: Lots of possible allocations to eliminate (zeros_like, asarray(rec))
# accept array_like input; make a copy to ensure a contiguous array
if cA is None and cD is None:
raise ValueError("At least one coefficient parameter must be "
"specified.")
# for complex inputs: compute real and imaginary separately then combine
if np.iscomplexobj(cA) or np.iscomplexobj(cD):
if cA is None:
cD = np.asarray(cD)
cA = np.zeros_like(cD)
elif cD is None:
cA = np.asarray(cA)
cD = np.zeros_like(cA)
return (idwt(cA.real, cD.real, wavelet, mode, axis) +
1j*idwt(cA.imag, cD.imag, wavelet, mode, axis))
if cA is not None:
dt = _check_dtype(cA)
cA = np.array(cA, dtype=dt)
if cD is not None:
dt = _check_dtype(cD)
cD = np.array(cD, dtype=dt)
if cA is not None and cD is not None:
if cA.dtype != cD.dtype:
# need to upcast to common type
cA = cA.astype(np.float64)
cD = cD.astype(np.float64)
elif cA is None:
cA = np.zeros_like(cD)
elif cD is None:
cD = np.zeros_like(cA)
# cA and cD should be same dimension by here
ndim = cA.ndim
mode = Modes.from_object(mode)
if not isinstance(wavelet, Wavelet):
wavelet = Wavelet(wavelet)
if axis < 0:
axis = axis + ndim
if not 0 <= axis < ndim:
raise ValueError("Axis greater than coefficient dimensions")
if ndim == 1:
rec = idwt_single(cA, cD, wavelet, mode)
else:
rec = idwt_axis(cA, cD, wavelet, mode, axis=axis)
return rec
def downcoef(part, data, wavelet, mode='symmetric', level=1):
"""
downcoef(part, data, wavelet, mode='symmetric', level=1)
Partial Discrete Wavelet Transform data decomposition.
Similar to `pywt.dwt`, but computes only one set of coefficients.
Useful when you need only approximation or only details at the given level.
Parameters
----------
part : str
Coefficients type:
* 'a' - approximations reconstruction is performed
* 'd' - details reconstruction is performed
data : array_like
Input signal.
wavelet : Wavelet object or name
Wavelet to use
mode : str, optional
Signal extension mode, see `Modes`. Default is 'symmetric'.
level : int, optional
Decomposition level. Default is 1.
Returns
-------
coeffs : ndarray
1-D array of coefficients.
See Also
--------
upcoef
"""
if np.iscomplexobj(data):
return (downcoef(part, data.real, wavelet, mode, level) +
1j*downcoef(part, data.imag, wavelet, mode, level))
# accept array_like input; make a copy to ensure a contiguous array
dt = _check_dtype(data)
data = np.array(data, dtype=dt)
if part not in 'ad':
raise ValueError("Argument 1 must be 'a' or 'd', not '%s'." % part)
mode = Modes.from_object(mode)
if not isinstance(wavelet, Wavelet):
wavelet = Wavelet(wavelet)
return np.asarray(_downcoef(part == 'a', data, wavelet, mode, level))
def upcoef(part, coeffs, wavelet, level=1, take=0):
"""
upcoef(part, coeffs, wavelet, level=1, take=0)
Direct reconstruction from coefficients.
|
ryfeus/lambda-packs | Shapely_numpy/source/numpy/distutils/__config__.py | Python | mit | 1,319 | 0.015921 | # This file is generated by /tmp/pip-kUGBJh-build/-c
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
|
lapack_opt_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
blas_opt_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
blis_info={}
openblas_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'lan | guage': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
openblas_lapack_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
lapack_mkl_info={}
blas_mkl_info={}
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
|
kernsuite-debian/lofar | CEP/GSM/bremen/recreate_tables.py | Python | gpl-3.0 | 8,597 | 0.001745 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tool to recreate all tables/procedures in the database.
"""
import argparse
import copy
import re
from os import path
from src.sqllist import re_sub
try:
import monetdb.sql as db
try:
import monetdb.exceptions as me
except ImportError:
# Older version
import monetdb.monetdb_exceptions as me
HAS_MONET = True
except ImportError:
HAS_MONET = False
try:
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
HAS_POSTGRESQL = True
except ImportError:
HAS_POSTGRESQL = False
import subprocess
class Recreator(object):
"""
Tool to recreate all tables/procedures in the database.
"""
# all procedures to be recreated
PROCEDURES = ['fill_temp_assoc_kind']
# list of views to be recreated
VIEWS = ['v_catalog_info']
# list of tables to be recreated
TABLES = ['frequencybands', 'datasets', 'runs', 'images',
'extractedsources', 'assocxtrsources', 'detections',
'runningcatalog', 'runningcatalog_fluxes',
'temp_associations', 'image_stats']
def __init__(self, database="test", use_monet=True):
self.monet = use_monet
if use_monet:
db_port = 50000
db_autocommit = True
db_host = "localhost"
db_dbase = database
self.database = database
db_user = "monetdb"
db_passwd = "monetdb"
if use_monet:
self.conn = db.connect(hostname=db_host, database=db_dbase,
username=db_user, password=db_passwd,
port=db_port,
autocommit=db_autocommit)
else:
connect = psycopg2.connect(host=db_host, user=db_user,
password=db_passwd, database=db_dbase)
connect.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
self.conn = connect.cursor()
def get_table_exists(self, tab_name):
"""
Check if the table exists in the database.
"""
if self.monet:
cur = self.conn.cursor()
cur.execute(
"select count(*) from sys.tables where name = '%s';"
% tab_name)
else:
cur = self.conn
cur.exe | cute(
"select count(*) from pg_tables where tablename ='%s';"
% tab_name)
data = cur.fetchone()
return data[0] == 1
def drop_table(self, tab_name):
"""
Drop table if it exists.
"""
if self.get_table_exists(tab_name):
if self.monet:
self.conn.execute("drop t | able %s;" % tab_name)
else:
self.conn.execute("drop table %s cascade;" % tab_name)
self.conn.execute(
"drop sequence if exists seq_%s cascade;" % tab_name)
print('Table %s dropped' % tab_name)
# For MonetDB-PostgreSQL convertion.
PG_SUBSTITUTOR = [
(r'next value for "(.*?)"', r"nextval('\1'::regclass)"),
#(r'^create sequence (.*?)$', ''),
(r'as integer', ''),
(r' double ', ' double precision '),
(r'current_timestamp\(\)', 'current_timestamp'),
]
def refactor_lines(self, sql_lines):
"""
Prepare SQL code for MonetDB/PostgreSQL.
Remove all comments, make necessary substitutions.
"""
sql_lines = re_sub(r'/\*.*?\*/', '', sql_lines, flags=re.DOTALL)
sql_lines = re_sub(r'--.*$', '', sql_lines, flags=re.MULTILINE)
if not self.monet:
# Has to apply substitutions for PostgreSQL.
for from_, to_ in self.PG_SUBSTITUTOR:
sql_lines = re_sub(from_, to_, sql_lines,
flags=re.MULTILINE | re.IGNORECASE)
return sql_lines
def create_table(self, tab_name):
"""
Create a table with a given name.
"""
self.run_sql_file("sql/tables/create.table.%s.sql" % tab_name)
print("Table %s recreated" % tab_name)
def create_view(self, view_name):
"""
Create a view with a given name.
"""
self.run_sql_file("sql/create.view.%s.sql" % view_name)
print("View %s recreated" % view_name)
def create_procedure(self, tab_name):
"""
Create a procedure with a given name.
Procedure SQL is located in the project files:
sql/pg/create.procedure.NAME.sql (PostrgeSQL) or
sql/create.procedure.NAME.sql (MonetDB).
"""
if self.monet:
sql_file = open("sql/create.procedure.%s.sql" % tab_name, 'r')
else:
sql_file = open("sql/pg/create.procedure.%s.sql" % tab_name, 'r')
sql_lines = ''.join(sql_file.readlines())
sql_lines = self.refactor_lines(sql_lines)
#print sql_lines
self.conn.execute(sql_lines)
print("Procedure %s recreated" % tab_name)
def run_sql_file(self, filename):
"""
Execute SQL from file (with proper substitutions for psql.
"""
sql_file = open(filename, 'r')
sql_lines = ''.join(sql_file.readlines())
sql_lines = self.refactor_lines(sql_lines)
self.conn.execute(sql_lines)
def reload_frequencies(self):
"""
Load frequencies tables from file "sql/tables/freq.dat".
Use bulk load from MonetDB/PostgreSQL.
"""
if self.monet:
self.conn.execute("copy into frequencybands from '%s';" %
path.realpath('sql/tables/freq.dat'))
else:
sp = subprocess.Popen(['psql', '-U', 'monetdb',
'-d', self.database, '-c',
"copy frequencybands " \
"from stdin delimiter '|'" \
" null 'null';"],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
for line in open('sql/tables/freq.dat', 'r').readlines():
sp.stdin.write(line)
sp.communicate()
print('Frequencies loaded')
def run_set(self, aset, subroutine):
for item in aset:
subroutine(item)
def run(self):
error_set = []
if HAS_MONET:
error_set.append(me.OperationalError)
if HAS_POSTGRESQL:
error_set.append(psycopg2.ProgrammingError)
error_set = tuple(error_set)
try:
for procedure in self.PROCEDURES:
if self.monet:
try:
self.conn.execute("drop procedure %s;" %
procedure)
print("drop procedure %s;" % procedure)
except error_set:
pass
for view in self.VIEWS:
try:
self.conn.execute("drop view %s;" % view)
except error_set:
pass
print("drop view %s;" % view)
drop_tables = copy.copy(self.TABLES)
drop_tables.reverse()
print('=' * 20)
self.run_set(drop_tables, self.drop_table)
print('=' * 20)
self.run_set(self.TABLES, self.create_table)
if not self.monet:
self.run_sql_file('sql/pg/indices.sql')
print('Indices recreated')
self.run_sql_file('sql/pg/pg_comments.sql')
print('Comments added')
print('=' * 20)
self.run_set(self.PROCEDURES, self.create_procedure)
self.run_set(self.VIEWS, self.create_view)
self.reload_frequencies()
except db.Error as exc:
raise exc
self.conn.close()
return 0
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="""
***Database recreator.
***Created by A. Mints (2012).
*WARNING!!!* Clears all data from the database.""",
formatter_class=argparse.RawDescriptionHelpFo |
iocanto/bug-python-libraries | sample.py | Python | gpl-3.0 | 1,158 | 0.003454 | '''
*******************************************************************************
* sample.py 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.
*
* sample.py is distributed in th | e 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 Licen | se
* along with sample.py. If not, see <http://www.gnu.org/licenses/>.
********************************************************************************
Created on Jan 13, 2010
@author: iocanto
'''
import BUGBaseControl
import InputEventProvider
if __name__ == "__main__":
print "STARTING BugBaseControl TEST"
BUGBaseControl.Test()
print "\nSTARTING InputEventProvider TEST"
print "The test will run for 60 sec, Press any key"
InputEventProvider.Test()
|
harveywwu/vnpy | vnpy/trader/gateway/tkproGateway/TradeApi/trade_api.py | Python | mit | 19,713 | 0.008573 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
from builtins import *
import pandas as pd
from . import utils
class EntrustOrder(object):
def __init__(self, security, action, price, size):
self.security = security
self.action = action
self.price = price
self.size = size
def set_log_dir(log_dir):
if log_dir:
try:
import jrpc
jrpc.set_log_dir(log_dir)
except Exception as e:
print("Exception", e)
class TradeApi(object):
def __init__(self, addr, use_jrpc=True, prod_type="jzts"):
"""
use_jrpc:
True -- Use jrcp_client of C version, for jzts only
False -- Use pure python version
prod_type:
"jaqs" -- jrpc_msgpack_wth_snappy
"jzts" -- jrpc_msgpack
"""
self._remote = None
if prod_type == "jzts":
try:
if use_jrpc:
import jrpc
self._remote = jrpc.JsonRpcClient()
else:
from . import jrpc_py
self._remote = jrpc_py.JRpcClient(data_format="msgpack")
except Exception as e:
print("Exception", e)
if not self._remote:
from . import jrpc_py
self._remote = jrpc_py.JRpcClient(data_format="msgpack")
else:
from . import jrpc_py
self._remote = jrpc_py.JRpcClient(data_format="msgpack_snappy")
self._remote.on_rpc_callback = self._on_rpc_callback
self._remote.on_disconnected = self._on_disconnected
self._remote.on_connected = self._on_connected
self._remote.connect(addr)
self._ordstatus_callback = None
self._taskstatus_callback = None
self._internal_order_callback = None
self._trade_callback = None
self._on_connection_callback = None
self._connected = False
self._username = ""
self._password = ""
self._strategy_id = 0
self._strategy_selected = False
self._data_format = "default"
def __del__(self):
self._remote.close()
def _on_rpc_callback(self, method, data):
# print "_on_rpc_callback:", method, data
if method == "oms.orderstatus_ind":
if self._data_format == "obj":
data = utils.to_obj("Order", data)
if self._ordstatus_callback:
self._ordstatus_callback(data)
elif method == "oms.taskstatus_ind":
if self._data_format == "obj":
data = utils.to_obj("TaskStatus", data)
if self._taskstatus_callback:
self._taskstatus_callback(data)
elif method == "oms.trade_ind":
if self._data_format == "obj":
data = utils.to_obj("Trade", data)
if self._trade_callback:
self._trade_callback(data)
elif method == "oms.internal_order_ind":
if self._data_format == "obj":
data = utils.to_obj("QuoteOrder", data)
if self._internal_order_callback:
self._internal_order_callback(data)
def _on_disconnected(self):
print("TradeApi: _on_disconnected")
self._connected = False
self._strategy_selected = False
if self._on_connection_callback:
self._on_connection_callback(False)
def _on_connected(self):
print("TradeApi: _on_connected")
self._connected = True
self._do_login()
self._do_use_strategy()
if self._on_connection_callback:
self._on_connection_callback(True)
def _check_session(self):
if not self._connected:
return (False, "no connection")
if self._strategy_selected:
return (True, "")
r, msg = self._do_login()
if not r: return (r, msg)
if self._strategy_id:
return self._do_use_strategy()
else:
return (r, msg)
def set_data_format(self, format):
self._data_format = format
def set_connection_callback(self, callback):
self._on_connection_callback = callback
def set_ordstatus_callback(self, callback):
self._ordstatus_callback = callback
def set_trade_callback(self, callback):
self._trade_callback = callback
def set_task_callback(self, callback):
self._taskstatus_callback = callback
def set_quoteorder_callback(self, callback):
self._internal_order_callback = callback
def _get_format(self, format, default_format):
if format:
return format
elif self._data_format != "default":
return self._data_format
else:
return default_format
def login(self, username, password, format=""):
self._username = username
self._password = password
return self._do_login(format=format)
def _do_login(self, format=""):
# Shouldn't check connected flag here. ZMQ is a mesageq queue!
# if !self._connected :
# return (False, "-1,no connection")
if self._username and self._password:
rpc_params = {"username": self._username,
"password": self._password}
cr = self._remote.call("auth.login", rpc_params)
f = self._get_format(format, "")
if f != "obj" and f != "":
f = ""
return utils.extract_result(cr, format=f, class_name="UserInfo")
else:
return (False, "-1,empty username or password")
def logout(self):
rpc_params = {}
cr = self._remote.call("auth.logout", rpc_params)
return utils.extract_result(cr)
def close(self):
self._remote.close()
def use_strategy(self, strategy_id):
if strategy_id:
self._strategy_id = strategy_id
return self._do_use_strategy()
else:
# Query
rpc_params = {"account_id": 0}
cr = self._remote.call("auth.use_strategy", rpc_params)
r, msg = utils.extract_result(cr)
self._strategy_selected = r
return (r, msg)
def _do_use_strategy(self):
if self._strategy_id:
rpc_params = {"account_id": self._strategy_id}
cr = self._remote.call("auth.use_strategy", rpc_params)
r, msg = utils.extract_result(cr)
self._s | trategy_selected = r
return (r, msg)
else:
| return (False, "-1,no strategy_id was specified")
def confirm_internal_order(self, task_id, confirmed):
"""
return (result, message)
if result is None, message contains error information
"""
r, msg = self._check_session()
if not r: return (None, msg)
rpc_params = {"task_id": task_id,
"confirmed": confirmed}
cr = self._remote.call("oms.confirm_internal_order", rpc_params)
return utils.extract_result(cr)
def order(self, security, price, size, algo="", algo_param={}, userdata=""):
"""
return (result, message)
if result is None, message contains error information
"""
r, msg = self._check_session()
if not r: return (None, msg)
rpc_params = {"security": security,
"price": price,
"size": int(size),
"algo": algo,
"algo_param": json.dumps(algo_param),
"user": self._username,
"userdata": userdata}
|
clones/django-profiles | profiles/urls.py | Python | bsd-3-clause | 919 | 0 | """
URLConf for Django user profile management.
Recommended usage is to use a call to ``include()`` in your project's
root URLConf to include this URLConf for any URL beginning with
'/profiles/'.
"""
from django.conf.urls.defaults import *
from profiles import views
urlpatterns = patterns('',
url(r'^create/$',
views.create_profile,
name='profiles_create_profile'),
url(r'^edit/$',
views.edit_profile,
name='profiles_edit_profile'),
url(r'^(?P<username>\w+)/$',
views.profile_detail,
| name='profiles_profile_detail'),
url(r'^$',
| views.profile_list,
name='profiles_profile_list'),
)
|
jimporter/doppel | doppel/__init__.py | Python | bsd-3-clause | 1,483 | 0 | import errno
import os
import shutil
def mkdir(path, mode=0o777, exist_ok=False):
try:
os.mkdir(path, mode)
except OSError as e:
if not exist_ok or e.errno != errno.EEXIST or not os.path.isdir(path):
raise
def makedirs(path, mode=0o777, exist_ok=False):
try:
os.makedirs(path, mode)
except OSError as e:
if not exist_ok or e.errno != errno.EEXIST or not os.path.isdir(path):
raise
def parent_dir(path):
return os.path.normpath(os.path.join(path, os.pardir))
def existing_parent(path):
while not os.path.exists(path):
path = parent_dir(path)
return path
def remove(path, nonexist_ok=False):
try:
os.remove(path)
except OSError as e:
if not nonexist_ok | or e.errno | != errno.ENOENT:
raise
def copy(src, dst, recursive=False, symlink='relative', mode=None):
if symlink != 'never' and os.path.islink(src):
link = os.readlink(src)
if symlink == 'always' or not os.path.isabs(link):
remove(dst, nonexist_ok=True)
os.symlink(link, dst)
return
if os.path.isdir(src):
mkdir(dst, exist_ok=True)
if recursive:
for name in os.listdir(src):
copy(os.path.join(src, name), os.path.join(dst, name))
else:
shutil.copyfile(src, dst)
if mode is not None:
os.chmod(dst, mode)
else:
shutil.copymode(src, dst)
|
gencer/python-phonenumbers | python/tests/testdata/region_882.py | Python | apache-2.0 | 527 | 0.011385 | """Auto-generated file, do not edit by hand. 882 m | etadata"""
from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_882 = PhoneMetadata(id='001', country_code=882, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='\\d{9}', possible_length=(9,)),
mobile=PhoneNumber | Desc(national_number_pattern='\\d{9}', example_number='123456789', possible_length=(9,)),
number_format=[NumberFormat(pattern='(\\d)(\\d{4})(\\d{4})', format='\\1 \\2 \\3')])
|
noironetworks/group-based-policy | gbpservice/neutron/tests/unit/nfp/orchestrator/mock_dicts.py | Python | apache-2.0 | 29,927 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE | -2.0
#
# U | nless 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.
"""This module has the input data for heat_driver UTs."""
class DummyDictionaries(object):
"""Implements the input data for heat_driver UTs.
This class holds the input data that are required in
testing the heat_driver test cases.
"""
DEFAULT_LBV2_CONFIG = {
"heat_template_version": "2015-10-15",
"description": "Configuration for Haproxy Neutron LB V2 service",
"parameters": {
"lb_port": {
"type": "number",
"default": 80,
"description": "Port used by the load balancer"
},
"app_port": {
"type": "number",
"default": 80,
"description": "Port used by the servers"
},
"Subnet": {
"type": "string",
"description": "Subnet on which the LB will be located"
},
"vip_ip": {
"type": "string",
"description": "VIP IP Address"
},
"service_chain_metadata": {
"type": "string",
"description": "sc metadata"
}
},
"resources": {
"monitor": {
"type": "OS::Neutron::LBaaS::HealthMonitor",
"properties": {
"delay": 3,
"type": "HTTP",
"timeout": 3,
"max_retries": 3,
"pool": {
"get_resource": "pool"
}
}
},
"pool": {
"type": "OS::Neutron::LBaaS::Pool",
"properties": {
"lb_algorithm": "ROUND_ROBIN",
"protocol": "HTTP",
"listener": {
"get_resource": "listener"
}
}
},
"listener": {
"type": "OS::Neutron::LBaaS::Listener",
"properties": {
"loadbalancer": {
"get_resource": "loadbalancer"
},
"protocol": "HTTP",
"protocol_port": {
"get_param": "lb_port"
}
}
},
"loadbalancer": {
"type": "OS::Neutron::LBaaS::LoadBalancer",
"properties": {
"vip_subnet": {
"get_param": "Subnet"
},
"provider": "loadbalancerv2",
"vip_address": {
"get_param": "vip_ip"
},
"description": {
"get_param": "service_chain_metadata"
}
}
}
}
}
DEFAULT_FW_CONFIG = {
'heat_template_version': '2013-05-23',
'description': 'Template to deploy firewall',
'resources': {
'sc_firewall_rule3': {
'type': 'OS::Neutron::FirewallRule',
'properties': {
'action': 'allow',
'destination_port': '82',
'protocol': 'tcp', 'name': 'Rule_3'
}
},
'sc_firewall_rule2': {
'type': 'OS::Neutron::FirewallRule',
'properties': {
'action': 'allow',
'destination_port': '81',
'protocol': 'tcp', 'name': 'Rule_2'
}
},
'sc_firewall_rule1': {
'type': 'OS::Neutron::FirewallRule',
'properties': {
'action': 'allow',
'destination_port': '80',
'protocol': 'tcp',
'name': 'Rule_1'
}
},
'sc_firewall_rule0': {
'type': 'OS::Neutron::FirewallRule',
'properties': {
'action': 'allow',
'destination_port': '22',
'protocol': 'tcp', 'name': 'Rule_0'
}
},
'sc_firewall_rule4': {
'type': 'OS::Neutron::FirewallRule',
'properties': {
'action': 'allow',
'protocol': 'icmp',
'name': 'Rule_4'
}
},
'sc_firewall_policy': {
'type': 'OS::Neutron::FirewallPolicy',
'properties': {
'name': '',
'firewall_rules': [
{'get_resource': 'sc_firewall_rule0'},
{'get_resource': 'sc_firewall_rule1'},
{'get_resource': 'sc_firewall_rule2'},
{'get_resource': 'sc_firewall_rule3'},
{'get_resource': 'sc_firewall_rule4'}]
}
},
'sc_firewall': {
'type': 'OS::Neutron::Firewall',
'properties': {
'firewall_policy_id': {
'get_resource': 'sc_firewall_policy'
},
'name': 'serviceVM_infra_FW',
'description': {'insert_type': 'east_west'}
}
}
}
}
DEFAULT_VPN_CONFIG = {
'resources': {
'IKEPolicy': {
'type': 'OS::Neutron::IKEPolicy',
'properties': {
'name': 'IKEPolicy',
'auth_algorithm': 'sha1',
'encryption_algorithm': '3des',
'pfs': 'group5',
'lifetime': {
'units': 'seconds',
'value': 3600
},
'ike_version': 'v1',
'phase1_negotiation_mode': 'main'
}
},
'VPNService': {
'type': 'OS::Neutron::VPNService',
'properties': {
'router_id': {
'get_param': 'RouterId'
},
'subnet_id': {
'get_param': 'Subnet'
},
'admin_state_up': 'true',
'description': {
'get_param': 'ServiceDescription'
},
'name': 'VPNService'
}
},
'site_to_site_connection1': {
'type': 'OS::Neutron::IPsecSiteConnection',
'properties': {
'psk': 'secret',
'initiator': 'bi-directional',
'name': 'site_to_site_connection1',
'admin_state_up': 'true',
'description':
'fip=1.103.1.20;tunnel_local_cidr=11.0.1.0/24;\
user_access_ip=1.103.2.20;fixed_ip=192.168.0.3;\
standby_fip=1.103.1.21;service_vendor=vyos;\
stitching_cidr=192.168.0.0/28;\
stitching_gateway=192.168.0.1;mgmt_gw_ip=120.0.0.1',
'peer_cidrs': ['11.0.0.0/24'],
'mtu': 1500,
'ikepolicy_id': {
'get_resource': 'IKEPolicy'
},
'dpd': {
'interval': 30,
' |
sklam/numba | numba/tests/doc_examples/test_literally_usage.py | Python | bsd-2-clause | 1,625 | 0 | # "magictoken" is used for markers as beginning and ending of example text.
import unittest
from numba.tests.support import captured_stdout
class DocsLiterallyUsageTest(unittest.TestCase):
def test_literally_usage(self):
with captured_stdout():
# magictoken.ex_literally_usage.begin
import numba
def power(x, n):
raise NotImplementedError
@numba.extending.overload(power)
def ov_power(x, n):
if isinstance(n, numba.types.Literal):
# only if `n` is a literal
if n.literal_value == 2:
# special case: square
print("square")
return lambda x, n: x * x
elif n.literal_value == 3:
# special case: cubic
print("cubic")
return lambda x, n: x * x * x
print("generic")
return lambda x, n: x ** n
@numba.njit
def test_power(x, n):
return power(x, numba.literally(n | ))
# should print "square" and "9"
print(test_power(3, 2))
# should print "cubic" and "27"
print(test_power(3, 3))
# should print "generic" and "81"
print(test_power(3, 4))
# magictoken.ex_literally_usage.end
assert test_power(3, 2) == 3 ** 2
assert te | st_power(3, 3) == 3 ** 3
assert test_power(3, 4) == 3 ** 4
if __name__ == '__main__':
unittest.main()
|
nkgilley/home-assistant | tests/components/google_translate/__init__.py | Python | apache-2.0 | 50 | 0 | """Tests for the Google Tr | anslate integration."""
| |
mfherbst/spack | var/spack/repos/builtin/packages/nwchem/package.py | Python | lgpl-2.1 | 9,995 | 0.002401 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import sys
import os
class Nwchem(Package):
"""High-performance computational chemistry software"""
homepage = "http://www.nwchem-sw.org"
url = "http://www.nwchem-sw.org/images/Nwchem-6.6.revision27746-src.2015-10-20.tar.gz"
tags = ['ecp', 'ecp-apps']
version('6.8', '50b18116319f4c15d1cb7eaa1b433006',
url='https://github.com/nwchemgit/nwchem/archive/v6.8-release.tar.gz')
version('6.6', 'c581001c004ea5e5dfacb783385825e3',
url='http://www.nwchem-sw.org/images/Nwchem-6.6.revision27746-src.2015-10-20.tar.gz')
depends_on('blas')
depends_on('lapack')
depends_on('mpi')
depends_on('scalapack')
depends_on('python@2.7:2.8', type=('build', 'link', 'run'))
# first hash is sha256 of the patch (required for URL patches),
# second is sha256 for the archive.
# patches for 6.6-27746:
urls_for_patches = {
'@6.6': [
('http://www.nwchem-sw.org/images/Tddft_mxvec20.patch.gz', 'ae04d4754c25fc324329dab085d4cc64148c94118ee702a7e14fce6152b4a0c5', 'cdfa8a5ae7d6ee09999407573b171beb91e37e1558a3bfb2d651982a85f0bc8f'),
('http://www.nwchem-sw.org/images/Tools_lib64.patch.gz', 'ef2eadef89c055c4651ea807079577bd90e1bc99ef6c89f112f1f0e7560ec9b4', '76b8d3e1b77829b683234c8307fde55bc9249b87410914b605a76586c8f32dae'),
('http://www.nwchem-sw.org/images/Config_libs66.patch.gz', '56f9c4bab362d82fb30d97564469e77819985a38e15ccaf04f647402c1ee248e', 'aa17f03cbb22ad7d883e799e0fddad1b5957f5f30b09f14a1a2caeeb9663cc07'),
('http://www.nwchem-sw.org/images/Cosmo_meminit.patch.gz', 'f05f09ca235ad222fe47d880bfd05a1b88d0148b990ca8c7437fa231924be04b', '569c5ee528f3922ee60ca831eb20ec6591633a36f80efa76cbbe41cabeb9b624'),
('http://www.nwchem-sw.org/images/Sym_abelian.patch.gz', 'e3470fb5786ab30bf2eda3bb4acc1e4c48fb5e640a09554abecf7d22b315c8fd', 'aa693e645a98dbafbb990e26145d65b100d6075254933f36326cf00bac3c29e0'),
('http://www.nwchem-sw.org/images/Xccvs98.patch.gz', '75540e0436c12e193ed0b644cff41f5036d78c101f14141846083f03ad157afa', '1c0b0f1293e3b9b05e9e51e7d5b99977ccf1edb4b072872c8316452f6cea6f13'),
('http://www.nwchem-sw.org/images/Dplot_tolrho.patch.gz', '8c30f92730d15f923ec8a623e3b311291eb2ba8b9d5a9884716db69a18d14f24', '2ebb1a5575c44eef4139da91f0e1e60057b2eccdba7f57a8fb577e840c326cbb'),
('http://www.nwchem-sw.org/images/Driver_smalleig.patch.gz', 'a040df6f1d807402ce552ba6d35c9610d5efea7a9d6342bbfbf03c8d380a4058', 'dd65bfbae6b472b94c8ee81d74f6c3ece37c8fc8766ff7a3551d8005d44815b8'),
('http://www.nwchem-sw.org/images/Ga_argv.patch.gz', '6fcd3920978ab95083483d5ed538cd9a6f2a80c2cafa0c5c7450fa5621f0a314', '8a78cb2af14314b92be9d241b801e9b9fed5527b9cb47a083134c7becdfa7cf1'),
('http://www.nwchem-sw.org/images/Raman_displ.patch.gz', 'ca4312cd3ed1ceacdc3a7d258bb05b7824c393bf44f44c28a789ebeb29a8dba4', '6a16f0f589a5cbb8d316f68bd2e6a0d46cd47f1c699a4b256a3973130061f6c3'),
('http://www.nwchem-sw.org/images/Ga_defs.patch.gz', 'f8ac827fbc11f7d2a9d8ec840c6f79d4759ef782bd4d291f2e88ec81b1b230aa', 'c6f1a48338d196e1db22bcfc6087e2b2e6eea50a34d3a2b2d3e90cccf43742a9'),
('http://www.nwchem-sw.org/images/Zgesvd.patch.gz', 'c333a94ceb2c35a490f24b007485ac6e334e153b03cfc1d093b6037221a03517', '4af592c047dc3e0bc4962376ae2c6ca868eb7a0b40a347ed9b88e887016ad9ed'),
('http://www.nwchem-sw.org/images/Cosmo_dftprint.patch.gz', '449d59983dc68c23b34e6581370b2fb3d5ea425b05c3182f0973e5b0e1a62651', 'd3b73431a68d6733eb7b669d471e18a83e03fa8e40c48e536fe8edecd99250ff'),
('http://www.nwchem-sw.org/images/Txs_gcc6.patch.gz', '1dab87f23b210e941c765f7dd7cc2bed06d292a2621419dede73f10ba1ca1bcd', '139692215718cd7414896470c0cc8b7817a73ece1e4ca93bf752cf1081a195af'),
('http://www.nwchem-sw.org/images/Gcc6_optfix.patch.gz', '8f8a5f8246bc1e42ef0137049acab4448a2e560339f44308703589adf753c148', '15cff43ab0509e0b0e83c49890032a848d6b7116bd6c8e5678e6c933f2d051ab'),
('http://www.nwchem-sw.org/images/Util_gnumakefile.patch.gz', '173e17206a9099c3512b87e3f42441f5b089db82be1d2b306fe2a0070e5c8fad', '5dd82b9bd55583152295c999a0e4d72dd9d5c6ab7aa91117c2aae57a95a14ba1'),
('http://www.nwchem-sw.org/images/Util_getppn.patch.gz', 'c4a23592fdcfb1fb6b65bc6c1906ac36f9966eec4899c4329bc8ce12015d2495', '8be418e1f8750778a31056f1fdf2a693fa4a12ea86a531f1ddf6f3620421027e'),
('http://www.nwchem-sw.org/images/Gcc6_macs_optfix.patch.gz', 'ff33d5f1ccd33385ffbe6ce7a18ec1506d55652be6e7434dc8065af64c879aaa', 'fade16098a1f54983040cdeb807e4e310425d7f66358807554e08392685a7164'),
('http://www.nwchem-sw.org/images/Notdir_fc.patch.gz', '54c722fa807671d6bf1a056586f0923593319d09c654338e7dd461dcd29ff118', 'a6a233951eb254d8aff5b243ca648def21fa491807a66c442f59c437f040ee69')
]
}
# Iterate over patches
for __condition, __urls in urls_for_patches.items():
for __url, __sha256, __archive_sha256 in __urls:
patch(__url, when=__condition, level=0, sha256=__sha256, archive_sha256=__archive_sha256)
def install(self, spec, prefix):
scalapack = spec['scalapack'].libs
lapack = spec['lapack'].libs
blas = spec['blas'].libs
# see http://www.nwchem-sw.org/index.php/Compiling_NWChem
args = []
args.extend([
'NWCHEM_TOP=%s' % self.stage.source_path,
# NWCHEM is picky about FC and CC. They should NOT be full path.
# see http://www.nwchem-sw.org/index.php/Special:AWCforum/sp/id7524
'CC=%s' % os.path.basename(spack_cc),
'FC=%s' % os.path.basename(spack_fc),
'USE_MPI=y',
'MPI_LOC=%s' % spec['mpi'].prefix,
'USE_PYTHONCONFIG=y',
'PYTHONVERSION=%s' % spec['python'].version.up_to(2),
'PYTHONHOME=%s' % spec['python'].home,
'BLASOPT=%s' % ((lapack + blas).ld_flags),
'BLAS_LIB=%s' % blas.ld_flags,
| 'LAPACK_LIB=%s' % lapack.ld_flags,
'USE_SCALAPACK=y',
'SCALAPACK=%s' % scalapack.ld_flags,
'NWCHEM_MODULES=all python',
'NWCHEM_LONG_PATHS=Y' # by default NWCHEM_TOP is 64 char max
])
# TODO: query if blas/lapack/scalapack uses 64bit Ints
# A flag to distinguish between 32bit and 64bit integers in linear
# algebra (Blas, Lapack, Scalapack)
use_32_bit_l | in_alg = True
if use_32_bit_lin_alg:
args.extend([
'USE_64TO32=y',
'BLAS_SIZE=4',
'LAPACK_SIZE=4',
'SCALAPACK_SIZE=4'
])
else:
args.extend([
'BLAS_SIZE=8',
'LAPACK_SIZE=8'
'SCALAPACK_SIZE=8'
])
if sys.platform == |
fnp/prawokultury | shop/models.py | Python | agpl-3.0 | 4,642 | 0.004094 | # -*- coding: utf-8 -*-
# This file is part of PrawoKultury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from datetime import datetime
from django.core.mail import send_mail, mail_managers
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _, override
import getpaid
from migdal.models import Entry
from . import app_settings
class Offer(models.Model):
""" A fund | raiser for a particular book. """
entry = models.OneToOneField(Entry, models.CASCADE) # filter publications!
price = models.DecimalField(_('price'), decimal_places=2, max_digits=6)
cost_const = models.DecimalField(decimal_place | s=2, max_digits=6)
cost_per_item = models.DecimalField(decimal_places=2, max_digits=6, default=0)
class Meta:
verbose_name = _('offer')
verbose_name_plural = _('offers')
ordering = ['entry']
def __unicode__(self):
return unicode(self.entry)
def get_absolute_url(self):
return self.entry.get_absolute_url()
def total_per_item(self):
return self.price + self.cost_per_item
def price_per_items(self, items):
return self.cost_const + items * self.total_per_item()
class Order(models.Model):
""" A person paying for a book.
The payment was completed if and only if payed_at is set.
"""
offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'))
items = models.IntegerField(verbose_name=_('items'), default=1)
name = models.CharField(_('name'), max_length=127, blank=True)
email = models.EmailField(_('email'), db_index=True)
address = models.TextField(_('address'), db_index=True)
payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
language_code = models.CharField(max_length = 2, null = True, blank = True)
class Meta:
verbose_name = _('order')
verbose_name_plural = _('orders')
ordering = ['-payed_at']
def __unicode__(self):
return "%s (%d egz.)" % (unicode(self.offer), self.items)
def get_absolute_url(self):
return self.offer.get_absolute_url()
def amount(self):
return self.offer.price_per_items(self.items)
def notify(self, subject, template_name, extra_context=None):
context = {
'order': self,
'site': Site.objects.get_current(),
}
if extra_context:
context.update(extra_context)
with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
send_mail(subject,
render_to_string(template_name, context),
getattr(settings, 'CONTACT_EMAIL', 'prawokultury@nowoczesnapolska.org.pl'),
[self.email],
fail_silently=False
)
def notify_managers(self, subject, template_name, extra_context=None):
context = {
'order': self,
'site': Site.objects.get_current(),
}
if extra_context:
context.update(extra_context)
with override(app_settings.DEFAULT_LANGUAGE):
mail_managers(subject, render_to_string(template_name, context))
# Register the Order model with django-getpaid for payments.
getpaid.register_to_payment(Order, unique=False, related_name='payment')
def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
""" Set payment details for getpaid. """
payment.amount = order.amount()
payment.currency = 'PLN'
getpaid.signals.new_payment_query.connect(new_payment_query_listener)
def user_data_query_listener(sender, order, user_data, **kwargs):
""" Set user data for payment. """
user_data['email'] = order.email
getpaid.signals.user_data_query.connect(user_data_query_listener)
def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
""" React to status changes from getpaid. """
if old_status != 'paid' and new_status == 'paid':
instance.order.payed_at = datetime.now()
instance.order.save()
instance.order.notify(
_('Your payment has been completed.'),
'shop/email/payed.txt'
)
instance.order.notify_managers(
_('New order has been placed.'),
'shop/email/payed_managers.txt'
)
getpaid.signals.payment_status_changed.connect(payment_status_changed_listener, dispatch_uid='shop.models.payment_status_changed_listener')
|
OpenSPA/dvbapp | lib/python/Components/Timezones.py | Python | gpl-2.0 | 1,411 | 0.041106 | import xml.etree.cElementTree
from os import environ, unlink, symlink, path
from Tools.Directories import SCOPE_SKIN, resolveFilename
import time
from Tools.StbHardware import setRTCoffset
class Timezones:
def __init__(self):
self.timezones = []
self.readTimezonesFromFile()
def readTimezonesFromFile(self):
try:
root = xml.etree.cElementTree.parse(resolveFilename(SCOPE_SKIN, 'timezone.xml')).getroot()
for zone in root.findal | l("zone"):
self.timezones.append((zone.get('name',""), zone.get('zone',"")))
except:
pass
if len(self.timezones) == 0:
self.timezones = [("UTC", "UTC")]
def activateTimezone(self, index):
if len(self.timezones) <= index:
return
environ['TZ'] = self.timezones[index][1]
try:
un | link("/etc/localtime")
except OSError:
pass
try:
symlink("/usr/share/zoneinfo/%s" %(self.timezones[index][1]), "/etc/localtime")
except OSError:
pass
try:
time.tzset()
except:
from enigma import e_tzset
e_tzset()
if path.exists("/proc/stb/fp/rtc_offset"):
setRTCoffset()
def getTimezoneList(self):
return [ str(x[0]) for x in self.timezones ]
def getDefaultTimezone(self):
# TODO return something more useful - depending on country-settings?
t = "(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Vienna"
for (a,b) in self.timezones:
if a == t:
return a
return self.timezones[0][0]
timezones = Timezones()
|
devinbalkind/eden | tests/dbmigration/old_models/db.py | Python | mit | 749 | 0 | if not request.env.web2py_runtime_gae:
db = DAL("sqlite://storage.sqlite")
else:
db = DAL("google:datastore")
session.connect(request, response, db=db)
# Test for removing a table, this table is removed in the next revision
db.define_table("removing",
Field("name")
)
db.define_table("main",
Field("remove_id", "integer")
)
# Test for renaming a field
db.define_table("renaming",
| Field("renamed")
)
# Test for adding and deleting a field
db.define_table("edit",
Field("name", "integer",
default="2")
)
# END =========================================================================
| |
faribas/RMG-Py | rmgpy/statmech/rotationTest.py | Python | mit | 34,218 | 0.007248 | #!/usr/bin/env python
# encoding: utf-8
################################################################################
#
# RMG - Reaction Mechanism Generator
#
# Copyright (c) 2002-2009 Prof. William H. Green (whgreen@mit.edu) and the
# RMG Team (rmg_dev@mit.edu)
#
# 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 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
################################################################################
"""
This script contains unit tests of the :mod:`rmgpy.statmech.rotation` module.
"""
import unittest
import math
import numpy
from rmgpy.statmech.rotation import LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor
import rmgpy.constants as constants
################################################################################
class TestLinearRotor(unittest.TestCase):
"""
Contains unit tests of the LinearRotor class.
"""
def setUp(self):
"""
A function run before each unit test in this class.
"""
self.inertia = 11.75
self.symmetry = 2
self.quantum = False
self.mode = LinearRotor(
inertia = (self.inertia,"amu*angstrom^2"),
symmetry = self.symmetry,
quantum = self.quantum,
)
def test_getRotationalConstant(self):
"""
Test getting the LinearRotor.rotationalConstant property.
"""
Bexp = 1.434692
Bact = self.mode.rotationalConstant.value_si
self.assertAlmostEqual(Bexp, Bact, 4)
def test_setRotationalConstant(self):
"""
Test setting the LinearRotor.rotationalConstant property.
"""
B = self.mode.rotationalConstant
B.value_si *= 2
self.mode.rotationalConstant = B
Iexp = 0.5 * self.inertia
Iact = self.mode.inertia.value_si * constants.Na * 1e23
self.assertAlmostEqual(Iexp, Iact, 4)
def test_getLevelEnergy(self):
"""
Test the LinearRotor.getLevelEnergy() method.
"""
B = self.mode.rotationalConstant.value_si * constants.h * constants.c * 100.
B *= constants.Na
for J in range(0, 100):
Eexp = B * J * (J + 1)
Eact = self.mode.getLevelEnergy(J)
if J == 0:
self.assertEqual(Eact, 0)
else:
self.assertAlmostEqual(Eexp, Eact, delta=1e-4*Eexp)
def test_getLevelDegeneracy(self):
"""
Test the LinearRotor.getLevelDegeneracy() method.
"""
for J in range(0, 100):
gexp = 2 * J + 1
gact = self.mode.getLevelDegeneracy(J)
self.assertEqual(gexp, gact)
def test_getPartitionFunction_classical(self):
"""
Test the LinearRotor.getPartitionFunction() method for a classical
rotor.
"""
self.mode.quantum = False
Tlist = numpy.array([300,500,1000,1500,2000])
Qexplist = numpy.array([72.6691, 121.115, 242.230, 363.346, 484.461])
for T, Qexp in zip(Tlist, Qexplist):
Qact = self.mode.getPartitionFunction(T)
self.assertAlmostEqual(Qexp, Qact, delta=1e-4*Qexp)
def test_getPartitionFunction_quantum(self):
"""
Test the LinearRotor.getPartitionFunction() method for a quantum
rotor.
"""
self.mode.quantum = True
Tlist = numpy.array([300,500,1000,1500,2000])
Qexplist = numpy.array([72.8360, 121.282, 242.391, 363.512, 484.627])
for T, Qexp in zip(Tlist, Qexplist):
Qact = self.mode.getPartitionFunction(T)
self.assertAlmostEqual(Qexp, Qact, delta=1e-4*Qexp)
def test_getHeatCapacity_classical(self):
"""
Test the LinearRotor.getHeatCapacity() method using a classical rotor.
"""
self.mode.quantum = False
Tlist = numpy.array([300,500,1000,1500,2000])
Cvexplist = numpy.array([1, 1, 1, 1, 1]) * constants.R
for T, Cvexp in zip(Tlist, Cvexplist):
Cvact = self.mode.getHeatCapacity(T)
self.assertAlmostEqual(Cvexp, Cvact, delta=1e-4*Cvexp)
def test_getHeatCapacity_quantum(self):
"""
Test the LinearRotor.getHeatCapacity() method using a quantum rotor.
"""
self.mode.quantum = True
Tlist = numpy.array([300,500,1000,1500,2000])
Cvexplist = numpy.array([1, 1, 1, 1, 1]) * constants.R
for T, Cvexp in zip(Tlist, Cvexplist):
Cvact = self.mode.getHeatCapacity(T)
self.assertAlmostEqual(Cvexp, Cvact, delta=1e-4*Cvexp)
def test_getEnthalpy_classical(self):
"""
Test the LinearRotor.getEnthalpy() method using a classical rotor.
"""
self.mode.quantum = False
Tlist = numpy.array([300,500,1000,1500,2000])
Hexplist = numpy.array([1, 1, 1, 1, 1]) * constants.R * Tlist
for T, Hexp in zip(Tlist, Hexplist):
Hact = self.mode.getEnthalpy(T)
self.assertAlmostEqual(Hexp, Hact, delta=1e-4*Hexp)
def test_getEnthalpy_quantum(self):
"""
Test the LinearRotor.getEnthalpy() method using a quantum rotor.
"""
self.mode.quantum = True
Tlist = numpy.array([300,500,1000,1500,2000])
Hexplist = numpy.array([0.997705, 0.998624, 0.999312, 0.999541, 0.999656]) * constants.R * Tlist
for T, Hexp in zip(Tlist, Hexplist):
Hact = self.mode.getEnthalpy(T)
self.assertAlmostEqual(Hexp, Hact, delta=1e-4*Hexp)
def test_getEntropy_classical(self):
"""
Test the LinearRotor.getEntropy() method using a classical rotor.
"""
self.mode.quantum = False
Tlist = numpy.array([300,500,1000,1500,2000])
Sexplist = numpy.array([5.28592, 5.79674, 6.48989, 6.89535, 7.18304]) * constants.R
for T, Sexp in zip(Tlist, Sexplist):
Sact = self.mode.getEntropy(T)
self.assertAlmostEqual(Sexp, Sact, delta=1e-4*Sexp)
def test_getEntropy_quantum(self):
"""
Test the LinearRotor.getEntropy() method using a quantum rotor.
"""
self.mode.quantum = True
Tlist = numpy.array([300,500,1000,1500,2000])
Sexplist = numpy.array([5.28592, 5.79674, 6.48989, 6.89535, 7.18304]) * constants.R
for T, Sexp in zip(Tlist, Sexplist):
Sact = self.mode.getEntropy(T)
self.assertAlmostEqual(Sexp, Sact, delta=1e-4*Sexp)
def test_getSumOfStates_classical(self):
"""
Test the LinearRotor.getSumOfStates() method using a classical rotor.
"""
| self.mode.quantum = False
Elist = numpy.arange(0, 2000*11.96, 1.0*11.96)
densStates = self.mode.getDensityOfStates(Elist)
| sumStates = self.mode.getSumOfStates(Elist)
for n in range(1, len(Elist)):
self.assertAlmostEqual(numpy.sum(densStates[0:n]) / sumStates[n], 1.0, 3)
def test_getSumOfStates_quantum(self):
"""
Test the LinearRotor.getSumOfStates() method using a quantum rotor.
"""
self.mode.quantum = True
|
kadamski/func | func/overlord/func_command.py | Python | gpl-2.0 | 2,133 | 0.007501 | #!/usr/bin/python
## func command line interface & client lib
##
## Copyright 2007,2008 Red Hat, Inc
## +AUTHORS
##
## This software may be freely redistributed under the terms of the GNU
## general public license.
##
## 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., 675 Mass Ave, Cambridge, MA 02139, USA.
import sys
import command
import func.module_loader as module_loader
from func.overlord import client,base_command
class FuncCommandLine(command.Command):
name = "func"
usage = "func [--options] \"hostname glob\" module method [arg1] [arg2] ... "
subCommandClasses = []
def __init__(self):
modules = module_loader.load_modules('func/overlord/cmd_modules/', base_command.BaseCommand)
for x in modules.keys():
self.subCommandClasses.append(modules[x].__class__)
command.Command.__init__(self)
def do(self, args):
pass
def addOptions(self):
self.parser.add_option('', '--version', action="store_true",
help="show version information")
# just some ugly | goo to try to guess if arg[1] is hostnamegoo or
# a command name
def _isGlob(self, str):
if str.find("*") or str.find("?") or str.find("[") or str.find("]"):
return True
return False
def handleArguments(self, args):
if len(args) < 2:
sys.stde | rr.write("see the func manpage for usage\n")
sys.exit(411)
minion_string = args[0]
# try to be clever about this for now
if client.is_minion(minion_string) or self._isGlob(minion_string):
self.server_spec = minion_string
args.pop(0)
# if it doesn't look like server, assume it
# is a sub command? that seems wrong, what about
# typo's and such? How to catch that? -akl
# maybe a class variable self.data on Command?
def handleOptions(self, options):
if options.version:
#FIXME
sys.stderr.write("version is NOT IMPLEMENTED YET\n")
|
reTXT/thrift | lib/py/src/protocol/TBinaryProtocol.py | Python | apache-2.0 | 7,772 | 0.009779 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# | distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you un | der 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 .TProtocol import TType, TProtocolBase, TProtocolException
from struct import pack, unpack
class TBinaryProtocol(TProtocolBase):
"""Binary implementation of the Thrift protocol driver."""
# NastyHaxx. Python 2.4+ on 32-bit machines forces hex constants to be
# positive, converting this into a long. If we hardcode the int value
# instead it'll stay in 32 bit-land.
# VERSION_MASK = 0xffff0000
VERSION_MASK = -65536
# VERSION_1 = 0x80010000
VERSION_1 = -2147418112
TYPE_MASK = 0x000000ff
def __init__(self, trans, strictRead=False, strictWrite=True, **kwargs):
TProtocolBase.__init__(self, trans)
self.strictRead = strictRead
self.strictWrite = strictWrite
self.string_length_limit = kwargs.get('string_length_limit', None)
self.container_length_limit = kwargs.get('container_length_limit', None)
def _check_string_length(self, length):
self._check_length(self.string_length_limit, length)
def _check_container_length(self, length):
self._check_length(self.container_length_limit, length)
def writeMessageBegin(self, name, type, seqid):
if self.strictWrite:
self.writeI32(TBinaryProtocol.VERSION_1 | type)
self.writeString(name)
self.writeI32(seqid)
else:
self.writeString(name)
self.writeByte(type)
self.writeI32(seqid)
def writeMessageEnd(self):
pass
def writeStructBegin(self, name):
pass
def writeStructEnd(self):
pass
def writeFieldBegin(self, name, type, id):
self.writeByte(type)
self.writeI16(id)
def writeFieldEnd(self):
pass
def writeFieldStop(self):
self.writeByte(TType.STOP)
def writeMapBegin(self, ktype, vtype, size):
self.writeByte(ktype)
self.writeByte(vtype)
self.writeI32(size)
def writeMapEnd(self):
pass
def writeListBegin(self, etype, size):
self.writeByte(etype)
self.writeI32(size)
def writeListEnd(self):
pass
def writeSetBegin(self, etype, size):
self.writeByte(etype)
self.writeI32(size)
def writeSetEnd(self):
pass
def writeBool(self, bool):
if bool:
self.writeByte(1)
else:
self.writeByte(0)
def writeByte(self, byte):
buff = pack("!b", byte)
self.trans.write(buff)
def writeI16(self, i16):
buff = pack("!h", i16)
self.trans.write(buff)
def writeI32(self, i32):
buff = pack("!i", i32)
self.trans.write(buff)
def writeI64(self, i64):
buff = pack("!q", i64)
self.trans.write(buff)
def writeDouble(self, dub):
buff = pack("!d", dub)
self.trans.write(buff)
def writeBinary(self, str):
self.writeI32(len(str))
self.trans.write(str)
def readMessageBegin(self):
sz = self.readI32()
if sz < 0:
version = sz & TBinaryProtocol.VERSION_MASK
if version != TBinaryProtocol.VERSION_1:
raise TProtocolException(
type=TProtocolException.BAD_VERSION,
message='Bad version in readMessageBegin: %d' % (sz))
type = sz & TBinaryProtocol.TYPE_MASK
name = self.readString()
seqid = self.readI32()
else:
if self.strictRead:
raise TProtocolException(type=TProtocolException.BAD_VERSION,
message='No protocol version header')
name = self.trans.readAll(sz)
type = self.readByte()
seqid = self.readI32()
return (name, type, seqid)
def readMessageEnd(self):
pass
def readStructBegin(self):
pass
def readStructEnd(self):
pass
def readFieldBegin(self):
type = self.readByte()
if type == TType.STOP:
return (None, type, 0)
id = self.readI16()
return (None, type, id)
def readFieldEnd(self):
pass
def readMapBegin(self):
ktype = self.readByte()
vtype = self.readByte()
size = self.readI32()
self._check_container_length(size)
return (ktype, vtype, size)
def readMapEnd(self):
pass
def readListBegin(self):
etype = self.readByte()
size = self.readI32()
self._check_container_length(size)
return (etype, size)
def readListEnd(self):
pass
def readSetBegin(self):
etype = self.readByte()
size = self.readI32()
self._check_container_length(size)
return (etype, size)
def readSetEnd(self):
pass
def readBool(self):
byte = self.readByte()
if byte == 0:
return False
return True
def readByte(self):
buff = self.trans.readAll(1)
val, = unpack('!b', buff)
return val
def readI16(self):
buff = self.trans.readAll(2)
val, = unpack('!h', buff)
return val
def readI32(self):
buff = self.trans.readAll(4)
val, = unpack('!i', buff)
return val
def readI64(self):
buff = self.trans.readAll(8)
val, = unpack('!q', buff)
return val
def readDouble(self):
buff = self.trans.readAll(8)
val, = unpack('!d', buff)
return val
def readBinary(self):
size = self.readI32()
self._check_string_length(size)
s = self.trans.readAll(size)
return s
class TBinaryProtocolFactory(object):
def __init__(self, strictRead=False, strictWrite=True, **kwargs):
self.strictRead = strictRead
self.strictWrite = strictWrite
self.string_length_limit = kwargs.get('string_length_limit', None)
self.container_length_limit = kwargs.get('container_length_limit', None)
def getProtocol(self, trans):
prot = TBinaryProtocol(trans, self.strictRead, self.strictWrite,
string_length_limit=self.string_length_limit,
container_length_limit=self.container_length_limit)
return prot
class TBinaryProtocolAccelerated(TBinaryProtocol):
"""C-Accelerated version of TBinaryProtocol.
This class does not override any of TBinaryProtocol's methods,
but the generated code recognizes it directly and will call into
our C module to do the encoding, bypassing this object entirely.
We inherit from TBinaryProtocol so that the normal TBinaryProtocol
encoding can happen if the fastbinary module doesn't work for some
reason. (TODO(dreiss): Make this happen sanely in more cases.)
In order to take advantage of the C module, just use
TBinaryProtocolAccelerated instead of TBinaryProtocol.
NOTE: This code was contributed by an external developer.
The internal Thrift team has reviewed and tested it,
but we cannot guarantee that it is production-ready.
Please feel free to report bugs and/or success stories
to the public mailing list.
"""
pass
class TBinaryProtocolAcceleratedFactory(object):
def __init__(self,
string_length_limit=None,
container_length_limit=None):
self.string_length_limit = string_length_limit
self.container_length_limit = container_length_limit
def getProtocol(self, trans):
return TBinaryProtocolAccelerated(
trans,
string_length_limit=self.string_length_limit,
container_length_limit=self.container_length_limit)
|
Bforartists/scons | scons-local/SCons/Tool/f03.py | Python | mit | 1,990 | 0.002513 | """engine.SCons.Tool.f03
Tool-specific initialization for the generic Posix f03 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# | a copy of this softwar | e 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 OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/f03.py 2014/07/05 09:42:21 garyo"
import SCons.Defaults
import SCons.Tool
import SCons.Util
import fortran
from SCons.Tool.FortranCommon import add_all_to_env, add_f03_to_env
compilers = ['f03']
def generate(env):
add_all_to_env(env)
add_f03_to_env(env)
fcomp = env.Detect(compilers) or 'f03'
env['F03'] = fcomp
env['SHF03'] = fcomp
env['FORTRAN'] = fcomp
env['SHFORTRAN'] = fcomp
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
redsk/neo_merger | neo_merger.py | Python | gpl-2.0 | 10,267 | 0.007013 | import sys
class MergeKBs():
def __init__(self, WNnodesFilename, WNedgesFilename, CNnodesFilename, CNedgesFilename, matchedNodesFilename, matchedEdgesFilename, matchKBs):
self.WNnodesFilename = WNnodesFilename
self.WNedgesFilename = WNedgesFilename
self.CNnodesFilename = CNnodesFilename
self.CNedgesFilename = CNedgesFilename
self.matchedNodesFilename = matchedNodesFilename
self.matchedEdgesFilename = matchedEdgesFilename
self.matchedRels = []
self.matchKBs = matchKBs
def mergeKBs(self):
print 'Reading WordNet nodes and edges...',
sys.stdout.flush()
self.WNnodesList, self.WNnodesFields, self.WNnodesTypes = self.readCSV(self.WNnodesFilename)
self.WNrelsList, self.WNrelsFields, self.WNrelsTypes = self.readCSV(self.WNedgesFilename)
print 'done.'
print 'Reading ConceptNet nodes and edges...',
sys.stdout.flush()
self.CNnodesList, self.CNnodesFields, self.CNnodesTypes = self.readCSV(self.CNnodesFilename)
self.CNrelsList, self.CNrelsFields, self.CNrelsTypes = self.readCSV(self.CNedgesFilename)
print 'done.'
print 'Adding KB source property to relationships...',
sys.stdout.flush()
self.addKBsourceProperty()
print 'done.'
print 'Creating data structures...',
sys.stdout.flush()
self.wn = OrderedDictionary(self.getDictFromListOfNodes(self.WNnodesList))
self.cn = OrderedDictionary(self.getDictFromListOfNodes(self.CNnodesList))
print 'done.'
print 'Writing merged Nodes File...',
sys.stdout.flush()
self.writeCSV( self.matchedNodesFilename,
[self.WNnodesList, self.CNnodesList], \
[self.WNnodesFields, self.CNnodesFields], \
[self.WNnodesTypes, self.CNnodesTypes] )
print 'done.'
if self.matchKBs == 'match':
print 'Matching nodes...',
sys.stdout.flush()
self.matchNodes()
print 'done.'
print 'Writing merged Edges File...',
sys.stdout.flush()
self.writeCSV( self.matchedEdgesFilename, \
[self.WNrelsList, self.CNrelsList, self.matchedRels], \
[self.WNrelsFields, self.CNrelsFields], \
[self.WNrelsTypes, self.CNrelsTypes] )
print 'done.'
def readCSV(self, filename):
lines = None
with open(filename, 'r') as f:
lines = f.readlines()
fields = lines[0][:-1].split('\t') # [:-1] to remove '\n'
types = []
for f in fields:
t = ''
Scolon = f.split(':')
if len(Scolon) > 1:
if Scolon[1] == 'int':
t = 'i'
elif Scolon[1] == 'float':
t = 'f'
else:
t = 's' # string
if '[]' in f:
t = t + 'a' # array of
# override for 'id:ID', ':LABEL', etc.
if f in ['id:ID', ':LABEL', ':START_ID', ':END_ID', ':TYPE']:
t = 's'
types.append(t)
l = []
for i in range(1, len(lines)):
values = lines[i][:-1].split('\t') # [:-1] to remove '\n'
name = values[0][1:-1] # removing ""
# if name.startswith('wn/'):
# name = name[3:]
n = {}
for j in range(0, len(values)):
if values[j] != '' and values[j] != '""': # in that case, the value is null for that record
if types[j] == 'i':
n[fields[j]] = int(values[j])
elif types[j] == 'f':
n[fields[j]] = float(values[j])
elif types[j] == 's':
if values[j][0] == '"' and values[j][-1] == '"':
n[fields[j]] = values[j][1:-1] # removing ""
else:
n[fields[j]] = values[j] # Labels might have no ""...
elif types[j] == 'ia':
n[fields[j]] = [int(i) for i in values[j].split(';')]
elif types[j] == 'fa':
n[fields[j]] = [float(i) for i in values[j].split(';')]
elif types[j] == 'sa':
n[fields[j]] = values[j][1:-1].split(';')
l.append(n)
return l, fields, types
# A 'KB' source property is added to relationships to make it easier to
# calculate paths that stay within specific KBs.
def addKBsourceProperty(self):
self.WNrelsFields.append('KB')
self.CNrelsFields.append('KB')
self.WNrelsTypes.append('s')
self.CNrelsTypes.ap | pend('s')
for r in self.WNrelsList:
r['KB'] = "W"
for r in self.CNrelsList:
r['KB'] = "C"
def getDictFromListOfNodes(self, l):
d = {}
for e in l:
d[ e['id:ID'] ] = e
return d
def writeCSV(self, filename, ItemsLists, ItemFields, ItemsTypes):
matchedFields | , matchedTypes = self.matchHeaders(ItemFields, ItemsTypes)
with open(filename, 'w') as of:
header = '\t'.join(matchedFields)
of.write(header + '\n')
for l in ItemsLists:
for i in l:
line = ''
for idx, f in enumerate(matchedFields):
if f in i:
if matchedTypes[idx] in ['i', 'f']:
line += str(i[f])
#of.write(str(i[f]))
elif matchedTypes[idx] == 's':
line += '"{0}"'.format(i[f])
# of.write( '"{0}"'.format(i[f]) )
elif matchedTypes[idx] in ['ia', 'fa']:
line += '"{0}"'.format( ';'.join([str(j) for j in i[f]]) )
# of.write( '"{0}"'.format( ';'.join([str(j) for j in i[f]]) ) )
elif matchedTypes[idx] == 'sa':
line += '"{0}"'.format( ';'.join(i[f]) )
# of.write( '"{0}"'.format( ';'.join(i[f]) ) )
line += '\t'
#of.write('\t')
of.write( line[:-1] + '\n' ) # line[:-1] because there's an extra tab at the end
# of.write('\n')
def matchHeaders(self, FieldsList, TypesList):
matchedFields = []
matchedTypes = []
for idxFL, fl in enumerate(FieldsList):
for idxF, f in enumerate(fl):
if f not in matchedFields:
matchedFields.append(f)
matchedTypes.append( TypesList[idxFL][idxF] )
return matchedFields, matchedTypes
def addRel(self, c, w):
self.matchedRels.append( {':START_ID':c, ':END_ID':w, ':TYPE':'KBmatch', 'KB':'M'} )
def matchNodes(self):
self.matchedRels = []
matched = 0
multiple_matched = 0
for idx, c in enumerate(self.cn.nd):
t = c[6:].replace('_', '+').split('/')
if len(t) > 1:
w = 'wn/' + t[0] + '-' + t[1]
if t[1] == 'a':
if w not in self.wn.nd:
w = w[:-1] + 's'
if w in self.wn.nd:
matched += 1
self.addRel(c, w)
else:
w = 'wn/' + t[0]
if w in self.wn.nd:
matched += 1
self.addRel(c, w)
else:
mf = False
for pos in ['n', 'v', 'a', 'r', 's']:
s = w + '-' + pos
if s in self.wn.nd:
matched += 1
self.addRel(c, s)
if mf == False:
mf = True
else:
|
mick-d/nipype | nipype/interfaces/afni/tests/test_auto_TCorrelate.py | Python | bsd-3-clause | 1,367 | 0.02414 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrelate
def test_T | Correlate_inputs():
input_map = dict(args=d | ict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
num_threads=dict(nohash=True,
usedefault=True,
),
out_file=dict(argstr='-prefix %s',
name_source='xset',
name_template='%s_tcorr',
),
outputtype=dict(),
pearson=dict(argstr='-pearson',
),
polort=dict(argstr='-polort %d',
),
terminal_output=dict(deprecated='1.0.0',
nohash=True,
),
xset=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=-2,
),
yset=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=-1,
),
)
inputs = TCorrelate.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_TCorrelate_outputs():
output_map = dict(out_file=dict(),
)
outputs = TCorrelate.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
|
sfu-rcg/ampush | amlib/conf.py | Python | mit | 1,274 | 0 | import os
from ConfigParser import ConfigParser
from amlib import argp
tmp_conf = ConfigParser()
tmp_path = os.path.dirname(os.path.abspath(__file__)) # /base/lib/here
tmp_path = tmp_path.split('/')
conf_path = '/'.join(tmp_path[0:-1]) # /base/lib
tmp_conf.read(conf_path+'/ampush.conf')
c = {}
c.update(tmp_conf.items('default'))
# select target AD container: default or user-specified with --mode?
if argp.a['mode'] is not None:
try:
container_conf_key = 'am_container_' + argp.a['mode']
c['am_container'] = c[container_conf_key]
except KeyError:
log_msg = 'Terminating. No such parameter in ampush.conf: ' + \
container_conf_key
raise Exception(log_msg)
else:
c['am_container'] = c['am_container_default']
# sele | ct alternate flat file automount maps: default o | r user-specified
# set passed via --source?
if argp.a['source'] is not None:
try:
ff_map_dir_conf_key = 'flat_file_map_dir_' + argp.a['source']
c['flat_file_map_dir'] = c[ff_map_dir_conf_key]
except KeyError:
log_msg = 'Terminating. No such parameter in ampush.conf: ' + \
ff_map_dir_conf_key
raise Exception(log_msg)
else:
c['flat_file_map_dir'] = c['flat_file_map_dir_default']
|
mariocesar/namegenerator | codenamegenerator/__main__.py | Python | mit | 1,218 | 0.001642 | import argparse
from . import dictionary_sample, generate_codenames
def main():
parser = argparse.ArgumentParser(
prog="codenamegenerator", description="Code name generator"
)
parser.add_argument("num", type=int, default=1)
parser.add_argument("-c", "--capitalize", action="store_true", d | efault=False)
parser.add_argument("-t", "--title", action="store_true", default=False)
parser.add_argum | ent("-s", "--slugify", action="store_true", default=False)
parser.add_argument("--prefix", help="Prefix dictionary", default="adjectives")
parser.add_argument(
"--suffix",
help="Suffix dictionary",
default="mobi_notable_scientists_and_hackers",
)
args = parser.parse_args()
for codename in generate_codenames(
prefix=args.prefix, suffix=args.suffix, num=args.num
):
if args.capitalize:
codename = codename.capitalize()
elif args.title:
codename = codename.title()
elif args.slugify:
codename = codename.replace(" ", "_")
else:
codename = codename.lower()
# TODO: support output formats: plain, csv, json, xml
print(codename)
main()
|
robbiet480/home-assistant | homeassistant/components/plugwise/climate.py | Python | apache-2.0 | 9,147 | 0.000219 | """Plugwise Climate component for Home Assistant."""
import logging
from Plugwise_Smile.Smile import Smile
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from homeassistant.core import callback
from . import SmileGateway
from .const import DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP, DOMAIN, SCHEDULE_OFF, SCHEDULE_ON
HVAC_MODES_HEAT_ONLY = [HVAC_MODE_HEAT, HVAC_MODE_AUTO]
HVAC_MODES_HEAT_COOL = [HVAC_MODE_HEAT_COOL, HVAC_MODE_AUTO]
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Smile Thermostats from a config entry."""
api = hass.data[DOMAIN][config_entry.entry_id]["api"]
coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"]
entities = []
thermostat_classes = [
"thermostat",
"zone_thermostat",
"thermostatic_radiator_valve",
]
all_devices = api.get_all_devices()
for dev_id, device_properties in all_devices.items():
if device_properties["class"] not in thermostat_classes:
continue
thermostat = PwThermostat(
api,
coordinator,
device_properties["name"],
dev_id,
device_properties["location"],
device_properties["class"],
DEFAULT_MIN_TEMP,
DEFAULT_MAX_TEMP,
)
entities.append(thermostat)
async_add_entities(entities, True)
class PwThermostat(SmileGateway, ClimateEntity):
"""Representation of an Plugwise thermostat."""
def __init__(
self, api, coordinator, name, dev_id, loc_id, model, min_temp, max_temp
):
"""Set up the Plugwise API."""
super().__init__(api, coordinator, name, dev_id)
self._api = api
self._loc_id = loc_id
self._model = model
self._min_temp = min_temp
self._max_temp = max_temp
self._selected_schema = None
self._last_active_schema = None
self._preset_mode = None
self._presets = None
self._presets_list = None
self._heating_state = None
self._cooling_state = None
self._compressor_state = None
self._dhw_state = None
self._hvac_mode = None
self._schema_names = None
self._schema_status = None
self._temperature = None
self._setpoint = None
self._water_pressure = None
self._schedule_temp = None
self._hvac_mode = None
self._single_thermostat = self._api.single_master_thermostat()
self._unique_id = f"{dev_id}-climate"
@property
def hvac_action(self):
"""Return the current action."""
if self._single_thermostat:
if self._heating_state:
return CURRENT_HVAC_HEAT
if self._cooling_state:
return CURRENT_HVAC_COOL
return CURRENT_HVAC_IDLE
if self._heating_state is not None:
if self._setpoint > self._temperature:
return CURRENT_HVAC_HEAT
return CURRENT_HVAC_IDLE
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def device_state_attributes(self):
"""Return the device specific state attributes."""
attributes = {}
if self._schema_names:
attributes["available_schemas"] = self._schema_names
if self._selected_schema:
attributes["selected_schema"] = self._selected_schema
return attributes
@property
def preset_modes(self):
"""Return the available preset modes list."""
return self._presets_list
@property
def hvac_modes(self):
"""Return the available hvac modes list."""
if self._heating_state is not None:
if self._compressor_state is not None:
return HVAC_MODES_HEAT_COOL
return HVAC_MODES_HEAT_ONLY
@property
def hvac_mode(self):
"""Return current | active hvac state."""
return self._hvac_mode
@property
def target_temperature(self):
"""Return the target_temperature."""
return self._setpoint
@property
def preset_mode(self):
"""Return the active preset."""
if self._presets:
return self._preset_mode
retur | n None
@property
def current_temperature(self):
"""Return the current room temperature."""
return self._temperature
@property
def min_temp(self):
"""Return the minimal temperature possible to set."""
return self._min_temp
@property
def max_temp(self):
"""Return the maximum temperature possible to set."""
return self._max_temp
@property
def temperature_unit(self):
"""Return the unit of measured temperature."""
return TEMP_CELSIUS
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if (temperature is not None) and (
self._min_temp < temperature < self._max_temp
):
try:
await self._api.set_temperature(self._loc_id, temperature)
self._setpoint = temperature
self.async_write_ha_state()
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
else:
_LOGGER.error("Invalid temperature requested")
async def async_set_hvac_mode(self, hvac_mode):
"""Set the hvac mode."""
state = SCHEDULE_OFF
if hvac_mode == HVAC_MODE_AUTO:
state = SCHEDULE_ON
try:
await self._api.set_temperature(self._loc_id, self._schedule_temp)
self._setpoint = self._schedule_temp
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
try:
await self._api.set_schedule_state(
self._loc_id, self._last_active_schema, state
)
self._hvac_mode = hvac_mode
self.async_write_ha_state()
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
async def async_set_preset_mode(self, preset_mode):
"""Set the preset mode."""
try:
await self._api.set_preset(self._loc_id, preset_mode)
self._preset_mode = preset_mode
self._setpoint = self._presets.get(self._preset_mode, "none")[0]
self.async_write_ha_state()
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
@callback
def _async_process_data(self):
"""Update the data for this climate device."""
climate_data = self._api.get_device_data(self._dev_id)
heater_central_data = self._api.get_device_data(self._api.heater_id)
if "setpoint" in climate_data:
self._setpoint = climate_data["setpoint"]
if "temperature" in climate_data:
self._temperature = climate_data["temperature"]
if "schedule_temperature" in climate_data:
self._schedule_temp = climate_data["schedule_temperature"]
if "available_schedules" in climate_data:
self._schema_names = climate_data["available_schedules"]
if "selected_schedule" in climate_data:
self._selected_schema = climate_data["selected_schedule"]
self._schema_status = False
if self._selected_schema is not None:
self._schema_status = True
if "last_used" in climate_data:
self._last_active_schema = climate_data["last_used"]
if "presets" in climate_data:
|
jasonwbw/jason_putils | putils/io/file_iter.py | Python | apache-2.0 | 1,029 | 0.003887 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
This is a tool for file iterate
@Author : Jasonwbw@yahoo.com
'''
import numpy
from itertools import izip
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def to_unicode(text, encoding='utf8', errors='strict'):
"""Convert a string (bytestring in `encoding` or unicode), to unicode."""
if isinstance(text, unicode):
return text
return unicode(text, encoding, errors=errors)
class LineSentence(object):
|
"""Simple format: one sentence = one line; words already preprocessed and separated by whitespace."""
def __init__(self, source):
"""
`source` can be either a string or a file object.
Example:
sentences = LineSentence('myfile.txt')
"""
self.source = source
def __iter__(self):
"""Iterate through the lines in the source."""
with open(self.source, 'rb') as fin:
for | line in fin:
yield to_unicode(line) |
dimagi/rapidsms-contrib-apps-dev | scheduler/views.py | Python | bsd-3-clause | 1,431 | 0.004892 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
from rapidsms.utils.pagination import paginated
from rapidsms.contrib.scheduler.models import EventSchedule
from rapidsms.contrib.scheduler.forms import ScheduleForm
@login_required
def index(request, template="scheduler/index.html"):
context = {}
schedules = EventSchedule.objects.all()
context['schedules'] = paginated(request, schedules)
return render_to_response(template, context, context_instance=RequestContext(request))
@login_required
def edit(request, pk, template="scheduler/edit.html"):
context = {}
schedule = get_object_or_404(EventSchedule, id=pk)
if request.met | hod == 'POST':
form = ScheduleForm(request.POST, instance= | schedule)
if form.is_valid():
form.save()
context['status'] = _("Schedule '%(name)s' successfully updated" % \
{'name':schedule.callback} )
else:
context['errors'] = form.errors
else:
form = ScheduleForm(instance=schedule)
context['form'] = form
context['schedule'] = schedule
return render_to_response(template, context, context_instance=RequestContext(req))
|
jeffthemaximum/jeffPD | config.py | Python | mit | 1,272 | 0.002358 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'frey.maxim@gmail.com'
MAIL_PASSWORD = 'Airjeff3'
FLASKY_MAIL_SUBJECT_PREFIX = '[JeffPD]'
FLASKY_MAIL_SENDER = 'frey.maxim@gmail.com'
FLASKY_ADMIN = 'frey.maxim@gmail.com'
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com: | 5432/d8hosmtv1eijgp'
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
class ProductionConfig(Config):
SQ | LALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
|
benosment/generators | generators-for-system-programmers/retuple.py | Python | gpl-2.0 | 417 | 0.01199 | # retuple.py
#
# Read a sequence of log lines and parse them into a sequence of tuples
loglines = open("access-log")
import re
log | pats = r'(\S+) (\S+) (\S+) \[(.*?)\] ' \
r'"(\S+) (\S+) (\S+)" (\S+) (\S+)'
logpat = re.compile(logpats)
groups = (logpat.match(line) for line in loglines)
tuples = (g.groups() f | or g in groups if g)
if __name__ == '__main__':
for t in tuples:
print t
|
box/box-python-sdk | test/functional/test_token_refresh.py | Python | apache-2.0 | 767 | 0.001304 | import pytest
from boxsdk.exception import BoxOAuthException
def test_expired_access_token_is_refreshed(box_oauth, box_client, mock_box):
# pylint:disable=protected-access
mock_box.oauth.expire_token(box_oa | uth._access_token)
# pylint:enable=protected-access
box_client.folder('0').get()
assert len(mock_box.requests) == 6 # GET /authorize, POST /authorize, /token, get_info, refresh /token, get_info
def test_expired_refresh_token_raises(box_oauth, box_client, mock_box):
# pylint:disable=protected-access
mock_box.oauth.expire_token(box_oauth._access_token)
mock_box.oauth.expire_token(box_oauth._refresh_token)
# pylint:enable=protected-access
with p | ytest.raises(BoxOAuthException):
box_client.folder('0').get()
|
mava-ar/sgk | src/dj_auth/signals.py | Python | apache-2.0 | 408 | 0 | from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from django.db.models.signals import post_save
from django.dispatch impor | t receiver
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
"""
Cr | eates a token whenever a User is created
"""
if created:
Token.objects.create(user=instance)
|
hsadler/con-science-twitter-bot | models/error_log.py | Python | mit | 1,068 | 0.0103 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Error Log model
import logging
logger = logging.getLogger('con_science_bot')
hdlr = logging.FileHandler('logs/error.log')
formatter = logging.Formatter('\n%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
import pprint
pp = pprint.PrettyPrinter(indent=4)
class ErrorLog:
def __init__(self, message):
self.message = message
# create instance from exception error
@classmethod
def log_exception(cls, message):
exception = cls(message=message)
logger.exception(exception.message)
return exception
# create instance from info
@classmethod
def log_info(cls, message):
info = cls(message=message)
logger.info(info.message)
return info
# test the logger
@classmethod
def test_error(cls):
try:
1/0
| except:
error_message = 'i am a test error message'
error = cls.log_e | xception(error_message)
|
realms-team/solmanager | libs/smartmeshsdk-REL-1.3.0.1/external_libs/cryptopy/crypto/passwords/__init__.py | Python | bsd-3-clause | 179 | 0.005587 | """ CryptoPy - a pure python cryptographic libraries
crypto.passwords package
Copyright (c) 2002 by P | aul A. Lambert
Read LICENS | E.txt for license information.
"""
|
superstack/nova | nova/tests/test_api.py | Python | apache-2.0 | 17,953 | 0.00039 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Unit tests for the API endpoint"""
import boto
from boto.ec2 import regioninfo
from boto.exception import EC2ResponseError
import datetime
import httplib
import random
import StringIO
import webob
from nova import context
from nova import exception
from nova import test
from nova.api import ec2
from nova.api.ec2 import apirequest
from nova.api.ec2 import cloud
from nova.api.ec2 import ec2utils
from nova.auth import manager
class FakeHttplibSocket(object):
"""a fake socket implementation for httplib.HTTPResponse, trivial"""
def __init__(self, response_string):
self.response_string = response_string
self._buffer = StringIO.StringIO(response_string)
def makefile(self, _mode, _other):
"""Returns the socket's internal buffer"""
return self._buffer
class FakeHttplibConnection(object):
"""A fake httplib.HTTPConnection for boto to use
requests made via this connection actually get translated and routed into
our WSGI app, we then wait for the response and turn it back into
the httplib.HTTPResponse that boto expects.
"""
def __init__(self, app, host, is_secure=False):
self.app = app
self.host = host
def request(self, method, path, data, headers):
req = webob.Request.blank(path)
req.method = method
req.body = data
req.headers = headers
req.headers['Accept'] = 'text/html'
req.host = self.host
# Call the WSGI app, get the HTTP response
resp = str(req.get_response(self.app))
# For some reason, the response doesn't have "HTTP/1.0 " prepended; I
# guess that's a function the web server usually provides.
resp = "HTTP/1.0 %s" % resp
self.sock = FakeHttplibSocket(resp)
self.http_response = httplib.HTTPResponse(self.sock)
self.http_response.begin()
def getresponse(self):
return self.http_response
def getresponsebody(self):
return self.sock.response_string
def close(self):
"""Required for compatibility with boto/tornado"""
pass
class XmlConversionTestCase(test.TestCase):
"""Unit test api xml conversion"""
def test_number_conversion(self):
conv = apirequest._try_convert
self.assertEqual(conv('None'), None)
self.assertEqual(conv('True'), True)
self.assertEqual(conv('False'), False)
self.assertEqual(conv('0'), 0)
self.assertEqual(conv('42'), 42)
self.assertEqual(conv('3.14'), 3.14)
self.assertEqual(conv('-57.12'), -57.12)
self.assertEqual(conv('0x57'), 0x57)
self.assertEqual(conv('-0x57'), -0x57)
self.assertEqual(conv('-'), '-')
self.assertEqual(conv('-0'), 0)
class Ec2utilsTestCase(test.TestCase):
def test_ec2_id_to_id(self):
self.assertEqual(ec2utils.ec2_id_to_id('i-0000001e'), 30)
self.assertEqual(ec2utils.ec2_id_to_id('ami-1d'), 29)
def test_bad_ec2_id(self):
self.assertRaises(exception.InvalidEc2Id,
ec2utils.ec2_id_to_id,
'badone')
def test_id_to_ec2_id(self):
self.assertEqual(ec2utils.id_to_ec2_id(30), 'i-0000001e')
self.assertEqual(ec2utils.id_to_ec2_id(29, 'ami-%08x'), 'ami-0000001d')
class ApiEc2TestCase(test.TestCase):
"""Unit test for the cloud controller on an EC2 API"""
def setUp(self):
super(ApiEc2TestCase, self).setUp()
self.manager = manager.AuthManager()
self.host = '127.0.0.1'
self.app = ec2.Authenticate(ec2.Requestify(ec2.Executor(),
'nova.api.ec2.cloud.CloudController'))
def expect_http(self, host=None, is_secure=False, api_version=None):
"""Returns a new EC2 connection"""
self.ec2 = boto.connect_ec2(
aws_access_key_id='fake',
aws_secret_access_key='fake',
is_secure=False,
region=regioninfo.RegionInfo(None, 'test', self.host),
port=8773,
path='/services/Cloud')
if api_version:
self.ec2.APIVersion = api_version
self.mox.StubOutWithMock(self.ec2, 'new_http_connection')
self.http = FakeHttplibConne | ction(
self.app, '%s:8773' % (self.host), False)
# pylint: disable=E1103
self.ec2.new_http_connection(host, is_secure).AndReturn(self.http)
return self.http
def test_return_valid_isoformat(self):
"""
Ensure that the ec2 api returns datetime in xs:dateTime
(which appar | ently isn't datetime.isoformat())
NOTE(ken-pepple): https://bugs.launchpad.net/nova/+bug/721297
"""
conv = apirequest._database_to_isoformat
# sqlite database representation with microseconds
time_to_convert = datetime.datetime.strptime(
"2011-02-21 20:14:10.634276",
"%Y-%m-%d %H:%M:%S.%f")
self.assertEqual(
conv(time_to_convert),
'2011-02-21T20:14:10Z')
# mysqlite database representation
time_to_convert = datetime.datetime.strptime(
"2011-02-21 19:56:18",
"%Y-%m-%d %H:%M:%S")
self.assertEqual(
conv(time_to_convert),
'2011-02-21T19:56:18Z')
def test_xmlns_version_matches_request_version(self):
self.expect_http(api_version='2010-10-30')
self.mox.ReplayAll()
user = self.manager.create_user('fake', 'fake', 'fake')
project = self.manager.create_project('fake', 'fake', 'fake')
# Any request should be fine
self.ec2.get_all_instances()
self.assertTrue(self.ec2.APIVersion in self.http.getresponsebody(),
'The version in the xmlns of the response does '
'not match the API version given in the request.')
self.manager.delete_project(project)
self.manager.delete_user(user)
def test_describe_instances(self):
"""Test that, after creating a user and a project, the describe
instances call to the API works properly"""
self.expect_http()
self.mox.ReplayAll()
user = self.manager.create_user('fake', 'fake', 'fake')
project = self.manager.create_project('fake', 'fake', 'fake')
self.assertEqual(self.ec2.get_all_instances(), [])
self.manager.delete_project(project)
self.manager.delete_user(user)
def test_terminate_invalid_instance(self):
"""Attempt to terminate an invalid instance"""
self.expect_http()
self.mox.ReplayAll()
user = self.manager.create_user('fake', 'fake', 'fake')
project = self.manager.create_project('fake', 'fake', 'fake')
self.assertRaises(EC2ResponseError, self.ec2.terminate_instances,
"i-00000005")
self.manager.delete_project(project)
self.manager.delete_user(user)
def test_get_all_key_pairs(self):
"""Test that, after creating a user and project and generating
a key pair, that the API call to list key pairs works properly"""
self.expect_http()
self.mox.ReplayAll()
keyname = "".join(random.choice("sdiuisudfsdcnpaqwertasd") \
|
goblinhack/MundusMeus | python/things/snow_deco.py | Python | lgpl-3.0 | 875 | 0.001143 | import tp
import mm
def th | ing_init(t):
return
def snow_deco1_init(name, short_name, tiles=[]):
x = tp.Tp(name)
x.set_short_name(short_name)
x.set_z_depth(mm.Z_DEPTH_SNOW)
x.set_is_snow_deco(True)
if tile | s is not None:
for t in tiles:
x.set_tile(t, delay_ms=50)
else:
x.set_tile(tile=name, delay_ms=50)
x.thing_init = thing_init
return x
def init():
snow_deco1_init(name="snow_deco",
short_name="Snow",
tiles=[
"snow_tl",
"snow_top",
"snow_tr",
"snow_left",
"snow_right",
"snow_bl",
"snow_bot",
"snow_br",
])
init()
|
ukBaz/ble_beacon | examples/workshop3.py | Python | gpl-2.0 | 635 | 0 | from scanner import protocols, hci_socket
import base64
for pkt in hci_socket.run():
ad = protocols.AdvertEventHandler(pkt)
if ad.eddystone_uid:
print(f'\nBeacon instance id: {ad.eddystone_uid.instance_id}'
f' @ ({ad.address[-5:]})')
if ad.eddystone_uid.instance_id == 0xbb:
namespace_bytes = ad.ed | dystone_uid.data_in[1:11]
h | idden_word = base64.b85decode(namespace_bytes).decode("utf-8")
print(f'Namespace Value:\t{ad.eddystone_uid.namespace_id}')
print(f'Namespace Bytes:\t{namespace_bytes}')
print(f'Hidden word: \t{hidden_word}')
|
assem-ch/snowball | python/stemwords.py | Python | bsd-3-clause | 3,277 | 0.001526 | import sys
import re
import codecs
import snowballstemmer
def usage():
print('''usage: %s [-l <language>] [-i <input file>] [-o <output file>] [-c <character encoding>] [-p[2]] [-h]
The input file consists of a list of words to be stemmed, one per
line. Words should be in lower case, but (for English) A-Z letters
are mapped to their a-z equivalents anyway. If omitted, stdin is
used.
If -c is given, the argument is the character encoding of the input
and output files. If it is omitted, the UTF-8 encoding is used.
If -p is given the output file consists of each word of the input
file followed by \"->\" followed by its stemmed equivalent.
If -p2 is given the output file is a two column layout containing
the input words in the first column and the stemmed eqivalents in
the second column.
Otherwise, the output file consists of the stemmed words, one per
line.
-h displays this help''' % sys.argv[0])
def main():
argv = sys.argv[1:]
if len(argv) < 5:
usage()
else:
pretty = 0
input = ''
output = ''
encoding = 'utf_8'
language = 'English'
show_help = False
while len(argv):
arg = argv[0]
argv = argv[1:]
if arg == '-h':
show_help = True
break
elif arg == "-p":
pretty = 1
elif arg == "-p2":
pretty = 2
elif arg == "-l":
if len(argv) == 0:
show_help = True
break
language = argv[0]
argv = argv[1:]
elif arg == "-i":
if len(argv) == 0:
show_help = True
break
input = argv[0]
argv = argv[1:]
elif arg == "-o":
if len(argv) == 0:
show_help = True
break
output = argv[0]
argv = argv[1:]
elif arg == "-c":
if len(argv) == 0:
show_help = True
break
encoding = argv[0]
if show_help or | input == '' or output == '':
usage()
else:
stemming(language, input, output, encoding, pretty)
def stemming(lang, input, output, encoding, pretty):
stemmer = snowballstemmer.stemmer(lang)
outfile = codecs.open(output, "w", encoding)
for original in codecs.open(input, "r", encoding).readlines():
original = original.strip()
# Convert only ASCII-lett | ers to lowercase, to match C behavior
original = ''.join((lower_(c) if 'A' <= c <= 'Z' else c for c in original))
stemmed = stemmer.stemWord(original)
if pretty == 0:
if stemmed != "":
outfile.write(stemmed)
elif pretty == 1:
outfile.write(original, " -> ", stemmed)
elif pretty == 2:
outfile.write(original)
if len(original) < 30:
outfile.write(" " * (30 - len(original)))
else:
outfile.write("\n")
outfile.write(" " * 30)
outfile.write(stemmed)
outfile.write('\n')
outfile.close()
main()
|
sharescience/ardupilot | Tools/scripts/build_binaries.py | Python | gpl-3.0 | 26,405 | 0.000227 | #!/usr/bin/env python
"""
script to build the latest binaries for each vehicle type, ready to upload
Peter Barker, August 2017
based on build_binaries.sh by Andrew Tridgell, March 2013
"""
from __future__ import print_function
import datetime
import optparse
import os
import re
import shutil
import time
import subprocess
import sys
import zlib
# local imports
import generate_manifest
class build_binaries(object):
def __init__(self, tags):
self.tags = tags
self.dirty = False
def progress(self, string):
'''pretty-print progress'''
print("BB: %s" % string)
def run_git(self, args):
'''run git with args git_args; returns git's output'''
cmd_list = ["git"]
cmd_list.extend(args)
return self.run_program("BB-GIT", cmd_list)
def board_branch_bit(self, board):
'''return a fragment which might modify the branch name.
this was previously used to have a master-AVR branch etc
if the board type was apm1 or apm2'''
return None
def board_options(self, board):
'''return board-specific options'''
if board == "bebop":
return ["--static"]
return []
def run_waf(self, args):
if os.path.exists("waf"):
waf = "./waf"
else:
waf = os.path.join(".", "modules", "waf", "waf-light")
cmd_list = [waf]
cmd_list.extend(args)
self.run_program("BB-WAF", cmd_list)
def run_program(self, prefix, cmd_list):
self.progress("Running (%s)" % " ".join(cmd_list))
p = subprocess.Popen(cmd_list, bufsize=1, stdin=None,
stdout=subprocess.PIPE, close_fds=True,
stderr=subprocess.STDOUT)
output = ""
while True:
x = p.stdout.readline()
if len(x) == 0:
returncode = os.waitpid(p.pid, 0)
if returncode:
break
# select not available on Windows... probably...
time.sleep(0.1)
continue
output += x
x = x.rstrip()
print("%s: %s" % (prefix, x))
(_, status) = returncode
if status != 0:
self.progress("Process failed (%s)" %
str(returncode))
raise subprocess.CalledProcessError(
returncode, cmd_list)
return output
def run_make(self, args):
cmd_list = ["make"]
cmd_list.extend(args)
self.run_program("BB-MAKE", cmd_list)
def run_git_update_submodules(self):
'''if submodules are present initialise and update them'''
if os.path.exists(os.path.join(self.basedir, ".gitmodules")):
self.run_git(["submodule",
"update",
"--init",
"--recursive",
"-f"])
def checkout(self, vehicle, ctag, cboard=None, cframe=None):
'''attempt to check out a git tree. Various permutations are
attempted based on ctag - for examplle, if the board is avr and ctag
is bob we will attempt to checkout bob-AVR'''
if self.dirty:
self.progress("Skipping checkout for dirty build")
return True
self.progress("Trying checkout %s %s %s %s" %
(vehicle, ctag, cboard, cframe))
self.run_git(['stash'])
if ctag == "latest":
vtag = "master"
else:
vtag = "%s-%s" % (vehicle, ctag)
branches = []
if cframe is not None:
# try frame specific tag
branches.append("%s-%s" % (vtag, cframe))
if cboard is not None:
bbb = self.board_branch_bit(cboard)
if bbb is not None:
# try board type specific branch extension
branches.append("".join([vtag, bbb]))
branches.append(vtag)
for branch in branches:
try:
self.progress("Trying branch %s" % branch)
self.run_git(["checkout", "-f", branch])
self.run_git_update_submodules()
self.run_git(["log", "-1"])
return True
except subprocess.CalledProcessError as e:
self.progress("Checkout branch %s failed" % branch)
pass
self.progress("Failed to find tag for %s %s %s %s" %
(vehicle, ctag, cboard, cframe))
return False
def skip_board_waf(self, board):
'''check if we should skip this build because we don't support the
board in this release
'''
try:
if self.string_in_filepath(board,
os.path.join(self.basedir,
'Tools',
'ardupilotwaf',
'boards.py')):
return False
except IOError as e:
if e. | errno != 2:
raise
# see if there's a hwdef.dat for this board:
if os.path.exists(os.path.join(self.basedir,
'libraries',
'AP_HAL_ChibiOS',
'hwdef',
| board)):
self.progress("ChibiOS build: %s" % (board,))
return False
self.progress("Skipping unsupported board %s" % (board,))
return True
def skip_frame(self, board, frame):
'''returns true if this board/frame combination should not be built'''
if frame == "heli":
if board in ["bebop", "aerofc-v1", "skyviper-v2450"]:
self.progress("Skipping heli build for %s" % board)
return True
return False
def first_line_of_filepath(self, filepath):
'''returns the first (text) line from filepath'''
with open(filepath) as fh:
line = fh.readline()
return line
def skip_build(self, buildtag, builddir):
'''check if we should skip this build because we have already built
this version
'''
if os.getenv("FORCE_BUILD", False):
return False
if not os.path.exists(os.path.join(self.basedir, '.gitmodules')):
self.progress("Skipping build without submodules")
return True
bname = os.path.basename(builddir)
ldir = os.path.join(os.path.dirname(os.path.dirname(
os.path.dirname(builddir))), buildtag, bname) # FIXME: WTF
oldversion_filepath = os.path.join(ldir, "git-version.txt")
if not os.path.exists(oldversion_filepath):
self.progress("%s doesn't exist - building" % oldversion_filepath)
return False
oldversion = self.first_line_of_filepath(oldversion_filepath)
newversion = self.run_git(["log", "-1"])
newversion = newversion.splitlines()[0]
oldversion = oldversion.rstrip()
newversion = newversion.rstrip()
self.progress("oldversion=%s newversion=%s" %
(oldversion, newversion,))
if oldversion == newversion:
self.progress("Skipping build - version match (%s)" %
(newversion,))
return True
self.progress("%s needs rebuild" % (ldir,))
return False
def write_string_to_filepath(self, string, filepath):
'''writes the entirety of string to filepath'''
with open(filepath, "w") as x:
x.write(string)
def addfwversion_gitversion(self, destdir, src):
# create git-version.txt:
gitlog = self.run_git(["log", "-1"])
gitversion_filepath = os.path.join(destdir, "git-version.txt")
gitversion_content = gitlog
versionfile = os.path.join(src, "version.h")
if os.path.exists(versionfile):
content = self.read_string_from_filepath(versionfile)
match = re.search('define.THISFIRMWARE "([^"]+)"', content)
|
cordis/pyschema | pyschema/nodes.py | Python | mit | 2,017 | 0 | from decimal import Decimal as DecimalDecoder
try:
from bson import ObjectId as ObjectIdEncoder
except ImportError:
def ObjectIdEncoder(*args):
raise ImportWarning('`bson` module not found')
from pyschema.bases import BaseNode
__all__ = [
'Node',
'Str',
'Unicode',
'Int',
'Bool',
'Float',
'Decimal',
'ObjectId',
'Builder',
'Registry',
'List',
'Dict',
]
class Node(BaseNode):
default_encode = None
default_decode = None
def __init__(self, key=None, decode=None, encode=None):
super(Node, self).__init__(key)
if decode is None:
decode = self.default_decode
if encode is None:
encode = self.default_encode
self.decode = decode
self.encode = encode
class Str(Node):
default_decode = str
class Unicode(Node):
default_decode = unicode
class Int(Node):
default_decode = int
class Bool(Node):
default_decode = bool
class Float(Node):
default_decode = float
class Decimal(Node):
default_decode = DecimalDecoder
defa | ult_encode = str
class ObjectId(Node):
default_decode = str
default_encode = ObjectIdEncoder
class Builder(Node):
default_decode = dict
def __init__(self, schema_cls, key=None):
super(Builder, self).__init__(key=key)
self. | schema_cls = schema_cls
class Registry(Node):
def __init__(self, args_getter, registry, key=None):
super(Registry, self).__init__(key=key)
self.args_getter = args_getter
self.registry = registry
class List(Node):
default_decode = list
default_encode = list
def __init__(self, node, **kwargs):
super(List, self).__init__(**kwargs)
self.node = node
class Dict(Node):
default_decode = dict
default_encode = dict
def __init__(self, value_node, key_node=None, **kwargs):
super(Dict, self).__init__(**kwargs)
self.value_node = value_node
self.key_node = key_node or Str()
|
bussiere/pypyjs | website/demo/home/rfk/repos/pypy/lib_pypy/_ctypes/basics.py | Python | mit | 7,084 | 0.005788 |
import _rawffi
import _ffi
import sys
try: from __pypy__ import builtinify
except ImportError: builtinify = lambda f: f
keepalive_key = str # XXX fix this when provided with test
def ensure_objects(where):
try:
ensure = where._ensure_objects
except AttributeError:
return None
return ensure()
def store_reference(where, base_key, target):
if '_index' not in where.__dict__:
# shortcut
where._ensure_objects()[str(base_key)] = target
return
key = [base_key]
while '_index' in where.__dict__:
key.append(where.__dict__['_index'])
where = where.__dict__['_base']
real_key = ":".join([str(i) for i in key])
where._ensure_objects()[real_key] = target
class ArgumentError(Exception):
pass
class COMError(Exception):
"Raised when a COM method call failed."
def __init__(self, hresult, text, details):
self.args = (hresult, text, details)
self.hresult = hresult
self.text = text
self.details = details
class _CDataMeta(type):
def from_param(self, value):
if isinstance(value, self):
return value
try:
as_parameter = value._as_parameter_
except AttributeError:
raise TypeError("expected %s instance instead of %s" % (
self.__name__, type(value).__name__))
else:
return self.from_param(as_parameter)
def get_ffi_argtype(self):
if self._ffiargtype:
return self._ffiargtype
self._ffiargtype = _shape_to_ffi_type(self._ffiargshape)
return self._ffiargtype
def _CData_output(self, resbuffer, base=None, index=-1):
#assert isinstance(resbuffer, _rawffi.ArrayInstance)
"""Used when data exits ctypes and goes into user code.
'resbuffer' is a _rawffi array of length 1 containing the value,
and this returns a general Python object that corresponds.
"""
res = object.__new__(self)
res.__class__ = self
res.__dict__['_buffer'] = resbuffer
res.__dict__['_base'] = base
res.__dict__['_index'] = index
return res
def _CData_retval(self, resbuffer):
return self._CData_output(resbuffer)
def __mul__(self, other):
from _ctypes.array import create_array_type
return create_array_type(self, other)
__rmul__ = __mul__
def _is_pointer_like(self):
return False
def in_dll(self, dll, name):
return self.from_address(dll._handle.getaddressindll(name))
class CArgObject(object):
""" simple wrapper around buffer, just for the case of freeing
it afterwards
"""
def __init__(self, obj, buffer):
self._obj = obj
self._buffer = buffer
def __del__(self):
self._buffer.free()
self._buffer = None
def __repr__(self):
return '<CArgObject %r>' % (self._obj,)
def __eq__(self, other):
return self._obj == other
def __ne__(self, other):
return self._obj != other
class _CData(object):
""" The most basic object for all ctypes types
"""
__metaclass__ = _CDataMeta
_objects = None
_ffiargtype = None
def __init__(self, *args, **kwds):
raise TypeError("%s has no type" % (type(self),))
def _ensure_objects(self):
if '_objects' not in self.__dict__:
if '_index' in self.__dict__:
return None
self.__dict__['_objects'] = {}
return self._objects
def __ctypes_from_outparam__(self):
return self
def _get_buffer_for_param(self):
return self
def _get_buffer_value(self):
return self._buffer[0]
def _to_ffi_param(self):
if self.__class__._is_pointer_like():
return self._get_buffer_value()
else:
return self.value
def __buffer__(self):
return buffer(self._buffer)
def _get_b_base(self):
try:
return self._base
except AttributeError:
return None
_b_base_ = property(_get_b_base)
_b_needsfree_ = False
@builtinify
def sizeof(tp):
if not isinstance(tp, _CDataMeta):
if isinstance(tp, _CData):
tp = type(tp)
else:
raise TypeError("ctypes type or instance expected, got %r" % (
type(tp).__name__,))
return tp._sizeofinstances()
@builtinify
def alignment(tp):
if not isinstance(tp, _CDataMeta):
if isinstance(tp, _CData):
tp = type(tp)
else:
raise TypeError("ctypes type or instance expected, got %r" % (
type(tp).__name__,))
return tp._alignmentofinstances()
@builtinify
def byref(cdata):
# "pointer" is imported at the end of this module to avoid circular
# imports
return pointer(cdata)
def cdata_from_address(self, address):
# fix the address: turn it into as unsigned, in case it's a negative number
address = address & (sys.maxint * 2 + 1)
instance = self.__new__(self)
lgt = getattr(self, '_length_', 1)
instance._buffer = self._ffiarray.fromaddress(address, lgt)
return instance
@builtinify
def addressof(tp):
return tp._buffer.buffer
# ----------------------------------------------------------------------
def is_struct_shape(shape):
# see the corresponding code to set the shape in
# _ctypes.structure._set_shape
return (isinstance(shape, tuple) and
len(shape) == 2 and
isinstance(shape[0], _rawffi.Structure) and
shape[1] == 1)
def _shape_to_ffi_type(shape):
try:
return _shape_to_ffi_type.typemap[shape]
except KeyError:
pass
if is_struct_shape(shape):
return shape[0].get_ffi_type()
| #
assert False, 'unknown shape %s' % (shape,)
_shape_to_ffi_type.typemap = {
'c' : _ffi.types.char,
'b' : _ffi.types.sbyte,
'B' : _ffi.types.ubyte,
'h' : _ffi.types.sshort,
'u' : _ffi.types.unichar,
'H' : _ffi.types.ushort,
'i' : _ffi.types.sint,
'I' : _ffi.types.uint,
'l' : _ffi.types.slong,
'L' : _ffi.types.ulong,
'q' : _ffi.types.slonglong,
'Q' : _ffi.types.ulonglong,
| 'f' : _ffi.types.float,
'd' : _ffi.types.double,
's' : _ffi.types.void_p,
'P' : _ffi.types.void_p,
'z' : _ffi.types.void_p,
'O' : _ffi.types.void_p,
'Z' : _ffi.types.void_p,
'X' : _ffi.types.void_p,
'v' : _ffi.types.sshort,
'?' : _ffi.types.ubyte,
}
# called from primitive.py, pointer.py, array.py
def as_ffi_pointer(value, ffitype):
my_ffitype = type(value).get_ffi_argtype()
# for now, we always allow types.pointer, else a lot of tests
# break. We need to rethink how pointers are represented, though
if my_ffitype is not ffitype and ffitype is not _ffi.types.void_p:
raise ArgumentError("expected %s instance, got %s" % (type(value),
ffitype))
return value._get_buffer_value()
# used by "byref"
from _ctypes.pointer import pointer
|
ibmsoe/ImpalaPPC | tests/custom_cluster/test_spilling.py | Python | apache-2.0 | 3,129 | 0.008949 | # Copyright (c) 2014 Cloudera, 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.
import logging
import pytest
from copy import deepcopy
from tests.common.custom_cluster_test_suite import CustomClusterTestSuite
from tests.common.test_dimensions import (TestDimension,
create_single_exec_option_dimension,
create_parquet_dimension)
class TestSpillStress(CustomClusterTestSuite):
@classmethod
def get_workload(self):
return 'targeted-stress'
@classmethod
def setup_class(cls):
cls._start_impala_cluster(['--impalad_args=--"read_size=270000"',
'catalogd_args="--loa | d_catalog_i | n_background=false"'])
super(CustomClusterTestSuite, cls).setup_class()
def setup_method(self, method):
# We don't need CustomClusterTestSuite.setup_method() or teardown_method() here
# since we're not doing per-test method restart of Impala.
pass
def teardown_method(self, method):
pass
@classmethod
def add_test_dimensions(cls):
super(TestSpillStress, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
# Each client will get a different test id.
# TODO: this test takes extremely long so only run on exhaustive. It would
# be good to configure it so we can run some version on core.
TEST_IDS = xrange(0, 3)
NUM_ITERATIONS = [1]
cls.TestMatrix.add_dimension(TestDimension('test_id', *TEST_IDS))
cls.TestMatrix.add_dimension(TestDimension('iterations', *NUM_ITERATIONS))
@pytest.mark.stress
def test_spill_stress(self, vector):
# Number of times to execute each query
for i in xrange(vector.get_value('iterations')):
self.run_test_case('agg_stress', vector)
class TestSpilling(CustomClusterTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestSpilling, cls).add_test_dimensions()
cls.TestMatrix.clear_constraints()
cls.TestMatrix.add_dimension(create_parquet_dimension('tpch'))
cls.TestMatrix.add_dimension(create_single_exec_option_dimension())
# Reduce the IO read size. This reduces the memory required to trigger spilling.
@pytest.mark.execute_serially
@CustomClusterTestSuite.with_args(
impalad_args="--read_size=200000",
catalogd_args="--load_catalog_in_background=false")
def test_spilling(self, vector):
new_vector = deepcopy(vector)
# remove this. the test cases set this explicitly.
del new_vector.get_value('exec_option')['num_nodes']
self.run_test_case('QueryTest/spilling', new_vector)
|
tatarbrot/foraging | hive_com.py | Python | gpl-3.0 | 687 | 0.004367 | #!/usr/bin/env python
from hive import *
from bee import *
from random import random as rand
import numpy as np
class HiveCom(Hive):
def __init__(self, x, y, n_bees, grid_size, grid):
self.directions = []
Hive.__init__( | self, x, y, n_bees, grid_size, grid)
def assign_settings(self, b | ee):
Hive.assign_settings(self, bee)
# direction
if len(self.directions) == 0:
new_angle = bee.compute_angle()
else:
new_angle = self.directions.pop()
bee.angle = new_angle
def load_settings_from(self, bee):
self.directions.append(bee.message)
Hive.load_settings_from(self, bee)
|
MayankGo/ec2-api | ec2api/config.py | Python | apache-2.0 | 2,017 | 0 | # Copyright 2014
# The Cloudscaling Group, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITION | S OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_config import cfg
from oslo_db import options
from oslo_log import log
from ec2api import pa | ths
from ec2api import version
CONF = cfg.CONF
_DEFAULT_SQL_CONNECTION = 'sqlite:///' + paths.state_path_def('ec2api.sqlite')
_DEFAULT_LOG_LEVELS = ['amqp=WARN', 'amqplib=WARN', 'boto=WARN',
'qpid=WARN', 'sqlalchemy=WARN', 'suds=INFO',
'oslo.messaging=INFO', 'iso8601=WARN',
'requests.packages.urllib3.connectionpool=WARN',
'urllib3.connectionpool=WARN', 'websocket=WARN',
'keystonemiddleware=WARN', 'routes.middleware=WARN',
'stevedore=WARN', 'glanceclient=WARN']
_DEFAULT_LOGGING_CONTEXT_FORMAT = ('%(asctime)s.%(msecs)03d %(process)d '
'%(levelname)s %(name)s [%(request_id)s '
'%(user_identity)s] %(instance)s'
'%(message)s')
def parse_args(argv, default_config_files=None):
log.set_defaults(_DEFAULT_LOGGING_CONTEXT_FORMAT, _DEFAULT_LOG_LEVELS)
log.register_options(CONF)
options.set_defaults(CONF, connection=_DEFAULT_SQL_CONNECTION,
sqlite_db='ec2api.sqlite')
cfg.CONF(argv[1:],
project='ec2api',
version=version.version_info.version_string(),
default_config_files=default_config_files)
|
leapcode/soledad | src/leap/soledad/server/launcher.py | Python | gpl-3.0 | 1,831 | 0 | # -*- coding: utf-8 -*-
# launcher.py
# Copyright (C) 2017 LEAP
#
# 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/>.
"""
Soledad Server launcher.
"""
import argparse
import os
import sys
from twisted.scripts.twistd import run
from leap.soledad import server, __version__
STANDALONE = getattr(sys, 'frozen', False)
de | f parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='store_true',
help='Print the program versi | on.')
return parser.parse_args()
def here(module=None):
if STANDALONE:
# we are running in a |PyInstaller| bundle
return sys._MEIPASS
else:
if module:
return os.path.dirname(module.__file__)
else:
return os.path.dirname(__file__)
def run_server():
# maybe print version and exit
args = parse_args()
if args.version:
print __version__
return
# launch soledad server using twistd
tac = os.path.join(here(server), 'server.tac')
args = [
'--nodaemon',
'--pidfile=',
'--syslog',
'--prefix=soledad-server',
'--python=%s' % tac,
]
sys.argv[1:] = args
run()
if __name__ == '__main__':
run_server()
|
davebridges/ExperimentDB | experimentdb/__init__.py | Python | bsd-3-clause | 2,496 | 0.003205 | """The experimentDB is a web-based application for the storage, organization and communication of experimental data with a focus on molecular biology and biochemical data. This application also stores data regarding reagents, including antibodies, constructs and other biomolecules as well as tracks the distribution of reagents. There is also some preliminary interfaces to other web resources.
This project contains several sub-applications as described below:
Projects
--------
The intent of this app is to co-ordinate specific projects. Projects are intended to be large, grant-sized larger projects in the laboratory. Subprojects are intended to be smaller, potentially paper sized groups of experiments. An experiment can be part of one, none or several projects or subprojects.
Data
----
This package defines experiments and the related data associated with them. The Experiment model is the focus of this entire project. It contains details about protocols, notes, reagents and project details. Results are associated with Experiment objects allowing for an Experiment to contain several results.
Cloning
-------
The cloning app defines the parameters for the synthesis and maintenance of constructs generated as part of an experiment. Constructs can be generated via either cloning or mutagenesis and will result in a Cloning or Mutagenesis object respectively.
Proteins
--------
The proteins referenced by this application may be targets of an experiment or reagent. This app also contains more detailed information about specific proteins, normally as accessed from public databases using either external databases or through Biopython tools.
Reagents
--------
The reagents app stores information about all tools used in research, most of which are defined by a particular Experiment object. These include Primer, Cell (cell lines), Antibody, Strain, Chemical and Construct objects. These models are abstract base classes of a superclass ReagentInfo which defines most of the | common relevant information.
External
--------
The idea is to attribute particular models with references regarding external contacts or vendors or to link in specific references important to the experiments or projects.
D | atasets
--------
The datasets app contains data and views for some external databases. This may include external databases accessed directly or with a mirrored internal database. This module is fairly research-interest specific and will likely be removed eventually.
"""
|
guyinatuxedo/escape | buf_ovf/b4_64/exploit.py | Python | gpl-3.0 | 1,016 | 0.01378 | #Import the pwntools library.
from pwn import *
#The process is like an actualy command you run, so you will have to adjust the path if your exploit isn't in the same directory as the challenge.
target = process("./b4_64")
#Just receive the first line, which for our purposes isn't important.
target.recvline()
#Store the address of the buffer in a variable, and strip away the newline t | o prevent conversion issues
address = target.recvline().strip("\n")
#Convert the string to a hexidecimal
address = int(address, 16)
#Pack the hexidecimal in little endian for 32 bit systems
address = p64(address)
print address
#Store the shellcode in a variable
shellcode = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"
#Make the filler to reach the eip register
filler = "0"*381
#Craft the payload
payload = shellcode + filler + address
| #Send the payload
target.sendline(payload)
#Drop into interactive mode so you can use the shell
target.interactive()
|
openstack/zaqar | zaqar/tests/unit/transport/wsgi/v1_1/test_messages.py | Python | apache-2.0 | 25,080 | 0 | # Copyright (c) 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 datetime
from unittest import mock
import uuid
import ddt
import falcon
from oslo_serialization import jsonutils
from oslo_utils import timeutils
from testtools import matchers
from zaqar import tests as testing
from zaqar.tests.unit.transport.wsgi import base
from zaqar.transport import validation
@ddt.ddt
class TestMessagesMongoDB(base.V1_1Base):
config_file = 'wsgi_mongodb.conf'
@testing.requires_mongodb
def setUp(self):
super(TestMessagesMongoDB, self).setUp()
self.default_message_ttl = self.boot.transport._defaults.message_ttl
if self.conf.pooling:
for i in range(4):
uri = "%s/%s" % (self.mongodb_url, str(i))
doc = {'weight': 100, 'uri': uri}
self.simulate_put(self.url_prefix + '/pools/' + str(i),
body=jsonutils.dumps(doc))
self.assertEqual(falcon.HTTP_201, self.srmock.status)
self.project_id = '7e55e1a7e'
self.headers = {
'Client-ID': str(uuid.uuid4()),
'X-Project-ID': self.project_id
}
# TODO(kgriffs): Add support in self.simulate_* for a "base path"
# so that we don't have to concatenate against self.url_prefix
# all over the place.
self.queue_path = self.url_prefix + '/queues/fizbit'
self.messages_path = self.queue_path + '/messages'
doc = '{"_ttl": 60}'
self.simulate_put(self.queue_path, body=doc, headers=self.headers)
def tearDown(self):
self.simulate_delete(self.queue_path, headers=self.headers)
if self.conf.pooling:
for i in range(4):
self.simulate_delete(self.url_prefix + '/pools/' + str(i),
headers=self.headers)
super(TestMessagesMongoDB, self).tearDown()
def test_name_restrictions(self):
sample_messages = [
{'body': {'key': 'value'}, 'ttl': 200},
]
messages_path = self.url_prefix + '/queues/%s/messages'
sample_doc = jsonutils.dumps({'messages': sample_messages})
self.simulate_post(messages_path % 'Nice-Boat_2',
body=sample_doc, headers=self.headers)
self.assertEqual(falcon.HTTP_201, self.srmock.status)
self.simulate_post(messages_path % 'Nice-Bo@t',
body=sample_doc, headers=self.headers)
self.assertEqual(falcon.HTTP_400, self.srmock.status)
self.simulate_post(messages_path % ('_niceboat' * 8),
body=sample_doc, headers=self.headers)
self.assertEqual(falcon.HTTP_400, self.srmock.status)
def _test_post(self, sample_messages):
sample_doc = jsonutils.dumps({'messages': sample_messages})
result = self.simulate_post(self.messages_path,
body=sample_doc, headers=self.headers)
self.assertEqual(falcon.HTTP_201, self.srmock.status)
result_doc = jsonutils.loads(result[0])
msg_ids = self._get_msg_ids(self.srmock.headers_dict)
self.assertEqual(len(sample_messages), len(msg_ids))
expected_resources = [str(self.messages_path + '/' + id)
for id in msg_ids]
self.assertEqual(expected_resources, result_doc['resources'])
# NOTE(kgriffs): As of v1.1, "partial" is no longer given
# in the response document.
self.assertNotIn('partial', result_doc)
self.assertEqual(len(sample_messages), len(msg_ids))
lookup = dict([(m['ttl'], m['body']) fo | r m in sample_messages])
# Test GET on the message resource directly
# NOTE(cpp-cabrera): force the passing of time to age a message
timeu | tils_utcnow = 'oslo_utils.timeutils.utcnow'
now = timeutils.utcnow() + datetime.timedelta(seconds=10)
with mock.patch(timeutils_utcnow) as mock_utcnow:
mock_utcnow.return_value = now
for msg_id in msg_ids:
message_uri = self.messages_path + '/' + msg_id
headers = self.headers.copy()
headers['X-Project-ID'] = '777777'
# Wrong project ID
self.simulate_get(message_uri, headers=headers)
self.assertEqual(falcon.HTTP_404, self.srmock.status)
# Correct project ID
result = self.simulate_get(message_uri, headers=self.headers)
self.assertEqual(falcon.HTTP_200, self.srmock.status)
# Check message properties
message = jsonutils.loads(result[0])
self.assertEqual(message_uri, message['href'])
self.assertEqual(lookup[message['ttl']], message['body'])
self.assertEqual(msg_id, message['id'])
# no negative age
# NOTE(cpp-cabrera): testtools lacks GreaterThanEqual on py26
self.assertThat(message['age'],
matchers.GreaterThan(-1))
# Test bulk GET
query_string = 'ids=' + ','.join(msg_ids)
result = self.simulate_get(self.messages_path,
query_string=query_string,
headers=self.headers)
self.assertEqual(falcon.HTTP_200, self.srmock.status)
result_doc = jsonutils.loads(result[0])
expected_ttls = set(m['ttl'] for m in sample_messages)
actual_ttls = set(m['ttl'] for m in result_doc['messages'])
self.assertFalse(expected_ttls - actual_ttls)
actual_ids = set(m['id'] for m in result_doc['messages'])
self.assertFalse(set(msg_ids) - actual_ids)
def test_exceeded_payloads(self):
# Get a valid message id
self._post_messages(self.messages_path)
msg_id = self._get_msg_id(self.srmock.headers_dict)
# Bulk GET restriction
query_string = 'ids=' + ','.join([msg_id] * 21)
self.simulate_get(self.messages_path,
query_string=query_string, headers=self.headers)
self.assertEqual(falcon.HTTP_400, self.srmock.status)
# Listing restriction
self.simulate_get(self.messages_path,
query_string='limit=21',
headers=self.headers)
self.assertEqual(falcon.HTTP_400, self.srmock.status)
# Bulk deletion restriction
query_string = 'ids=' + ','.join([msg_id] * 22)
self.simulate_delete(self.messages_path,
query_string=query_string, headers=self.headers)
self.assertEqual(falcon.HTTP_400, self.srmock.status)
def test_post_single(self):
sample_messages = [
{'body': {'key': 'value'}, 'ttl': 200},
]
self._test_post(sample_messages)
def test_post_multiple(self):
sample_messages = [
{'body': 239, 'ttl': 100},
{'body': {'key': 'value'}, 'ttl': 200},
{'body': [1, 3], 'ttl': 300},
]
self._test_post(sample_messages)
def test_post_optional_ttl(self):
sample_messages = {
'messages': [
{'body': 239},
{'body': {'key': 'value'}, 'ttl': 200},
],
}
# Manually check default TTL is max from config
sample_doc = jsonutils.dumps(sample_messages)
result = self.simulate_post(self.messages_path,
body=sample_doc, headers=self.headers)
self.assertEqual(falcon.HTTP_201, self.srmock. |
grehujt/leetcode | 17. Letter Combinations of a Phone Number/solution.py | Python | mit | 707 | 0.004243 | class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
def fill(n):
if n == l:
result.append(''.join(combination))
return
for cs in ds[digits[n]]:
| for c in cs:
combination[n] = c
fill(n+1)
ds = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
l = len(digits)
if l < 1:
re | turn []
combination = ['x'] * l
result = []
fill(0)
return result
print Solution().letterCombinations('238')
|
wilsonkichoi/zipline | zipline/data/minute_bars.py | Python | apache-2.0 | 33,297 | 0 | # Copyright 2016 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 json
import os
from os.path import join
from textwrap import dedent
from cachetools import LRUCache
import bcolz
from bcolz import ctable
from intervaltree import IntervalTree
import numpy as np
import pandas as pd
from zipline.data._minute_bar_internal import (
minute_value,
find_position_of_minute,
find_last_traded_position_internal
)
from zipline.gens.sim_engine import NANOS_IN_MINUTE
from zipline.utils.cli import maybe_show_progress
from zipline.utils.memoize import lazyval
US_EQUITIES_MINUTES_PER_DAY = 390
DEFAULT_EXPECTEDLEN = US_EQUITIES_MINUTES_PER_DAY * 252 * 15
OHLC_RATIO = 1000
class BcolzMinuteOverlappingData(Exception):
pass
class BcolzMinuteWriterColumnMismatch(Exception):
pass
def _calc_minute_index(market_opens, minutes_per_day):
minutes = np.zeros(len(market_opens) * minutes_per_day,
dtype='datetime64[ns]')
deltas = np.arange(0, minutes_per_day, dtype='timedelta64[m]')
for i, market_open in enumerate(market_opens):
start = market_open.asm8
minute_values = start + deltas
start_ix = minutes_per_day * i
end_ix = start_ix + minutes_per_day
minutes[start_ix:end_ix] = minute_values
return pd.to_datetime(minutes, utc=True, box=True)
def _sid_subdir_path(sid):
"""
Format subdir path to limit the number directories in any given
subdirectory to 100.
The number in each directory is designed to support at least 100000
equities.
Parameters:
-----------
sid : int
Asset identifier.
Returns:
--------
out : string
A path for the bcolz rootdir, including subdirectory prefixes based on
the padded string representation of the given sid.
e.g. 1 is formatted as 00/00/000001.bcolz
"""
padded_sid = format(sid, '06')
return os.path.join(
# subdir 1 00/XX
padded_sid[0:2],
# subdir 2 XX/00
padded_sid[2:4],
"{0}.bcolz".format(str(padded_sid))
)
class BcolzMinuteBarMetadata(object):
"""
Parameters
----------
first_trading_day : datetime-like
UTC midnight of the first day available in the dataset.
minute_index : pd.DatetimeIndex
The minutes which act as an index into the corresponding values
written into each sid's ctable.
market_opens : pd.DatetimeIndex
The market opens for each day in the data set. (Not yet required.)
market_closes : pd.DatetimeIndex
The market closes for each day in the data set. (Not yet required.)
ohlc_ratio : int
The factor by which the pricing data is multiplied so that the
float data can be stored as an integer.
"""
METADATA_FILENAME = 'metadata.json'
@classmethod
def metadata_path(cls, rootdir):
return os.path.join(rootdir, cls.METADATA_FILENAME)
@classmethod
def read(cls, rootdir):
path = cls.metadata_path(rootdir)
with open(path) as fp:
raw_data = json.load(fp)
first_trading_day = pd.Timestamp(
raw_data['first_trading_day'], tz='UTC')
market_opens = pd.to_datetime(raw_data['market_opens'],
unit='m',
utc=True)
market_closes = pd.to_datetime(raw_data['market_closes'],
unit='m',
utc=True)
ohlc_ratio = raw_data['ohlc_ratio']
return cls(first_trading_day,
market_opens,
market_closes,
ohlc_ratio)
def __init__(self, first_trading_day,
| market_opens,
market_closes,
ohlc_ratio):
self.first_trading_day = first_trading_day
self.market_opens = market_opens
self.market_closes = market_closes
self.ohlc_ratio = ohlc_ratio
def write(self, rootdir):
"""
Write the metadata to a JSON file in the rootdir.
Values contained in the metadata are:
first_trading_day | : string
'YYYY-MM-DD' formatted representation of the first trading day
available in the dataset.
minute_index : list of integers
nanosecond integer representation of the minutes, the enumeration
of which corresponds to the values in each bcolz carray.
ohlc_ratio : int
The factor by which the pricing data is multiplied so that the
float data can be stored as an integer.
"""
metadata = {
'first_trading_day': str(self.first_trading_day.date()),
'market_opens': self.market_opens.values.
astype('datetime64[m]').
astype(np.int64).tolist(),
'market_closes': self.market_closes.values.
astype('datetime64[m]').
astype(np.int64).tolist(),
'ohlc_ratio': self.ohlc_ratio,
}
with open(self.metadata_path(rootdir), 'w+') as fp:
json.dump(metadata, fp)
class BcolzMinuteBarWriter(object):
"""
Class capable of writing minute OHLCV data to disk into bcolz format.
Parameters
----------
first_trading_day : datetime
The first trading day in the data set.
rootdir : string
Path to the root directory into which to write the metadata and
bcolz subdirectories.
market_opens : pd.Series
The market opens used as a starting point for each periodic span of
minutes in the index.
The index of the series is expected to be a DatetimeIndex of the
UTC midnight of each trading day.
The values are datetime64-like UTC market opens for each day in the
index.
market_closes : pd.Series
The market closes that correspond with the market opens,
The index of the series is expected to be a DatetimeIndex of the
UTC midnight of each trading day.
The values are datetime64-like UTC market opens for each day in the
index.
The closes are written so that the reader can filter out non-market
minutes even though the tail end of early closes are written in
the data arrays to keep a regular shape.
minutes_per_day : int
The number of minutes per each period. Defaults to 390, the mode
of minutes in NYSE trading days.
ohlc_ratio : int, optional
The ratio by which to multiply the pricing data to convert the
floats from floats to an integer to fit within the np.uint32.
The default is 1000 to support pricing data which comes in to the
thousands place.
expectedlen : int, optional
The expected length of the dataset, used when creating the initial
bcolz ctable.
If the expectedlen is not used, the chunksize and corresponding
compression ratios are not ideal.
Defaults to supporting 15 years of NYSE equity market data.
see: http://bcolz.blosc.org/opt-tips.html#informing-about-the-length-of-your-carrays # noqa
Notes
-----
Writes a bcolz directory for each individual sid, all contained within
a root directory which also contains metadata about the entire dataset.
Each individual asset's data is stored as a bcolz table with a column for
each pricing field: (open, high, low, close, volume)
The open, high, low, and close columns are integers which are 1000 times
the quoted price, so that the data can r |
veltzer/demos-python | src/examples/short/keyring/get.py | Python | gpl-3.0 | 253 | 0 | #!/usr/bin/env python
"""
A basic example of how to get a pa | ssword from the default
keyring of you environment.
"""
import keyring
password = keyring.get_password(u"dummyapp", u"mark.v | eltzer@gmail.com")
print("your password is [{}]".format(password))
|
polyaxon/polyaxon | core/tests/test_polypod/test_resolvers/test_core_resolver.py | Python | apache-2.0 | 9,111 | 0.000439 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 pytest
import tempfile
from polyaxon import settings
from polyaxon.auxiliaries import (
get_default_init_container,
get_default_sidecar_container,
)
from polyaxon.connections.kinds import V1ConnectionKind
from polyaxon.connections.schemas import V1BucketConnection, V1K8sResourceSchema
from polyaxon.exceptions import PolyaxonCompilerError
from polyaxon.managers.agent import AgentConfigManager
from polyaxon.polyaxonfile.specs import kinds
from polyaxon.polyflow import V1CompiledOperation, V1RunKind
from polyaxon.polypod.compiler.resolver import BaseResolver
from polyaxon.schemas.cli.agent_config import AgentConfig
from polyaxon.schemas.types import V1ConnectionType, V1K8sResourceType
from polyaxon.utils.test_utils import BaseTestCase
@pytest.mark.polypod_mark
class TestResolver(BaseTestCase):
def setUp(self):
super().setUp()
self.compiled_operation = V1CompiledOperation.read(
{
"version": 1.1,
"kind": kinds.COMPILED_OPERATION,
"plugins": {
"auth": False,
"shm": False,
"collectLogs": False,
"collectArtifacts": False,
"collectResources": False,
},
"run": {"kind": V1RunKind.JOB, "container": {"image": "test"}},
}
)
def test_core_resolver_instance(self):
resolver = BaseResolver(
run=None,
compiled_operation=self.compiled_operation,
owner_name="user",
project_name="p1",
project_uuid=None,
run_name="j1",
run_uuid=None,
run_path="test",
params=None,
)
assert resolver.project_uuid == resolver.project_name
assert resolver.run_uuid == resolver.run_name
resolver = BaseResolver(
run=None,
compiled_operation=self.compiled_operation,
owner_name="user",
project_name="p1",
run_name="j1",
run_path="test",
project_uuid="some_uuid",
run_uuid="some_uuid",
params=None,
)
assert resolver.project_uuid != resolver.project_name
assert resolver.run_uuid != resolver.run_name
def test_resolve_connections_with_no_config(self):
settings.AGENT_CONFIG = None
resolver = BaseResolver(
run=None,
compiled_operation=self.compiled_operation,
owner_name="user",
project_name="p1",
project_uuid=None,
run_name="j1",
run_uuid=None,
run_path="test",
params=None,
)
with self.assertRaises(PolyaxonCompilerError):
resolver.resolve_connections()
def test_resolve_without_compiled_operation(self):
with self.assertRaises(PolyaxonCompilerError):
BaseResolver(
run=None,
compiled_operation=None,
owner_name="user",
project_name="p1",
project_uuid=None,
run_name="j1",
run_uuid=None,
run_path="test",
params=None,
)
def test_resolve_connections_with_invalid_config(self):
fpath = tempfile.mkdtemp()
AgentConfigManager.CONFIG_PATH = fpath
secret1 = V1K8sResourceType(
name="secret1",
schema=V1K8sResourceSchema(name="secret1"),
is_requested=True,
)
secret2 = V1K8sResourceType(
name="secret2",
schema=V1K8sResourceSchema(name="secret2"),
is_requested=True,
)
connection1 = V1ConnectionType(
name="test_s3",
kind=V1ConnectionKind.S3,
schema=V1BucketConnection(bucket="s3//:foo"),
secret=secret1.schema,
)
connection2 = V1ConnectionType(
name="test_gcs",
kind=V1ConnectionKind.GCS,
schema=V1BucketConnection(bucket="gcs//:foo"),
secret=secret1.schema,
)
connection3 = V1ConnectionType(
name="test_wasb",
kind=V1ConnectionKind.WASB,
schema=V1BucketConnection(bucket="wasbs//:foo"),
secret=secret2.schema,
)
settings.AGENT_CONFIG = AgentConfig(
namespace="foo",
artifacts_store=connection1,
connections=[connection2, connection3],
)
resolver = BaseResolver(
run=None,
compiled_operation=self.compiled_operation,
owner_name="user",
project_name="p1",
project_uuid=None,
run_name="j1",
run_uuid=None,
run_path="test",
params=None,
)
resolver.resolve_connections()
assert resolver.namespace == "foo"
assert resolver.connection_by_names == {connection1.name: connection1} |
assert resolver.a | rtifacts_store == connection1
assert [s.schema for s in resolver.secrets] == [secret1.schema, secret2.schema]
assert resolver.polyaxon_sidecar == get_default_sidecar_container()
assert resolver.polyaxon_init == get_default_init_container()
# Add run spec to resolve connections
compiled_operation = V1CompiledOperation.read(
{
"version": 1.1,
"kind": kinds.COMPILED_OPERATION,
"plugins": {
"auth": False,
"shm": False,
"collectLogs": False,
"collectArtifacts": False,
"collectResources": False,
},
"run": {
"kind": V1RunKind.JOB,
"container": {"image": "test"},
"connections": {connection3.name},
},
}
)
resolver = BaseResolver(
run=None,
compiled_operation=compiled_operation,
owner_name="user",
project_name="p1",
project_uuid=None,
run_name="j1",
run_uuid=None,
run_path="test",
params=None,
)
resolver.resolve_connections()
assert resolver.namespace == "foo"
assert resolver.connection_by_names == {
connection1.name: connection1,
connection3.name: connection3,
}
assert [s.schema for s in resolver.secrets] == [secret1.schema, secret2.schema]
assert resolver.artifacts_store == connection1
assert resolver.polyaxon_sidecar == get_default_sidecar_container()
assert resolver.polyaxon_init == get_default_init_container()
# Add run spec to resolve connections
compiled_operation = V1CompiledOperation.read(
{
"version": 1.1,
"kind": kinds.COMPILED_OPERATION,
"plugins": {
"auth": False,
"shm": False,
"collectLogs": False,
"collectArtifacts": False,
"collectResources": False,
},
"run": {
"kind": V1RunKind.JOB,
"container": {"image": "test"},
"connections": {
connection1.name,
connection2.name,
connection3.name,
|
socialwifi/dila | dila/data/base_strings.py | Python | bsd-3-clause | 2,698 | 0.002224 | import sqlalchemy
import sqlalchemy.dialects.postgresql as postgres_dialect
from sqlalchemy import orm
from dila.application import structures
from dila.data import engine
from dila.data import resources
class BaseString(engine.Base):
__tablename__ = 'base_string'
id = sqlalchemy.Column(postgres_dialect.UUID(as_uuid=True),
server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True,
nullable=False)
resource_pk = sqlalchemy.Column(
postgres_dialect.UUID(as_uuid=True), sqlalchemy.ForeignKey(resources.Resource.id), nullable=False)
resources = orm.relationship(resources.Resource, backref=orm.backref('translated_strings'))
base_string = sqlalchemy.Column(sqlalchemy.Text, nullable=False)
comment = sqlalchemy.Column(sqlalchemy.Text, nullable=False, default='')
context = sqlalchemy.Column(sqlalchemy.Text, nullable=False, default='')
plural = sqlalchemy.Column(sqlalchemy.Text, nullable=False, default='')
__table_args__ = (
sqlalchemy.UniqueConstraint('resource_pk', 'base_string', 'context', name='resource_base_string_context_uc'),
)
def as_data(self):
return structures.TranslatedStringData(
pk=self.id,
base_string=self.base_string,
plural=self.plural,
translation='',
comment=self.comment,
translator_comment='',
context=self.context,
resource_pk=self.resource_pk,
plural_translations=self.empty_plural_translations_data,
)
@property
def empty_plural_translations_data(self):
if self.plural:
return structures.PluralTranslations(few='', many='', other='')
else | :
return None
def add_or_update_base_string(resource_pk, base_string, *, comment, context, plural=''):
try:
base_string = BaseString.query.filter(
BaseString.resource_pk == resource_pk,
BaseString.base_string == base_string,
BaseString.context == (co | ntext or ''),
).one()
except sqlalchemy.orm.exc.NoResultFound:
base_string = BaseString(resource_pk=resource_pk, base_string=base_string, comment=comment, context=context,
plural=plural)
engine.session.add(base_string)
else:
base_string.comment = comment
base_string.plural = plural
engine.session.flush()
return base_string.id
def delete_old_strings(resource_pk, *, keep_pks):
BaseString.query.filter(
BaseString.resource_pk == resource_pk,
BaseString.id.notin_(keep_pks),
).delete(synchronize_session='fetch')
|
Datera/cinder | cinder/tests/unit/volume/drivers/netapp/dataontap/client/test_api.py | Python | apache-2.0 | 23,756 | 0.000042 | # Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Bob Callaway. 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 for NetApp API layer
"""
import ddt
from lxml import etree
import mock
from oslo_utils import netutils
import paramiko
import six
from six.moves import urllib
from cinder import exception
from cinder.i18n import _
from cinder import test
from cinder.tests.unit.volume.drivers.netapp.dataontap.client import (
fakes as zapi_fakes)
from cinder.volume.drivers.netapp.dataontap.client import api as netapp_api
@ddt.ddt
class NetAppApiServerTests(test.TestCase):
"""Test case for NetApp API server methods"""
def setUp(self):
self.root = netapp_api.NaServer('127.0.0.1')
super(NetAppApiServerTests, self).setUp()
@ddt.data(None, 'ftp')
def test_set_transport_type_value_error(self, transport_type):
"""Tests setting an invalid transport type"""
self.assertRaises(ValueError, self.root.set_transport_type,
transport_type)
@ddt.data({'params': {'transport_type': 'http',
'server_type_filer': 'filer'}},
{'params': {'transport_type': 'http',
'server_type_filer': 'xyz'}},
{'params': {'transport_type': 'https',
'server_type_filer': 'filer'}},
{'params': {'transport_type': 'https',
'server_type_filer': 'xyz'}})
@ddt.unpack
def test_set_transport_type_valid(self, params):
"""Tests setting a valid transport type"""
self.root._server_type = params['server_type_filer']
mock_invoke = self.mock_object(self.root, 'set_port')
self.root.set_transport_type(params['transport_type'])
expected_call_args = zapi_fakes.FAKE_CALL_ARGS_LIST
self.assertIn(mock_invoke.call_args, expected_call_args)
@ddt.data('stor', 'STORE', '')
def test_set_server_type_value_error(self, server_type):
"""Tests Value Error on setting the wrong server type"""
self.assertRaises(ValueError, self.root.set_server_type, server_type)
@ddt.data('!&', '80na', '')
def test_set_port__value_error(self, port):
"""Tests Value Error on trying to set port with a non-integer"""
self.assertRaises(ValueError, self.root.set_port, port)
@ddt.data('!&', '80na', '')
def test_set_timeout_value_error(self, timeout):
"""Tests Value Error on trying to set port with a non-integer"""
self.assertRaises(ValueError, self.root.set_timeout, timeout)
@ddt.data({'params': {'major': 1, 'minor': '20a'}},
{'params': {'major': '20a', 'minor': 1}},
{'params': {'major': '!*', 'minor': '20a'}})
@ddt.unpack
def test_set_api_version_value_error(self, params):
"""Tests Value Error on setting non-integer version"""
self.assertRaises(ValueError, self.root.set_api_version, **params)
def test_set_api_version_valid(self):
"""Tests Value Error on setting non-integer version"""
args = {'major': '20', 'minor': 1}
expected_call_args_list = [mock.call('20'), mock.call(1)]
mock_invoke = self.mock_object(six, 'text_type', return_value='str')
self.root.set_api_version(**args)
self.assertEqual(expected_call_args_list, mock_invoke.call_args_list)
@ddt.data({'params': {'result': zapi_fakes.FAKE_RESULT_API_ERR_REASON}},
{'params': {'result': zapi_fakes.FAKE_RESULT_API_ERRNO_INVALID}},
{'params': {'result': zapi_fakes.FAKE_RESULT_API_ERRNO_VALID}})
@ddt.unpack
def test_invoke_successfully_naapi_error(self, params):
"""Tests invoke successfully raising NaApiError"""
self.mock_object(self.root, 'send_http_request',
return_value=params['result'])
self.assertRaises(netapp_api.NaApiError,
self.root.invoke_successfully,
zapi_fakes.FAKE_NA_ELEMENT)
def test_invoke_successfully_no_error(self):
"""Tests invoke successfully with no errors"""
self.mock_object(self.root, 'send_http_request',
return_value=zapi_fakes.FAKE_RESULT_SUCCESS)
self.assertEqual(zapi_fakes.FAKE_RESULT_SUCCESS.to_string(),
self.root.invoke_successfully(
zapi_fakes.FAKE_NA_ELEMENT).to_string())
def test__create_request(self):
"""Tests method _create_request"""
self.root._ns = zapi_fakes.FAKE_XML_STR
self.root._api_version = '1.20'
self.mock_object(self.root, '_enable_tunnel_request')
self.mock_object(netapp_api.NaElement, 'add_child_elem')
self.mock_object(netapp_api.NaElement, 'to_string',
return_value=zapi_fakes.FAKE_XML_STR)
mock_invoke = self.mock_object(urllib.request, 'Request')
self.root._create_request(zapi_fakes.FAKE_NA_ELEMENT, True)
self.assertTrue(mock_invoke.called)
@ddt.data({'params': {'server': zapi_fakes.FAKE_NA_SERVER_API_1_5}},
{'params': {'server': zapi_fakes.FAKE_NA_SERVER_API_1_14}})
@ddt.unpack
def test__enable_tunnel_request__value_error(self, params):
"""Tests value errors with creating tunnel request"""
self.assertRaises(ValueError, params['server']._enable_tunnel_request,
'test')
def test__enable_tunnel_request_valid(self):
"""Tests creating tunnel request with correct values"""
netapp_elem = zapi_fakes.FAKE_NA_ELEMENT
server = zapi_fakes.FAKE_NA_SERVER_API_1_20
mock_invoke = self.mock_object(netapp_elem, 'add_attr')
expected_call_args = [mock.call('vfiler', 'filer'),
mock.call('vfiler', 'server')]
server._enable_tunnel_request(netapp_elem)
self.assertEqual(expected_call_args, mock_invoke.call_args_list)
def test__parse_response__naapi_error(self):
"""Tests NaApiError on no response"""
self.assertRaises(netapp_api.NaApiError,
self.root._parse_response, None)
def test__parse_response_no_error(self):
"""Tests parse function with appropriate response"""
mock_invoke = self.mock_object(etree, 'XML', return_value='xml')
self.root._parse_response(zapi_fakes.FAKE_XML_ST | R)
mock_invoke.assert_called_with(zapi_fakes.FAKE_XML_STR)
def test__build_opener_not_implemented_error(self):
"""Tests whether certificate style authorization raises Exception"""
self.root._auth_style = 'not_basic_auth'
self.assertRaises(NotImplementedError, self.root._build_opener)
def test__build_opener_valid(self):
| """Tests whether build opener works with valid parameters"""
self.root._auth_style = 'basic_auth'
mock_invoke = self.mock_object(urllib.request, 'build_opener')
self.root._build_opener()
self.assertTrue(mock_invoke.called)
@ddt.data(None, zapi_fakes.FAKE_XML_STR)
def test_send_http_request_value_error(self, na_element):
"""Tests whether invalid NaElement parameter causes error"""
self.assertRaises(ValueError, self.root.send_http_request, na_element)
def test_send_http_request_http_error(self):
"""Tests handling of HTTPError"""
na_element = zapi_fake |
projectcalico/calico-nova | nova/tests/unit/api/openstack/compute/contrib/test_server_groups.py | Python | apache-2.0 | 14,004 | 0.001428 | # Copyright (c) 2014 Cisco Systems, 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.
import webob
from nova.api.openstack.compute.contrib import server_groups
from nova.api.openstack.compute.plugins.v3 import server_groups as sg_v3
from nova.api.openstack import extensions
from nova import context
import nova.db
from nova import exception
from nova import objects
from nova.openstack.common import uuidutils
from nova import test
from nova.tests.unit.api.openstack import fakes
FAKE_UUID1 = 'a47ae74e-ab08-447f-8eee-ffd43fc46c16'
FAKE_UUID2 = 'c6e6430a-6563-4efa-9542-5e93c9e97d18'
FAKE_UUID3 = 'b8713410-9ba3-e913-901b-13410ca90121'
class AttrDict(dict):
def __getattr__(self, k):
return self[k]
|
def server_group_template(**kwargs):
sgroup = kwargs.cop | y()
sgroup.setdefault('name', 'test')
return sgroup
def server_group_resp_template(**kwargs):
sgroup = kwargs.copy()
sgroup.setdefault('name', 'test')
sgroup.setdefault('policies', [])
sgroup.setdefault('members', [])
return sgroup
def server_group_db(sg):
attrs = sg.copy()
if 'id' in attrs:
attrs['uuid'] = attrs.pop('id')
if 'policies' in attrs:
policies = attrs.pop('policies')
attrs['policies'] = policies
else:
attrs['policies'] = []
if 'members' in attrs:
members = attrs.pop('members')
attrs['members'] = members
else:
attrs['members'] = []
attrs['deleted'] = 0
attrs['deleted_at'] = None
attrs['created_at'] = None
attrs['updated_at'] = None
if 'user_id' not in attrs:
attrs['user_id'] = 'user_id'
if 'project_id' not in attrs:
attrs['project_id'] = 'project_id'
attrs['id'] = 7
return AttrDict(attrs)
class ServerGroupTestV21(test.TestCase):
validation_error = exception.ValidationError
def setUp(self):
super(ServerGroupTestV21, self).setUp()
self._setup_controller()
self.req = fakes.HTTPRequest.blank('')
def _setup_controller(self):
self.controller = sg_v3.ServerGroupController()
def test_create_server_group_with_no_policies(self):
sgroup = server_group_template()
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
def test_create_server_group_normal(self):
sgroup = server_group_template()
policies = ['anti-affinity']
sgroup['policies'] = policies
res_dict = self.controller.create(self.req,
body={'server_group': sgroup})
self.assertEqual(res_dict['server_group']['name'], 'test')
self.assertTrue(uuidutils.is_uuid_like(res_dict['server_group']['id']))
self.assertEqual(res_dict['server_group']['policies'], policies)
def _create_instance(self, context):
instance = objects.Instance(context=context, image_ref=1, node='node1',
reservation_id='a', host='host1', project_id='fake',
vm_state='fake', system_metadata={'key': 'value'})
instance.create()
return instance
def _create_instance_group(self, context, members):
ig = objects.InstanceGroup(context=context, name='fake_name',
user_id='fake_user', project_id='fake',
members=members)
ig.create()
return ig.uuid
def _create_groups_and_instances(self, ctx):
instances = [self._create_instance(ctx), self._create_instance(ctx)]
members = [instance.uuid for instance in instances]
ig_uuid = self._create_instance_group(ctx, members)
return (ig_uuid, instances, members)
def test_display_members(self):
ctx = context.RequestContext('fake_user', 'fake')
(ig_uuid, instances, members) = self._create_groups_and_instances(ctx)
res_dict = self.controller.show(self.req, ig_uuid)
result_members = res_dict['server_group']['members']
self.assertEqual(2, len(result_members))
for member in members:
self.assertIn(member, result_members)
def test_display_active_members_only(self):
ctx = context.RequestContext('fake_user', 'fake')
(ig_uuid, instances, members) = self._create_groups_and_instances(ctx)
# delete an instance
instances[1].destroy()
# check that the instance does not exist
self.assertRaises(exception.InstanceNotFound,
objects.Instance.get_by_uuid,
ctx, instances[1].uuid)
res_dict = self.controller.show(self.req, ig_uuid)
result_members = res_dict['server_group']['members']
# check that only the active instance is displayed
self.assertEqual(1, len(result_members))
self.assertIn(instances[0].uuid, result_members)
def test_create_server_group_with_illegal_name(self):
# blank name
sgroup = server_group_template(name='', policies=['test_policy'])
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# name with length 256
sgroup = server_group_template(name='1234567890' * 26,
policies=['test_policy'])
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# non-string name
sgroup = server_group_template(name=12, policies=['test_policy'])
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# name with leading spaces
sgroup = server_group_template(name=' leading spaces',
policies=['test_policy'])
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# name with trailing spaces
sgroup = server_group_template(name='trailing space ',
policies=['test_policy'])
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# name with all spaces
sgroup = server_group_template(name=' ',
policies=['test_policy'])
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
def test_create_server_group_with_illegal_policies(self):
# blank policy
sgroup = server_group_template(name='fake-name', policies='')
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# policy as integer
sgroup = server_group_template(name='fake-name', policies=7)
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# policy as string
sgroup = server_group_template(name='fake-name', policies='invalid')
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
# policy as None
sgroup = server_group_template(name='fake-name', policies=None)
self.assertRaises(self.validation_error, self.controller.create,
self.req, body={'server_group': sgroup})
def test_crea |
yarikoptic/pystatsmodels | statsmodels/tsa/tsatools.py | Python | bsd-3-clause | 17,721 | 0.005135 | import numpy as np
import numpy.lib.recfunctions as nprf
from statsmodels.tools.tools import add_constant
def add_tre | nd(X, trend="c", prepend=False):
"""
Adds a trend and/or constant to an array.
Parameters
----------
X : array-like
Original array of data.
trend : str {"c","t","ct","ctt"}
"c" add constant only
"t" add trend only
"ct" add constant and linear trend
"ctt" add constant and linear and quadratic trend.
prepend : bool
If True, prepends the new data to the columns of X.
Notes
-----
| Returns columns as ["ctt","ct","c"] whenever applicable. There is currently
no checking for an existing constant or trend.
See also
--------
statsmodels.add_constant
"""
#TODO: could be generalized for trend of aribitrary order
trend = trend.lower()
if trend == "c": # handles structured arrays
return add_constant(X, prepend=prepend)
elif trend == "ct" or trend == "t":
trendorder = 1
elif trend == "ctt":
trendorder = 2
else:
raise ValueError("trend %s not understood" % trend)
X = np.asanyarray(X)
nobs = len(X)
trendarr = np.vander(np.arange(1,nobs+1, dtype=float), trendorder+1)
# put in order ctt
trendarr = np.fliplr(trendarr)
if trend == "t":
trendarr = trendarr[:,1]
if not X.dtype.names:
if not prepend:
X = np.column_stack((X, trendarr))
else:
X = np.column_stack((trendarr, X))
else:
return_rec = data.__clas__ is np.recarray
if trendorder == 1:
if trend == "ct":
dt = [('const',float),('trend',float)]
else:
dt = [('trend', float)]
elif trendorder == 2:
dt = [('const',float),('trend',float),('trend_squared', float)]
trendarr = trendarr.view(dt)
if prepend:
X = nprf.append_fields(trendarr, X.dtype.names, [X[i] for i
in data.dtype.names], usemask=False, asrecarray=return_rec)
else:
X = nprf.append_fields(X, trendarr.dtype.names, [trendarr[i] for i
in trendarr.dtype.names], usemask=false, asrecarray=return_rec)
return X
def add_lag(x, col=None, lags=1, drop=False, insert=True):
"""
Returns an array with lags included given an array.
Parameters
----------
x : array
An array or NumPy ndarray subclass. Can be either a 1d or 2d array with
observations in columns.
col : 'string', int, or None
If data is a structured array or a recarray, `col` can be a string
that is the name of the column containing the variable. Or `col` can
be an int of the zero-based column index. If it's a 1d array `col`
can be None.
lags : int
The number of lags desired.
drop : bool
Whether to keep the contemporaneous variable for the data.
insert : bool or int
If True, inserts the lagged values after `col`. If False, appends
the data. If int inserts the lags at int.
Returns
-------
array : ndarray
Array with lags
Examples
--------
>>> import statsmodels.api as sm
>>> data = sm.datasets.macrodata.load()
>>> data = data.data[['year','quarter','realgdp','cpi']]
>>> data = sm.tsa.add_lag(data, 'realgdp', lags=2)
Notes
-----
Trims the array both forward and backward, so that the array returned
so that the length of the returned array is len(`X`) - lags. The lags are
returned in increasing order, ie., t-1,t-2,...,t-lags
"""
if x.dtype.names:
names = x.dtype.names
if not col and np.squeeze(x).ndim > 1:
raise IndexError, "col is None and the input array is not 1d"
elif len(names) == 1:
col = names[0]
if isinstance(col, int):
col = x.dtype.names[col]
contemp = x[col]
# make names for lags
tmp_names = [col + '_'+'L(%i)' % i for i in range(1,lags+1)]
ndlags = lagmat(contemp, maxlag=lags, trim='Both')
# get index for return
if insert is True:
ins_idx = list(names).index(col) + 1
elif insert is False:
ins_idx = len(names) + 1
else: # insert is an int
if insert > len(names):
raise Warning("insert > number of variables, inserting at the"+
" last position")
ins_idx = insert
first_names = list(names[:ins_idx])
last_names = list(names[ins_idx:])
if drop:
if col in first_names:
first_names.pop(first_names.index(col))
else:
last_names.pop(last_names.index(col))
if first_names: # only do this if x isn't "empty"
first_arr = nprf.append_fields(x[first_names][lags:],tmp_names,
ndlags.T, usemask=False)
else:
first_arr = np.zeros(len(x)-lags, dtype=zip(tmp_names,
(x[col].dtype,)*lags))
for i,name in enumerate(tmp_names):
first_arr[name] = ndlags[:,i]
if last_names:
return nprf.append_fields(first_arr, last_names,
[x[name][lags:] for name in last_names], usemask=False)
else: # lags for last variable
return first_arr
else: # we have an ndarray
if x.ndim == 1: # make 2d if 1d
x = x[:,None]
if col is None:
col = 0
# handle negative index
if col < 0:
col = x.shape[1] + col
contemp = x[:,col]
if insert is True:
ins_idx = col + 1
elif insert is False:
ins_idx = x.shape[1]
else:
if insert < 0: # handle negative index
insert = x.shape[1] + insert + 1
if insert > x.shape[1]:
insert = x.shape[1]
raise Warning("insert > number of variables, inserting at the"+
" last position")
ins_idx = insert
ndlags = lagmat(contemp, lags, trim='Both')
first_cols = range(ins_idx)
last_cols = range(ins_idx,x.shape[1])
if drop:
if col in first_cols:
first_cols.pop(first_cols.index(col))
else:
last_cols.pop(last_cols.index(col))
return np.column_stack((x[lags:,first_cols],ndlags,
x[lags:,last_cols]))
def detrend(x, order=1, axis=0):
'''detrend an array with a trend of given order along axis 0 or 1
Parameters
----------
x : array_like, 1d or 2d
data, if 2d, then each row or column is independently detrended with the
same trendorder, but independent trend estimates
order : int
specifies the polynomial order of the trend, zero is constant, one is
linear trend, two is quadratic trend
axis : int
for detrending with order > 0, axis can be either 0 observations by rows,
or 1, observations by columns
Returns
-------
detrended data series : ndarray
The detrended series is the residual of the linear regression of the
data on the trend of given order.
'''
x = np.asarray(x)
nobs = x.shape[0]
if order == 0:
return x - np.expand_dims(x.mean(ax), x)
else:
if x.ndim == 2 and range(2)[axis]==1:
x = x.T
elif x.ndim > 2:
raise NotImplementedError('x.ndim>2 is not implemented until it is needed')
#could use a polynomial, but this should work also with 2d x, but maybe not yet
trends = np.vander(np.arange(nobs).astype(float), N=order+1)
beta = np.linalg.lstsq(trends, x)[0]
resid = x - np.dot(trends, beta)
if x.ndim == 2 and range(2)[axis]==1:
resid = resid.T
return resid
def lagmat(x, maxlag, trim='forward', original='ex'):
'''create 2d array of lags
Parameters
----------
x : array_like, 1d or 2d
data; if 2d, observation in rows and variables in columns
max |
logston/django_openS3 | setup.py | Python | mit | 2,012 | 0 | #! /usr/bin/env python
import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import django_openS3
with open(os.path.join(os.path.dirname(__file__), "README.rst")) as file:
README = file.read()
with open(os.path.join(os.path.dirname(__file__), 'LICENSE')) as file:
LICENSE = file.read()
class Tox(TestCommand):
"""Command to make python setup.py test run."""
def finalize_options(self):
super().finalize_options()
self.test_args = []
self.test_suite = True
def run_tests(self):
# Do this import here because tests_require isn't processed
# early enough to do a module-level import.
from tox._cmdline import main
sys.exit(main(self.test_args))
CLASSIFIERS = [
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language | :: Python :: 3.4",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Utilities",
]
setup(name='django_openS3',
version=django_openS3.__version__,
author=django_openS3.__author__,
author_email=django_openS3.__email__,
maintainer=django_openS3.__author__,
maintainer_email=django_open | S3.__email__,
url='http://github.com/logston/django_openS3',
description='An openS3 wrapper for use with Django',
long_description=README,
license=LICENSE,
classifiers=CLASSIFIERS,
packages=['django_openS3'],
include_package_data=True,
package_data={'': ['LICENSE', 'README.rst']},
install_requires=[
'Django>=1.6',
'openS3>=0.2.0'
],
tests_require=['tox'],
cmdclass={'test': Tox})
|
anderson1008/NOCulator | hring/src/Script/eval_batch.py | Python | mit | 2,292 | 0.02007 | #!/usr/bin/python
import sys
import os
import re
import fnmatch
import string
import compute
import get
dir_canpc = "/home/anderson/Desktop/results/homo_mem/"
dir_alone = dir_canpc + "baseline/4x4_insn100K/"
dir_share = dir_canpc + "mshr/"
sum_ws = 0
sum_hs = 0
sum_uf = 0
eff_count = 0
ipc_alone = [2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91, 2.08, 2.16, 1.77, 1.91]
for sim_index in range(1, 27, 1):
input_file_alone = dir_alone + "sim_" + str(sim_index) + ".out"
input_file_share = dir_share + "sim_" + str(sim_index) + ".out"
exist_alone = os.path.exists(input_file_alone)
exist_share = os.path.exists(input_file_share)
if (exist_alone is False or exist_share is False):
print "Fail to find " + str (sim_index) + ".out or its counterpart."
continue
#print input_file_alone + " v.s. " + input_file_share
stat_alone = get.get_stat (input_file_alone)
stat_share = get.get_stat (input_file_share)
insns_alone = get.get_insns_persrc (stat_alone)
insns_share = get.get_insns_persrc (stat_share)
act_t_alone = get.get_active_cycles (stat_alone)
act_t_share = get.get_active_cycles (stat_share)
#ipc_alone = compute.cmp_ipc (insns_alone, act_t_alone)
ipc_share = compute.cmp_ipc (insns_share, act_t_share)
ws = compute.cmp_ws (ipc_alone, ipc_share)
hs = compute.cmp_hs (ipc_alone, ipc_share)
uf = compute.cmp_uf (ipc_alone, ipc_share)
| eff_count = eff_count + 1
sum_ws = sum_ws + w | s
sum_hs = sum_hs + hs
sum_uf = sum_uf + uf
#print "Weighted Speedup = " + str("%.3f" % ws)
#print "Harmonic Speedup = " + str("%.3f" % hs)
#print "Unfairness = " + str("%.3f" % uf)
avg_ws = sum_ws / eff_count
avg_hs = sum_hs / eff_count
avg_uf = sum_uf / eff_count
print "Weighted Speedup = " + str("%.3f" % avg_ws)
print "Harmonic Speedup = " + str("%.3f" % avg_hs)
print "Unfairness = " + str("%.3f" % avg_uf)
print "Based on " + str(eff_count) + " pairs of workloads."
|
videetssinghai/Blog-Rest-Api | posts/api/permissions.py | Python | mit | 196 | 0.010204 | from rest_framework.permissions import BasePermission
class IsOwnerOrReadOnly(BasePermission):
d | ef has_ | object_permission(self, request, view, obj):
return obj.user == request.user |
Eagles2F/sync-engine | tests/security/test_smtp_ssl.py | Python | agpl-3.0 | 3,497 | 0.000286 | import ssl
import json
import smtpd
import asyncore
import datetime
import pytest
import gevent
from tests.util.base import default_account
from tests.api.base import api_client, new_api_client
from tests.api | _legacy.base import api_client as api_legacy_client
__all__ = ['api_client', 'api_legacy_cl | ient', 'default_account']
SELF_SIGNED_CERTFILE = 'tests/data/self_signed_cert.pem'
SELF_SIGNED_KEYFILE = 'tests/data/self_signed_cert.key'
from inbox.sendmail.smtp.postel import SMTP_OVER_SSL_TEST_PORT
SMTP_SERVER_HOST = 'localhost'
SMTP_SERVER_PORT = SMTP_OVER_SSL_TEST_PORT
class BadCertSMTPServer(smtpd.DebuggingServer):
def __init__(self, localaddr, remoteaddr):
smtpd.DebuggingServer.__init__(self, localaddr, remoteaddr)
self.set_socket(ssl.wrap_socket(self.socket,
certfile=SELF_SIGNED_CERTFILE,
keyfile=SELF_SIGNED_KEYFILE,
server_side=True))
def run_bad_cert_smtp_server():
BadCertSMTPServer((SMTP_SERVER_HOST, SMTP_SERVER_PORT), (None, None))
asyncore.loop()
@pytest.yield_fixture(scope='function')
def bad_cert_smtp_server():
s = gevent.spawn(run_bad_cert_smtp_server)
yield s
s.kill()
@pytest.fixture(scope='function')
def local_smtp_account(db):
from inbox.auth.generic import GenericAuthHandler
handler = GenericAuthHandler(provider_name='custom')
acc = handler.create_account(db.session, 'user@gmail.com',
{'email': 'user@gmail.com',
'password': 'hunter2',
'imap_server_host': 'imap-test.nylas.com',
'imap_server_port': 143,
'smtp_server_host': SMTP_SERVER_HOST,
'smtp_server_port': SMTP_SERVER_PORT})
db.session.add(acc)
db.session.commit()
return acc
@pytest.fixture
def example_draft(db, default_account):
return {
'subject': 'Draft test at {}'.format(datetime.datetime.utcnow()),
'body': '<html><body><h2>Sea, birds and sand.</h2></body></html>',
'to': [{'name': 'The red-haired mermaid',
'email': default_account.email_address}]
}
def test_smtp_ssl_verification_bad_cert(db, bad_cert_smtp_server,
example_draft, local_smtp_account,
api_legacy_client):
error_msg = 'SMTP server SSL certificate verify failed'
api_client = new_api_client(db, local_smtp_account.namespace)
gevent.sleep(0.2) # let SMTP daemon start up
r = api_client.post_data('/send', example_draft)
assert r.status_code == 503
assert json.loads(r.data)['message'] == error_msg
def test_smtp_ssl_verification_bad_cert_legacy(db, bad_cert_smtp_server,
example_draft,
local_smtp_account,
api_legacy_client):
error_msg = 'SMTP server SSL certificate verify failed'
ns_public_id = local_smtp_account.namespace.public_id
r = api_legacy_client.post_data('/send', example_draft, ns_public_id)
assert r.status_code == 503
assert json.loads(r.data)['message'] == error_msg
if __name__ == '__main__':
server = BadCertSMTPServer((SMTP_SERVER_HOST, SMTP_SERVER_PORT), None)
asyncore.loop()
|
teythoon/Insekta | insekta/scenario/management/commands/vmd.py | Python | mit | 2,945 | 0.001698 | from __future__ import print_function
import time
import signal
from datetime import datetime
from django.core.management.base import NoArgsCommand
from django.conf import settings
from insekta.common.virt import connections
from insekta.scenario.models import ScenarioRun, RunTaskQueue, ScenarioError
from insekta.vm.models import VirtualMachineError
MIN_SLEEP = 1.0
class Command(NoArgsCommand):
help = 'Manages the state changes of virtual machines'
def handle_noargs(self, **options):
self.run = True
signal.signal(signal.SIGINT, lambda sig, frame: self.stop())
signal.signal(signal.SIGTERM, lambda sig, frame: self.stop())
last_call = time.time()
while self.run:
# Process all open tasks
for task in RunTaskQueue.objects.all():
try:
self._handle_task(task)
except ScenarioError:
# This can happen if someone manages the vm manually.
# We can just ignore it, it does no harm
pass
task.delete()
# Delete expired scenarios
expired_runs = ScenarioRun.objects.filter(last_activity__lt=
datetime.today() - settings.SCE | NARIO_EXPIRE_TIME)
for scenario_run in expired_runs:
try:
scenario_run.vm.destroy()
except VirtualMachineError:
| # We have an inconsistent state. See comment above.
pass
current_time = time.time()
time_passed = current_time - last_call
if time_passed < MIN_SLEEP:
time.sleep(MIN_SLEEP - time_passed)
last_call = current_time
connections.close()
def _handle_task(self, task):
scenario_run = task.scenario_run
vm = scenario_run.vm
db_state = vm.state
vm.refresh_state()
if vm.state != db_state:
vm.save()
# Scenario run was deleted in a previous task, we need to ignore
# all further task actions except create
if vm.state == 'disabled' and task.action != 'create':
return
if task.action == 'create':
if vm.state == 'disabled':
vm.create_domain()
vm.start()
elif task.action == 'start':
if vm.state == 'stopped':
vm.start()
elif task.action == 'stop':
if vm.state == 'started':
vm.stop()
elif task.action == 'suspend':
if vm.state == 'started':
vm.suspend()
elif task.action == 'resume':
if vm.state == 'suspended':
vm.resume()
elif task.action == 'destroy':
vm.destroy()
def stop(self):
print('Stopping, please wait a few moments.')
self.run = False
|
deuscoin-org/deuscoin-core | qa/rpc-tests/test_framework/bignum.py | Python | mit | 1,997 | 0.006009 | #
#
# bignum.py
#
# This file is copied from python-deuscoinlib.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bignum routines"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
def bin2bn(s):
l = 0
for ch in s:
l = (l << 8) | ch
return l
def bn2mpi(v):
have_ext = False
if v.bit_length() > 0:
have_ext = (v.bit_length() & 0x07) == 0
neg = False
if v < 0:
neg = True
v = -v
s = struct.pack(b">I", bn_bytes(v, have_ext))
ext = bytearray()
if have_ext:
ext.append(0)
v_bin = bn2bin(v)
if neg:
if have_ext:
ext[0] |= 0x80
else:
v_bin[0] |= 0x80
return s + ext + v_bin
def mpi2bn(s):
if len(s) < 4:
return None
s_size = bytes(s[:4])
v_len = struct.unpack(b">I", s_size)[0]
if len(s) != (v_len + 4):
return None
if v_len == 0:
return 0
v_str = bytearray(s[4:])
neg = False
i = v_str[0]
if i & 0x80:
neg = True
i &= ~0x80
v_str[0] = i
v = bin2bn(v_str)
if neg:
return -v
return v
# deuscoin-specific little endian format, with implicit size
def mpi2vch(s):
r = s[4:] # strip | size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
def vch2mpi(s):
r = struct.pack(b">I", len(s)) # size
r + | = s[::-1] # reverse string, converting LE->BE
return r
def vch2bn(s):
return mpi2bn(vch2mpi(s))
|
Sigmapoint/notos | src/notos/policies.py | Python | mit | 4,467 | 0.005373 | '''
Created on 25-07-2013
@author: kamil
'''
import logging
import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils.timezone import utc
from models import ScheduledPush
class BasePushPolicy:
ALLOWED_METHODS = ["POST", "PUT", "PATCH", "DELETE"]
MAX_RETRIES = 5
@classmethod
def registration_id_changed(cls, previous_id, current_id):
msg = "Registration id %s changed to %s"
logging.getLogger(__name__).warning(msg, previous_id, current_id)
@classmethod
def registration_id_revoked(cls, revoked_id):
msg = "Registration id %s was revoked"
logging.getLogger(__name__).warning(msg, revoked_id)
@classmethod
def should_retry(cls, scheduled_push, push_result):
return scheduled_push.attempt_no <= cls.MAX_RETRIES
def __init__(self, view, request, response):
self.view = view
self.request = request
self.response = response
def on_post(self):
return ({}, [], "update")
def on_put(self):
return ({}, [], "update")
def on_patch(self):
return ({}, [], "update")
def on_delete(self):
return ({}, [], "delete")
def get_entity_id(self, reg_id):
try:
obj = self.view.object
except AttributeError:
obj = None
try:
qs = self.view.qs
except AttributeError:
qs = None
if object:
ct = ContentType.objects.get_for_model(
obj,
for_concrete_model=True
)
app_label = ct.app_label
classname = self.view.object.__class__.__name__
entity_id = u".".join([app_label, classname])
elif qs:
ct = ContentType.objects.get_for_model(
qs.model,
| for_concrete_model=False
)
app_label = ct.app_label
classname = self.view.queryset.model.__name__
entity_id = u".".join([app_label, classname])
else:
entity_id = None
| return entity_id
def get_has_many(self, reg_id):
try:
obj = self.view.object
except AttributeError:
obj = None
try:
qs = self.view.qs
except AttributeError:
qs = None
if obj:
return False
elif qs:
return True
else:
return None
def get_obj(self, reg_id):
try:
obj = self.view.object
except AttributeError:
obj = None
return obj
def get_id(self, reg_id):
obj = self.get_obj(reg_id)
if obj:
return obj.id
else:
return None
def get_datetime(self, reg_id):
return datetime.datetime.utcnow().replace(tzinfo=utc)
def finalize_data(self, data, date_time, action, reg_id):
entity_id = self.get_entity_id(reg_id)
id = self.get_id(reg_id) #@ReservedAssignment
list = self.get_has_many(reg_id) #@ReservedAssignment
url = self.get_url(reg_id)
finalized = dict(data.items())
finalized.update({
"_entity": entity_id,
"_id": id,
"_url": url,
"_datetime": date_time.isoformat(),
"_list": list,
"_action": action,
})
return finalized
def get_url(self, reg_id):
obj = self.get_obj(reg_id)
try:
return obj.get_absolute_url()
except AttributeError:
return None
def trigger(self):
if not 200 <= self.response.status_code < 300:
return
if self.request.method in self.__class__.ALLOWED_METHODS:
suffix = self.request.method.lower()
callback = getattr(self, 'on_' + suffix)
data, registration_ids, action = callback()
for reg_id in registration_ids:
date_time = self.get_datetime(reg_id)
finalized_data = self.finalize_data(data, date_time, action, reg_id)
ScheduledPush.objects.create(
self.__class__,
send_at=datetime.datetime.utcnow().replace(tzinfo=utc),
registration_id=reg_id,
source=self.get_obj(reg_id),
data=finalized_data
) |
russelmahmud/mess-account | core/utils.py | Python | bsd-3-clause | 581 | 0.006885 | from datetime import date, timedelta, datetime
import time
def | get_first_day(dt, d_years=0, d_months=0):
# d_years, d_months are "deltas" to apply to dt
y, m = dt.year + d_years, dt.month + d_months
a, m = divmod(m-1, 12)
return date(y+a, m+1, 1)
def get_last_day(dt):
return get_first_day(dt, 0, 1) + timedelta(-1)
def str_to_date(value):
"""
Convert string to datatime object
"""
if not value:
| return value
if value.__class__.__name__ in ['date']:
return value
return datetime.strptime(value, "%Y-%m-%d").date()
|
jsvine/markovify | test/test_basic.py | Python | mit | 7,758 | 0.001676 | import unittest
import markovify
import os
import operator
def get_sorted(chain_json):
return sorted(chain_json, key=operator.itemgetter(0))
class MarkovifyTestBase(unittest.TestCase):
__test__ = False
def test_text_too_small(self):
text = "Example phrase. This is another example sentence."
text_model = markovify.Text(text)
assert text_model.make_sentence() is None
def test_sherlock(self):
text_model = self.sherlock_model
sent = text_model.make_sentence()
assert len(sent) != 0
def test_json(self):
text_model = self.sherlock_model
json_model = text_model.to_json()
new_text_model = markovify.Text.from_json(json_model)
sent = new_text_model.make_sentence()
assert len(sent) != 0
def test_chain(self):
text_model = self.sherlock_model
chain_json = text_model.chain.to_json()
stored_chain = markovify.Chain.from_json(chain_json)
assert get_sorted(stored_chain.to_json()) == get_sorted(chain_json)
new_text_model = markovify.Text.from_chain(chain_json)
assert get_sorted(new_text_model.chain.to_json()) == get_sorted(chain_json)
sent = new_text_model.make_sentence()
assert len(sent) != 0
def test_make_sentence_with_start(self):
text_model = self.sherlock_model
start_str = "Sherlock Holmes"
sent = text_model.make_sentence_with_start(start_str)
assert sent is not None
assert start_str == sent[: len(start_str)]
def test_make_sentence_with_start_one_word(self):
text_model = self.sherlock_model
start_str = "Sherlock"
sent = text_model.make_sentence_with_start(start_str)
assert sent is not None
assert start_str == sent[: len(start_str)]
def test_make_sentence_with_start_one_word_that_doesnt_begin_a_sentence(self):
text_model = self.sherlock_model
start_str = "dog"
with self.assertRaises(KeyError):
text_model.make_sentence_with_start(start_str)
def test_make_sentence_with_word_not_at_start_of_sentence(self):
text_model = self.sherlock_model
start_str = "dog"
sent = text_model.make_sentence_with_start(start_str, strict=False)
assert sent is not None
assert start_str == sent[: len(start_str)]
def test_make_sentence_with_words_not_at_start_of_sentence(self):
text_model = self.sherlock_model_ss3
# " I was " has 128 matches in sherlock.txt
# " was I " has 2 matches in sherlock.txt
start_str = "was I"
sent = text_model.make_sentence_with_start(start_str, strict=False, tries=50)
assert sent is not None
assert start_str == sent[: len(start_str)]
def test_make_sentence_with_words_not_at_start_of_sentence_miss(self):
text_model = self.sherlock_model_ss3
start_str = "was werewolf"
with self.assertRaises(markovify.text.ParamError):
text_model.make_sentence_with_start(start_str, strict=False, tries=50)
def test_make_sentence_with_words_not_at_start_of_sentence_of_state_size(self):
text_model = self.sherlock_model_ss2
start_str = "was I"
sent = text_model.make_sentence_with_start(start_str, strict=False, tries=50)
assert sent is not None
assert start_str == sent[: len(start_str)]
def test_make_sentence_with_words_to_many(self):
text_model = self.sherlock_model
start_str = "dog is good"
with self.assertRaises(markovify.text.ParamError):
text_model.make_sentence_with_start(start_str, strict=False)
def test_make_sentence_with_start_three_words(self):
start_str = "Sherlock Holmes was"
text_model = self.sherlock_model
try:
text_model.make_sentence_with_start(start_str)
assert False
except markovify.text.ParamError:
assert True
with self.assertRaises(Exception):
text_model.make_sentence_with_start(start_str)
text_model = self.sherlock_model_ss3
sent = text_model.make_sentence_with_start("Sherlock", tries=50)
assert markovify.chain.BEGIN not in sent
def test_short_sentence(self):
text_model = self.sherlock_model
sent = None
while sent is None:
sent = text_model.make_short_sentence(45)
assert len(sent) <= 45
def test_short_sentence_min_chars(self):
sent = None
while sent is None:
| sent = self.sherlock_model.make_short_sentence(100, min_chars=50)
assert len(sent) <= 100
assert len(sent) >= 50
def test_dont_test_output(self):
text_model = self.sherlock_model
sent = text_model.make_sentence(test_output=False)
assert sent is not None
def test_max_words(self):
text_model = self.sherlock_model
sent = text_model.make_sentence(max_words=0)
assert sent is None
def test_min_words(self):
te | xt_model = self.sherlock_model
sent = text_model.make_sentence(min_words=5)
assert len(sent.split(" ")) >= 5
def test_newline_text(self):
with open(
os.path.join(os.path.dirname(__file__), "texts/senate-bills.txt")
) as f:
model = markovify.NewlineText(f.read())
model.make_sentence()
def test_bad_corpus(self):
with self.assertRaises(Exception):
markovify.Chain(corpus="testing, testing", state_size=2)
def test_bad_json(self):
with self.assertRaises(Exception):
markovify.Chain.from_json(1)
def test_custom_regex(self):
with self.assertRaises(Exception):
markovify.NewlineText(
"This sentence contains a custom bad character: #.", reject_reg=r"#"
)
with self.assertRaises(Exception):
markovify.NewlineText("This sentence (would normall fail")
markovify.NewlineText("This sentence (would normall fail", well_formed=False)
class MarkovifyTest(MarkovifyTestBase):
__test__ = True
with open(os.path.join(os.path.dirname(__file__), "texts/sherlock.txt")) as f:
sherlock_text = f.read()
sherlock_model = markovify.Text(sherlock_text)
sherlock_model_ss2 = markovify.Text(sherlock_text, state_size=2)
sherlock_model_ss3 = markovify.Text(sherlock_text, state_size=3)
class MarkovifyTestCompiled(MarkovifyTestBase):
__test__ = True
with open(os.path.join(os.path.dirname(__file__), "texts/sherlock.txt")) as f:
sherlock_text = f.read()
sherlock_model = (markovify.Text(sherlock_text)).compile()
sherlock_model_ss2 = (markovify.Text(sherlock_text, state_size=2)).compile()
sherlock_model_ss3 = (markovify.Text(sherlock_text, state_size=3)).compile()
def test_recompiling(self):
model_recompile = self.sherlock_model.compile()
sent = model_recompile.make_sentence()
assert len(sent) != 0
model_recompile.compile(inplace=True)
sent = model_recompile.make_sentence()
assert len(sent) != 0
class MarkovifyTestCompiledInPlace(MarkovifyTestBase):
__test__ = True
with open(os.path.join(os.path.dirname(__file__), "texts/sherlock.txt")) as f:
sherlock_text = f.read()
sherlock_model = markovify.Text(sherlock_text)
sherlock_model_ss2 = markovify.Text(sherlock_text, state_size=2)
sherlock_model_ss3 = markovify.Text(sherlock_text, state_size=3)
sherlock_model.compile(inplace=True)
sherlock_model_ss2.compile(inplace=True)
sherlock_model_ss3.compile(inplace=True)
if __name__ == "__main__":
unittest.main()
|
chipaca/snapcraft | tests/unit/plugins/v1/test_maven.py | Python | gpl-3.0 | 23,004 | 0.001435 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2018-2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# 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 io
import os
import pathlib
import tarfile
from textwrap import dedent
from unittest import mock
from xml.etree import ElementTree
import fixtures
import pytest
from testtools.matchers import Equals, FileExists, HasLength
from snapcraft.internal import errors
from snapcraft.internal.meta.snap import Snap
from snapcraft.plugins.v1 import maven
from snapcraft.project import Project
from tests import unit
from . import PluginsV1BaseTestCase
class MavenPluginPropertiesTest(unit.TestCase):
def test_schema(self):
schema = maven.MavenPlugin.schema()
properties = schema["properties"]
self.assertTrue(
"maven-options" in properties,
'Expected "maven-options" to be included in ' "properties",
)
maven_options = properties["maven-options"]
self.assertTrue(
"type" in maven_options, 'Expected "type" to be included in "maven-options"'
)
self.assertThat(
maven_options["type"],
Equals("array"),
'Expected "maven-options" "type" to be "array", but '
'it was "{}"'.format(maven_options["type"]),
)
self.assertTrue(
"minitems" in maven_options,
'Expected "minitems" to be included in "maven-options"',
)
self.assertThat(
maven_options["minitems"],
Equals(1),
'Expected "maven-options" "minitems" to be 1, but '
'it was "{}"'.format(maven_options["minitems"]),
)
self.assertTrue(
"uniqueItems" in maven_options,
'Expected "uniqueItems" to be included in "maven-options"',
)
self.assertTrue(
maven_options["uniqueItems"],
'Expected "maven-options" "uniqueItems" to be "True"',
)
maven_targets = properties["maven-targets"]
self.assertTrue(
"type" in maven_targets, 'Expected "type" to be included in "maven-targets"'
)
self.assertThat(
maven_targets["type"],
Equals("array"),
'Expected "maven-targets" "type" to be "array", but '
'it was "{}"'.format(maven_targets["type"]),
)
self.assertTrue(
"minitems" in maven_targets,
'Expected "minitems" to be included in "maven-targets"',
)
self.assertThat(
maven_targets["minitems"],
Equals(1),
'Expected "maven-targets" "minitems" to be 1, but '
'it was "{}"'.format(maven_targets["minitems"]),
)
self.assertTrue(
"uniqueItems" in maven_targets,
'Expected "uniqueItems" to be included in "maven-targets"',
)
self.assertTrue(
maven_targets["uniqueItems"],
'Expected "maven-targets" "uniqueItems" to be "True"',
)
def test_get_pull_properties(self):
expected_pull_properties = [
"maven-version",
"maven-version-checksum",
"maven-openjdk-version",
]
resulting_pull_properties = maven.MavenPlugin.get_pull_properties()
self.assertThat(
resulting_pull_properties, HasLength(len(expected_pull_properties))
)
for property in expected_pull_properties:
self.assertIn(property, resulting_pull_properties)
def test_get_build_properties(self):
expected_build_properties = ["maven-options", "maven-targets"]
resulting_build_properties = maven.MavenPlugin.get_build_properties()
self.assertThat(
resulting_build_properties, HasLength(len(expected_build_properties))
)
for property in expected_build_properties:
self.assertIn(property, resulting_build_properties)
def _get_expected_java_version(maven_plugin) -> str:
base = maven_plugin.project._snap_meta.base
maven_openjdk_version = maven_plugin.options.maven_openjdk_version
if maven_openjdk_version:
expected_java_version = maven_openjdk_version
elif base in ("core", "core16"):
expected_java_version = "9"
else:
expected_java_version = "11"
return expected_java_version
_BASE_JAVA_COMBINATIONS = [
("", "core"),
("8", "core"),
("", "core16"),
("8", "core16"),
("", "core18"),
| ("11", "core18"),
]
@pytest.fixture(params=_BASE_JAVA_COMBINATIONS)
def maven_plugin(tmp_work_path, request):
"""Return an instance of MavenPlugin setup with different bases and java versions."""
java_version, base = request.param
cl | ass Options:
maven_options = []
maven_targets = [""]
maven_version = maven._DEFAULT_MAVEN_VERSION
maven_version_checksum = maven._DEFAULT_MAVEN_CHECKSUM
maven_openjdk_version = java_version
project = Project()
project._snap_meta = Snap(name="test-snap", base=base, confinement="strict")
return maven.MavenPlugin("test-part", Options(), project)
@pytest.fixture()
def maven_plugin_with_assets(maven_plugin):
"""Return an instance of MavenPlugin with artifacts setup using maven_plugin."""
pathlib.Path(maven_plugin.sourcedir).mkdir(parents=True)
expected_java_version = _get_expected_java_version(maven_plugin)
fake_java_path = (
pathlib.Path(maven_plugin.installdir)
/ f"usr/lib/jvm/java-{expected_java_version}-openjdk-amd64/bin/java"
)
fake_java_path.parent.mkdir(parents=True)
fake_java_path.touch()
maven_tar_path = (
pathlib.Path(maven_plugin.partdir)
/ f"maven/apache-maven-{maven_plugin.options.maven_version}-bin.tar.gz"
)
maven_tar_path.parent.mkdir(parents=True)
maven_tar_path.touch()
return maven_plugin
def test_stage_and_build_packages(maven_plugin):
expected_java_version = _get_expected_java_version(maven_plugin)
assert maven_plugin.stage_packages == [
f"openjdk-{expected_java_version}-jre-headless"
]
assert maven_plugin.build_packages == [
f"openjdk-{expected_java_version}-jdk-headless"
]
def test_build(mock_tar, mock_run, maven_plugin_with_assets):
plugin = maven_plugin_with_assets
def fake_run(cmd, *args, **kwargs):
os.makedirs(os.path.join(plugin.builddir, "target"))
open(os.path.join(plugin.builddir, "target", "jar.jar"), "w").close()
mock_run.side_effect = fake_run
plugin.build()
mock_run.assert_called_once_with(
["mvn", "package"], cwd=plugin.builddir, env=mock.ANY
)
def test_build_war(mock_tar, mock_run, maven_plugin_with_assets):
plugin = maven_plugin_with_assets
def fake_run(cmd, *args, **kwargs):
os.makedirs(os.path.join(plugin.builddir, "target"))
open(os.path.join(plugin.builddir, "target", "war.war"), "w").close()
mock_run.side_effect = fake_run
plugin.build()
mock_run.assert_called_once_with(
["mvn", "package"], cwd=plugin.builddir, env=mock.ANY
)
def test_build_with_targets(mock_tar, mock_run, maven_plugin_with_assets):
maven_plugin_with_assets.options.maven_targets = ["child1", "child2"]
plugin = maven_plugin_with_assets
def fake_run(cmd, *args, **kwargs):
os.makedirs(os.path.join(plugin.builddir, "child1", "target"))
os.makedirs(os.path.join(plugin.builddir, "child2", "target"))
open(
os.path.join(plugin.builddir, "child1", "target", "child1.jar"), "w"
).close()
open(
|
LighthouseHPC/lighthouse | sandbox/scripts/anamod2arff.py | Python | mit | 18,296 | 0.013172 | #!/usr/bin/env python
'''
Created on Feb 17, 2015
@author: norris
'''
import re, sys, os, argparse, glob, time, datetime, socket, random
from solvers import *
solveropts = getsolvers()
def readFeatures(dirname='anamod_features'):
files=glob.glob(dirname + '/*.anamod')
featuresre= re.compile(r'========([^=]+)========')
features = dict()
feature_times = dict()
# features dictionary is indexed by matrix name
# each value is a dictionary with keys corresponding to feature name and
# value corresponding to feature value
featurenames = None
for filename in files:
basename = os.path.basename(filename)
matrixname = basename.split('.')[0]
f = open(filename,'r')
contents = f.read()
f.close()
features[matrixname] = dict()
m = featuresre.search(contents)
if not m:
print "Could not extract features for " + str(filename)
continue
print "Extracting features for " + str(filename)
flines = m.group(1).split('\n')
tmpdictstr = '{'
for fl in flines:
if fl.startswith(' '):
nameval = fl.split(':')
nameval = [n.strip().replace('>','').replace('<','') for n in nameval]
valtime = nameval[1].split(',')
val = valtime[0]
if len(valtime)>1:
if not matrixname in feature_times.keys():
feature_times[matrixname] = dict()
feature_times[matrixname][nameval[0]] = valtime[1]
tmpd | ictstr += " '" + nameval[0] + "' : " + val + ','
tmpdictstr.rstrip(',')
tmpdictstr += '}'
features[matrixname] = eval(tmpdictstr.replace('****',"'?'").replace('-nan',"'?'").replace('inf',"float('Inf')"))
#print feature_times
return | features, feature_times
def readFeaturesTrilinos(path='tpetra_properties/12procs_results.csv'):
fd = open(path,'r')
lines = fd.readlines()
fd.close()
features = dict()
# features dictionary is indexed by matrix name
# each value is a dictionary with keys corresponding to feature name and
# value corresponding to feature value
featurenames = []
for s in lines[0].strip().strip(',').split(',')[1:]:
if s.startswith("Eigen"):
featurenames.append('"%s Re"' % s)
featurenames.append('"%s Im"' % s)
else:
featurenames.append('"%s"' % s)
for line in lines[1:]:
contents = line.strip().strip(',').split(',')
matrixname = contents[0].replace('.mtx','')
features[matrixname] = dict()
i = 1
for c in contents[2:]:
if featurenames[i].startswith('"Eigen'):
if c.find(':') > 0:
real,imaginary=c.split(':')
features[matrixname][featurenames[i]] = real
features[matrixname][featurenames[i+1]] = imaginary
else:
features[matrixname][featurenames[i]] = '?'
features[matrixname][featurenames[i+1]] = '?'
i += 1
else:
features[matrixname][featurenames[i]] = c.replace('unconverged','?').replace('-nan','?')
i += 1
return features
def readPerfDataBelos(features,filename):
matrices = open(filename).readlines()
perf = dict()
solvers = dict()
missing = []
for matrixline in matrices:
# Log format, example line:
# 1138_bus.mtx, Block CG, RELAXATION, unconverged, 1000, 0.035481
data = [x.strip() for x in matrixline.split(',')]
solverID = data[1]+ '*' + data[2] # KSP, PC
convergence = data[3]
matrixname = data[0].split('.')[0]
if not matrixname in features.keys():
if matrixname not in missing: missing.append(matrixname)
continue
if not features[matrixname]: continue
if matrixname not in perf.keys():
perf[matrixname] = {'mintime':sys.float_info.max}
perf[matrixname][solverID] = [data[1],data[2],data[3],data[-1]]
if solverID not in solvers.keys():
solvers[solverID] = 0
solvers[solverID] += 1
time = data[-1]
if convergence.strip() == 'unconverged':
time = str(sys.float_info.max)
perf[matrixname][solverID][3] = time
dtime = float(time)
if dtime < perf[matrixname]['mintime']:
#print matrixname, solverID, features[matrixname]
perf[matrixname]['mintime'] = dtime
print "No features found for these matrices, their solver times have not been included: ", ','.join(missing)
print "Number of solvers considered: ", len(solvers.keys())
return perf, solvers
def readPerfData(features,dirname,threshold):
'''Log format excerpt (solver, preconditioner, convergence reason, time, tolerance)
Beginning of each matrixname.solverhash.log file (more recent tests only)
Hash: 43373443
tcqmr | icc | -3 | 1.926556e+02 | 84.0693 | 10000
...
On other platforms, we need to extract this data from the petsc command line options, which
are also in the log
'''
#solvers = getsolvers()
files = glob.glob(dirname+'/*.log')
#files = open(".bgq",'r').readlines()
print "Reading performance data from", len(files), "files"
perf = dict()
solversamples = dict()
count = 0
for logfile in files:
#logfile = dirname + '/' + logfile.strip()
print count, ": Processing", logfile
count += 1
statinfo = os.stat(logfile)
fname=os.path.basename(logfile)
parts = fname.split('.')
pval = 'p1'
if len(parts) == 4: matrixname,hashid,pval = parts[:3]
else: matrixname,hashid = parts[:2]
nprocs = pval.strip('p')
if not matrixname in features.keys():
print "No features found for this matrix"
continue
if not features[matrixname]: continue
#print matrixname
if matrixname not in perf.keys():
perf[matrixname] = {'mintime':sys.float_info.max}
solverID = hashid
fd = open(logfile,'r')
contents = fd.read()
fd.close()
if contents.find('-hash ') < 0: continue
lines = contents.split('\n')
if len(lines) < 2: #Check for timeout
if lines[-1].strip().endswith('timeout'):
perf[matrixname] = {'mintime':sys.float_info.max}
solverpc = solveropts[solverID].split()
s = solverpc[1]
p = ' '.join(solverpc[3:])
perf[matrixname][solverID] = [s,p,'-100',str(sys.float_info.max),str(sys.float_info.max),nprocs]
continue
bgqdata = []
for l in lines:
if l.startswith('Machine characteristics: Linux-2.6.32-431.el6.ppc64-ppc64-with-redhat-6.5-Santiago'):
# This is a BG/Q log, which had some custom output
bgqdata = [d.strip() for d in lines[1].split('|')]
break
#else:
options=False
#data [solver, preconditioner, convergence reason, time, tolerance, numprocs]
data = ['','','','','','']
for l in lines:
tmp=''
if options:
if l.startswith('-ksp_type'):
data[0] = l.split()[-1]
elif l.startswith('-pc_type'):
if data[1]: tmp=data[1]
data[1] = l.split()[-1] + tmp
elif l.startswith('-pc_'):
if data[1]: tmp=data[1]
data[1] = tmp + l.split()[-1]
# ------
if l.startswith("#PETSc Option Table entries:"):
options=True
elif l.startswith("#End of PETSc Option Table entries"):
break
elif l.startswith("MatSolve"):
data[3] = l.split()[3] # time
else: continue
if bgqdata: data[3] = bgqdata[3]
data[5] = str(nprocs)
print data
#solvername = solvers[hashid]
|
vtemian/uni-west | second_year/os/exams/round2/scheduler/parsers/base.py | Python | apache-2.0 | 207 | 0 | from abc | import ABCMeta, abstractmethod
class Parser(object):
__meta__ = ABCMeta
def __init__(self, source):
self.source = source
@abstractmethod
| def schedule(self):
pass
|
bendemott/solr-zkutil | solrzkutil/__init__.py | Python | mit | 38,530 | 0.00654 | #!/usr/bin/python
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import time
import argparse
from datetime import datetime, timedelta, tzinfo
from textwrap import dedent
import json
from random import choice
import webbrowser
import itertools
import logging
import threading
from threading import Thread
from os.path import expanduser, expandvars, dirname, exists, join
log = logging.getLogger()
logging.basicConfig()
import pendulum
import six
from six.moves import input
from tzlocal import get_localzone
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.protocol.states import EventType
from kazoo.handlers.threading import KazooTimeoutError
import colorama
from colorama import Fore, Back, Style
from solrzkutil.util import netcat, text_type, parse_zk_hosts, get_leader, get_server_by_id
from solrzkutil.parser import parse_admin_dump, parse_admin_cons
from solrzkutil.healthy import (check_zookeeper_connectivity,
check_ephemeral_sessions_fast,
check_ephemeral_znode_consistency,
check_ephemeral_dump_consistency,
check_watch_sessions_clients,
check_watch_sessions_duplicate,
check_queue_sizes,
check_watch_sessions_valid,
check_overseer_election,
get_solr_session_ids,
multi_admin_command)
__application__ = 'solr-zkutil'
COMMANDS = {
# key: cli-value
# do not change the keys, but you may freely change the values of the tuple, to modify
# the command or description.
'solr': ('live-nodes', 'List Solr Live Nodes from ZooKeeper'),
'clusterstate': ('clusterstate', 'List Solr Collections and Nodes'),
'watch': ('watch', 'Watch a ZooKeeper Node for Changes'),
'test': ('test', 'Test Each Zookeeper Ensemble node for replication and client connectivity'), # TODO
'status': ('stat', 'Check ZooKeeper ensemble status'),
'config': ('config', 'Show connection strings, or set environment configuration'),
'admin': ('admin', 'Execute a ZooKeeper administrative command'),
'ls': ('ls', 'List a ZooKeeper Node'),
'sessions': ('session-reset', 'Reset ZooKeeper sessions, each client will receive a SESSION EXPIRED notification, and will automatically reconnect. Solr ephemeral nodes should re-register themselves.'),
'health': ('health', 'Test/Check the health of Zookeeper and Solr, any errors or problems will be printed to the console.')
}
CONFIG_DIRNAME = __application__
HEADER_STYLE = Back.CYAN + Fore.WHITE + Style.BRIGHT
HEADER_JUST = 10
TITLE_STYLE = Fore.CYAN + Style.BRIGHT
INFO_STYLE = Fore.YELLOW + Style.BRIGHT
ERROR_STYLE = Back.WHITE + Fore.RED + Style.BRIGHT
INPUT_STYLE = Fore.WHITE + Style.BRIGHT
BLUE_STYLE = Fore.BLUE + Style.BRIGHT
DIFF_STYLE = Fore.MAGENTA + Style.BRIGHT
STATS_STYLE = Fore.MAGENTA + Style.BRIGHT
GREEN_STYLE = Fore.GREEN + Style.BRIGHT
ZK_LIVE_NODES = '/live_nodes'
ZK_CLUSTERSTATE = '/clusterstate.json'
MODE_LEADER = 'leader'
# the first event will always be triggered immediately to show the existing state of the node
# instead of saying 'watch event' tell the user we are just displaying initial sta | te.
WATCH_COUNTER = 0
ZK_ADMIN_CMDS = {
'conf': {
'help': 'Print details about serving configuration.',
'example': '',
'version': '3.3.0',
},
'cons': {
'help': ('List full connection/session details for all clients connected to | this server. '
'Includes information on numbers of packets received/sent, session id, operation '
'latencies, last operation performed, etc...'),
'example': '',
'version': '3.3.0',
},
'crst':{
'help': 'Reset connection/session statistics for all connections.',
'example': '',
'version': '3.3.0',
},
'dump':{
'help': 'Lists the outstanding sessions and ephemeral nodes. This only works on the leader.',
'example': '',
'version': '',
},
'envi':{
'help': 'Print details about serving environment',
'example': '',
'version': '',
},
'ruok':{
'help': 'Tests if server is running in a non-error state. The server will respond with imok if it is running. Otherwise it will not respond at all.',
'example': '',
'version': '',
},
'srst':{
'help': 'Reset server statistics.',
'example': '',
'version': '',
},
'srvr':{
'help': 'Lists full details for the server.',
'example': '',
'version': '3.3.0',
},
'stat':{
'help': 'Lists brief details for the server and connected clients.',
'example': '',
'version': '',
},
'wchs':{
'help': 'Lists brief information on watches for the server.',
'example': '',
'version': '3.3.0',
},
'wchc':{
'help': 'Lists detailed information on watches for the server, by session. (may be expensive)',
'example': '',
'version': '3.3.0',
},
'dirs':{
'help': 'Shows the total size of snapshot and log files in bytes',
'example': '',
'version': '3.5.1',
},
'wchp':{
'help': 'Lists detailed information on watches for the server, by path. This outputs a list of paths (znodes) with associated sessions.',
'example': '',
'version': '3.3.0',
},
'mntr': {
'help': 'Outputs a list of variables that could be used for monitoring the health of the cluster.',
'example': '3.4.0'
},
'isro':{
'help': 'Tests if server is running in read-only mode. The server will respond with "ro" if in read-only mode or "rw" if not in read-only mode.',
'example': '',
'version': '3.4.0',
},
'gtmk':{
'help': 'Gets the current trace mask as a 64-bit signed long value in decimal format. See stmk for an explanation of the possible values.',
'example': '',
'version': '',
},
'stmk':{
'help': 'Sets the current trace mask. The trace mask is 64 bits, where each bit enables or disables a specific category of trace logging on the server.',
'example': '',
'version': '',
},
}
ZNODE_DEBUG_ATTRS = [
'aversion',
'cversion',
'version',
'numChildren',
'ctime',
'mtime',
'czxid',
'mzxid',
'pzxid',
'dataLength',
'ephemeralOwner',
]
NEW_TAB = 2
def config_path():
conf = None
if os.name == 'nt':
conf = os.path.expandvars("%%appdata%%/.%s/environments.json" % CONFIG_DIRNAME)
else:
conf = os.path.expanduser("~/.%s/environments.json" % CONFIG_DIRNAME)
return conf
def config():
conf = config_path()
if not exists(conf):
if not exists(dirname(conf)):
os.makedirs(dirname(conf))
open(conf, mode='w').write(dedent('''
{
"DEV": "localhost:2181",
"QA": "localhost:2181",
"PILOT": "localhost:2181",
"PROD": "localhost:2181"
}
'''))
return json.loads(open(conf, mode='r').read().strip())
def style_header(text, width = 0):
if not text:
return ''
width = max(len(text) + HEADER_JUST * 2, width)
pad = ' ' * width
output = '\n%s%s\n%s\n%s%s\n' % (HEADER_STYLE, pad, text.center(width), pad, Style.RESET_ALL)
return output
def style_text(text, styles, ljust=0, rjust=0, cen=0, lpad=0, rpad=0, pad=0, char=' ', restore=''):
if not text:
return ''
# Ensure we have unicode in both python 2/3
text = text_type(text)
styles = text_type(styles)
char = text_type(char)
restore = text_type(restore)
reset_all = text_type(Style.RESET_ALL)
style = ''.join(styles)
text = text.ljust(ljust, char)
text = text.rjust(rjust, char)
tex |
Letractively/spiff | src/FooLib/OptionParser.py | Python | gpl-2.0 | 2,493 | 0.005616 | # Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import re
from getopt import getopt
True = 1
False = 0
def parse_options(argv, options):
"""
Parses the options into the given list, returns a tuple containing the new
list and the remaining arguments.
"""
# Use getopt | to parse the options.
short = ''.join([option[1] or '' for option in options])
lon | g = [option[0] for option in options]
try:
opts, args = getopt(argv[1:], short, long)
except:
raise Exception("Invalid arguments")
# Copy the default options into a hash.
option_hash = {}
for option in options:
long = option[0].replace('=', '')
option_hash[long] = option[2]
# Walk through all options and sort them into a hash.
for key, value in opts:
found = False
for option in options:
long = option[0] or ''
short = option[1] or ''
if long.endswith('='):
long = long.replace('=', '')
short = short.replace(':', '')
if key not in ('--'+long, '-'+short):
continue
found = True
#print "Short:", short, "Long:", long
# Flags.
if not option[0].endswith('='):
option_hash[long] = True
continue
# Key/value pairs.
if type(option_hash[long]) == type({}):
value = value.split('=')
option_hash[long][value[0]] = value[1]
# Strings.
elif re.match('^\d+$', value) is None:
option_hash[long] = value
# Integer.
else:
option_hash[long] = int(value)
if not found:
raise Exception("Invalid argument '%s'" % key)
return (option_hash, args)
|
vikkyrk/incubator-beam | sdks/python/apache_beam/runners/dataflow/internal/dependency_test.py | Python | apache-2.0 | 16,889 | 0.00521 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not 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.
#
"""Unit tests for the setup module."""
import logging
import os
import shutil
import tempfile
import unittest
from apache_beam.io.filesystems import FileSystems
from apache_beam.runners.dataflow.internal import dependency
from apache_beam.runners.dataflow.internal import names
from apache_beam.utils.pipeline_options import GoogleCloudOptions
from apache_beam.utils.pipeline_options import PipelineOptions
from apache_beam.utils.pipeline_options import SetupOptions
class SetupTest(unittest.TestCase):
def update_options(self, options):
setup_options = options.view_as(SetupOptions)
setup_options.sdk_location = ''
google_cloud_options = options.view_as(GoogleCloudOptions)
if google_cloud_options.temp_location is None:
google_cloud_options.temp_location = google_cloud_options.staging_location
def create_temp_file(self, path, contents):
with open(path, 'w') as f:
f.write(contents)
return f.name
def populate_requirements_cache(self, requirements_file, cache_dir):
_ = requirements_file
self.create_temp_file(os.path.join(cache_dir, 'abc.txt'), 'nothing')
self.create_temp_file(os.path.join(cache_dir, 'def.txt'), 'nothing')
def test_no_staging_location(self):
with self.assertRaises(RuntimeError) as cm:
dependency.stage_job_resources(PipelineOptions())
self.assertEqual('The --staging_location option must be specified.',
cm.exception.message)
def test_no_temp_location(self):
staging_dir = tempfile.mkdtemp()
options = PipelineOptions()
google_cloud_options = options.view_as(GoogleCloudOptions)
google_cloud_options.staging_location = staging_dir
self.update_options(options)
google_cloud_options.temp_location = None
with self.assertRaises(RuntimeError) as cm:
dependency.stage_job_resources(options)
self.assertEqual('The --temp_location option must be specified.',
cm.exception.message)
def test_no_main_session(self):
staging_dir = tempfile.mkdtemp()
options = PipelineOptions()
options.view_as(GoogleCloudOptions).staging_location = staging_dir
options.view_as(SetupOptions).save_main_session = False
self.update_options(options)
self.assertEqual(
[],
dependency.stage_job_resources(options))
def test_with_main_session(self):
staging_dir = tempfile.mkdtemp()
options = PipelineOptions()
options.view_as(GoogleCloudOptions).staging_location = staging_dir
options.view_as(SetupOptions).save_main_session = True
self.update_options(options)
self.assertEqual(
[names.PICKLED_MAIN_SESSION_FILE],
dependency.stage_job_resources(options))
self.assertTrue(
os.path.isfile(
os.path.join(staging_dir, names.PICKLED_MAIN_SESSION_FILE)))
def test_default_resources(self):
staging_dir = tempfile.mkdtemp()
options = PipelineOptions()
options.view_as(GoogleCloudOptions).staging_location = staging_dir
self.update_options(options)
self.assertEqual(
[],
dependency.stage_job_resources(options))
def test_with_requirements_file(self):
try:
staging_dir = tempfile.mkdtemp()
requirements_cache_dir = tempfile.mkdtemp()
source_dir = tempfile.mkdtemp()
options = PipelineOptions()
options.view_as(GoogleCloudOptions).staging_location = staging_dir
self.update_options(options)
options.view_as(SetupOptions).requirements_cache = requirements_cache_dir
options.view_as(SetupOptions).requirements_file = os.path.join(
source_dir, dependency.REQUIREMENTS_FILE)
self.create_temp_file(
os.path.join(source_dir, dependency.REQUIREMENTS_FILE), 'nothing')
self.assertEqual(
sorted([dependency.REQUIREMENTS_FILE,
'abc.txt', 'def.txt']),
sorted(dependency.stage_job_resources(
options,
populate_requirements_cache=self.populate_requirements_cache)))
self.assertTrue(
os.path.isfile(
os.path.join(staging_dir, dependency.REQUIREMENTS_FILE)))
self.assertTrue(os.path.isfile(os.path.join(staging_dir, 'abc.txt')))
self.assertTrue(os.path.isfile(os.path.join(staging_dir, 'def.txt')))
finally:
shutil.rmtree(staging_dir)
shutil.rmtree(requirements_cache_dir)
shutil.rmtree(source_dir)
def test_requirements_file_not_present(self):
staging_dir = tempfile.mkdtemp()
with self.assertRaises(RuntimeError) as cm:
options = PipelineOptions()
options.view_as(GoogleCloudOptions).staging_location = staging_dir
self.update_options(options)
options.view_as(SetupOptions).requirements_file = 'nosuchfile'
dependency.stage_job_resources(
options, populate_requirements_cache=self.populate_requirements_cache)
self.assertEqual(
cm.exception.message,
'The file %s cannot be found. It was specified in the '
'--requirements_file command line option.' % 'nosuchfile')
def test_with_requirements_file_and_cache(self):
staging_dir = tempfile.mkdtemp()
source_dir = tempfile.mkdtemp()
options = PipelineOptions()
options.view_as(GoogleCloudOptions).staging_location = staging_dir
self.update_options(options)
options.view_as(SetupOptions).requirements_file = os.path.join(
source_dir, dependency.REQUIREMENTS_FILE)
options.view_as(SetupOptions).requirements_cache = os.path.join(
tempfile.gettempdir(), 'alternative-cache-dir')
self.create_temp_file(
os.path.join(source_dir, dependency.REQUIREMENTS_FILE), 'nothing')
self.assertEqual(
sorted([dependency.REQUIREMENTS_FILE,
'abc.txt', 'def.txt']),
sorted(dependency.stage_job_resources(
options,
populate_requirements_cache=self.populate_requirements_cache)))
self.assertTrue(
os.path.isfile(
os.path.join(staging_dir, dependency.REQUIREMENTS_FILE)))
self.assertTrue(os.path.isfile(os.path.join(staging_dir, 'abc.txt')))
self.assertTrue(os.path.isfile(os.path.join(staging_dir, 'def.txt')))
def test_with_setup_file(self):
staging_dir = tempfile.mkdtemp()
source_dir = tempfile.mkdtemp()
self.create_temp_file(
os.path.join(source_dir, 'setup.py'), 'notused')
options = PipelineOptions()
options.view_as(Goo | gleCloudOptions).staging_location = staging_dir
self.update_options(options)
options.view | _as(SetupOptions).setup_file = os.path.join(
source_dir, 'setup.py')
self.assertEqual(
[dependency.WORKFLOW_TARBALL_FILE],
dependency.stage_job_resources(
options,
# We replace the build setup command because a realistic one would
# require the setuptools package to be installed. Note that we can't
# use "touch" here to create the expected output tarball file, since
# touch is not available on Windows, so we invoke python to produce
# equivalent behavior.
build_setup_args=[
'python', '-c', 'open(__import__("sys").argv[1], "a")',
os.path.join(source_dir, dependency.WORKFLOW_TARBALL_FILE)],
temp_dir=source_dir))
self.assertTrue(
os.path.isfile(
os.path.join(staging_dir, dependency.WORKFLOW_TARB |
ahmedaljazzar/edx-platform | common/djangoapps/third_party_auth/migrations/0021_sso_id_verification.py | Python | agpl-3.0 | 1,186 | 0.00253 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-11 15:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('third_party_auth', '0020_cleanup_slug_fields'),
]
operations = [
migrations.AddField(
model_name='lti | providerconfig',
name='enable_sso_id_verification',
field=models.BooleanField(default=False, help_text=b'Use the presence of a profile from a trusted third party as proof of identity verification.'),
),
migrations.AddField(
model_name='oauth2providerconfig',
na | me='enable_sso_id_verification',
field=models.BooleanField(default=False, help_text=b'Use the presence of a profile from a trusted third party as proof of identity verification.'),
),
migrations.AddField(
model_name='samlproviderconfig',
name='enable_sso_id_verification',
field=models.BooleanField(default=False, help_text=b'Use the presence of a profile from a trusted third party as proof of identity verification.'),
),
]
|
formalmethods/intrepyd | intrepyd/iec611312py/stmtbuilder.py | Python | bsd-3-clause | 8,639 | 0.002199 | """
Copyright (C) 2018 Roberto Bruttomesso <roberto.bruttomesso@gmail.com>
This file is distributed under the terms of the 3-clause BSD License.
A copy of the license can be found in the root directory or at
https://opensource.org/licenses/BSD-3-Clause.
Author: Roberto Bruttomesso <roberto.bruttomesso@gmail.com>
Date: 29/10/2018
This module implements the main parsing routine of IEC61131 text
"""
from intrepyd.iec611312py.IEC61131ParserVisitor import IEC61131ParserVisitor
from intrepyd.iec611312py.statement import Assignment, IfThenElse, Case
from intrepyd.iec611312py.expression import VariableOcc, ConstantOcc, Expression, Range, FunctionOcc, ParamInit, TRUE
from intrepyd.iec611312py.variable import Variable
def isNumber(text):
for i in range(len(text)):
if not text[i].isdigit() and text[i] != '.':
return False
return True
def computeCompositeDatatype(var, name2var):
tokens = var.split('.')
if len(tokens) != 2:
raise RuntimeError('Cannot handle nested structures')
baseType = name2var[tokens[0]]
for name, variable in baseType.datatype.fields.iteritems():
if name == tokens[1]:
return variable.datatype
return None
class STMTBuilder(IEC61131ParserVisitor):
"""
Vistor that builds statements from the IEC program
"""
def __init__(self, name2var, pou2inputs):
self._statements = []
self._name2var = name2var
self._pou2inputs = pou2inputs
@property
def statements(self):
return self._statements
def visitBodyST(self, ctx):
self._statements = ctx.getChild(0).accept(self)
def visitStmt_block(self, ctx):
return [ctx.getChild(i).accept(self) for i in range(ctx.getChildCount())]
def visitSt_stmt(self, ctx):
return ctx.getChild(0).accept(self)
def visit_stmt(self, ctx):
return ctx.getChild(0).accept(self)
def visitAssignVariable(self, ctx):
lhs = ctx.getChild(0).accept(self)
rhs = ctx.getChild(2).accept(self)
return Assignment(lhs, rhs)
def visitAssignCompositeAccess(self, ctx):
lhs = ctx.getChild(0).accept(self)
rhs = ctx.getChild(2).accept(self)
return Assignment(lhs, rhs)
def visitExpression(self, ctx):
return ctx.getChild(0).accept(self)
def visitBinaryBoolExpression(self, ctx):
return self._binaryExpressionHelper(ctx)
def visitBinaryTermExpression(self, ctx):
return self._binaryExpressionHelper(ctx)
def visitUnaryBoolExpression(self, ctx):
return self._unaryExpressionHelper(ctx)
def visitUnaryTermExpression(self, ctx):
return self._unaryExpressionHelper(ctx)
def visitLeafBoo | lExpression(self, ctx):
return ctx.getChild(0).accept(self)
def | visitParBoolExpression(self, ctx):
return ctx.subexpr.accept(self)
def visitParTermExpression(self, ctx):
return ctx.subexpr.accept(self)
def visitSimple_var(self, ctx):
var = ctx.getChild(0).getText()
if not var in self._name2var:
raise RuntimeError('Undeclared variable ' + var)
return VariableOcc(self._name2var[var])
def visitComposite_access(self, ctx):
base = ctx.getChild(0).getText()
if not base in self._name2var:
raise RuntimeError('Undeclared variable ' + base)
var = ctx.getText()
if not var in self._name2var:
datatype = computeCompositeDatatype(var, self._name2var)
self._name2var[var] = Variable(var, datatype, Variable.FIELD)
return VariableOcc(self._name2var[var])
def visitArray_access(self, ctx):
raise NotImplementedError
def visitVariable_bit_access(self, ctx):
raise NotImplementedError
def visitConstant(self, ctx):
cst = ctx.getText()
return ConstantOcc(cst)
def visitCallBoolExpression(self, ctx):
return self._callExpressionHelper(ctx)
def visitCallTermExpression(self, ctx):
return self._callExpressionHelper(ctx)
def visitCustomCallExpression(self, ctx):
pouName = ctx.getChild(0).getText()
if not pouName in self._pou2inputs:
raise('Could not find pou ' + pouName)
inputs = self._pou2inputs[pouName]
paramInits = []
param = 0
if ctx.getChildCount() > 2:
for i in range(2, ctx.getChildCount(), 2):
paramInit = ctx.getChild(i).accept(self)
paramInits.append(paramInit)
paramInit.rhs.datatype = inputs[param].datatype
param += 1
return FunctionOcc(ctx.getChild(0).getText(), paramInits)
def visitFunc_param_init(self, ctx):
param = ctx.getChild(0).getText()
value = ctx.getChild(2).getText()
if isNumber(value):
return ParamInit(param, ConstantOcc(value)) # type will be set by caller
return ParamInit(param, VariableOcc(Variable(value, None, Variable.TEMP))) # type will be set by caller
def visitIf_stmt(self, ctx):
return ctx.getChild(0).accept(self)
def visitIf_simple_stmt(self, ctx):
conditions = []
statements = []
conditions.append(ctx.ifexpr.accept(self))
statements.append(ctx.ifstmt.accept(self))
return IfThenElse(conditions, statements)
def visitIf_elseif_stmt(self, ctx):
conditions = []
statements = []
conditions.append(ctx.ifexpr.accept(self))
statements.append(ctx.ifstmt.accept(self))
conds, stmts = ctx.elsifstmt.accept(self)
for cond in conds:
conditions.append(cond)
for stmt in stmts:
statements.append(stmt)
return IfThenElse(conditions, statements)
def visitIf_else_stmt(self, ctx):
conditions = []
statements = []
conditions.append(ctx.ifexpr.accept(self))
statements.append(ctx.ifstmt.accept(self))
conditions.append(TRUE)
statements.append(ctx.elsestmt.accept(self))
return IfThenElse(conditions, statements)
def visitIf_complete_stmt(self, ctx):
conditions = []
statements = []
conditions.append(ctx.ifexpr.accept(self))
statements.append(ctx.ifstmt.accept(self))
conds, stmts = ctx.elsifstmt.accept(self)
for cond in conds:
conditions.append(cond)
for stmt in stmts:
statements.append(stmt)
conditions.append(TRUE)
statements.append(ctx.elsestmt.accept(self))
return IfThenElse(conditions, statements)
def visitElsif_stmt_list(self, ctx):
conditions = []
statements = []
for i in range(ctx.getChildCount()):
cond, stmt = ctx.getChild(i).accept(self)
conditions.append(cond)
statements.append(stmt)
return conditions, statements
def visitElsif_stmt(self, ctx):
return ctx.expr.accept(self), ctx.stmtblock.accept(self)
def visitCase_stmt(self, ctx):
expression = ctx.expr.accept(self)
selections, statements = ctx.casesel.accept(self)
if ctx.getChildCount() == 7:
# There is else too
selections.append([expression])
statements.append(ctx.elsestmt.accept(self))
return Case(expression, selections, statements)
def visitCase_selections(self, ctx):
selections = []
statements = []
for i in range(ctx.getChildCount()):
sel, stmt = ctx.getChild(i).accept(self)
selections.append(sel)
statements.append(stmt)
return selections, statements
def visitCase_selection(self, ctx):
return ctx.getChild(0).accept(self), ctx.getChild(2).accept(self)
def visitCase_list(self, ctx):
return [ctx.getChild(i).accept(self) for i in range(0, ctx.getChildCount(), 2)]
def visitCaseRange(self, ctx):
return Range(ctx.start.getText(), ctx.to.getText())
def visitCaseExpression(self, ctx):
return ctx.getChild(0).accept(self)
def _binaryExpressionHelper(self, ctx):
operator = ctx.op.text
argu |
wangtaoking1/found_website | 项目代码/classification.py | Python | gpl-2.0 | 6,580 | 0.037633 | # -*- coding: utf-8 -*-
#search函数,参数为输入文件,输出文件,关键词。关键词与输入文件的每六行进行匹配(六行为一条微博),如果出现该关键词,则把该微博输出到输出文件中
def search(input_file,output_file,key):
line = input_file.readline()
if line == "\n":
line = input_file.readline()
while line: #如果文件没有结束,继续读取
lines = ""
lines += line
for i in range (1,6):
line = input_file.readline()
lines += line #在文件中连续读六行,并放到lines中
index = lines.find(key)
if index == -1: #如果找不到关键词,pass
pass
else:
output_file.write(lines) #若找到,则写到输出文件中
line = input_file.readline()
try:
s = "\n"
inputFile=open("data/weibo.txt","r") #在所有微博中匹配关键词
wallet=open("data/allClasses/wallet.txt","w")
wallet.write(s)
search(inputFile,wallet,"钱包") #匹配关键词“钱包”
inputFile.close()
wallet.close()
inputFile=open("data/weibo.txt","r")
campuscard=open("data/allClasses/campuscard.txt","w")
campuscard.write(s)
search(inputFile,campuscard,"校园卡") #匹配关键词“校园卡”
inputFile.close()
campuscard.close()
inputFile=open("data/weibo.txt","r")
bankcard=open("data/allClasses/bankcard.txt","w")
bankcard.write(s)
search(inputFile,bankcard,"银行卡") #匹配关键词“银行卡”
inputFile.close()
bankcard.close()
inputFile=open("data/weibo.txt","r")
idcard=open("data/allClasses/IDcard.txt","w")
idcard.write(s)
search(inputFile,idcard,"身份证") #匹配关键词“身份证”
inputFile.close()
idcard.close()
inputFile=open("data/weibo.txt","r")
cellphone=open("data/allClasses/cellphone.txt","a")
cellphone.truncate()
cellphone.write(s)
search(inputFile,cellphone,"手机") #匹配关键词“手机”
inputFile.close()
cellphone.close()
inputF | ile=open("data/weibo.txt","r") |
cellphone=open("data/allClasses/cellphone.txt","a")
search(inputFile,cellphone,"iphone")
inputFile.close()
cellphone.close()
inputFile=open("data/weibo.txt","r")
key=open("data/allClasses/key.txt","w")
key.write(s)
search(inputFile,key,"钥匙") #匹配关键词“钥匙”
inputFile.close()
key.close()
inputFile=open("data/weibo.txt","r")
flashdisk=open("data/allClasses/flashdisk.txt","a")
flashdisk.truncate()
flashdisk.write(s)
search(inputFile,flashdisk,"U盘") #匹配关键词“U盘”
inputFile.close()
flashdisk.close()
inputFile=open("data/weibo.txt","r")
flashdisk=open("data/allClasses/flashdisk.txt","a")
search(inputFile,flashdisk,"优盘")
inputFile.close()
flashdisk.close()
except IOError,e:
print "open file error",e
try:
inputFile=open("data/find.txt","r") #在“找到”的微博中匹配关键词
wallet=open("data/findClasses/wallet.txt","w")
search(inputFile,wallet,"钱包")
inputFile.close()
wallet.close()
inputFile=open("data/find.txt","r")
campuscard=open("data/findClasses/campuscard.txt","w")
search(inputFile,campuscard,"校园卡")
inputFile.close()
campuscard.close()
inputFile=open("data/find.txt","r")
bankcard=open("data/findClasses/bankcard.txt","w")
search(inputFile,bankcard,"银行卡")
inputFile.close()
bankcard.close()
inputFile=open("data/find.txt","r")
idcard=open("data/findClasses/IDcard.txt","w")
search(inputFile,idcard,"身份证")
inputFile.close()
idcard.close()
inputFile=open("data/find.txt","r")
cellphone=open("data/findClasses/cellphone.txt","a")
cellphone.truncate()
search(inputFile,cellphone,"手机")
inputFile.close()
cellphone.close()
inputFile=open("data/find.txt","r")
cellphone=open("data/findClasses/cellphone.txt","a")
search(inputFile,cellphone,"iphone")
inputFile.close()
cellphone.close()
inputFile=open("data/find.txt","r")
key=open("data/findClasses/key.txt","w")
search(inputFile,key,"钥匙")
inputFile.close()
key.close()
inputFile=open("data/find.txt","r")
flashdisk=open("data/findClasses/flashdisk.txt","a")
flashdisk.truncate()
search(inputFile,flashdisk,"U盘")
inputFile.close()
flashdisk.close()
inputFile=open("data/find.txt","r")
flashdisk=open("data/findClasses/flashdisk.txt","a")
search(inputFile,flashdisk,"优盘")
inputFile.close()
flashdisk.close()
except IOError,e:
print "open file error",e
try:
inputFile=open("data/lost.txt","r") #在“丢失”的微博中匹配关键词
wallet=open("data/lostClasses/wallet.txt","w")
search(inputFile,wallet,"钱包")
inputFile.close()
wallet.close()
inputFile=open("data/lost.txt","r")
campuscard=open("data/lostClasses/campuscard.txt","w")
search(inputFile,campuscard,"校园卡")
inputFile.close()
campuscard.close()
inputFile=open("data/lost.txt","r")
bankcard=open("data/lostClasses/bankcard.txt","w")
search(inputFile,bankcard,"银行卡")
inputFile.close()
bankcard.close()
inputFile=open("data/lost.txt","r")
idcard=open("data/lostClasses/IDcard.txt","w")
search(inputFile,idcard,"身份证")
inputFile.close()
idcard.close()
inputFile=open("data/lost.txt","r")
cellphone=open("data/lostClasses/cellphone.txt","a")
cellphone.truncate()
search(inputFile,cellphone,"手机")
inputFile.close()
cellphone.close()
inputFile=open("data/lost.txt","r")
cellphone=open("data/lostClasses/cellphone.txt","a")
search(inputFile,cellphone,"iphone")
inputFile.close()
cellphone.close()
inputFile=open("data/lost.txt","r")
key=open("data/lostClasses/key.txt","w")
search(inputFile,key,"钥匙")
inputFile.close()
key.close()
inputFile=open("data/lost.txt","r")
flashdisk=open("data/lostClasses/flashdisk.txt","a")
flashdisk.truncate()
search(inputFile,flashdisk,"U盘")
inputFile.close()
flashdisk.close()
inputFile=open("data/lost.txt","r")
flashdisk=open("data/lostClasses/flashdisk.txt","a")
search(inputFile,flashdisk,"优盘")
inputFile.close()
flashdisk.close()
except IOError,e:
print "open file error",e
|
TwilioDevEd/api-snippets | rest/incoming-phone-numbers/list-post-example-1/list-post-example-1.7.x.py | Python | mit | 660 | 0 | # Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# Your Account Sid | and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secu | re
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
number = client.incoming_phone_numbers \
.create(friendly_name="My Company Line",
voice_url="http://demo.twilio.com/docs/voice.xml",
phone_number="+15105647903",
voice_method="GET")
print(number.sid)
|
curtisalexander/csvsubquery | csvsubquery.py | Python | mit | 1,220 | 0.006557 | #!/usr/bin/env python
import csv
import click # pip install click -- assumes version 5.x
@click.command()
@click.option('--incsv', type=click.File(mode='rU', lazy=True), help='input csv (the larger of the csv files)')
@click.option('--subcsv', type=click.File(mode='rU', lazy=True), help='subquery csv (the smaller of the csv files)')
@click.option('--outcsv', type=click.File(mode='w', lazy=True), help='output csv')
@click.option('--key', help=' | key variable to be used for the subquery - only supports a single key')
def subquery(incsv, subcsv, outcsv, key):
"""Perform a subquery using CSV files with a common key.
\b
Example:
csvsubquery.py -- | incsv /dir/to/infile.csv --subcsv /dir/to/subfile.csv --outcsv /dir/to/outfile.csv --key keyvar
"""
sub_reader = csv.DictReader(subcsv)
key_subset = {row[key] for row in sub_reader}
in_reader = csv.DictReader(incsv)
header = next(in_reader)
out_writer = csv.DictWriter(outcsv, header, extrasaction='ignore')
out_writer.writeheader()
for row in in_reader:
if row[key] in key_subset:
out_writer.writerows([dict(zip(header, [row[c] for c in header]))])
if __name__ == '__main__':
subquery()
|
nburn42/tensorflow | tensorflow/python/ops/linalg/linear_operator_test_util.py | Python | apache-2.0 | 28,767 | 0.005597 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable 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.
# ==============================================================================
"""Utilities for testing `LinearOperator` and sub-classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import numpy as np
import six
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops.linalg import linalg_impl as linalg
from tensorflow.python.ops.linalg import linear_operator_util
from tensorflow.python.platform import test
class OperatorBuildInfo(object):
"""Object encoding expected shape for a test.
Encodes the expected shape of a matrix for a test. Also
allows additional metadata for the test harness.
"""
def __init__(self, shape, **kwargs):
self.shape = shape
self.__dict__.update(kwargs)
@six.add_metaclass(abc.ABCMeta) # pylint: disable=no-init
class LinearOperatorDerivedClassTest(test.TestCase):
"""Tests for derived classes.
Subclasses should implement every abstractmethod, and this will enable all
test methods to work.
"""
# Absolute/relative tolerance for tests.
_atol = {
dtypes.float16: 1e-3, |
dtypes.float32: 1e-6,
dtypes.float64: 1e-12,
dtypes.complex64: 1e-6,
dtypes.complex128: 1e-12
}
_rtol = {
dtypes.float16: 1e-3,
dtypes.float32: 1e-6,
dtypes.float64: 1e-12,
dtypes.complex64: 1e-6,
dtypes.complex128: 1e-12
}
def assertAC(self, x, y):
"""Derived classes can set _atol, _rtol to get different tolera | nce."""
dtype = dtypes.as_dtype(x.dtype)
atol = self._atol[dtype]
rtol = self._rtol[dtype]
self.assertAllClose(x, y, atol=atol, rtol=rtol)
@property
def _adjoint_options(self):
return [False, True]
@property
def _adjoint_arg_options(self):
return [False, True]
@property
def _dtypes_to_test(self):
# TODO(langmore) Test tf.float16 once tf.matrix_solve works in 16bit.
return [dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128]
@property
def _use_placeholder_options(self):
return [False, True]
@abc.abstractproperty
def _operator_build_infos(self):
"""Returns list of OperatorBuildInfo, encapsulating the shape to test."""
raise NotImplementedError("operator_build_infos has not been implemented.")
@abc.abstractmethod
def _operator_and_mat_and_feed_dict(self, build_info, dtype, use_placeholder):
"""Build a batch matrix and an Operator that should have similar behavior.
Every operator acts like a (batch) matrix. This method returns both
together, and is used by tests.
Args:
build_info: `OperatorBuildInfo`, encoding shape information about the
operator.
dtype: Numpy dtype. Data type of returned array/operator.
use_placeholder: Python bool. If True, initialize the operator with a
placeholder of undefined shape and correct dtype.
Returns:
operator: `LinearOperator` subclass instance.
mat: `Tensor` representing operator.
feed_dict: Dictionary.
If placholder is True, this must contains everything needed to be fed
to sess.run calls at runtime to make the operator work.
"""
# Create a matrix as a numpy array with desired shape/dtype.
# Create a LinearOperator that should have the same behavior as the matrix.
raise NotImplementedError("Not implemented yet.")
@abc.abstractmethod
def _make_rhs(self, operator, adjoint, with_batch=True):
"""Make a rhs appropriate for calling operator.solve(rhs).
Args:
operator: A `LinearOperator`
adjoint: Python `bool`. If `True`, we are making a 'rhs' value for the
adjoint operator.
with_batch: Python `bool`. If `True`, create `rhs` with the same batch
shape as operator, and otherwise create a matrix without any batch
shape.
Returns:
A `Tensor`
"""
raise NotImplementedError("_make_rhs is not defined.")
@abc.abstractmethod
def _make_x(self, operator, adjoint, with_batch=True):
"""Make an 'x' appropriate for calling operator.matmul(x).
Args:
operator: A `LinearOperator`
adjoint: Python `bool`. If `True`, we are making an 'x' value for the
adjoint operator.
with_batch: Python `bool`. If `True`, create `x` with the same batch shape
as operator, and otherwise create a matrix without any batch shape.
Returns:
A `Tensor`
"""
raise NotImplementedError("_make_x is not defined.")
@property
def _tests_to_skip(self):
"""List of test names to skip."""
# Subclasses should over-ride if they want to skip some tests.
# To skip "test_foo", add "foo" to this list.
return []
def _skip_if_tests_to_skip_contains(self, test_name):
"""If self._tests_to_skip contains test_name, raise SkipTest exception.
See tests below for usage.
Args:
test_name: String name corresponding to a test.
Raises:
SkipTest Exception, if test_name is in self._tests_to_skip.
"""
if test_name in self._tests_to_skip:
self.skipTest(
"{} skipped because it was added to self._tests_to_skip.".format(
test_name))
def test_to_dense(self):
self._skip_if_tests_to_skip_contains("to_dense")
for use_placeholder in self._use_placeholder_options:
for build_info in self._operator_build_infos:
for dtype in self._dtypes_to_test:
with self.test_session(graph=ops.Graph()) as sess:
sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED
operator, mat, feed_dict = self._operator_and_mat_and_feed_dict(
build_info, dtype, use_placeholder=use_placeholder)
op_dense = operator.to_dense()
if not use_placeholder:
self.assertAllEqual(build_info.shape, op_dense.get_shape())
op_dense_v, mat_v = sess.run([op_dense, mat], feed_dict=feed_dict)
self.assertAC(op_dense_v, mat_v)
def test_det(self):
self._skip_if_tests_to_skip_contains("det")
for use_placeholder in self._use_placeholder_options:
for build_info in self._operator_build_infos:
for dtype in self._dtypes_to_test:
with self.test_session(graph=ops.Graph()) as sess:
sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED
operator, mat, feed_dict = self._operator_and_mat_and_feed_dict(
build_info, dtype, use_placeholder=use_placeholder)
op_det = operator.determinant()
if not use_placeholder:
self.assertAllEqual(build_info.shape[:-2], op_det.get_shape())
op_det_v, mat_det_v = sess.run(
[op_det, linalg_ops.matrix_determinant(mat)],
feed_dict=feed_dict)
self.assertAC(op_det_v, mat_det_v)
def test_log_abs_det(self):
self._skip_if_tests_to_skip_contains("log_abs_det")
for use_placeholder in self._use_placeholder_options:
for build_info in self._operator_build_infos:
for dtype in self._dtypes_to_test:
with self.test_session(graph=ops.Graph()) as sess:
sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED
|
lyndsysimon/django-changelog | tests/test_settings.py | Python | gpl-3.0 | 2,637 | 0.001517 | import os
# Build paths inside t | he project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.co | ntenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tests',
'changelog',
]
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'tests.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'changelog',
'USER': 'postgres',
'PASSWORD': '',
'PORT': '',
'HOST': 'localhost',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'basic': {
'format': '%(levelname)s [%(name)s] %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'basic'
},
},
'loggers': {
'changelog': {
'handlers': ['console'],
'level': 'INFO',
'propogate': True,
}
}
}
CHANGELOG_TRACKED_FIELDS = {
'tests.TrackedModel': (
'tracked_char',
),
}
|
tdruez/django-registration | registration/runtests.py | Python | bsd-3-clause | 2,003 | 0 | """
A standalone test runner script, configuring the minimum settings
required for tests to execute.
Re-use at your own risk: many Django applications will require
different settings and/or templates to run their tests.
"""
import os
import sys
# Make sure the app is (at least temporarily) on the import path.
APP_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, APP_DIR)
# Minimum settings required for the app's tests.
SETTINGS_DICT = {
'BASE_DIR': APP_DIR,
'INSTALLED_APPS': (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'registration',
),
'ROOT_URLCONF': 'registration.backends.default.urls',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(APP_DIR, 'db.sqlite3'),
},
},
'MIDDLEWARE_CLASSES': (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
'SITE_ID': 1,
'TEMPLATE_DIRS': (
os.path.join(APP_DIR, 'tests/templates'),
),
}
def run_te | sts():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
fro | m django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application cache
# and other bits:
import django
if hasattr(django, 'setup'):
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['registration.tests'])
sys.exit(bool(failures))
|
michael-okeefe/soep-sandbox | src/python2/dump_source.py | Python | mit | 815 | 0.006135 | # Import the JModelica.org Python packages
import pymodelica
from pymodelica.compiler_wrappers import ModelicaCompiler
# Create a compiler and compiler target object
mc = ModelicaCom | piler()
# Build trees as if for an FMU or Model Exchange v 1.0
#target = mc.create_target_object("me", "1.0")
source = mc.parse_model("CauerLowPassAnalog.mo")
indent_a | mount = 2
def dump(src, fid, indent=0):
ind = " " * (indent_amount * indent)
try:
fid.write(ind + src.getNodeName() + "\n")
except:
fid.write(ind + "exception: " + str(src) + "\n")
try:
for idx in range(src.numChild):
dump(src.children[idx], fid, indent+1)
except:
fid.write(ind + "(exception)\n")
# dump the filter instance
with open('out.txt', 'w') as fid:
dump(source, fid, 0)
print "DONE!"
|
ktkirk/HSSI | IoT/iot_lcd.py | Python | bsd-2-clause | 1,768 | 0.005656 | #!/usr/bin/env python
from __future__ import print_function
import time
import pyupm_grove as grove
import pyupm_i2clcd as lcd
import pyupm_th02 as th02
import pyupm_guvas12d as upmUV
import pyupm_grovemoisture as upmMoisture
from phant import Phant
import requests
from iot_utils import *
__author__ = 'KT Kirk'
# Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS)
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
myLcd.setColor(53, 249, 39 ) # Green
myLcd.setCursor(0,0)
myLcd.write('IoT')
# Instantiate a Grove Moisture sensor on analog pin A1
moisture = upmMoisture.GroveMoisture(1)
# Create the light sensor object using AI2 pin 2
light = grove.GroveLight(2)
# Instantiate a UV sensor on analog pin A3
uv = upmUV.GUVAS12D(3);
# analog voltage, usually 3.3 or 5.0
GUVAS12D_AREF = 5.0;
SAMPLES_PER_QUERY = 1024;
# Create the temperature sensor ob | ject using AIO pin 0
i2c_th = th02.TH02()
#
p = Phant(keys["publicKey"],
'device', 'temp', 'humidity', 'light', "uv", "moisture",
private_key=keys["privateKey"])
device = open("/factory/serial_nu | mber").read().strip('\n')
while(True):
temp = i2c_th.getTemperature()
humid = i2c_th.getHumidity()
lux_val = light.value()
uv_val = uv.value(GUVAS12D_AREF, SAMPLES_PER_QUERY)
moisture_val = moisture.value()
myLcd.setCursor(1, 0)
try:
p.log(device, temp, humid, lux_val, uv_val, moisture_val)
except requests.exceptions.ConnectionError as e:
print("Connection error with data.sparkfun.com")
myLcd.setColor(255, 0, 0) # Red
myLcd.write("Error")
else:
myLcd.setColor(53, 39, 249) # Bl
myLcd.write("Sent Bytes: {}".format(p.remaining_bytes))
#data = p.get()
#print(data['temp'])
time.sleep(60 * 5)
|
metacloud/molecule | test/unit/command/test_syntax.py | Python | mit | 1,887 | 0 | # Copyright (c) 2015-2018 Cisco 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, 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 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
| # DEALINGS IN THE SOFTWARE.
import pytest
from molecule.command import syntax
@pytest.fixture
def _patched_ansible_syntax(mocker):
return mocker.patch('molecule.provisioner.ansible.Ansible.syntax')
# NOTE(retr0h): The use of the `patched_config_validate` fixture, disables
# config.Config._validate from executing. T | hus preventing odd side-effects
# throughout patched.assert_called unit tests.
def test_execute(mocker, patched_logger_info, _patched_ansible_syntax,
patched_config_validate, config_instance):
s = syntax.Syntax(config_instance)
s.execute()
x = [
mocker.call("Scenario: 'default'"),
mocker.call("Action: 'syntax'"),
]
assert x == patched_logger_info.mock_calls
_patched_ansible_syntax.assert_called_once_with()
|
correctiv/correctiv-justizgelder | correctiv_justizgelder/views.py | Python | mit | 1,160 | 0 | from django.views.generic import ListView, DetailView
from .forms import OrganisationSearchForm
from .models import Organisation
class OrganisationSearchView(ListView):
template_name = 'justizgelder/search.html'
paginate_by = 25
def get_queryset(self):
self.form = OrganisationSearchForm(self.request.GET)
result, self.aggregates = self.form.search()
return result
def get_context_data(self, **kwargs):
context = super(Organisat | ionSearchView,
self).get_context_data(**kwargs)
context['aggregates'] = self.aggregates
context['query'] = self.request.GET.get('q')
context['form'] = self.form
context['base_template'] = 'justizgelder/search_base.html'
if self.request.GET.get('embed'):
context['base_template'] = 'justizgelder/embed_base.html'
return context
class OrganisationDetail(DetailView):
templat | e_name = 'justizgelder/organisation_detail.html'
model = Organisation
def get_context_data(self, **kwargs):
context = super(OrganisationDetail, self).get_context_data(**kwargs)
return context
|
stencila/hub | manager/accounts/api/serializers_account_image.py | Python | apache-2.0 | 740 | 0.001351 | from rest_framework import serializers
from accounts.models import Account
class AccountImageSerializer(serializers.Serializer):
"""
A serializer for account images.
The main purpose of this class is to provide a subschema
for the type of the account.image in | responses.
"""
small = serializers.CharField()
medium = serializers.CharField()
large = serializers.CharField()
@staticmethod
def create(request, account: Account):
"""Get the URLs of alternative image sizes for the account."""
return dict(
[
(size, request.build_absolute_uri(getattr(a | ccount.image, size)),)
for size in ("small", "medium", "large")
]
)
|
ChessCorp/docker-ascii-map | tests/raster_test.py | Python | mit | 3,352 | 0.00179 | import unittest
from docker_ascii_map.raster import Raster, Boundary, RasterCell
class RasterTests(unittest.TestCase):
def test_empty_raster(self):
raster = Raster()
self.assertEqual('', str(raster))
self.assertEqual((0, 0), raster.size())
self.assertEqual(RasterCell(), raster.get(5, 4))
def test_expansion(self):
raster = Raster()
raster.write(8, 0, ' ')
raster.write(0, 4, ' ')
self.assertEqual(
' \n'
'\n'
'\n'
'\n'
' \n'
, str(raster)
)
def test_basic_raster(self):
raster = Raster()
raster.write(0, 0, 'a')
self.assertEqual('a\n', str(raster))
self.assertEqual((1, 1), raster.size())
def test_multiline(self):
raster = Raster()
raster.write(2, 1, 'a')
self.assertEqual('\n a\n', str(raster))
self.assertEqual((3, 2), raster.size())
def test_string(self):
raster = Raster()
raster.write(2, 1, 'abc')
raster.write(3, 1, 'abc')
raster.write(4, 1, 'abc')
self.assertEqual('\n aaabc\n', str(raster))
def test_write_raster(self):
r1 = Raster()
r1.write(0, 0, 'Hello', r1)
r2 = Raster()
r2.write(0, 0, 'World !', r2)
r = Raster()
r.write(0, 0, r1)
r.write(2, 1, r2)
self.assertEqual('Hello\n World !\n', str(r))
self.assertEqual((9, 2), r.size())
def test_boundaries(self):
r = Raster()
r.write(4, 2, 'Hello', 'Origin1')
r.write(4, 3, 'Hello', 'Origin1')
r.write(4, 4, 'World', 'Origin2')
self.assertEqual('4,2 5x2', str(r.origin_bounds('Origin1')))
self.assertEqual('4,4 5x1', str(r.origin_bounds('Origin2')))
self.assertEqual(None, r.origin_bounds('Origin3'))
def test_boundary(self):
self.assertEqual('4,2 5x2', str(Boundary(4, 2, 5, 2)))
self.assertEqual(Boundary(4, 2, 5, 2), Boundary(4, 2, 5, 2))
def test_line_horizontal(self):
r = Raster()
r.draw_line(0, 0, 4, 0)
self.assertEqual(
'----\n',
str(r)
)
def test_line_up(self):
r = Raster()
r.draw_line(0, 3, 6, 0)
self.assertEqual(
' +--\n'
' |\n'
' |\n'
'---+\n'
| , str(r)
)
def test_line_overlap(self):
r = Raster()
r.draw_line(0, 3, 6, 2)
r.draw_line(0, 3, 6, 0)
self.assertEqual(
' +--\n'
' |\n'
' +--\n'
| '---+\n'
, str(r)
)
def test_color_disabled(self):
r = Raster()
r.write(0, 0, 'Red', color='red')
r.write(0, 1, 'Green', color='green')
self.assertEqual(
'Red\n'
'Green\n'
, str(r)
)
def test_color_enabled(self):
r = Raster()
r.write(0, 0, 'Red', color='red')
r.write(0, 1, 'Green', color='green')
self.assertEqual(
'\x1b[31mR\x1b[0m\x1b[31me\x1b[0m\x1b[31md\x1b[0m\n\x1b[32mG\x1b[0m\x1b[32mr\x1b[0m\x1b[32me\x1b[0m\x1b[32me\x1b[0m\x1b[32mn\x1b[0m\n'
, r.text(True)
)
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.