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 |
|---|---|---|---|---|---|---|---|---|
zengenti/ansible | lib/ansible/modules/network/exoscale/exo_dns_record.py | Python | gpl-3.0 | 12,408 | 0.00137 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2016, René Moser <mail@renemoser.net>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: exo_dns_record
short_description: Manages DNS records on Exoscale DNS.
description:
- Create, update and delete records.
version_added: "2.2"
author: "René Moser (@resmo)"
options:
name:
description:
- Name of the record.
required: false
default: ""
domain:
description:
- Domain the record is related to.
required: true
record_type:
description:
- Type of the record.
required: false
default: A
choices: ['A', 'ALIAS', 'CNAME', 'MX', 'SPF', 'URL', 'TXT', 'NS', 'SRV', 'NAPTR', 'PTR', 'AAAA', 'SSHFP', 'HINFO', 'POOL']
aliases: ['rtype', 'type']
content:
description:
- Content of the record.
- Required if C(state=present) or C(name="")
required: false
default: null
aliases: ['value', 'address']
ttl:
description:
- TTL of the record in seconds.
required: false
default: 3600
prio:
description:
- Priority of the record.
required: false
default: null
aliases: ['priority']
multiple:
description:
- Whether there are more than one records with similar C(name).
- Only allowed with C(record_type=A).
- C(content) will not be updated as it is used as key to find the record.
required: false
default: null
aliases: ['priority']
state:
description:
- State of the record.
required: false
default: 'present'
choices: [ 'present', 'absent' ]
api_key:
description:
- API key of the Exoscale DNS API.
required: false
default: null
api_secret:
description:
- Secret key of the Exoscale DNS API.
required: false
default: null
api_timeout:
description:
- HTTP timeout to Exoscale DNS API.
required: false
default: 10
api_region:
description:
- Name of the ini section in the C(cloustack.ini) file.
required: false
default: cloudstack
validate_certs:
description:
- Validate SSL certs of the Exoscale DNS API.
required: false
default: true
requirements:
- "python >= 2.6"
notes:
- As Exoscale DNS uses the same API key and secret for all services, we reuse the config used for Exscale Compute based on CloudStack.
The config is read from several locations, in the following order.
The C(CLOUDSTACK_KEY), C(CLOUDSTACK_SECRET) environment variables.
A C(CLOUDSTACK_CONFIG) environment variable pointing to an C(.ini) file,
A C(cloudstack.ini) file in the current working directory.
A C(.cloudstack.ini) file in the users home directory.
Optionally multiple credentials and endpoints can be specified using ini sections in C(cloudstack.ini).
Use the argument C(api_region) to select the section name, default section is C(cloudstack).
- This module does not support multiple A records and will complain properly if you try.
- More information Exoscale DNS can be found on https://community.exoscale.ch/documentation/dns/.
- This module supports check mode and diff.
'''
EXAMPLES = '''
# Create or update an A record.
- local_action:
module: exo_dns_record
name: web-vm-1
domain: example.com
content: 1.2.3.4
# Update an existing A record with a new IP.
- local_action:
module: exo_dns_record
name: web-vm-1
domain: example.com
content: 1.2.3.5
# Create another A record with same name.
- local_action:
module: exo_dns_record
name: web-vm-1
domain: example.com
content: 1.2.3.6
multiple: yes
# Create or update a CNAME record.
- local_action:
module: exo_dns_record
name: www
domain: example.com
record_type: CNAME
content: web-vm-1
# Create or update a MX record.
- local_action:
module: exo_dns_record
domain: example.com
record_type: MX
content: mx1.example.com
prio: 10
# delete a MX record.
- local_action:
module: exo_dns_record
domain: example.com
record_type: MX
content: mx1.example.com
state: absent
# Remove a record.
- local_action:
module: exo_dns_record
name: www
domain: example.com
| state: absent
'''
RETURN = '''
---
exo_dns_record:
description: API record results
returned: success
type: dictionary
contains:
content:
description: value of the record
returned: success
type: string
sample: 1.2.3.4
created_at:
description: When the record was created
returned: success
type: string
sample: "2016-08-12T15:24:23.989Z"
| domain:
description: Name of the domain
returned: success
type: string
sample: example.com
domain_id:
description: ID of the domain
returned: success
type: int
sample: 254324
id:
description: ID of the record
returned: success
type: int
sample: 254324
name:
description: name of the record
returned: success
type: string
sample: www
parent_id:
description: ID of the parent
returned: success
type: int
sample: null
prio:
description: Priority of the record
returned: success
type: int
sample: 10
record_type:
description: Priority of the record
returned: success
type: string
sample: A
system_record:
description: Whether the record is a system record or not
returned: success
type: bool
sample: false
ttl:
description: Time to live of the record
returned: success
type: int
sample: 3600
updated_at:
description: When the record was updated
returned: success
type: string
sample: "2016-08-12T15:24:23.989Z"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.exoscale import (
ExoDns,
exo_dns_argument_spec,
exo_dns_required_together
)
EXO_RECORD_TYPES = [
'A',
'ALIAS',
'CNAME',
'MX',
'SPF',
'URL',
'TXT',
'NS',
'SRV',
'NAPTR',
'PTR',
'AAAA',
'SSHFP',
'HINFO',
'POOL'
]
class ExoDnsRecord(ExoDns):
def __init__(self, module):
super(ExoDnsRecord, self).__init__(module)
self.content = self.module.params.get('content')
if self.content:
self.content = self.content.lower()
self.domain = self.module.params.get('domain').lower()
self.name = self.module.params.get('name').lower()
if self.name == self.domain:
self.name = ""
self.multiple = self.module.params.get('multiple')
self.record_type = self.module.params.get('record_type')
if self.multiple and self.record_type != 'A':
self.module.fail_json(msg="Multiple is only usable with record_type A")
def _create_record(self, record):
self.result['changed'] = True
data = {
'record': {
'name': self.name,
'record_type': self.record_type,
'con |
StingraySoftware/dave | src/test/python/test/utils/test_dave_reader.py | Python | apache-2.0 | 4,412 | 0.002267 | from test.fixture import *
from hypothesis import given
from hypothesis.strategies import text
from astropy.io import fits
import utils.dave_reader as DaveReader
from utils.dave_reader import save_to_intermediate_file, load_dataset_from_intermediate_file
import utils.file_utils as FileUtils
from stingray.events import EventList
from stingray import Lightcurve, Powerspectrum, AveragedCrossspectrum
from hendrics.io import HEN_FILE_EXTENSION
import numpy as np
class TestStingrayTypes():
@classmethod
def setup_class(cls):
cls.dum = 'bubu' + HEN_FILE_EXTENSION
def test_load_and_save_events(self):
events = EventList([0, 2, 3.], pi=[1, 2, 3], mjdref=54385.3254923845,
gti = np.longdouble([[-0.5, 3.5]]))
events.energy = np.array([3., 4., 5.])
save_to_intermediate_file(events, self.dum)
ds = load_dataset_from_intermediate_file(self.dum)
assert ds
def test_load_and_save_lcurve(self):
lcurve = Lightcurve(np.linspace(0, 10, 15), np.random.poisson(30, 15),
mjdref=54385.3254923845,
gti = np.longdouble([[-0.5, 3.5]]))
save_to_intermediate_file(lcurve, self.dum)
ds = load_dataset_from_intermediate_file(self.dum)
assert ds
@given(text())
def test_get_txt_dataset(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "Test_Input_1.txt")
table_id = "EVENTS"
header_names = ["TIME", "PHA", "Color1", "Color2"]
dataset = DaveReader.get_txt_dataset(destination, table_id, header_names)
num_rows = 10
assert dataset
assert len(dataset.tables) == 2
assert table_id in dataset.tables
table = dataset.tables[table_id]
assert len(table.columns) == len(header_names)
assert len(table.columns[header_names[0]].values) == num_rows
@given(text())
def test_get_fits_dataset_lc(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "Test_Input_2.lc")
ds_id = "fits_table"
table_ids = ["Primary", "RATE", "STDGTI"]
hdulist = fits.open(destination)
dataset = DaveReader.get_fits_dataset(hdulist, ds_id, table_ids)
assert dataset
assert len(dataset.tables) == 2
assert table_ids[1] in dataset.tables
assert len(dataset.tables[table_ids[1]].columns) == 4
@given(text())
def test_get_fits_table_column_names(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "test.evt")
# Opening Fits
hdulist = fits.open(destination)
column_names = DaveReader.get_fits_table_column_names(hdulist, "EVENTS")
assert len(column_names) == 2
@given(text())
def test_get_fits_dataset_evt(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "test.evt")
ds_id = "fits_table"
table_ids = ["Primary", "EVENTS", "GTI"]
hdulist = fits.open(destination)
dataset = DaveReader.get_fits_dataset(hdulist, ds_id, table_ids)
assert dataset
assert len(dataset.tables) == 2
assert table_ids[1] in dataset.tables
assert len | (dataset.tables[table_ids[1]].columns) == 2
@given(text())
def test_get_events_fits_dataset_with_stingray(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "test.evt") |
ds_id = "fits_table"
table_ids = ["Primary", "EVENTS", "GTI"]
# Opening Fits
hdulist = fits.open(destination)
dataset = DaveReader.get_events_fits_dataset_with_stingray(destination, hdulist)
assert dataset
assert len(dataset.tables) == 2
assert table_ids[1] in dataset.tables
assert len(dataset.tables[table_ids[1]].columns) == 2
@given(text())
def test_get_lightcurve_fits_dataset_with_stingray(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "PN_source_lightcurve_raw.lc")
# Opening Fits
hdulist = fits.open(destination)
dataset = DaveReader.get_lightcurve_fits_dataset_with_stingray(destination, hdulist, hduname='RATE',
column='TIME', gtistring='GTI,STDGTI')
assert dataset
@given(text())
def test_get_file_dataset(s):
destination = FileUtils.get_destination(TEST_RESOURCES, "Test_Input_2.lc")
ds_id = "fits_table"
table_ids = ["Primary", "RATE", "STDGTI"]
hdulist = fits.open(destination)
dataset = DaveReader.get_fits_dataset(hdulist, ds_id, table_ids)
assert dataset
assert len(dataset.tables) == 2
assert table_ids[1] in dataset.tables
|
rocket-league-replays/rocket-league-replays | rocket_league/apps/replays/migrations/0039_auto_20160417_1058.py | Python | gpl-3.0 | 548 | 0.001825 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db im | port migrations, models
class Migration(migrations.Migration):
dependencies = [
('replays', '0038_auto_20160417_1042'),
]
operations = [
migrations.CreateModel(
name='Body',
fields=[
('id', models.PositiveIntegerField(serialize=False, primary_key=True, db_index=True, unique=True)),
| ('name', models.CharField(max_length=100, default='Unknown')),
],
),
]
|
AButenko/selenium_tests | framework/gui/loginpage.py | Python | bsd-3-clause | 1,961 | 0.00306 | # -*- coding: utf-8 -*-
from framework.gui.common.basepage import BasePage
from framework.gui.common.locators import HOMEPAGE
from framework.gui.common.tools import wait_for_page_load, page_contain_assert
from selenium.webdriver.common.keys import Keys
# from se | lenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.support.wait import WebDriverWait
class LoginPage(BasePage):
def __init__(self, driver):
super().__init__(driver)
self.login_page = HOMEPAGE + "/l | ogin"
self.logout_page = HOMEPAGE + "/account/logout"
def enter_login_credentials(self, username, password):
name = self._driver.find_element_by_name("username")
name.send_keys(username)
psswd = self._driver.find_element_by_name("password")
psswd.send_keys(password)
return name, psswd
def login(self, username="user@phptravels.com", password="demouser"):
self._driver.get(self.login_page)
page_contain_assert(self._driver, title=["Login"], page_source=["Email", "Password", "Remember Me",
"Login", "Sign Up", "Forget Password"])
name, psswd = self.enter_login_credentials(username, password)
with wait_for_page_load(self._driver):
psswd.send_keys(Keys.RETURN)
# wait = WebDriverWait(driver, 2)
# wait.until(EC.title_is("My Account"))
page_contain_assert(self._driver, title=["My Account"], page_source=["Hi, ", "Booking",
"My Profile", "Wishlist", "Newsletter"])
def logout(self):
if self.logout_page not in self._driver.page_source:
# TODO raise error here
self.login()
page_contain_assert(self._driver, page_source=[self.logout_page])
self._driver.get(self.logout_page)
page_contain_assert(self._driver, title=["Login"]) |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/tools/dist_test/scripts/k8s_tensorflow_test.py | Python | apache-2.0 | 4,446 | 0.001574 | # Copyright 2017 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 go | verning permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.tools.dist_test.scripts.k8s_tensorflow_lib."""
from __f | uture__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.platform import googletest
from tensorflow.tools.dist_test.scripts import k8s_tensorflow_lib
class K8sTensorflowTest(googletest.TestCase):
def testGenerateConfig_LoadBalancer(self):
# Use loadbalancer
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=True,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=False)
self.assertTrue('LoadBalancer' in config)
# Don't use loadbalancer
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=False,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=False)
self.assertFalse('LoadBalancer' in config)
def testGenerateConfig_SharedVolume(self):
# Use shared directory
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=False,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=True)
self.assertTrue('/shared' in config)
# Don't use shared directory
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=False,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=False)
self.assertFalse('/shared' in config)
def testEnvVar(self):
# Use loadbalancer
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=True,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=False,
env_vars={'test1': 'test1_value', 'test2': 'test2_value'})
self.assertTrue('{name: "test1", value: "test1_value"}' in config)
self.assertTrue('{name: "test2", value: "test2_value"}' in config)
def testClusterSpec(self):
# Use cluster_spec
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=True,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=False,
use_cluster_spec=True)
self.assertFalse('worker_hosts' in config)
self.assertFalse('ps_hosts' in config)
self.assertTrue(
'"--cluster_spec=worker|abc-worker0:5000,ps|abc-ps0:5000"' in config)
# Don't use cluster_spec
config = k8s_tensorflow_lib.GenerateConfig(
num_workers=1,
num_param_servers=1,
port=5000,
request_load_balancer=True,
docker_image='test_image',
name_prefix='abc',
use_shared_volume=False,
use_cluster_spec=False)
self.assertFalse('cluster_spec' in config)
self.assertTrue('"--worker_hosts=abc-worker0:5000"' in config)
self.assertTrue('"--ps_hosts=abc-ps0:5000"' in config)
def testWorkerHosts(self):
self.assertEquals(
'test_prefix-worker0:1234',
k8s_tensorflow_lib.WorkerHosts(1, 1234, 'test_prefix'))
self.assertEquals(
'test_prefix-worker0:1234,test_prefix-worker1:1234',
k8s_tensorflow_lib.WorkerHosts(2, 1234, 'test_prefix'))
def testPsHosts(self):
self.assertEquals(
'test_prefix-ps0:1234,test_prefix-ps1:1234',
k8s_tensorflow_lib.PsHosts(2, 1234, 'test_prefix'))
if __name__ == '__main__':
googletest.main()
|
carolinux/QGIS | python/plugins/processing/script/ScriptAlgorithmProvider.py | Python | gpl-2.0 | 3,302 | 0.000909 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ScriptAlgorithmProvider.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from PyQt4.QtGui import QIcon
from processing.core.ProcessingConfig import ProcessingConfig, Setting
from processing.core.AlgorithmProvider import AlgorithmProvider
from processing.gui. | EditScriptAction import EditScriptAction
from processing.gui.DeleteScriptAction import DeleteScriptAction
from processing.gui.CreateNewScriptAction import CreateNewScriptAction
from processing.script.ScriptUtils import ScriptUtils
from processing.script.AddScriptFromFileAction import AddScriptFromFileAction
from processing.gui.GetScriptsAndModels import GetScriptsAction
pluginPath = os.path.split(os.path.dirname(__fil | e__))[0]
class ScriptAlgorithmProvider(AlgorithmProvider):
def __init__(self):
AlgorithmProvider.__init__(self)
self.actions.extend([CreateNewScriptAction(self.tr('Create new script', 'ScriptAlgorithmProvider'),
CreateNewScriptAction.SCRIPT_PYTHON),
AddScriptFromFileAction(),
GetScriptsAction()])
self.contextMenuActions = \
[EditScriptAction(EditScriptAction.SCRIPT_PYTHON),
DeleteScriptAction(DeleteScriptAction.SCRIPT_PYTHON)]
def initializeSettings(self):
AlgorithmProvider.initializeSettings(self)
ProcessingConfig.addSetting(Setting(self.getDescription(),
ScriptUtils.SCRIPTS_FOLDER,
self.tr('Scripts folder', 'ScriptAlgorithmProvider'),
ScriptUtils.scriptsFolder(), valuetype=Setting.FOLDER))
def unload(self):
AlgorithmProvider.unload(self)
ProcessingConfig.addSetting(ScriptUtils.SCRIPTS_FOLDER)
def getIcon(self):
return QIcon(os.path.join(pluginPath, 'images', 'script.png'))
def getName(self):
return 'script'
def getDescription(self):
return self.tr('Scripts', 'ScriptAlgorithmProvider')
def _loadAlgorithms(self):
folder = ScriptUtils.scriptsFolder()
self.algs = ScriptUtils.loadFromFolder(folder)
def addAlgorithmsFromFolder(self, folder):
self.algs.extend(ScriptUtils.loadFromFolder(folder))
|
larsks/cloud-init | cloudinit/distros/centos.py | Python | gpl-3.0 | 245 | 0 | # This file is part of cloud-init. See LICENSE file for license information.
from cloudinit.distros import rhel
fr | om cloudinit import log as logging
LOG = logging.getLogger(__name__ | )
class Distro(rhel.Distro):
pass
# vi: ts=4 expandtab
|
nathanbjenx/cairis | cairis/core/TemplateRequirement.py | Python | apache-2.0 | 1,446 | 0.011757 | # 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, e | ither express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
__author__ = 'Shamal Faily'
class TemplateRequirement:
def __init__(self,reqId,reqName,assetName,reqType,reqDesc,reqRat,reqFC):
s | elf.theId = reqId
self.theName = reqName
self.theAssetName = assetName
self.theType = reqType
self.theDescription= reqDesc
self.theRationale = reqRat
self.theFitCriterion = reqFC
def id(self): return self.theId
def name(self): return self.theName
def asset(self): return self.theAssetName
def type(self): return self.theType
def description(self): return self.theDescription
def rationale(self): return self.theRationale
def fitCriterion(self): return self.theFitCriterion
|
jerryling315/ShadowsocksFork | playground/socketServer_client2.py | Python | apache-2.0 | 173 | 0.00578 | __author__ = 'Exmof'
import socket
HOST = 'loca | lhost'
PORT = 1033
s | oc = socket.socket()
soc.connect((HOST, PORT))
data = soc.recv(1024)
soc.close()
print("Received", data) |
cyx1231st/nova | nova/scheduler/rpcapi.py | Python | apache-2.0 | 6,665 | 0 | # Copyright 2013, Red Hat, 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.
"""
Client side of the scheduler manager RPC API.
"""
import oslo_messaging as messaging
import nova.conf
from nova.objects import base as objects_base
from nova import rpc
CONF = nova.conf.CONF
class SchedulerAPI(object):
'''Client side of the scheduler rpc API.
API version history:
* 1.0 - Initial version.
* 1.1 - Changes to prep_resize():
* remove instance_uuid, add instance
* remove instance_type_id, add instance_type
* remove topic, it was unused
* 1.2 - Remove topic from run_instance, it was unused
* 1.3 - Remove instance_id, add instance to live_migration
* 1.4 - Remove update_db from prep_resize
* 1.5 - Add reservations argument to prep_resize()
* 1.6 - Remove reservations argument to run_instance()
* 1.7 - Add create_volume() method, remove topic from live_migration()
* 2.0 - Remove 1.x backwards compat
* 2.1 - Add image_id to create_volume()
* 2.2 - Remove reservations argument to create_volume()
* 2.3 - Remove create_volume()
* 2.4 - Change update_service_capabilities()
* accepts a list of capabilities
* 2.5 - Add get_backdoor_port()
* 2.6 - Add select_hosts()
... Grizzly supports message version 2.6. So, any changes to existing
methods in 2.x after that point should be done such that they can
handle the version_cap being set to 2.6.
* 2.7 - Add select_destinations()
* 2.8 - Deprecate prep_resize() -- JUST KIDDING. It is still used
by the compute manager for retries.
* 2.9 - Added the legacy_bdm_in_spec parameter to run_instance()
... Havana supports message version 2.9. So, any changes to existing
methods in 2.x after that point should be done such that they can
handle the version_cap being set to 2.9.
* Deprecated live_migration() call, moved to conductor
* Deprecated select_hosts()
3.0 - Removed backwards compat
... Icehouse and Juno support message version 3.0. So, any changes to
existing methods in 3.x after that point should be done such that they
can handle the version_cap being set to 3.0.
* 3.1 - Made select_destinations() send flavor object
* 4.0 - Removed backwards compat for Icehouse
* 4.1 - Add update_aggregates() and delete_aggregate()
* 4.2 - Added update_instance_info(), delete_instance_info(), and
sync_instance_info() methods
... Kilo and Liberty support message version 4.2. So, any
changes to existing methods in 4.x after that point should be
done such that they can handle the version_cap being set to
4.2.
* 4.3 - Modify select_destinations() signature by providing a
RequestSpec obj
'''
VERSION_ALIASES = {
'grizzly': '2.6',
'havana': '2.9',
'icehouse': '3.0',
'juno': '3.0',
'kilo': '4.2',
'liberty': '4.2',
}
def __init__(self):
super(SchedulerAPI, self).__init__()
target = messaging.Target(topic=CONF.scheduler_topic, version='4.0')
version_cap = self.VERSION_ALIASES.get(CONF.upgrade_levels.scheduler,
CONF.upgrade_levels.scheduler)
serializer = objects_base.NovaObjectSerializer()
self.client = rpc.get_client(target, version_cap=version_cap,
serializer=serializer)
def select_destinations(self, ctxt, spec_obj):
version = '4.3'
msg_args = {'spec_obj': spec_obj}
if not self.client.can_send_version(version):
del msg_args['spe | c_obj']
msg_args['request_spec'] = spec_obj.to_legacy_request_spec_dict()
msg_args['filter_properties'
] = spec_obj.to_legacy_filter_properties_dict()
version = '4.0'
cctxt = self.client.prepare(version=version)
return cctxt.call(ctxt, 'select_destinations', **msg_args)
def update_aggregates(self, ctxt, aggregates):
# NOTE(sbauza): Yes, it's a fanout, we need to update | all schedulers
cctxt = self.client.prepare(fanout=True, version='4.1')
cctxt.cast(ctxt, 'update_aggregates', aggregates=aggregates)
def delete_aggregate(self, ctxt, aggregate):
# NOTE(sbauza): Yes, it's a fanout, we need to update all schedulers
cctxt = self.client.prepare(fanout=True, version='4.1')
cctxt.cast(ctxt, 'delete_aggregate', aggregate=aggregate)
def update_instance_info(self, ctxt, host_name, instance_info):
cctxt = self.client.prepare(version='4.2', fanout=True)
return cctxt.cast(ctxt, 'update_instance_info', host_name=host_name,
instance_info=instance_info)
def delete_instance_info(self, ctxt, host_name, instance_uuid):
cctxt = self.client.prepare(version='4.2', fanout=True)
return cctxt.cast(ctxt, 'delete_instance_info', host_name=host_name,
instance_uuid=instance_uuid)
def sync_instance_info(self, ctxt, host_name, instance_uuids):
cctxt = self.client.prepare(version='4.2', fanout=True)
return cctxt.cast(ctxt, 'sync_instance_info', host_name=host_name,
instance_uuids=instance_uuids)
# NOTE(CHANGE)
# TODO(Yingxin): Bump version
def notify_schedulers(self, ctxt, host_name, scheduler=None):
if scheduler is not None:
cctxt = self.client.prepare(version='4.0', server=scheduler)
else:
cctxt = self.client.prepare(version='4.0', fanout=True)
return cctxt.cast(ctxt, 'notified_by_remote', host_name=host_name)
def send_commit(self, ctxt, commit, compute, scheduler, seed):
cctxt = self.client.prepare(version='4.0', server=scheduler)
cctxt.cast(ctxt, 'receive_commit',
commit=commit, compute=compute, seed=seed)
|
dstufft/warehouse | warehouse/config.py | Python | apache-2.0 | 18,226 | 0.000988 | # 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 enum
import os
import shlex
import transaction
from pyramid import renderers
from pyramid.config import Configurator as _Configurator
from pyramid.response import Response
from pyramid.security import Allow, Authenticated
from pyramid.tweens import EXCVIEW
from pyramid_rpc.xmlrpc import XMLRPCRenderer
from warehouse.errors import BasicAuthBreachedPassword
from warehouse.utils.static import ManifestCacheBuster
from warehouse.utils.wsgi import ProxyFixer, VhmRootRemover, HostRewrite
class Environment(enum.Enum):
production = "production"
development = "development"
class Configurator(_Configurator):
def add_wsgi_middleware(self, middleware, *args, **kwargs):
middlewares = self.get_settings().setdefault("wsgi.middlewares", [])
middlewares.append((middleware, args, kwargs))
def make_wsgi_app(self, *args, **kwargs):
# Get the WSGI application from the underlying configurator
app = super().make_wsgi_app(*args, **kwargs)
# Look to see if we have any WSGI middlewares configured.
for middleware, args, kw in self.get_settings()["wsgi.middlewares"]:
app = middleware(app, *args, **kw)
# Finally, return our now wrapped app
return app
class RootFactory:
__parent__ = None
__name__ = None
__acl__ = [(Allow, "group:admins", "admin"), (Allow, Authenticated, "manage:user")]
def __init__(self, request):
pass
def require_https_tween_factory(handler, registry):
if not registry.settings.get("enforce_https", True):
return handler
def require_https_tween(request):
# If we have an :action URL and we're not using HTTPS, then we want to
# return a 403 error.
if request.params.get(":action", None) and request.scheme != "https":
resp = Response("SSL is required.", status=403, content_type="text/plain")
resp.status = "403 SSL is required"
resp.headers["X-Fastly-Error"] = "803"
return resp
return handler(request)
return require_https_tween
def activate_hook(request):
if request.path.startswith(("/_debug_toolbar/", "/static/")):
return False
return True
def commit_veto(request, response):
# By default pyramid_tm will veto the commit anytime request.exc_info is not None,
# we are going to copy that logic with one difference, we are still going to commit
# if the exception was for a BreachedPassword.
# TODO: We should probably use a registry or something instead of hardcoded.
exc_info = getattr(request, "exc_info", None)
if exc_info is not None and not isinstance(exc_info[1], BasicAuthBreachedPassword):
return True
def template_view(config, name, route, template, route_kw=None):
if route_kw is None:
route_kw = {}
config.add_route(name, route, **route_kw)
config.add_view(renderer=template, route_name=name)
def maybe_set(settings, name, envvar, coercer=None, default=None):
if envvar in os.environ:
value = os.environ[envvar]
if coercer is not None:
value = coercer(value)
settings.setdefault(name, value)
elif default is not None:
settings.setdefault(name, default)
def maybe_set_compound(settings, base, name, envvar):
if envvar in os.environ:
value = shlex.split(os.environ[envvar])
kwargs = {k: v for k, v in (i.split("=") for i in value[1:])}
settings[".".join([base, name])] = value[0]
for key, value in kwargs.items():
settings[".".join([base, key])] = value
def configure(settings=None):
if settings is None:
settings = {}
# Add information about the current copy of the code.
maybe_set(settings, "warehouse.commit", "SOURCE_COMMIT", default="null")
# Set the environment from an environment variable, if one hasn't already
# been set.
maybe_set(
settings,
"warehouse.env",
"WAREHOUSE_ENV",
Environment,
default=Environment.production,
)
# Pull in default configuration from the environment.
maybe_set(settings, "warehouse.token", "WAREHOUSE_TOKEN")
maybe_set(settings, "warehouse.num_proxies", "WAREHOUSE_NUM_PROXIES", int)
maybe_set(settings, "warehouse.theme", "WAREHOUSE_THEME")
maybe_set(settings, "warehouse.domain", "WAREHOUSE_DOMAIN")
maybe_set(settings, "forklift.domain", "FORKLIFT_DOMAIN")
maybe_set(settings, "warehouse.legacy_domain", "WAREHOUSE_LEGACY_DOMAIN")
maybe_set(settings, "site.name", "SITE_NAME", default="Warehouse")
maybe_set(settings, "aws.key_id", "AWS_ACCESS_KEY_ID")
maybe_set(settings, "aws.secret_key", "AWS_SECRET_ACCESS_KEY")
maybe_set(settings, "aws.region", "AWS_REGION")
maybe_set(settings, "gcloud.credentials", "GCLOUD_CREDENTIALS")
maybe_set(settings, "gcloud.project", "GCLOUD_PROJECT")
maybe_set(settings, "warehouse.trending_table", "WAREHOUSE_TRENDING_TABLE")
maybe_set(settings, "celery.broker_url", "BROKER_URL")
maybe_set(settings, "celery.result_url", "REDIS_URL")
maybe_set(settings, "celery.scheduler_url", "REDIS_URL")
maybe_set(settings, "database.url", "DATABASE_URL")
maybe_set(settings, "elasticsearch.url", "ELASTICSEARCH_URL")
maybe_set(settings, "elasticsearch.url", "ELASTICSEARCH_SIX_URL")
maybe_set(settings, "sentry.dsn", "SENTRY_DSN")
maybe_set(settings, "sentry.frontend_dsn", "SENTRY_FRONTEND_DSN")
maybe_set(settings, "sentry.transport", "SENTRY_TRANSPORT")
maybe_set(settings, "sessions.url", "REDIS_URL")
maybe_set(settings, "ratelimit.url", "REDIS_URL")
maybe_set(settings, "sessions.secret", "SESSION_SECRET")
maybe_set(settings, "camo.url", "CAMO_URL")
maybe_set(settings, "camo.key", "CAMO_KEY")
maybe_set(settings, "docs.url", "DOCS_URL")
maybe_set(settings, "ga.tracking_id", "GA_TRACKING_ID")
maybe_set(settings, "statuspage.url", "STATUSPAGE_URL")
maybe_set(settings, "token.password.secret", "TOKEN_PASSWORD_SECRET")
maybe_set(settings, "token.email.secret", "TOKEN_EMAIL_SECRET")
maybe_set(settings, "warehouse.xmlrpc.cache.url", "REDIS_URL")
maybe_set(settings, "token.password.max_age", "TOKEN_PASSWORD_MAX_AGE", coercer=int)
maybe_set(settings, "token.email.max_age", "TOKEN_EMAIL_MAX_AGE", coercer=int)
maybe_set(
settings,
"token.default.max_age",
"TOKEN_DEFAULT_MAX_AGE",
coercer=int,
default=21600, # 6 hours
)
maybe_set_compound(settings, "files", "backend", "FILES_BACKEND")
maybe_set_compound(settings, "docs", "backend", "DOCS_BACKEND")
maybe_set_compound(settings, "origin_cache", "backend", "ORIGIN_CACHE")
maybe_set_compound(settings, "mail", "backend", "MAIL_BACKEND")
maybe_set_compound(settings, "metrics", "backend", "METRICS_BACKEND")
maybe_set_compound(settings, "breached_passwords", "backend", "BREACHED_PASSWORDS")
# Add the settings we use when the environment is set to development.
if settings["warehouse.env"] == Environment.develop | ment:
settings.setdefault("enforce_https", False)
settings.setdefault("pyramid.reload_assets", True)
settings.setdefault("pyramid.reload_templates", True)
settings.setdefault("pyramid.prevent_http_cache", True)
settings.setdefault("debugtoolbar.hosts", ["0.0.0.0/0"])
settings.setdefault(
"debugtoolbar.panels",
[
| ".".join(["pyramid_debugtoolbar.panels", panel])
for panel in [
"versions.VersionDebugPanel",
" |
daverigby/kv_engine | scripts/cbnt_perfsuite_strip_results.py | Python | bsd-3-clause | 2,943 | 0.001019 | #!/usr/bin/env python2.7
"""
Copyright 2018 Couchbase, 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.
This script removes lines from the perfsuite test files which contain
a match to the input strings
Usage: python cbnt_perfsuite_strip_results.py -d . -p output -i '.pct99' -i '.pct95'
"""
import optparse
from os import listdir
from os.path import isfile, join
import sys
def main():
parser = optparse.OptionParser()
required_args = optparse.OptionGroup(parser, 'Required Arguments')
required_args.add_option('-d', '--dir', action='store', type='string',
dest='input_dir', help='The directory where the '
| 'test files are located')
required_args.add_option('-p', '--prefix', action='store', type='string',
dest='prefix', help='The prefix each of the test '
'files start with')
requir | ed_args.add_option('-i', '--ignore', dest='ignore', action='append',
help='Section of string used to ignore results, '
'eg \'.pct96\'')
parser.add_option_group(required_args)
(options, args) = parser.parse_args()
# Check no arguments were passed to the script,
# everything is done through options parsing
if len(args) != 0:
print('cbnt_perfsuite_strip_results does not take any direct arguments')
parser.print_help()
sys.exit(-2)
# Check that all options have a setting, even the
# optional ones. Optional args should all have default values.
for option in options.__dict__:
if options.__dict__[option] is None:
print('Some required arguments were not set')
parser.print_help()
sys.exit(-2)
# Get a list of all files in the directory with the matching prefix
input_files = [f for f in listdir(options.input_dir.strip()) if
(isfile(join(options.input_dir.strip(), f)) and
f.startswith(options.prefix))]
# Strip out the results from the files matching the input ignores
for i in input_files:
f = open(i, 'r')
lines = f.readlines()
f.close()
f = open(i, 'w')
for l in lines:
if any(x in l for x in options.ignore):
continue
f.write(l)
f.close()
if __name__ == '__main__':
main()
|
pybee/seasnake | tests/test_enum.py | Python | bsd-3-clause | 3,328 | 0 | from __future__ import unicode_literals
from tests.utils import ConverterTestCase
class EnumTestCase(ConverterTestCase):
def test_empty(self):
self.assertGeneratedOutput(
"""
enum Bar {
};
""",
"""
from enum import Enum
class Bar(Enum):
pass
"""
)
def test_without_values(self):
self.assertGeneratedOutput(
"""
enum Bar {
TOP,
RIGHT,
BOTTOM,
LEFT
};
""",
"""
from enum import Enum
class Bar(Enum):
TOP = 0
RIGHT = 1
BOTTOM = 2
LEFT = 3
"""
)
def test_values(self):
self.assertGeneratedOutput(
"""
| enum Bar {
TOP = 37,
RIGHT = 42,
BOTTOM = 55,
LEFT = 69
};
""",
"""
from enum import Enum
class Bar(Enum):
TOP = 37
RIGHT = 42
BOTTOM = 55
LEFT = 69
"""
)
def test_initial_values(self):
self.assertGeneratedOutput(
"""
enum Bar {
TOP = 37,
RIGHT,
BOTTOM,
LEFT
};
""",
"""
from enum import Enum
class Bar(Enum):
TOP = 37
RIGHT = 38
BOTTOM = 39
LEFT = 40
"""
)
def test_multiple_initial_values(self):
self.assertGeneratedOutput(
"""
enum Bar {
TOP = 37,
RIGHT,
BOTTOM = 42,
LEFT
};
""",
"""
from enum import Enum
class Bar(Enum):
TOP = 37
RIGHT = 38
BOTTOM = 42
LEFT = 43
"""
)
def test_expressions_for_values(self):
self.assertGeneratedOutput(
"""
enum Bar {
TOP = 1 << 0,
RIGHT = 1 << 1,
BOTTOM = 1 << 2,
LEFT = 1 << 3
};
""",
"""
from enum import Enum
class Bar(Enum):
TOP = 1
RIGHT = 2
BOTTOM = 4
LEFT = 8
"""
)
def test_local_enum_reference(self):
self.assertGeneratedOutput(
"""
enum Bar {
TOP,
RIGHT,
BOTTOM,
LEFT
};
void test() {
Bar position = TOP;
}
""",
"""
from enum import Enum
class Bar(Enum):
TOP = 0
RIGHT = 1
BOTTOM = 2
LEFT = 3
def test():
position = Bar.TOP
"""
)
| |
ottokart/punctuator2 | main.py | Python | mit | 6,735 | 0.003563 | # coding: utf-8
from __future__ import division, print_function
from collections import OrderedDict
from time import time
import models
import data
import theano
try:
import cPickle
except ImportError:
import _pickle as cPickle
import sys
import os.path
try:
input = raw_input
except NameError:
pass
import theano.tensor as T
import numpy as np
MAX_EPOCHS = 50
MINIBATCH_SIZE = 128
L2_REG = 0.0
CLIPPING_THRESHOLD = 2.0
PATIENCE_EPOCHS = 1
"""
Bi-directional RNN with attention
For a sequence of N words, the model makes N punctuation decisions (no punctuation before the first word, but there's a decision after the last word or before </S>)
"""
def get_minibatch(file_name, batch_size, shuffle, with_pauses=False):
dataset = data.load(file_name)
if shuffle:
np.random.shuffle(dataset)
X_batch = []
Y_batch = []
if with_pauses:
P_batch = []
if len(dataset) < batch_size:
print("WARNING: Not enough samples in '%s'. Reduce mini-batch size to %d or use a dataset with at least %d words." % (
file_name,
len(dataset),
MINIBATCH_SIZE * data.MAX_SEQUENCE_LEN))
for subsequence in dataset:
X_batch.append(subsequence[0])
Y_batch.append(subsequence[1])
if with_pauses:
P_batch.append(subsequence[2])
if len(X_batch) == batch_size:
# Transpose, because the model assumes the first axis is time
X = np.array(X_batch, dtype=np.int32).T
Y = np.array(Y_batch, dtype=np.int32).T
if with_pauses:
P = np.array(P_batch, dtype=theano.config.floatX).T
if with_pauses:
yield X, Y, P
else:
y | ield X, Y
X_batch = []
Y_batch = []
if with_pauses:
P_batch = []
if __name__ == "__main__":
if len(s | ys.argv) > 1:
model_name = sys.argv[1]
else:
sys.exit("'Model name' argument missing!")
if len(sys.argv) > 2:
num_hidden = int(sys.argv[2])
else:
sys.exit("'Hidden layer size' argument missing!")
if len(sys.argv) > 3:
learning_rate = float(sys.argv[3])
else:
sys.exit("'Learning rate' argument missing!")
model_file_name = "Model_%s_h%d_lr%s.pcl" % (model_name, num_hidden, learning_rate)
print(num_hidden, learning_rate, model_file_name)
word_vocabulary = data.read_vocabulary(data.WORD_VOCAB_FILE)
punctuation_vocabulary = data.iterable_to_dict(data.PUNCTUATION_VOCABULARY)
x = T.imatrix('x')
y = T.imatrix('y')
lr = T.scalar('lr')
continue_with_previous = False
if os.path.isfile(model_file_name):
while True:
resp = input("Found an existing model with the name %s. Do you want to:\n[c]ontinue training the existing model?\n[r]eplace the existing model and train a new one?\n[e]xit?\n>" % model_file_name)
resp = resp.lower().strip()
if resp not in ('c', 'r', 'e'):
continue
if resp == 'e':
sys.exit()
elif resp == 'c':
continue_with_previous = True
break
if continue_with_previous:
print("Loading previous model state")
net, state = models.load(model_file_name, MINIBATCH_SIZE, x)
gsums, learning_rate, validation_ppl_history, starting_epoch, rng = state
best_ppl = min(validation_ppl_history)
else:
rng = np.random
rng.seed(1)
print("Building model...")
net = models.GRU(
rng=rng,
x=x,
minibatch_size=MINIBATCH_SIZE,
n_hidden=num_hidden,
x_vocabulary=word_vocabulary,
y_vocabulary=punctuation_vocabulary
)
starting_epoch = 0
best_ppl = np.inf
validation_ppl_history = []
gsums = [theano.shared(np.zeros_like(param.get_value(borrow=True))) for param in net.params]
cost = net.cost(y) + L2_REG * net.L2_sqr
gparams = T.grad(cost, net.params)
updates = OrderedDict()
# Compute norm of gradients
norm = T.sqrt(T.sum(
[T.sum(gparam ** 2) for gparam in gparams]
))
# Adagrad: "Adaptive subgradient methods for online learning and stochastic optimization" (2011)
for gparam, param, gsum in zip(gparams, net.params, gsums):
gparam = T.switch(
T.ge(norm, CLIPPING_THRESHOLD),
gparam / norm * CLIPPING_THRESHOLD,
gparam
) # Clipping of gradients
updates[gsum] = gsum + (gparam ** 2)
updates[param] = param - lr * (gparam / (T.sqrt(updates[gsum] + 1e-6)))
train_model = theano.function(
inputs=[x, y, lr],
outputs=cost,
updates=updates
)
validate_model = theano.function(
inputs=[x, y],
outputs=net.cost(y)
)
print("Training...")
for epoch in range(starting_epoch, MAX_EPOCHS):
t0 = time()
total_neg_log_likelihood = 0
total_num_output_samples = 0
iteration = 0
for X, Y in get_minibatch(data.TRAIN_FILE, MINIBATCH_SIZE, shuffle=True):
total_neg_log_likelihood += train_model(X, Y, learning_rate)
total_num_output_samples += np.prod(Y.shape)
iteration += 1
if iteration % 100 == 0:
sys.stdout.write("PPL: %.4f; Speed: %.2f sps\n" % (np.exp(total_neg_log_likelihood / total_num_output_samples), total_num_output_samples / max(time() - t0, 1e-100)))
sys.stdout.flush()
print("Total number of training labels: %d" % total_num_output_samples)
total_neg_log_likelihood = 0
total_num_output_samples = 0
for X, Y in get_minibatch(data.DEV_FILE, MINIBATCH_SIZE, shuffle=False):
total_neg_log_likelihood += validate_model(X, Y)
total_num_output_samples += np.prod(Y.shape)
print("Total number of validation labels: %d" % total_num_output_samples)
ppl = np.exp(total_neg_log_likelihood / total_num_output_samples)
validation_ppl_history.append(ppl)
print("Validation perplexity is %s" % np.round(ppl, 4))
if ppl <= best_ppl:
best_ppl = ppl
net.save(model_file_name, gsums=gsums, learning_rate=learning_rate, validation_ppl_history=validation_ppl_history, best_validation_ppl=best_ppl, epoch=epoch, random_state=rng.get_state())
elif best_ppl not in validation_ppl_history[-PATIENCE_EPOCHS:]:
print("Finished!")
print("Best validation perplexity was %s" % best_ppl)
break
|
mattilyra/gensim | gensim/corpora/bleicorpus.py | Python | lgpl-2.1 | 5,756 | 0.002085 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""Сorpus in Blei's LDA-C format."""
from __future__ import with_statement
from os import path
import logging
from gensim import utils
from gensim.corpora import IndexedCorpus
from six.moves import xrange
logger = logging.getLogger(__name__)
class BleiCorpus(IndexedCorpus):
"""Corpus in Blei's LDA-C format.
The corpus is represented as two files: one describing the documents, and another
describing the mapping between words and their ids.
Each document is one line::
N fieldId1:fieldValue1 fieldId2:fieldValue2 ... fieldIdN:fieldValueN
The vocabulary is a file with words, one word per line; word at line K has an implicit `id=K`.
"""
def __init__(self, fname, fname_vocab=None):
"""
Parameters
----------
fname : str
Path to corpus.
fname_vocab : str, optional
Vocabulary file. If `fname_vocab` is None, searching one of variants:
* `fname`.vocab
* `fname`/vocab.txt
* `fname_without_ext`.vocab
* `fname_folder`/vocab.txt
Raises
------
IOError
If vocabulary file doesn't exist.
"""
IndexedCorpus.__init__(self, fname)
logger.info("loading corpus from %s", fname)
if fname_vocab is None:
fname_base, _ = path.splitext(fname)
fname_dir = path.dirname(fname)
for fname_vocab in [
utils.smart_extension(fname, '.vocab'),
utils.smart_extension(fname, '/vocab.txt'),
utils.smart_extension(fname_base, '.vocab'),
utils.smart_extension(fname_dir, '/vocab.txt'),
]:
if path.exists(fname_vocab):
break
else:
raise IOError('BleiCorpus: could not find vocabulary file')
self.fname = fname
with utils.smart_open(fname_vocab) as fin:
words = [utils.to_unicode(word).rstrip() for word in fin]
self.id2word = dict(enumerate(words))
def __iter__(self):
"""Iterate over the corpus, returning one sparse (BoW) vector at a time.
Yields
------
list of (int, float)
Document's BoW representation.
"""
lineno = -1
with utils.smart_open(self.fname) as fin:
for lineno, line in enumerate(fin):
yield self.line2doc(line)
self.length = lineno + 1
def line2doc(self, line):
"""Convert line in Blei LDA-C format to document (BoW representation).
Parameters
----------
line : str
Line in Blei's LDA-C format.
Returns
-------
list of (int, float)
Document's BoW representation.
"""
parts = utils.to_unicode(line).split()
if int(parts[0]) != len(parts) - 1:
raise ValueError("invalid format in %s: %s" % (self.fname, repr(line)))
doc = [part.rsplit(':', 1) for part in parts[1:]]
doc = [(int(p1), float(p2)) for p1, p2 in doc]
return doc
@staticmethod
def save_corpus(fname, corpus, id2word=None, metadata=False):
"""Save a corpus in the LDA-C format.
Notes
-----
There are actually two files saved: | `fname` and `fname.vocab`, where `fname.vocab` is the vocabulary file.
Parameters
----------
fname : str
Path to output file.
corpus : iterable of iterable of (int, float)
Input corpus in BoW format.
id2word : dict of (str, str), optional
Mapping id -> word for `corpus`.
metadata : bool, optional
| THIS PARAMETER WILL BE IGNORED.
Returns
-------
list of int
Offsets for each line in file (in bytes).
"""
if id2word is None:
logger.info("no word id mapping provided; initializing from corpus")
id2word = utils.dict_from_corpus(corpus)
num_terms = len(id2word)
else:
num_terms = 1 + max([-1] + id2word.keys())
logger.info("storing corpus in Blei's LDA-C format into %s", fname)
with utils.smart_open(fname, 'wb') as fout:
offsets = []
for doc in corpus:
doc = list(doc)
offsets.append(fout.tell())
parts = ["%i:%g" % p for p in doc if abs(p[1]) > 1e-7]
fout.write(utils.to_utf8("%i %s\n" % (len(doc), ' '.join(parts))))
# write out vocabulary, in a format compatible with Blei's topics.py script
fname_vocab = utils.smart_extension(fname, '.vocab')
logger.info("saving vocabulary of %i words to %s", num_terms, fname_vocab)
with utils.smart_open(fname_vocab, 'wb') as fout:
for featureid in xrange(num_terms):
fout.write(utils.to_utf8("%s\n" % id2word.get(featureid, '---')))
return offsets
def docbyoffset(self, offset):
"""Get document corresponding to `offset`.
Offset can be given from :meth:`~gensim.corpora.bleicorpus.BleiCorpus.save_corpus`.
Parameters
----------
offset : int
Position of the document in the file (in bytes).
Returns
-------
list of (int, float)
Document in BoW format.
"""
with utils.smart_open(self.fname) as f:
f.seek(offset)
return self.line2doc(f.readline())
|
arth-co/shoop | shoop_tests/notify/test_notification.py | Python | agpl-3.0 | 3,453 | 0.001158 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.contrib.auth.models import AnonymousUser
from django.core.urlresolvers import set_urlconf, reverse
import pytest
from shoop.notify import Context
from shoop.notify.actions.notification import AddNotification
from shoop.notify.enums import Priority, RecipientType
from shoop.notify.models.notification import Notification
from shoop_tests.notify.utils import make_bind_data
from shoop_tests.utils import very_recently
from shoop_tests.utils.fixtures import regular_user
__all__ = ["regular_user"] # fix qa kvetch
@pytest.mark.django_db
@pytest.mark.parametrize("specific_user", (False, True))
def test_notification(admin_user, specific_user):
AddNotification(make_bind_data(
variables={"priority": "priority"},
constants={
"message": "Hi {{ name }}!",
"message_identifier": "hi mom",
"url": "http://burymewithmymoney.com/",
"recipient_type": (RecipientType.SPECIFIC_USER if specific_user else RecipientType.ADMINS),
"recipient": (admin_user if specific_user else None),
"priority": Priority.CRITICAL
}
)).execute(Context.from_variables(name="Justin Case"))
notif = Notification.objects.last()
assert isinstance(notif, Notification)
if specific_user:
assert notif.recipient == admin_user
assert Notification.objects.unread_for_user(admin_user).get(pk=notif.pk)
assert notif.identifier == "hi mom"
assert notif.message == "Hi Justin Case!"
assert notif.priority == Priority.CRITICAL
assert notif.url == "http://burymewithmymoney.com/"
with pytest.raises(ValueError):
notif.url = "http://www.theuselessweb.com/"
assert not notif.is_read
notif.mark_read(admin_user) # Once, for setting
notif.mark_read(admin_user) # Twice, for branch checking
assert notif.marked_read_by == admin_user
assert very_recently(notif.marked_read_on)
@pytest.mark.django_db
def test_no_notifs_for_anon(regular_user):
assert not Notification.objects.for_user(regular_user).exists()
assert not Notification.objects.for_user(AnonymousUser()).exists()
@pytest.mark.django_db
def test_misconfigured_add_notification_is_noop():
n_notifs = Notification.objects.count()
AddNotification(make_bind_data(
constants={
"recipient_type": RecipientType.SPECIFIC_USER,
"message": "This'll never get delivered!",
}
)).execute(Context())
assert Notification.objects.count() == n_notifs
def test_misconfigured_specific_notification_fails():
with pytest.raises(ValueError):
Notification.objects.create(recipient_type=RecipientType.SPECIFIC_USER)
@pytest.mark.django_db
def test_notification_reverse_url():
try:
set_urlconf("shoop_tests.notify.notification_test_urls")
n = Notification()
kwargs = dict(viewname="test", kwargs={"arg": "yes"}) # kwargs within kwargs, oh my
n.set_reverse_url(**kwargs | )
n.save()
| with pytest.raises(ValueError):
n.set_reverse_url()
assert n.url == reverse(**kwargs)
finally:
set_urlconf(None)
def test_urlless_notification():
assert not Notification().url
|
avara1986/gozokia | gozokia/utils/functional.py | Python | mit | 4,105 | 0.000487 | import copy
import operator
empty = object()
def unpickle_lazyobject(wrapped):
"""
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
"""
return wrapped
def new_method_proxy(func):
def inner(self, *args):
if self._wrapped is empty:
self._setup()
return func(self._wrapped, *args)
return inner
class LazyObj | ect(object):
"""
A wrapper for another class that can be used to delay instantiation of the
wrapped class.
By subclassing, you have the opportunity to intercept and alter the
instantiation. If you don't need to do that, use SimpleLazyObject.
"""
# Avoid infinite rec | ursion when tracing __init__ (#19456).
_wrapped = None
def __init__(self):
self._wrapped = empty
__getattr__ = new_method_proxy(getattr)
def __setattr__(self, name, value):
if name == "_wrapped":
# Assign to __dict__ to avoid infinite __setattr__ loops.
self.__dict__["_wrapped"] = value
else:
if self._wrapped is empty:
self._setup()
setattr(self._wrapped, name, value)
def __delattr__(self, name):
if name == "_wrapped":
raise TypeError("can't delete _wrapped.")
if self._wrapped is empty:
self._setup()
delattr(self._wrapped, name)
def _setup(self):
"""
Must be implemented by subclasses to initialize the wrapped object.
"""
raise NotImplementedError('subclasses of LazyObject must provide a _setup() method')
# Because we have messed with __class__ below, we confuse pickle as to what
# class we are pickling. We're going to have to initialize the wrapped
# object to successfully pickle it, so we might as well just pickle the
# wrapped object since they're supposed to act the same way.
#
# Unfortunately, if we try to simply act like the wrapped object, the ruse
# will break down when pickle gets our id(). Thus we end up with pickle
# thinking, in effect, that we are a distinct object from the wrapped
# object, but with the same __dict__. This can cause problems (see #25389).
#
# So instead, we define our own __reduce__ method and custom unpickler. We
# pickle the wrapped object as the unpickler's argument, so that pickle
# will pickle it normally, and then the unpickler simply returns its
# argument.
def __reduce__(self):
if self._wrapped is empty:
self._setup()
return (unpickle_lazyobject, (self._wrapped,))
# We have to explicitly override __getstate__ so that older versions of
# pickle don't try to pickle the __dict__ (which in the case of a
# SimpleLazyObject may contain a lambda). The value will end up being
# ignored by our __reduce__ and custom unpickler.
def __getstate__(self):
return {}
def __deepcopy__(self, memo):
if self._wrapped is empty:
# We have to use type(self), not self.__class__, because the
# latter is proxied.
result = type(self)()
memo[id(self)] = result
return result
return copy.deepcopy(self._wrapped, memo)
__bytes__ = new_method_proxy(bytes)
__str__ = new_method_proxy(str)
__bool__ = new_method_proxy(bool)
# Introspection support
__dir__ = new_method_proxy(dir)
# Need to pretend to be the wrapped class, for the sake of objects that
# care about this (especially in equality tests)
__class__ = property(new_method_proxy(operator.attrgetter("__class__")))
__eq__ = new_method_proxy(operator.eq)
__ne__ = new_method_proxy(operator.ne)
__hash__ = new_method_proxy(hash)
# List/Tuple/Dictionary methods support
__getitem__ = new_method_proxy(operator.getitem)
__setitem__ = new_method_proxy(operator.setitem)
__delitem__ = new_method_proxy(operator.delitem)
__iter__ = new_method_proxy(iter)
__len__ = new_method_proxy(len)
__contains__ = new_method_proxy(operator.contains) |
slavapestov/swift | utils/profdata_merge/server.py | Python | apache-2.0 | 2,159 | 0 | # utils/profdata_merge/server.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
# This file contains the server and handler definitions that pass files to
# the merge worker processes.
import SocketServer
import thread
import logging
from main import SERVER_ADDRESS, TESTS_FINISHED_SENTINEL
class ProfdataTCPHandler(SocketServer.StreamRequestHandler):
def report(self, msg):
"""Convenience method for reporting status from the workers."""
logging.info("[ProfdataTCPHandler]: %s" % msg)
def handle(self):
"""Receive a newline-separated list of filenames from a TCP connection
and add them to the shared merge queue, where the workers will
execute llvm-profdata merge commands."""
data = self.rfile.read()
self.report("received data (length %d): %s" % (len(data), repr(data)))
# Stop once we receive the sentinel
if data.startswith(TESTS_FINISHED_SENTINEL):
self.report("received sentinel; killing server...")
self.finish()
| self.connection.close()
def kill_server(server):
server.shutdown()
# must be killed on another thread, or else deadlock
thread.start_new_thread(kill_server, (self.server,))
else:
# Add all the files to the queue
for f in data.splitlines():
f = f.strip()
if f in self.server.files_merged:
return
self.server.files_merged.add(f)
| self.server.file_queue.put(f)
class ProfdataServer(SocketServer.TCPServer, object):
def __init__(self, file_queue):
super(ProfdataServer, self).__init__(SERVER_ADDRESS,
ProfdataTCPHandler)
self.file_queue = file_queue
self.files_merged = set()
|
rfedmi/reposdmpdos | davidmp/mainIndex.py | Python | gpl-2.0 | 385 | 0.01039 | # coding: utf-8
'''
Create | d on 17/2/2015
@author: PC06
'''
from include import app
from flask.templating import render_template
from ec.edu.itsae.dao import PersonaDA | O
@app.route("/")
def login():
return render_template("login.html")
@app.route("/persona")
def index():
x=PersonaDAO.PersonaDAO().reportarPersona()
print x
return render_template("index.html", dato=x) |
KenanBek/rslservices | app/payroll/migrations/0010_auto_20160803_1622.py | Python | gpl-3.0 | 1,650 | 0.003636 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('payroll', '0009_auto_20160722_1720'),
]
operations = [
migrations.AddField(
mod | el_name='netsalary',
name='company_gross_spf',
field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3),
preserve_de | fault=True,
),
migrations.AddField(
model_name='netsalary',
name='company_li_spf',
field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3),
preserve_default=True,
),
migrations.AddField(
model_name='netsalary',
name='company_net_spf',
field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3),
preserve_default=True,
),
migrations.AddField(
model_name='netsalary',
name='life_insurance_amount',
field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3),
preserve_default=True,
),
migrations.AddField(
model_name='netsalary',
name='sick_leave_amount',
field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3),
preserve_default=True,
),
migrations.AddField(
model_name='netsalary',
name='vacation_leave_amount',
field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3),
preserve_default=True,
),
]
|
Dakno/compose | compose/config/validation.py | Python | apache-2.0 | 8,262 | 0.003631 | import json
import os
from functools import wraps
from docker.utils.ports import split_port
from jsonschema import Draft4Validator
from jsonschema import FormatChecker
from jsonschema import ValidationError
from .errors import ConfigurationError
DOCKER_CONFIG_HINTS = {
'cpu_share': 'cpu_shares',
'add_host': 'extra_hosts',
'hosts': 'extra_hosts',
'extra_host': 'extra_hosts',
'device': 'devices',
'link': 'links',
'load_image': 'load_image',
'memory_swap': 'memswap_limit',
'port': 'ports',
'privilege': 'privileged',
'priviliged': 'privileged',
'privilige': 'privileged',
'volume': 'volumes',
'workdir': 'working_dir',
}
VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
@FormatChecker.cls_checks(
format="ports",
raises=ValidationError(
"Invalid port formatting, it should be "
"'[[remote_ip:]remote_port:]port[/protocol]'"))
def format_ports(instance):
try:
split_port(instance)
except ValueError:
return False
return True
def validate_service_names(func):
@wraps(func)
def func_wrapper(config):
for service_name in config.keys():
if type(service_name) is int:
raise ConfigurationError(
"Service name: {} needs to be a string, eg '{}'".format(service_name, service_name)
)
return func(config)
return func_wrapper
def validate_top_level_object(func):
@wraps(func)
def func_wrapper(config):
if not isinstance(config, dict):
raise ConfigurationError(
"Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
)
return func(config)
return func_wrapper
def get_unsupported_config_msg(service_name, error_key):
msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
if error_key in DOCKER_CONFIG_HINTS:
msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
return msg
def process_errors(errors):
"""
jsonschema gives us an error tree full of information to explain what has
gone wrong. Process each error and pull out relevant information and re-write
helpful error messages that are relevant.
"""
def _parse_key_from_error_msg(error):
return error.message.split("'")[1]
def _clean_error_message(message):
return message.replace("u'", "'")
def _parse_valid_types_from_schema(schema):
"""
Our defined types using $ref in the schema require some extra parsing
retrieve a helpful type for error message display.
"""
if '$ref' in schema:
return schema['$ref'].replace("#/definitions/", "").replace("_", " ")
else:
return str(schema['type'])
root_msgs = []
invalid_keys = []
required = []
type_errors = []
other_errors = []
for error in errors:
# handle root level errors
if len(error.path) == 0:
if error.validator == 'type':
msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
root_msgs.append(msg)
elif error.validator == 'additionalProperties':
invalid_service_name = _parse_key_from_error_msg(error)
msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
root_msgs.append(msg)
else:
root_msgs.append(_clean_error_message(error.message))
else:
# handle service level errors
service_name = error.path[0]
# pop the service name off our path
error.path.popleft()
if error.validator == 'additionalProperties':
invalid_config_key = _parse_key_from_error_msg(error)
invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
elif error.validator == 'anyOf':
if 'image' in error.instance and 'build' in error.instance:
required.append(
"Service '{}' has both an image and build path specified. "
"A service can either be built to image or use an existing "
"image, not bo | th.".format(service_name))
elif 'image' not in error.instance and 'build' not in error.instance:
required.appen | d(
"Service '{}' has neither an image nor a build path "
"specified. Exactly one must be provided.".format(service_name))
elif 'image' in error.instance and 'dockerfile' in error.instance:
required.append(
"Service '{}' has both an image and alternate Dockerfile. "
"A service can either be built to image or use an existing "
"image, not both.".format(service_name))
else:
required.append(_clean_error_message(error.message))
elif error.validator == 'oneOf':
config_key = error.path[0]
valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
valid_type_msg = " or ".join(valid_types)
type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
service_name, config_key, valid_type_msg)
)
elif error.validator == 'type':
msg = "a"
if error.validator_value == "array":
msg = "an"
if len(error.path) > 0:
config_key = " ".join(["'%s'" % k for k in error.path])
type_errors.append(
"Service '{}' configuration key {} contains an invalid "
"type, it should be {} {}".format(
service_name,
config_key,
msg,
error.validator_value))
else:
root_msgs.append(
"Service '{}' doesn\'t have any configuration options. "
"All top level keys in your docker-compose.yml must map "
"to a dictionary of configuration options.'".format(service_name))
elif error.validator == 'required':
config_key = error.path[0]
required.append(
"Service '{}' option '{}' is invalid, {}".format(
service_name,
config_key,
_clean_error_message(error.message)))
elif error.validator == 'dependencies':
dependency_key = list(error.validator_value.keys())[0]
required_keys = ",".join(error.validator_value[dependency_key])
required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
dependency_key, service_name, dependency_key, required_keys))
else:
config_key = " ".join(["'%s'" % k for k in error.path])
err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
other_errors.append(err_msg)
return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
def validate_against_schema(config):
config_source_dir = os.path.dirname(os.path.abspath(__file__))
schema_file = os.path.join(config_source_dir, "schema.json")
with open(schema_file, "r") as schema_fh:
schema = json.load(schema_fh)
validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
if errors:
error_msg = process_errors(errors)
|
OCA/management-system | mgmtsystem_survey/models/__init__.py | Python | agpl-3.0 | 93 | 0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) | .
from . import survey_s | urvey
|
globality-corp/microcosm-dynamodb | microcosm_dynamodb/health.py | Python | apache-2.0 | 163 | 0.006135 | """
Simple dynamodb health check.
" | ""
def check_health(graph):
# TODO: Is there a basic service health check to perform here aki | n to 'SELECT 1;' ?
pass
|
PhonologicalCorpusTools/SLP-Annotator | bin/position_hand.py | Python | gpl-3.0 | 8,676 | 0.012679 | # Import statements
import re
import os
from math import pi, radians
import bpy
"""To Run in Blender:
filename = 'C:\\Users\\mFry2\\Google Drive\\PCT\\position_hand.py'
exec(compile(open(filename).read(), filename, 'exec'))
"""
# Function to translate handshape coding to degrees of rotation, adduction, flexion
def translate_finger_code_to_degrees(finger, hand, code, handShapeParams):
# flexionDictionary parameters: [proximal, medial, distal] joints
if hand == 'L':
flexionDict = {'H':[30, 15, 10], 'E':[20, 10, 5], 'e': [10, 5, 0], 'i':[-45, -50, -60], 'F':[-80, -90, -75], '_':[0,0,0]}
abductDict = {'middle': {'=':0, '<':10}, 'ring': {'=':0, '<':10}, 'pinky': {'=':0, '<':20}}
rotDict = {'middle': {'=':0, '<':5}, 'ring': {'=':0, '<':-5}, 'pinky': {'=':0, '<':-10}}
elif hand == 'R':
flexionDict = {'H':[-30, -15, -10], 'E':[-20, -10, -5], 'e': [-10, -5, 0], 'i':[45, 50, 60], 'F':[80, 90, 75], '_':[0,0,0]}
abductDict = {'middle': {'=':0, '<':-10}, 'ring': {'=':0, '<':-10}, 'pinky': {'=':0, '<':-20}}
rotDict = {'middle': {'=':0, '<':5}, 'ring': {'=':0, '<':-5}, 'pinky': {'=':0, '<':-10}}
if finger == 'thumb':
| if code[1] == '<':
handShapeParams['thumb.01.' + hand] = [0, 0, 0]
if code[0] == 'O' and hand == 'L':
handShapeParams['thumb.01.' + hand + '.001'] = [0, -70, -40]
handShapeParams['thumb.02.' + hand] = [0, -70, | flexionDict[code[2]][0]]
handShapeParams['thumb.03.' + hand] = [0, 0, flexionDict[code[3]][1]]
elif code[0] == 'O' and hand == 'R':
handShapeParams['thumb.01.' + hand + '.001'] = [0, 70, 40]
handShapeParams['thumb.02.' + hand] = [0, -70, flexionDict[code[2]][0]]
handShapeParams['thumb.03.' + hand] = [0, 0, flexionDict[code[3]][1]]
elif finger == 'index':
handShapeParams['finger_index.01.' + hand] = [0, 0, flexionDict[code[1]][0]]
handShapeParams['finger_index.02.' + hand] = [0, 0, flexionDict[code[2]][1]]
handShapeParams['finger_index.03.' + hand] = [0, 0, flexionDict[code[3]][2]]
else:
# Parameters: [adduction, rotation, flexion]
handShapeParams['finger_' + finger + '.01.' + hand] = [abductDict[finger][code[0]], rotDict[finger][code[0]], flexionDict[code[2]][0]]
handShapeParams['finger_' + finger + '.02.' + hand] = [0, rotDict[finger][code[0]], flexionDict[code[3]][1]]
handShapeParams['finger_' + finger + '.03.' + hand] = [0, rotDict[finger][code[0]], flexionDict[code[4]][2]]
if finger == 'middle' and code[0] == '<':
tempParam = handShapeParams['finger_index.01.' + hand]
handShapeParams['finger_index.01.' + hand] = [-10, tempParam[1], tempParam[2]]
return handShapeParams
"""
def translate_thumb_codes_to_position(hand, shapeCode, contactCode, handShapeParams):
# r = radial, f = friction, d = distal, p =proximal, m = medial
handShapeParams['thumb.01.' + hand + '.001'] =
handShapeParams['thumb.01.' + hand] =
handShapeParams['thumb.02.' + hand] =
handShapeParams['thumb.03.' + hand] =
"""
def position_hand():
with open(os.path.join(os.getcwd(), 'handCode.txt'), 'r') as inFile:
code = inFile.read()
parseCode = re.split('\]\d\[+', code[1:])
[armShape, thumbShape, thumbFingerContact, indexShape, middleShape, ringShape, pinkyShape] = parseCode[:]
# Set hand & generate degrees of rotation, adduction & flexion
hand = 'L'
handShapeParams = dict()
handShapeParams = translate_finger_code_to_degrees('index', hand, indexShape, handShapeParams)
handShapeParams = translate_finger_code_to_degrees('middle', hand, middleShape, handShapeParams)
handShapeParams = translate_finger_code_to_degrees('ring', hand, ringShape, handShapeParams)
handShapeParams = translate_finger_code_to_degrees('pinky', hand, pinkyShape, handShapeParams)
handShapeParams = translate_finger_code_to_degrees('thumb', hand, thumbShape, handShapeParams)
# Position model in blender
bpy.ops.object.posemode_toggle()
# deactive current bone select
if not bpy.context.active_pose_bone == None:
#print("Bone selected: " + str(bpy.context.active_pose_bone.name))
deactThisBone = bpy.context.active_pose_bone.name
deactThisBone = bpy.data.objects["Armature"].pose.bones[deactThisBone].bone
deactThisBone.select = False
#Cycle through finger bones in handShapeParams to modify the hand model:
for strBone, param in handShapeParams.items():
actThisBone = bpy.data.objects["Armature"].pose.bones[strBone].bone
actThisBone.select = True
eleVDegree = param[2]
addVDegree = param[0]
rotVDegree = param[1]
eleVRadian = (eleVDegree/360)*2*pi
addVRadian = (addVDegree/360)*2*pi
rotVRadian = (rotVDegree/360)*2*pi
if '001' in strBone:
# Flexion/Extension occurs by moving joints about the y-axis
bpy.ops.transform.rotate(value = eleVRadian, constraint_axis=(False, True, False))
# Rotation of joints to reflect how natural hands adduct by moving joints about the x-axis
bpy.ops.transform.rotate(value=rotVRadian, axis = (True, False, False))
# Adduction of fingers occurs by moving the proximal joint (e.g. finger_index.01.L) about the z-axis
bpy.ops.transform.rotate(value=addVRadian, axis = (False, False, True))
else:
# Flexion/Extension occurs by moving joints about the y-axis
bpy.ops.transform.rotate(value = eleVRadian, constraint_axis=(False, True, False))
# Rotation of joints to reflect how natural hands adduct by moving joints about the x-axis
bpy.ops.transform.rotate(value=rotVRadian, axis = (True, False, False))
# Adduction of fingers occurs by moving the proximal joint (e.g. finger_index.01.L) about the z-axis
bpy.ops.transform.rotate(value=addVRadian, axis = (False, False, True),)
#Deactivate bone
deactThisBone = actThisBone
deactThisBone.select = False
#bpy.ops.transform.rotate(value = 0.2, axis=(.305, 0.885, -0.349), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
deactThisBone.select = True
bpy.ops.object.posemode_toggle()
bpy.ops.object.camera_add(view_align = True)
bpy.context.scene.camera = bpy.data.objects['Camera']
camera = bpy.context.object
camera.location = (-0.75, -0.14, 1.75)
# camera.rotation_euler = (0.0, 0.0, radians(90))
#Previous code for monitoring progression of algorithm
#print(bpy.data.objects['Armature'].pose.bones.keys())
# List of Bones: ['hand.L', 'palm.02.L.001', 'palm.02.L', 'finger_middle.01.L', 'finger_middle.02.L', 'finger_middle.03.L', 'palm.03.L.001', 'palm.03.L', 'finger_ring.01.L', 'finger_ring.02.L', 'finger_ring.03.L', 'palm.04.L.001', 'palm.04.L', 'finger_pinky.01.L', 'finger_pinky.02.L', 'finger_pinky.03.L', 'palm.01.L.001', 'palm.01.L', 'thumb.01.L.001', 'thumb.01.L', 'thumb.02.L', 'thumb.03.L', 'finger_index.01.L', 'finger_index.02.L', 'finger_index.03.L', 'shoulder.R', 'upper_arm.R', 'forearm.R', 'forearm.R.003', 'hand.R', 'palm.01.R.001', 'palm.01.R', 'thumb.01.R.001', 'thumb.01.R', 'thumb.02.R', 'thumb.03.R', 'finger_index.01.R', 'finger_index.02.R', 'finger_index.03.R', 'palm.02.R.001', 'palm.02.R', 'finger_middle.01.R', 'finger_middle.02.R', 'finger_middle.03.R', 'palm.03.R.001', 'palm.03.R', 'finger_ring.01.R', 'finger_ring.02.R', 'finger_ring.03.R', 'palm.04.R.001', 'palm.04.R', 'finger_pinky.01.R', 'finger_pinky.02.R', 'finger_pinky.03.R']
# Template: finger_index/middle/ring/pinky.joint.L/R
scene = bpy.context.scene
scene.render.image_settings.file_format = 'PNG' # set output format to .png
scene.frame_set(1)
# scene.render.filepath = os.path.join(os.getcwd(), 'hand_output.png')
path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'media', 'hand_output.png')
scene.render.filepath = path
bpy.o |
gjlawran/ckanext-bcgov | ckanext/bcgov/scripts/export/run_exporter.py | Python | agpl-3.0 | 518 | 0.017375 | # run using env as parameter: python run_exporter.py cad | id api_key
import exporter
#parse into data type files
import dataset_export
import update_datastore_content #enter key as an argument
from sys import argv
script, env, res_id, api_key = argv
with open(env + '.csv', 'w') as f:
csv_string = exporter.export( | 'https://' + env + '.data.gov.bc.ca', 'columns.json')
f.write(csv_string)
if __name__ == '__main__':
dataset_export.export_type(env)
update_datastore_content.update_resource(env, res_id, api_key) |
melviso/phycpp | beatle/app/resources/_folder.py | Python | gpl-2.0 | 5,664 | 0.052613 | # -*- coding: utf-8 -*-
_folder = [
"24 24 273 2",
" c None",
". c #F6D021",
"+ c #FACF0E",
"@ c #FAD00F",
"# c #FAD00E",
"$ c #FACF0C",
"% c #F5CD22",
"& c #EEDA94",
"* c #F2C32C",
"= c #F5D463",
"- c #F3D35E",
"; c #F6D055",
"> c #F3CE4A",
", c #F3CA36",
"' c #F2E4C1",
") c #F7EED0",
"! c #F7EAC7",
"~ c #F6E8BE",
"{ c #F4E5B6",
"] c #F6E0AE",
"^ c #F5DEA4",
"/ c #F5DD9C",
"( c #F6DB9A",
"_ c #F7E6B6",
": c #E99A0A",
"< c #EFECEC",
"[ c #F0F4FC",
"} c #F1F4FC",
"| c #F1F2FB",
"1 c #F2F3F8",
"2 c #F2F2F6",
"3 c #F3F2F6",
"4 c #F1F1F4",
" | 5 c #F2F1F4",
"6 c #F3F1F5",
"7 c #F5F2F6",
"8 c #F4F1F4",
"9 c #F0F0F0", |
"0 c #ECF1F1",
"a c #E5B157",
"b c #EEC742",
"c c #F1C616",
"d c #F6CD16",
"e c #F8D21A",
"f c #FAD31B",
"g c #F9D51F",
"h c #FAD627",
"i c #F9D62C",
"j c #F9D731",
"k c #F8D835",
"l c #F9DA37",
"m c #F9D939",
"n c #F9DA39",
"o c #F8D939",
"p c #F7D939",
"q c #F8D738",
"r c #F6D33C",
"s c #F4CF44",
"t c #EECA59",
"u c #F1C121",
"v c #F6C803",
"w c #F9CE06",
"x c #FBD609",
"y c #FDD90B",
"z c #FDD910",
"A c #FCDB16",
"B c #FBDC1D",
"C c #FCDD22",
"D c #FDDD26",
"E c #FDDE2B",
"F c #FDDE2D",
"G c #FEDF2E",
"H c #FDDD31",
"I c #FBDC30",
"J c #F9D835",
"K c #F7CE27",
"L c #EDBD20",
"M c #F2C530",
"N c #F7C901",
"O c #FBD105",
"P c #FCD708",
"Q c #FFDB0C",
"R c #FEDC12",
"S c #FDDC17",
"T c #FDDE1C",
"U c #FDDF23",
"V c #FEDF28",
"W c #FEDF2C",
"X c #FEE02E",
"Y c #FFE12F",
"Z c #FEE02F",
"` c #FEDE30",
" . c #FCDD33",
".. c #FBD726",
"+. c #F8CB00",
"@. c #F1C733",
"#. c #F4C73C",
"$. c #F7C502",
"%. c #FBD004",
"&. c #FDD408",
"*. c #FDD90C",
"=. c #FED911",
"-. c #FEDB17",
";. c #FEDC1D",
">. c #FDDD22",
",. c #FEDE27",
"'. c #FEDE2B",
"). c #FEDD2C",
"!. c #FEDE2C",
"~. c #FEDE2E",
"{. c #FDDD2F",
"]. c #FCD716",
"^. c #FACE02",
"/. c #F7CA00",
"(. c #F1C740",
"_. c #F2C848",
":. c #F7C201",
"<. c #FACD03",
"[. c #FCD207",
"}. c #FDD70A",
"|. c #FED710",
"1. c #FDD815",
"2. c #FDD91B",
"3. c #FEDB21",
"4. c #FEDB27",
"5. c #FEDC2A",
"6. c #FDDC2C",
"7. c #FDDD2C",
"8. c #FDDA1D",
"9. c #FCD405",
"0. c #FDD101",
"a. c #FBCE00",
"b. c #F7C800",
"c. c #F1CB56",
"d. c #F5CC54",
"e. c #F6BF01",
"f. c #F9C903",
"g. c #FCD106",
"h. c #FED409",
"i. c #FDD40F",
"j. c #FCD614",
"k. c #FDD71A",
"l. c #FFD823",
"m. c #FFD829",
"n. c #FED824",
"o. c #FDD618",
"p. c #FCD40A",
"q. c #FFD201",
"r. c #FFD302",
"s. c #FED001",
"t. c #FBCC00",
"u. c #F7C700",
"v. c #F4D065",
"w. c #F3C958",
"x. c #F6BC01",
"y. c #FAC404",
"z. c #FCCC07",
"A. c #FED00B",
"B. c #FED211",
"C. c #FFD418",
"D. c #FFD31A",
"E. c #FDD115",
"F. c #FBD007",
"G. c #FDCF00",
"H. c #FDCF01",
"I. c #FCCD00",
"J. c #FACB00",
"K. c #F8C700",
"L. c #F4D274",
"M. c #F3C85C",
"N. c #F3B700",
"O. c #FABF04",
"P. c #FAC705",
"Q. c #FCC906",
"R. c #FDC905",
"S. c #FECA03",
"T. c #FDCA00",
"U. c #FDCB00",
"V. c #FDC900",
"W. c #FDC800",
"X. c #FCCB00",
"Y. c #FBCB01",
"Z. c #FCCB01",
"`. c #F8C800",
" + c #F5D885",
".+ c #F3C562",
"++ c #F3AF00",
"@+ c #F7B801",
"#+ c #F7BE00",
"$+ c #FAC001",
"%+ c #F9C101",
"&+ c #FAC200",
"*+ c #FCC201",
"=+ c #FBC301",
"-+ c #FAC300",
";+ c #FBC300",
">+ c #F9C300",
",+ c #F9C401",
"'+ c #F9C602",
")+ c #F9C801",
"!+ c #F9CA00",
"~+ c #F9CD00",
"{+ c #F7C900",
"]+ c #F6DA8C",
"^+ c #F1C268",
"/+ c #F1A901",
"(+ c #F5AF01",
"_+ c #F4B400",
":+ c #F6B701",
"<+ c #F6BA01",
"[+ c #F6BC00",
"}+ c #F7BD00",
"|+ c #F7BE01",
"1+ c #F8BE01",
"2+ c #F8BF02",
"3+ c #F7C001",
"4+ c #F6C100",
"5+ c #F8C401",
"6+ c #F9C802",
"7+ c #F8CE00",
"8+ c #F6C800",
"9+ c #F3D88F",
"0+ c #EFBF6B",
"a+ c #EEA200",
"b+ c #EFA800",
"c+ c #F1AC00",
"d+ c #F2AE01",
"e+ c #F2B001",
"f+ c #F3B400",
"g+ c #F2B600",
"h+ c #F4BA00",
"i+ c #F5BC00",
"j+ c #F4BD00",
"k+ c #F5C101",
"l+ c #F5C502",
"m+ c #F6C700",
"n+ c #F8CA01",
"o+ c #F8CE02",
"p+ c #F6C500",
"q+ c #F2D691",
"r+ c #E7C48C",
"s+ c #E09D25",
"t+ c #DB9A20",
"u+ c #D79719",
"v+ c #D39515",
"w+ c #CE9111",
"x+ c #CA910E",
"y+ c #CA8F0A",
"z+ c #C89008",
"A+ c #C89007",
"B+ c #CA9107",
"C+ c #CB950B",
"D+ c #CC980E",
"E+ c #CF9D12",
"F+ c #D3A215",
"G+ c #D8A81A",
"H+ c #DEAD20",
"I+ c #E0AB24",
"J+ c #E7D0A4",
"K+ c #EAE8E8",
"L+ c #E6E3E2",
"M+ c #E1DFDE",
"N+ c #DDDBDA",
"O+ c #D2D1D0",
"P+ c #CECDCC",
"Q+ c #CCCAC9",
"R+ c #CCCBCA",
"S+ c #CDCDCC",
"T+ c #D4D4D3",
"U+ c #DFDDDD",
"V+ c #E3E0E0",
"W+ c #E7E4E4",
"X+ c #EBE9E8",
" ",
" ",
" ",
" ",
" . + @ # $ % ",
" & * = - ; > , ' ) ! ~ { ] ^ / ( _ ",
" : < [ } | 1 1 2 3 4 5 6 7 8 9 0 a ",
" b c d e f g h i j k l m n o p q r s t ",
" u v w x y z A B C D E F G H H I J K L ",
" M N O P Q R S T U V W X Y Z ` ...+.@. ",
" #.$.%.&.*.=.-.;.>.,.'.).!.~.{.].^./.(. ",
" _.:.<.[.}.|.1.2.3.4.5.6.7.8.9.0.a.b.c. ",
" d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v. ",
" w.x.y.z.A.B.C.D.E.F.G.H.s.s.s.I.J.K.L. ",
" M.N.O.P.Q.R.S.T.U.V.W.V.X.Y.Z.J.J.`. + ",
" .+++@+#+$+%+&+*+=+-+;+>+,+'+)+!+~+{+]+ ",
" ^+/+(+_+:+<+[+}+|+1+2+3+4+5+6++.7+8+9+ ",
" 0+a+b+c+d+e+f+g+N.h+i+j+k+l+m+n+o+p+q+ ",
" r+s+t+u+v+w+x+y+z+A+B+C+D+E+F+G+H+I+J+ ",
" K+L+M+N+O+P+Q+Q+R+S+T+U+V+W+X+ ",
" ",
" ",
" ",
" "]
|
p0psicles/SickRage | sickbeard/helpers.py | Python | gpl-3.0 | 59,494 | 0.002588 | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
# Git: https://github.com/SickRage/SickRage.git
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
import os
import io
import ctypes
import random
import re
import socket
import stat
import tempfile
import time
import traceback
import urllib
import urllib2
import hashlib
import httplib
import urlparse
import uuid
import base64
import zipfile
import datetime
import errno
import ast
import operator
import platform
import sickbeard
import adba
import requests
import certifi
from contextlib import closing
from socket import timeout as SocketTimeout
from sickbeard import logger, classes
from sickbeard.common import USER_AGENT
from sickbeard import db
from sickbeard.notifiers import synoindex_notifier
from sickrage.helper.common import http_code_description, media_extensions, pretty_file_size, subtitle_extensions, episode_num
from sickrage.helper.encoding import ek
from sickrage.helper.exceptions import ex
from sickrage.show.Show import Show
from itertools import izip, cycle
import shutil
import shutil_custom
import xml.etree.ElementTree as ET
import json
shutil.copyfile = shutil_custom.copyfile_custom
# pylint: disable=protected-access
# Access to a protected member of a client class
urllib._urlopener = classes.SickBeardURLopener()
def fixGlob(path):
path = re.sub(r'\[', '[[]', path)
return re.sub(r'(?<!\[)\]', '[]]', path)
def indentXML(elem, level=0):
"""
Does our pretty printing, makes Matt very happy
"""
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indentXML(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def remove_non_release_groups(name):
"""
Remove non release groups from name
"""
if not name:
return name
# Do not remove all [....] suffixes, or it will break anime releases ## Need to verify this is true now
# Check your database for funky release_names and add them here, to improve failed handling, archiving, and history.
# select release_name from tv_episodes WHERE LENGTH(release_name);
# [eSc], [SSG], [GWC] are valid release groups for non-anime
removeWordsList = {
r'\[rartv\]$': 'searchre',
r'\[rarbg\]$': 'searchre',
r'\[eztv\]$': 'searchre',
r'\[ettv\]$': 'searchre',
r'\[cttv\]$': 'searchre',
r'\[vtv\]$': 'searchre',
r'\[EtHD\]$': 'searchre',
r'\[GloDLS\]$': 'searchre',
r'\[silv4\]$': 'searchre',
r'\[Seedbox\]$': 'searchre',
r'\[PublicHD\]$': 'searchre',
r'\[AndroidTwoU\]$': 'searchre',
r'\[brassetv]\]$': 'searchre',
r'\.\[BT\]$': 'searchre',
r' \[1044\]$': 'searchre',
r'\.RiPSaLoT$': 'searchre',
r'\.GiuseppeTnT$': 'searchre',
r'\.Renc$': 'searchre',
r'\.gz$': 'searchre',
r'(?<![57])\.1$': 'searchre',
r'-NZBGEEK$': 'searchre',
r'-Siklopentan$': 'searchre',
r'-Chamele0n$': 'searchre',
r'-Obfuscated$': 'searchre',
r'-\[SpastikusTV\]$': 'searchre',
r'-RP$': 'searchre',
r'-20-40$': 'searchre',
r'\.\[www\.usabit\.com\]$': 'searchre',
r'^\[www\.Cpasbien\.pe\] ': 'searchre',
r'^\[www\.Cpasbien\.com\] ': 'searchre',
r'^\[ www\.Cpasbien\.pw \] ': 'searchre',
r'^\.www\.Cpasbien\.pw': 'searchre',
r'^\[www\.newpct1\.com\]': 'searchre',
r'^\[ www\.Cpasbien\.com \] ': 'searchre',
r'- \{ www\.SceneTime\.com \}$': 'searchre',
r'^\{ www\.SceneTime\.com \} - ': 'searchre',
r'^\]\.\[www\.tensiontorrent.com\] - ': 'searchre',
r'^\]\.\[ www\.tensiontorrent.com \] - ': 'searchre',
r'- \[ www\.torrentday\.com \]$': 'searchre',
r'^\[ www\.TorrentDay\.com \] - ': 'searchre',
r'\[NO-RAR\] - \[ www\.torrentday\.com \]$': 'searchre',
}
_name = name
for remove_string, remove_type in removeWordsList.iteritems():
if remove_type == 'search':
_name = _name.replace(remove_string, '')
elif remove_type == 'searchre':
_name = re.sub(r'(?i)' + remove_string, '', _name)
return _name
def isMediaFile(filename):
"""
Check if named file may contain media
:param filename: Filename to check
:return: True if this is a known media file, False if not
"""
# ignore samples
try:
if re.search(r'(^|[\W_])(?<!shomin.)(sample\d*)[\W_]', filename, re.I):
return False
# ignore RARBG release intro
if re.search(r'^RARBG\.\w+\.(mp4|avi|txt)$', filename, re.I):
return False
# ignore MAC OS's retarded "resource fork" files
if filename.startswith('._'):
return False
sepFile = filename.rpartition(".")
if re.search('extras?$', sepFile[0], re.I):
return False
if sepFile[2].lower() in media_extensions:
return True
else:
return False
except TypeError as error: # Not a string
logger.log('Invalid filename. Filename must be a string. %s' % error, logger.DEBUG) # pylint: disable=no-member
return False
def isRarFile(filename):
"""
Check if file is a RAR file, or part of a RAR set
:param filename: Filename to check
:return: True if this is RAR/Part file, False if not
"""
archive_regex = r'(?P<file>^(?P<base>(?:(?!\.part\d+\.rar$).)*)\.(?:(?:part0*1\.)?rar)$)'
if re.search(archive_regex, filename):
return True
return False
def isBeingWritten(filepath):
"""
Check if file has been written in last 60 seconds
:param filepath: Filename to check
:return: True if file has been written recently, False if none
"""
# Return True if file was modified within 60 seconds. it might still be being written to.
ctime = max(ek(os.path.getctime, filepath), ek(os.path.getmtime, filepath))
if ctime > time.time() - 60:
return True
return False
def remove_file_failed(failed_file):
"""
Remove file from filesystem
:param file: File to remove
"""
try:
ek(os.remove, failed_file)
except Exception | :
pass
def makeDir(path):
"""
Make a directory on the filesystem
:param path: directory to make
:retur | n: True if success, False if failure
"""
if not ek(os.path.isdir, path):
try:
ek(os.makedirs, path)
# do the library update for synoindex
synoindex_notifier.addFolder(path)
except OSError:
return False
return True
def searchIndexerForShowID(regShowName, indexer=None, indexer_id=None, ui=None):
"""
Contacts indexer to check for information on shows by showid
:param regShowName: Name of show
:param indexer: Which indexer to use
:param indexer_id: Which indexer ID to look for
:param ui: Custom UI for indexer use
:return:
"""
showNames = [re.sub('[. -]', ' ', regShowName)]
# Query Indexers for each search term and build the list of results
for i in sickbeard.indexerApi().indexers if not indexer else int(indexer or []):
# Query Indexers for each search term and build the li |
tensorflow/privacy | tensorflow_privacy/privacy/analysis/privacy_accountant.py | Python | apache-2.0 | 4,041 | 0.004702 | # Copyright 2021, The TensorFlow Authors.
#
# 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
#
# https://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.
"""PrivacyAccountant abstract base class."""
import abc
import enum
from tensorflow_privacy.privacy.analysis import dp_event
from tensorflow_priva | cy.privacy.analysis import dp_event_builder
class NeighboringRelation(enum.Enum):
ADD_OR_REMOVE_ONE = 1
REPLACE_ONE = 2
class UnsupportedEventError(Exception):
"""Exception to raise if _compose is called on unsupported event type."""
class PrivacyAccountant(metaclass=abc.ABCMeta):
"""Abstract base class for privacy accountan | ts."""
def __init__(self, neighboring_relation: NeighboringRelation):
self._neighboring_relation = neighboring_relation
self._ledger = dp_event_builder.DpEventBuilder()
@property
def neighboring_relation(self) -> NeighboringRelation:
"""The neighboring relation used by the accountant.
The neighboring relation is expected to remain constant after
initialization. Subclasses should not override this property or change the
value of the private attribute.
"""
return self._neighboring_relation
@abc.abstractmethod
def supports(self, event: dp_event.DpEvent) -> bool:
"""Checks whether the `DpEvent` can be processed by this accountant.
In general this will require recursively checking the structure of the
`DpEvent`. In particular `ComposedDpEvent` and `SelfComposedDpEvent` should
be recursively examined.
Args:
event: The `DpEvent` to check.
Returns:
True iff this accountant supports processing `event`.
"""
@abc.abstractmethod
def _compose(self, event: dp_event.DpEvent, count: int = 1):
"""Updates internal state to account for application of a `DpEvent`.
Calls to `get_epsilon` or `get_delta` after calling `_compose` will return
values that account for this `DpEvent`.
Args:
event: A `DpEvent` to process.
count: The number of times to compose the event.
"""
def compose(self, event: dp_event.DpEvent, count: int = 1):
"""Updates internal state to account for application of a `DpEvent`.
Calls to `get_epsilon` or `get_delta` after calling `compose` will return
values that account for this `DpEvent`.
Args:
event: A `DpEvent` to process.
count: The number of times to compose the event.
Raises:
UnsupportedEventError: `event` is not supported by this
`PrivacyAccountant`.
"""
if not isinstance(event, dp_event.DpEvent):
raise TypeError(f'`event` must be `DpEvent`. Found {type(event)}.')
if not self.supports(event):
raise UnsupportedEventError('Unsupported event: {event}.')
self._ledger.compose(event, count)
self._compose(event, count)
@property
def ledger(self) -> dp_event.DpEvent:
"""Returns the (composed) `DpEvent` processed so far by this accountant."""
return self._ledger.build()
@abc.abstractmethod
def get_epsilon(self, target_delta: float) -> float:
"""Gets the current epsilon.
Args:
target_delta: The target delta.
Returns:
The current epsilon, accounting for all composed `DpEvent`s.
"""
def get_delta(self, target_epsilon: float) -> float:
"""Gets the current delta.
An implementer of `PrivacyAccountant` may choose not to override this, in
which case `NotImplementedError` will be raised.
Args:
target_epsilon: The target epsilon.
Returns:
The current delta, accounting for all composed `DpEvent`s.
"""
raise NotImplementedError()
|
pratikmallya/heat | heat/tests/test_sahara_job_binary.py | Python | apache-2.0 | 5,419 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import six
from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import sahara
from heat.engine.resources.openstack.sahara import job_binary
from heat.engine import scheduler
from heat.tests import common
from heat.tests import utils
job_binary_template = """
heat_template_version: 2015-10-15
resources:
job-binary:
type: OS::Sahara::JobBinary
properties:
name: my-jb
url: swift://container/jar-example.jar
credentials: {'user': 'admin','password': 'swordfish'}
"""
class SaharaJobBinaryTest(common.HeatTestCase):
def setUp(self):
super(SaharaJobBinaryTest, self).setUp()
t = template_format.parse(job_binary_template)
self.stack = utils.parse_stack(t)
resource_defns = self.stack.t.resource_definitions(self.stack)
self.rsrc_defn = resource_defns['job-binary']
self.client = mock.Mock()
self.pat | chobject(job_binary.JobBinary, 'client',
return_value=self.client)
def _create_resource(self, name, snippet, stack):
jb = job_bina | ry.JobBinary(name, snippet, stack)
value = mock.MagicMock(id='12345')
self.client.job_binaries.create.return_value = value
scheduler.TaskRunner(jb.create)()
return jb
def test_create(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
args = self.client.job_binaries.create.call_args[1]
expected_args = {
'name': 'my-jb',
'description': '',
'url': 'swift://container/jar-example.jar',
'extra': {
'user': 'admin',
'password': 'swordfish'
}
}
self.assertEqual(expected_args, args)
self.assertEqual('12345', jb.resource_id)
expected_state = (jb.CREATE, jb.COMPLETE)
self.assertEqual(expected_state, jb.state)
def test_resource_mapping(self):
mapping = job_binary.resource_mapping()
self.assertEqual(1, len(mapping))
self.assertEqual(job_binary.JobBinary,
mapping['OS::Sahara::JobBinary'])
def test_update(self):
jb = self._create_resource('job-binary', self.rsrc_defn,
self.stack)
self.rsrc_defn['Properties']['url'] = (
'internal-db://94b8821d-1ce7-4131-8364-a6c6d85ad57b')
scheduler.TaskRunner(jb.update, self.rsrc_defn)()
data = {
'name': 'my-jb',
'description': '',
'url': 'internal-db://94b8821d-1ce7-4131-8364-a6c6d85ad57b',
'extra': {
'user': 'admin',
'password': 'swordfish'
}
}
self.client.job_binaries.update.assert_called_once_with(
'12345', data)
self.assertEqual((jb.UPDATE, jb.COMPLETE), jb.state)
def test_delete(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
scheduler.TaskRunner(jb.delete)()
self.assertEqual((jb.DELETE, jb.COMPLETE), jb.state)
self.client.job_binaries.delete.assert_called_once_with(
jb.resource_id)
def test_delete_not_found(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
self.client.job_binaries.delete.side_effect = (
sahara.sahara_base.APIException(error_code=404))
scheduler.TaskRunner(jb.delete)()
self.assertEqual((jb.DELETE, jb.COMPLETE), jb.state)
self.client.job_binaries.delete.assert_called_once_with(
jb.resource_id)
def test_show_attribute(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
value = mock.MagicMock()
value.to_dict.return_value = {'jb': 'info'}
self.client.job_binaries.get.return_value = value
self.assertEqual({'jb': 'info'}, jb.FnGetAtt('show'))
def test_validate_invalid_url(self):
self.rsrc_defn['Properties']['url'] = 'internal-db://38273f82'
jb = job_binary.JobBinary('job-binary', self.rsrc_defn, self.stack)
ex = self.assertRaises(exception.StackValidationFailed, jb.validate)
error_msg = ('resources.job-binary.properties: internal-db://38273f82 '
'is not a valid job location.')
self.assertEqual(error_msg, six.text_type(ex))
def test_validate_password_without_user(self):
self.rsrc_defn['Properties']['credentials'].pop('user')
jb = job_binary.JobBinary('job-binary', self.rsrc_defn, self.stack)
ex = self.assertRaises(exception.StackValidationFailed, jb.validate)
error_msg = ('Property error: resources.job-binary.properties.'
'credentials: Property user not assigned')
self.assertEqual(error_msg, six.text_type(ex))
|
rohitwaghchaure/erpnext_develop | erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py | Python | gpl-3.0 | 24,694 | 0.026444 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe, erpnext
import frappe.model
from frappe.utils import cint, flt, today, nowdate, add_days
import frappe.defaults
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory, \
test_records as pr_test_records
from erpnext.controllers.accounts_controller import get_payment_terms
from erpnext.exceptions import InvalidCurrency
from erpnext.stock.doctype.stock_entry.test_stock_entry import get_qty_after_transaction
from erpnext.accounts.doctype.account.test_account import get_inventory_account
test_dependencies = ["Item", "Cost Center", "Payment Term", "Payment Terms Template"]
test_ignore = ["Serial No"]
class TestPurchaseInvoice(unittest.TestCase):
def setUp(self):
unlink_payment_on_cancel_of_invoice()
frappe.db.set_value("Buying Settings", None, "allow_multiple_items", 1)
def tearDown(self):
unlink_payment_on_cancel_of_invoice(0)
def test_gl_entries_without_perpetual_inventory(self):
wrapper = frappe.copy_doc(test_records[0])
set_perpetual_inventory(0, wrapper.company)
self.assertTrue(not cint(erpnext.is_perpetual_inventory_enabled(wrapper.company)))
wrapper.insert()
wrapper.submit()
wrapper.load_from_db()
dl = wrapper
expected_gl_entries = {
"_Test Payable - _TC": [0, 1512.0],
"_Test Account Cost for Goods Sold - _TC": [1250, 0],
"_Test Account Shipping Charges - _TC": [100, 0],
"_Test Account Excise Duty - _TC": [140, 0],
"_Test Account Education Cess - _TC": [2.8, 0],
"_Test Account S&H Education Cess - _TC": [1.4, 0],
"_Test Account CST - _TC": [29.88, 0],
"_Test Account VAT - _TC": [156.25, 0],
"_Test Account Discount - _TC": [0, 168.03],
"Round Off - _TC": [0, 0.3]
}
gl_entries = frappe.db.sql("""select account, debit, credit from `tabGL Entry`
where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl.name, as_dict=1)
for d in gl_entries:
self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account))
def test_gl_entries_with_perpetual_inventory(self):
pi = frappe.copy_doc(test_records[1])
set_perpetual_inventory(1, pi.company)
self.assertTrue(cint(erpnext.is_perpetual_inventory_enabled(pi.company)), 1)
pi.insert()
pi.submit()
self.check_gle_for_pi(pi.name)
set_perpetual_inventory(0, pi.company)
def test_terms_added_after_save(self):
pi = frappe.copy_doc(test_records[1])
pi.insert()
self.assertTrue(pi.payment_schedule)
self.assertEqual(pi.payment_schedule[0].due_date, pi.due_date)
def test_payment_entry_unlink_against_purchase_invoice(self):
from erpnext.accounts.doctype.payment_entry.test_payment_entry import get_payment_entry
unlink_payment_on_cancel_of_invoice(0)
pi_doc = make_purchase_invoice()
pe = get_payment_entry("Purchase Invoice", pi_doc.name, bank_account="_Test Bank - _TC")
pe.reference_no = "1"
pe.reference_date = nowdate()
pe.paid_from_account_currency = pi_doc.currency
pe.paid_to_account_currency = pi_doc.currency
pe.source_exchange_rate = 1
pe.target_exchange_rate = 1
pe.paid_amount = pi_doc.grand_total
pe.save(ignore_permissions=True)
pe.submit()
pi_doc = frappe.get_doc('Purchase Invoice', pi_doc.name)
self.assertRaises(frappe.LinkExistsError, pi_doc.cancel)
def test_gl_entries_with_perpetual_inventory_against_pr(self):
pr = frappe.copy_doc(pr_test_records[0])
set_perpetual_inventory(1, pr.company)
self.assertTrue(cint(erpnext.is_perpetual_inventory_enabled(pr.company)), 1)
pr.submit()
pi = frappe.copy_doc(test_records[1])
for d in pi.get("items"):
d.purchase_receipt = pr.name
pi.insert()
pi.submit()
self.check_gle_for_pi(pi.name)
set_perpetual_inventory(0, pr.company)
def check_gle_for_pi(self, pi):
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` | where voucher_type='Purchase Inv | oice' and voucher_no=%s
order by account asc""", pi, as_dict=1)
self.assertTrue(gl_entries)
expected_values = dict((d[0], d) for d in [
["_Test Payable - _TC", 0, 720],
["Stock Received But Not Billed - _TC", 500.0, 0],
["_Test Account Shipping Charges - _TC", 100.0, 0],
["_Test Account VAT - _TC", 120.0, 0],
])
for i, gle in enumerate(gl_entries):
self.assertEquals(expected_values[gle.account][0], gle.account)
self.assertEquals(expected_values[gle.account][1], gle.debit)
self.assertEquals(expected_values[gle.account][2], gle.credit)
def test_purchase_invoice_change_naming_series(self):
pi = frappe.copy_doc(test_records[1])
pi.insert()
pi.naming_series = 'TEST-'
self.assertRaises(frappe.CannotChangeConstantError, pi.save)
pi = frappe.copy_doc(test_records[0])
pi.insert()
pi.naming_series = 'TEST-'
self.assertRaises(frappe.CannotChangeConstantError, pi.save)
def test_gl_entries_with_aia_for_non_stock_items(self):
pi = frappe.copy_doc(test_records[1])
set_perpetual_inventory(1, pi.company)
self.assertTrue(cint(erpnext.is_perpetual_inventory_enabled(pi.company)), 1)
pi.get("items")[0].item_code = "_Test Non Stock Item"
pi.get("items")[0].expense_account = "_Test Account Cost for Goods Sold - _TC"
pi.get("taxes").pop(0)
pi.get("taxes").pop(1)
pi.insert()
pi.submit()
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
order by account asc""", pi.name, as_dict=1)
self.assertTrue(gl_entries)
expected_values = sorted([
["_Test Payable - _TC", 0, 620],
["_Test Account Cost for Goods Sold - _TC", 500.0, 0],
["_Test Account VAT - _TC", 120.0, 0],
])
for i, gle in enumerate(gl_entries):
self.assertEquals(expected_values[i][0], gle.account)
self.assertEquals(expected_values[i][1], gle.debit)
self.assertEquals(expected_values[i][2], gle.credit)
set_perpetual_inventory(0, pi.company)
def test_purchase_invoice_calculation(self):
pi = frappe.copy_doc(test_records[0])
pi.insert()
pi.load_from_db()
expected_values = [
["_Test Item Home Desktop 100", 90, 59],
["_Test Item Home Desktop 200", 135, 177]
]
for i, item in enumerate(pi.get("items")):
self.assertEqual(item.item_code, expected_values[i][0])
self.assertEqual(item.item_tax_amount, expected_values[i][1])
self.assertEqual(item.valuation_rate, expected_values[i][2])
self.assertEqual(pi.base_net_total, 1250)
# tax amounts
expected_values = [
["_Test Account Shipping Charges - _TC", 100, 1350],
["_Test Account Customs Duty - _TC", 125, 1350],
["_Test Account Excise Duty - _TC", 140, 1490],
["_Test Account Education Cess - _TC", 2.8, 1492.8],
["_Test Account S&H Education Cess - _TC", 1.4, 1494.2],
["_Test Account CST - _TC", 29.88, 1524.08],
["_Test Account VAT - _TC", 156.25, 1680.33],
["_Test Account Discount - _TC", 168.03, 1512.30],
]
for i, tax in enumerate(pi.get("taxes")):
self.assertEqual(tax.account_head, expected_values[i][0])
self.assertEqual(tax.tax_amount, expected_values[i][1])
self.assertEqual(tax.total, expected_values[i][2])
def test_purchase_invoice_with_subcontracted_item(self):
wrapper = frappe.copy_doc(test_records[0])
wrapper.get("items")[0].item_code = "_Test FG Item"
wrapper.insert()
wrapper.load_from_db()
expected_values = [
["_Test FG Item", 90, 59],
["_Test Item Home Desktop 200", 135, 177]
]
for i, item in enumerate(wrapper.get("items")):
self.assertEqual(item.item_code, expected_values[i][0])
self.assertEqual(item.item_tax_amount, expected_values[i][1])
self.assertEqual(item.valuation_rate, expected_values[i][2])
self.assertEqual(wrapper.base_net_total, 1250)
# tax amounts
expected_values = [
["_Test Account Shipping Charges - _TC", 100, 1350],
["_Test Account Customs Duty - _TC", 125, 1350],
["_Test Account Excise Duty - _TC", 140, 1490],
["_Test Account Education Cess - _TC", 2.8, 1492.8],
["_Test Account S&H Education Cess - _TC", 1.4, 1494.2],
["_Test Account CST - _TC", 29.88, 1524.08],
|
DaanHoogland/cloudstack | systemvm/debian/opt/cloud/bin/cs/CsLoadBalancer.py | Python | apache-2.0 | 3,393 | 0.001768 | # 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.
import logging
import os.path
import re
from cs.CsDatabag import CsDataBag
from CsProcess import CsProcess
from CsFile import CsFile
import CsHelper
HAPROXY_CONF_T = "/etc/haproxy/haproxy.cfg.new"
HAPROXY_CONF_P = "/etc/haproxy/haproxy.cfg"
class CsLoadBalancer(CsDataBag):
""" Manage Load Balancer entries """
def process(self):
if "config" not in self.dbag.keys():
return
if 'configuration' not in self.dbag['config'][0].keys():
return
config = self.dbag['config'][0]['configuration']
file1 = CsFile(HAPROXY_CONF_T)
file1.empty()
for x in config:
[file1.append | (w, -1) for w in x.split('\n')]
file1.commit()
file2 = CsFile(HAPROXY_CONF_P)
| if not file2.compare(file1):
CsHelper.copy(HAPROXY_CONF_T, HAPROXY_CONF_P)
proc = CsProcess(['/run/haproxy.pid'])
if not proc.find():
logging.debug("CsLoadBalancer:: will restart HAproxy!")
CsHelper.service("haproxy", "restart")
else:
logging.debug("CsLoadBalancer:: will reload HAproxy!")
CsHelper.service("haproxy", "reload")
add_rules = self.dbag['config'][0]['add_rules']
remove_rules = self.dbag['config'][0]['remove_rules']
stat_rules = self.dbag['config'][0]['stat_rules']
self._configure_firewall(add_rules, remove_rules, stat_rules)
def _configure_firewall(self, add_rules, remove_rules, stat_rules):
firewall = self.config.get_fw()
logging.debug("CsLoadBalancer:: configuring firewall. Add rules ==> %s" % add_rules)
logging.debug("CsLoadBalancer:: configuring firewall. Remove rules ==> %s" % remove_rules)
logging.debug("CsLoadBalancer:: configuring firewall. Stat rules ==> %s" % stat_rules)
for rules in add_rules:
path = rules.split(':')
ip = path[0]
port = path[1]
firewall.append(["filter", "", "-A INPUT -p tcp -m tcp -d %s --dport %s -m state --state NEW -j ACCEPT" % (ip, port)])
for rules in remove_rules:
path = rules.split(':')
ip = path[0]
port = path[1]
firewall.append(["filter", "", "-D INPUT -p tcp -m tcp -d %s --dport %s -m state --state NEW -j ACCEPT" % (ip, port)])
for rules in stat_rules:
path = rules.split(':')
ip = path[0]
port = path[1]
firewall.append(["filter", "", "-A INPUT -p tcp -m tcp -d %s --dport %s -m state --state NEW -j ACCEPT" % (ip, port)])
|
ava-project/ava-website | website/core/settings/common/auth.py | Python | mit | 608 | 0.006579 | LOG | IN_URL = '/user/login'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRE | CT_URL = '/'
AUTHENTICATION_BACKENDS = [
'user.backend.AuthenticationBackend',
'user.backend.EmailBackend',
]
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',
},
]
|
jorgecarleitao/xapian-haystack | tests/xapian_tests/tests/test_interface.py | Python | gpl-2.0 | 8,542 | 0.002927 | from __future__ import unicode_literals
import datetime
from django.db.models import Q
from django.test import TestCase
from haystack import connections
from haystack.inputs import AutoQuery
from haystack.query import SearchQuerySet
from ..models import Document
from ..search_indexes import DocumentIndex
from ..tests.test_backend import pks
class InterfaceTestCase(TestCase):
"""
Tests the interface of Xapian-Haystack.
Tests related to usability and expected behavior
go here.
"""
def setUp(self):
super(InterfaceTestCase, self).setUp()
types_names = ['book', 'magazine', 'article']
texts = ['This is a huge text',
'This is a medium text',
'This is a small text']
dates = [datetime.date(year=2010, month=1, day=1),
datetime.date(year=2010, month=2, day=1),
datetime.date(year=2010, month= | 3, day=1)]
summaries = ['This is a huge corrup\xe7\xe3o summary',
'This is a medium summary',
'This is a small summary']
for i in range(1, 13):
doc = Document()
doc.type_name = types_names[i % 3]
doc.number = i * 2
doc.name = "%s %d" % (doc.type_name, doc.number)
doc.date = dates[i % 3]
doc.summary = summaries[i % 3]
doc.text = texts[i % 3]
doc.save()
| self.index = DocumentIndex()
self.ui = connections['default'].get_unified_index()
self.ui.build(indexes=[self.index])
self.backend = connections['default'].get_backend()
self.backend.update(self.index, Document.objects.all())
self.queryset = SearchQuerySet()
def tearDown(self):
Document.objects.all().delete()
#self.backend.clear()
super(InterfaceTestCase, self).tearDown()
def test_count(self):
self.assertEqual(self.queryset.count(), Document.objects.count())
def test_content_search(self):
result = self.queryset.filter(content='medium this')
self.assertEqual(sorted(pks(result)),
pks(Document.objects.all()))
# documents with "medium" AND "this" have higher score
self.assertEqual(pks(result)[:4], [1, 4, 7, 10])
def test_field_search(self):
self.assertEqual(pks(self.queryset.filter(name__contains='8')), [4])
self.assertEqual(pks(self.queryset.filter(type_name='book')),
pks(Document.objects.filter(type_name='book')))
self.assertEqual(pks(self.queryset.filter(text__contains='text huge')),
pks(Document.objects.filter(text__contains='text huge')))
def test_field_contains(self):
self.assertEqual(pks(self.queryset.filter(summary__contains='huge')),
pks(Document.objects.filter(summary__contains='huge')))
result = self.queryset.filter(summary__contains='huge summary')
self.assertEqual(sorted(pks(result)),
pks(Document.objects.all()))
# documents with "huge" AND "summary" have higher score
self.assertEqual(pks(result)[:4], [3, 6, 9, 12])
def test_field_exact(self):
self.assertEqual(pks(self.queryset.filter(name__exact='8')), [])
self.assertEqual(pks(self.queryset.filter(name__exact='magazine 2')), [1])
def test_content_exact(self):
self.assertEqual(pks(self.queryset.filter(content__exact='huge')), [])
def test_content_and(self):
self.assertEqual(pks(self.queryset.filter(content='huge').filter(summary='medium')), [])
self.assertEqual(len(self.queryset.filter(content='huge this')), 12)
self.assertEqual(len(self.queryset.filter(content='huge this').filter(summary__contains='huge')), 4)
def test_content_or(self):
self.assertEqual(len(self.queryset.filter(content='huge medium')), 8)
self.assertEqual(len(self.queryset.filter(content='huge medium small')), 12)
def test_field_and(self):
self.assertEqual(pks(self.queryset.filter(name='8').filter(name='4')), [])
def test_field_or(self):
self.assertEqual(pks(self.queryset.filter(name__contains='8 4')), [2, 4])
def test_field_in(self):
self.assertEqual(set(pks(self.queryset.filter(name__in=['magazine 2', 'article 4']))),
set(pks(Document.objects.filter(name__in=['magazine 2', 'article 4']))))
self.assertEqual(pks(self.queryset.filter(number__in=[4])),
pks(Document.objects.filter(number__in=[4])))
self.assertEqual(pks(self.queryset.filter(number__in=[4, 8])),
pks(Document.objects.filter(number__in=[4, 8])))
def test_private_fields(self):
self.assertEqual(pks(self.queryset.filter(django_id=4)),
pks(Document.objects.filter(id__in=[4])))
self.assertEqual(pks(self.queryset.filter(django_id__in=[2, 4])),
pks(Document.objects.filter(id__in=[2, 4])))
self.assertEqual(set(pks(self.queryset.models(Document))),
set(pks(Document.objects.all())))
def test_field_startswith(self):
self.assertEqual(len(self.queryset.filter(name__startswith='magaz')), 4)
self.assertEqual(set(pks(self.queryset.filter(summary__startswith='This is a huge'))),
set(pks(Document.objects.filter(summary__startswith='This is a huge'))))
def test_auto_query(self):
# todo: improve to query text only.
self.assertEqual(set(pks(self.queryset.auto_query("huge OR medium"))),
set(pks(Document.objects.filter(Q(text__contains="huge") |
Q(text__contains="medium")))))
self.assertEqual(set(pks(self.queryset.auto_query("huge AND medium"))),
set(pks(Document.objects.filter(Q(text__contains="huge") &
Q(text__contains="medium")))))
self.assertEqual(set(pks(self.queryset.auto_query("text:huge text:-this"))),
set(pks(Document.objects.filter(Q(text__contains="huge") &
~Q(text__contains="this")))))
self.assertEqual(len(self.queryset.filter(name=AutoQuery("8 OR 4"))), 2)
self.assertEqual(len(self.queryset.filter(name=AutoQuery("8 AND 4"))), 0)
def test_value_range(self):
self.assertEqual(set(pks(self.queryset.filter(number__lt=3))),
set(pks(Document.objects.filter(number__lt=3))))
self.assertEqual(set(pks(self.queryset.filter(django_id__gte=6))),
set(pks(Document.objects.filter(id__gte=6))))
def test_date_range(self):
date = datetime.date(year=2010, month=2, day=1)
self.assertEqual(set(pks(self.queryset.filter(date__gte=date))),
set(pks(Document.objects.filter(date__gte=date))))
date = datetime.date(year=2010, month=3, day=1)
self.assertEqual(set(pks(self.queryset.filter(date__lte=date))),
set(pks(Document.objects.filter(date__lte=date))))
def test_order_by(self):
# private order
self.assertEqual(pks(self.queryset.order_by("-django_id")),
pks(Document.objects.order_by("-id")))
# value order
self.assertEqual(pks(self.queryset.order_by("number")),
pks(Document.objects.order_by("number")))
# text order
self.assertEqual(pks(self.queryset.order_by("summary")),
pks(Document.objects.order_by("summary")))
# date order
self.assertEqual(pks(self.queryset.order_by("-date")),
pks(Document.objects.order_by("-date")))
def test_non_ascii_search(self):
"""
Regression test for #119.
"""
self.assertEqual(pks(self.queryset.filter(content='corrup\xe7\xe3o')),
pks(Document.objects.filter(summary__contains=' |
Synss/pyhard2 | pyhard2/ctrlr/deltaelektronika.py | Python | mit | 1,159 | 0 | """Graphical user interface to Delta-Elektronika SM-700 Series
controllers."""
import sys
import pyhard2.driver as drv
import pyhard2.driver.virtual as virtual
import pyhard2.driver.deltaelektronika as delta
import pyhard2.ctrlr as ctrlr
def createController():
"""Initialize controller."""
config = ctrlr.Config("deltaelektronika", "SM-700")
if not config.nodes:
config.nodes, config.names = ([1], ["SM700"] | )
if config.virtual:
driver = virtual.VirtualInstrument()
iface = ctrlr.virtualInstrumentController(config, driver)
else:
driver = delta.Sm700Series(drv.Serial(config.port))
iface = ctrlr.Controller(config, driver)
iface.addCommand(dri | ver.source.voltage, "Voltage", poll=True, log=True)
iface.addCommand(driver.source.current, "Current", poll=True, log=True)
iface.populate()
return iface
def main(argv):
"""Start controller."""
from PyQt4 import QtGui
app = QtGui.QApplication(argv)
app.lastWindowClosed.connect(app.quit)
iface = createController()
iface.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main(sys.argv)
|
mediawiki-utilities/python-mwdb | mwdb/schema.py | Python | mit | 7,277 | 0.000275 | """
A :class:`mwdb.Schema` represents a pool of connections to a database. New
connections will be spawned as needed. A :class:`mwdb.Schema`
can execite queries within the context of a :func:`mwdb.Schema.transaction` or
directly via :func:`mwdb.Schema.execute`.
.. autoclass:: mwdb.Schema
:members:
:member-order: bysource
"""
from contextlib import contextmanager
from sqlalchemy import MetaData, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from .errors import TableDoesNotExist
class Schema():
INDEX_TABLE_MAP = {
'archive_userindex': 'archive',
'revision_userindex': 'revision',
'logging_logindex': 'logging',
'logging_userindex': 'logging',
'recentchanges_userindex': 'recentchanges',
'filearchive_userindex': 'filearchive',
'ipblocks_ipindex': 'ipblocks',
'oldimage_userindex': 'oldimage'
}
"""
Maps the weird view names on labs back to the table names in the
production database.
"""
ONLY_TABLES = (
'abuse_filter', 'abuse_filter_action', 'abuse_filter_log',
'archive', 'archive_userindex',
'category', 'categorylinks',
'change_tag',
'ep_articles', 'ep_cas', 'ep_courses',
'ep_events', 'ep_instructors', 'ep_oas', 'ep_orgs',
'ep_revisions', 'ep_students', 'ep_users_per_course',
'externallinks',
'filearchive', 'filearchive_userindex',
'flaggedimages', 'flaggedpage_config', 'flaggedpage_pending',
'flaggedpages', 'flaggedrevs', 'flaggedrevs_promote',
'flaggedrevs_statistics', 'flaggedrevs_stats', 'flaggedrevs_stats2',
'flaggedrevs_tracking', 'flaggedtemplates', 'geo_tags',
'global_block_whitelist',
'image', 'imagelinks',
'interwiki',
'ipblocks', 'ipblocks_ipindex',
'iwlinks',
'l10n_cache', 'langlinks',
'localisation', 'localisation_file_hash',
'logging', 'logging_logindex', 'logging_userindex',
'mark_as_helpful',
'math',
'module_deps',
'msg_resource_links',
'oldimage', 'oldimage_userindex',
'ores_classification', 'ores_model',
'page', 'page_assessments', 'page_assessments_projects',
'page_props', 'page_restrictions',
'pagelinks',
'pagetriage_log', 'pagetriage_page', 'pagetriage_page_tags',
'pagetriage_tags',
'pif_edits',
'protected_titles',
'recentchanges', 'recentchanges_userindex',
'redirect',
'revision', 'revision_userindex',
'site_identifiers', 'site_stats', 'sites',
'tag_summary',
'templatelinks',
'transcode',
'updatelog', 'updates',
'user', 'user_former_groups', 'user_groups', 'user_properties',
'user_properties_anon',
'valid_tag',
'watchlist_count',
'wbc_entity_usage',
'wikilove_image_log', 'wikilove_log')
"""
A list of tables that will be loaded from the underlying schema.
"""
def __init__(self, engine_or_url, only_tables=None, *args, **kwargs):
"""
:Parameters:
engine_or_url : :class:`sqlalchemy.engine.Engine` or `str`
Either a ready-made :class:`sqlalchemy.engine.Engine` or a
URL for an engine.
*args
Passed on to :func:`sqlalchemy.create_engine`.
*kwargs
Passed on to :func:`sqlalchemy.create_engine`.
"""
if isinstance(engine_or_url, Engine):
self.engine = engine_or_url
else:
# This option disables memory buffering of result sets. By setting
# it this way, we allow the user to disagree.
execution_options = {'stream_results': True}
execution_options.update(kwargs.get('execution_options', {}))
kwargs['execution_options'] = execution_options
self.engine = create_engine(engine_or_url, *args, **kwargs)
self.meta = MetaData(bind=self.engine)
self.meta.reflect(views=True, only=only_tables or self.ONLY_TABLES)
self.public_replica = 'revision_userindex' in self.meta
"""
`bool`
`True` if the schema is part of a public replica with
`_userindex` and `_logindex` views.
"""
self.Session = sessionmaker(bind=self.engine)
def __getattr__(self, table_name):
if table_name in self.meta.tables:
return self.meta.tables[table_name]
else:
if table_name in self.TABLE_MAP:
return self.meta.tables[self.TABLE_MAP[table_name]]
else:
raise TableDoesNotExist(table_name)
@contextmanager
def transaction(self):
"""
Provides a transactional scope around a series of operations on a
:class:`sqlalchemy.Session` through the use of a
`https://docs.python.org/3/reference/compound_stmts.html#the-with-statement <with statement>`_
If any exception is raised within the context of a transation session,
the changes will be rolled-back. If the transactional session
completes without error, the changes will committed.
:Example:
>>> import mwdb
>>> enwiki = mwdb.Schema("mysql+pymysql://enwiki.labsdb/enwiki_p" +
... "?read_default_file=~/replica.my.cnf")
>>>
>>> with enwiki.transation() as session:
... print(session.query(enwiki.user)
... .filter_by(user_name="EpochFail")
... .first())
...
(6396742, b'EpochFail', b'', None, None, None, None, None, None,
None, None, None, b'20080208222802', None, 4270, None)
"""
session = self.Session()
| try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
def execute(self, clause, params=None, **kwargs):
"""
Executes a a query and returns the result.
:Example:
>>> | import mwdb
>>> enwiki = mwdb.Schema("mysql+pymysql://enwiki.labsdb/enwiki_p" +
... "?read_default_file=~/replica.my.cnf")
>>>
>>> result = enwiki.execute("SELECT * FROM user " +
... "WHERE user_id=:user_id",
... {'user_id': 6396742})
>>>
>>> print(result.fetchone())
(6396742, b'EpochFail', b'', None, None, None, None, None, None,
None, None, None, b'20080208222802', None, 4270, None)
:Parameters:
clause : `str`
The query to execute.
params : `dict` | `list` ( `dict` )
A set of key/value pairs to substitute into the clause. If a
list is provided, an executemany() will take place.
**kwargs
Passed on to :mod:`sqlalchemy`
"""
with self.transaction() as session:
return session.execute(clause, params=params, **kwargs)
|
unnikrishnankgs/va | venv/lib/python3.5/site-packages/nbconvert/exporters/html.py | Python | bsd-2-clause | 3,189 | 0.004078 | """HTML Exporter class"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from traitlets import default, Unicode
from traitlets.config import Config
from nbconvert.filters.highlight import Highlight2HTML
from nbconvert.filters.markdown_mistune import IPythonRenderer, MarkdownWithMath
from .templateexporter import TemplateExporter
class HTMLExporter(TemplateExporter):
"""
Exports a basic HTML document. This exporter assists with the export of
HTML. Inherit from it if you are writing your own HTML template and need
custom preprocessors/filters. If you don't need custom preprocessors/
filters, just change the 'template_file' config option.
"""
anchor_link_text = Unicode(u'¶',
help="The text used as the text for anchor links.").tag(config=True)
@default('file_extension')
def _file_extension_default(self):
return '.html'
@default('default_template_path')
def _default_template_path_default(self):
return os.path.join("..", "templates", "html")
@default('template_file')
def _template_file_default(self):
return 'full'
output_mimetype = 'text/html'
@property
def default_config(self):
c = Config({
'NbConvertBase': {
'display_data_priority' : ['application/vnd.jupyter.widget-state+json',
'application/vnd.jupyter.widget-view+json',
'application/javascript',
'text/html',
'text/markdown',
'image/svg+xml',
'text/latex',
'image | /png',
| 'image/jpeg',
'text/plain'
]
},
'CSSHTMLHeaderPreprocessor':{
'enabled':True
},
'HighlightMagicsPreprocessor': {
'enabled':True
}
})
c.merge(super(HTMLExporter,self).default_config)
return c
def markdown2html(self, source):
"""Markdown to HTML filter respecting the anchor_link_text setting"""
renderer = IPythonRenderer(escape=False,
anchor_link_text=self.anchor_link_text)
return MarkdownWithMath(renderer=renderer).render(source)
def default_filters(self):
for pair in super(HTMLExporter, self).default_filters():
yield pair
yield ('markdown2html', self.markdown2html)
def from_notebook_node(self, nb, resources=None, **kw):
langinfo = nb.metadata.get('language_info', {})
lexer = langinfo.get('pygments_lexer', langinfo.get('name', None))
self.register_filter('highlight_code',
Highlight2HTML(pygments_lexer=lexer, parent=self))
return super(HTMLExporter, self).from_notebook_node(nb, resources, **kw)
|
QuantumElephant/horton | horton/io/xyz.py | Python | gpl-3.0 | 2,419 | 0.00124 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON 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.
#
# HORTON 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/>
#
# --
'''XYZ file format'''
import numpy as np
from horton.units import angstrom
from horton.periodic import periodic
__all__ = ['load_xyz', 'dump_xyz']
def load_xyz(filename):
'''Load a molecular geometry from a .xyz file.
**Argument:**
filename
The file to load the geometry from
**Returns:** dictionary with ``title`, ``coordinates`` and ``numbers``.
'''
f = file(filename)
size = int(f.next())
title = f.next().strip()
coordinates = np.empty((size, 3), float)
numbers = np.empty(size, int)
for i in xrange(size):
words = f.next().split()
numbers[i] = periodic[words[0]].number
coordinates[i,0] = float(words[1])*angstrom
coordinates[i,1] = float(words[2])*angstrom
coordinates[i,2] = float(words[3])*angstrom
f.close()
return {
'title': title,
'coordinates': coordinates,
'numbers': numbers
}
def dump_xyz(filename, data):
'''Write an ``.xyz`` file.
**Arguments:**
filename
The name of the file to be written. This usually the extension
| ".xyz".
| data
An IOData instance. Must contain ``coordinates`` and ``numbers``.
May contain ``title``.
'''
with open(filename, 'w') as f:
print >> f, data.natom
print >> f, getattr(data, 'title', 'Created with HORTON')
for i in xrange(data.natom):
n = periodic[data.numbers[i]].symbol
x, y, z = data.coordinates[i]/angstrom
print >> f, '%2s %15.10f %15.10f %15.10f' % (n, x, y, z)
|
nagyistoce/netzob | src/netzob/Import/TreeViews/TreeProcessesGenerator.py | Python | gpl-3.0 | 5,577 | 0.010946 | # -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| | |
#| Netzob : Inferring communication protocols |
#+---------------------------------------------------------------------------+
#| Copyright (C) 2011 Georges Bossert and Frédéric Guihéry |
#| This program is free software: you can redistr | ibute 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/>. |
#+---------------------------------------------------------------------------+
#| @url : http://www.netzob.org |
#| @contact : contact@netzob.org |
#| @sponsors : Amossys, http://www.amossys.fr |
#| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ |
#+---------------------------------------------------------------------------+
#+----------------------------------------------
#| Global Imports
#+----------------------------------------------
from gettext import gettext as _
import logging
from gi.repository import Gtk
#+----------------------------------------------
#| Local Imports
#+----------------------------------------------
from netzob.Common.ExecutionContext import ExecutionContext
#+----------------------------------------------
#| TreeProcessGenerator:
#| update and generates the treestore
#| dedicated to the processes
#+----------------------------------------------
class TreeProcessesGenerator():
#+----------------------------------------------
#| Constructor:
#| @param processes : the processes
#+----------------------------------------------
def __init__(self, processes):
self.processes = processes
self.treestore = None
self.treeview = None
# create logger with the given configuration
self.log = logging.getLogger('netzob.Capturing.TreeViews.TreeProcessesGenerator.py')
#+----------------------------------------------
#| initialization:
#| builds and configures the treeview
#+----------------------------------------------
def initialization(self):
# Tree store contains:
# str : text (process Command)
# str : text (process PID)
# str : color foreground
# str : color background
self.treestore = Gtk.TreeStore(str, str, str, str)
self.treeview = Gtk.TreeView(self.treestore)
# messages list
self.scroll = Gtk.ScrolledWindow()
self.scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.scroll.show()
self.scroll.set_size_request(200, 300)
self.scroll.add(self.treeview)
lvcolumn = Gtk.TreeViewColumn(_("Processes"))
lvcolumn.set_sort_column_id(1)
cell = Gtk.CellRendererText()
lvcolumn.pack_start(cell, True)
cell.set_property('background-set', True)
cell.set_property('foreground-set', True)
lvcolumn.add_attribute(cell, "text", 0)
lvcolumn.add_attribute(cell, "foreground", 2)
lvcolumn.add_attribute(cell, "background", 3)
self.treeview.append_column(lvcolumn)
self.treeview.show()
#+----------------------------------------------
#| clear:
#| Clear the class
#+----------------------------------------------
def clear(self):
del self.processes[:]
#+----------------------------------------------
#| default:
#| Update the treestore in normal mode
#+----------------------------------------------
def default(self):
self.log.debug("Updating the treestore of the processes in default mode")
self.treestore.clear()
self.updateProcessesList()
for process in self.processes:
iter = self.treestore.append(None, [process.getName(), process.getPid(), '#000000', '#FFFFFF'])
def updateProcessesList(self):
self.log.debug("Updating the list of executing processes.")
self.processes = ExecutionContext.getCurrentProcesses()
#+----------------------------------------------
#| GETTERS:
#+----------------------------------------------
def getTreeview(self):
return self.treeview
def getScrollLib(self):
return self.scroll
def getProcesses(self):
return self.processes
#+----------------------------------------------
#| SETTERS:
#+----------------------------------------------
def setProcess(self, processes):
self.processes = processes
|
KoderDojo/hackerrank | python/challenges/python/collections-default-dict.py | Python | mit | 294 | 0 | from collections impor | t defaultdict
n, m = map(int, input().strip().split(' '))
a = defaultdict(list)
b = []
for i in range(n):
char = input().strip()
a[char].append(str(i+1))
for j in range(m):
b.append(input().s | trip())
for k in b:
print(' '.join(a[k]) if k in a else -1)
|
ergodicbreak/evennia | evennia/contrib/tutorial_world/objects.py | Python | bsd-3-clause | 40,255 | 0.003155 | """
TutorialWorld - basic objects - Griatch 2011
This module holds all "dead" object definitions for
the tutorial world. Object-commands and -cmdsets
are also defined here, together with the object.
Objects:
TutorialObject
Readable
Climbable
Obelisk
LightSource
CrumblingWall
Weapon
WeaponRack
"""
from future.utils import listvalues
import random
from evennia import DefaultObject, DefaultExit, Command, CmdSet
from evennia import utils
from evennia.utils import search
from evennia.utils.spawner import spawn
#------------------------------------------------------------
#
# TutorialObject
#
# The TutorialObject is the base class for all items
# in the tutorial. They have an attribute "tutorial_info"
# on them that the global tutorial command can use to extract
# interesting behind-the scenes information about the object.
#
# TutorialObjects may also be "reset". What the reset means
# is up to the object. It can be the resetting of the world
# itself, or the removal of an inventory item from a
# character's inventory when leaving the tutorial, for example.
#
#------------------------------------------------------------
class TutorialObject(DefaultObject):
"""
This is the baseclass for all objects in the tutorial.
"""
def at_object_creation(self):
"Called when the object is first created."
super(TutorialObject, self).at_object_creation()
self.db.tutorial_info = "No tutorial info is available for this object."
def reset(self):
"Resets the object, whatever that may mean."
self.location = self.home
#----------------- | -------------------------------------------
#
# Readable - an object that can be "read"
#
#-------- | ----------------------------------------------------
#
# Read command
#
class CmdRead(Command):
"""
Usage:
read [obj]
Read some text of a readable object.
"""
key = "read"
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
Implements the read command. This simply looks for an
Attribute "readable_text" on the object and displays that.
"""
if self.args:
obj = self.caller.search(self.args.strip())
else:
obj = self.obj
if not obj:
return
# we want an attribute read_text to be defined.
readtext = obj.db.readable_text
if readtext:
string = "You read {C%s{n:\n %s" % (obj.key, readtext)
else:
string = "There is nothing to read on %s." % obj.key
self.caller.msg(string)
class CmdSetReadable(CmdSet):
"""
A CmdSet for readables.
"""
def at_cmdset_creation(self):
"""
Called when the cmdset is created.
"""
self.add(CmdRead())
class Readable(TutorialObject):
"""
This simple object defines some attributes and
"""
def at_object_creation(self):
"""
Called when object is created. We make sure to set the needed
Attribute and add the readable cmdset.
"""
super(Readable, self).at_object_creation()
self.db.tutorial_info = "This is an object with a 'read' command defined in a command set on itself."
self.db.readable_text = "There is no text written on %s." % self.key
# define a command on the object.
self.cmdset.add_default(CmdSetReadable, permanent=True)
#------------------------------------------------------------
#
# Climbable object
#
# The climbable object works so that once climbed, it sets
# a flag on the climber to show that it was climbed. A simple
# command 'climb' handles the actual climbing. The memory
# of what was last climbed is used in a simple puzzle in the
# tutorial.
#
#------------------------------------------------------------
class CmdClimb(Command):
"""
Climb an object
Usage:
climb <object>
This allows you to climb.
"""
key = "climb"
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"Implements function"
if not self.args:
self.caller.msg("What do you want to climb?")
return
obj = self.caller.search(self.args.strip())
if not obj:
return
if obj != self.obj:
self.caller.msg("Try as you might, you cannot climb that.")
return
ostring = self.obj.db.climb_text
if not ostring:
ostring = "You climb %s. Having looked around, you climb down again." % self.obj.name
self.caller.msg(ostring)
# set a tag on the caller to remember that we climbed.
self.caller.tags.add("tutorial_climbed_tree", category="tutorial_world")
class CmdSetClimbable(CmdSet):
"Climbing cmdset"
def at_cmdset_creation(self):
"populate set"
self.add(CmdClimb())
class Climbable(TutorialObject):
"""
A climbable object. All that is special about it is that it has
the "climb" command available on it.
"""
def at_object_creation(self):
"Called at initial creation only"
self.cmdset.add_default(CmdSetClimbable, permanent=True)
#------------------------------------------------------------
#
# Obelisk - a unique item
#
# The Obelisk is an object with a modified return_appearance method
# that causes it to look slightly different every time one looks at it.
# Since what you actually see is a part of a game puzzle, the act of
# looking also stores a key attribute on the looking object (different
# depending on which text you saw) for later reference.
#
#------------------------------------------------------------
class Obelisk(TutorialObject):
"""
This object changes its description randomly, and which is shown
determines which order "clue id" is stored on the Character for
future puzzles.
Important Attribute:
puzzle_descs (list): list of descriptions. One of these is
picked randomly when this object is looked at and its index
in the list is used as a key for to solve the puzzle.
"""
def at_object_creation(self):
"Called when object is created."
super(Obelisk, self).at_object_creation()
self.db.tutorial_info = "This object changes its desc randomly, and makes sure to remember which one you saw."
self.db.puzzle_descs = ["You see a normal stone slab"]
# make sure this can never be picked up
self.locks.add("get:false()")
def return_appearance(self, caller):
"""
This hook is called by the look command to get the description
of the object. We overload it with our own version.
"""
# randomly get the index for one of the descriptions
descs = self.db.puzzle_descs
clueindex = random.randint(0, len(descs) - 1)
# set this description, with the random extra
string = "The surface of the obelisk seem to waver, shift and writhe under your gaze, with " \
"different scenes and structures appearing whenever you look at it. "
self.db.desc = string + descs[clueindex]
# remember that this was the clue we got. The Puzzle room will
# look for this later to determine if you should be teleported
# or not.
caller.db.puzzle_clue = clueindex
# call the parent function as normal (this will use
# the new desc Attribute we just set)
return super(Obelisk, self).return_appearance(caller)
#------------------------------------------------------------
#
# LightSource
#
# This object emits light. Once it has been turned on it
# cannot be turned off. When it burns out it will delete
# itself.
#
# This could be implemented using a single-repeat Script or by
# registering with the TickerHandler. We do it simpler by
# using the delay() utility function. This is very simple
# to use but does not survive a server @reload. Because of
# where the light matters (in the Dark Room where you can
# find new light sources easily), this is okay here.
#
#------------------------------------------------------------
class CmdLight(Command):
"""
Creates light w |
cmos3511/cmos_linux | python/op/op_site/proj_checker/migrations/0002_proj_lock.py | Python | gpl-3.0 | 375 | 0 | # Generated by D | jango 2.0 on 2017-12-14 08:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('proj_checker', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='proj',
name='lock',
field=models.BooleanField(default=Fal | se),
),
]
|
vencax/feincms-auth-app | socialauthapp/views.py | Python | bsd-2-clause | 1,277 | 0.005482 | '''
Created on Feb 14, 2012
@author: vencax
'''
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView
from django.views.generic.base import TemplateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .profile import ProfileEditForm
class LoginView(TemplateView):
template_name = 'registration/login.html'
class UserUpdateView(FormView):
template_name = 'fcmsregistration/update.html'
form_class = ProfileEditForm
def get_form_kwargs(self):
kwargs = super(UserUpdateView, self).get_form_kwargs()
kwargs['instance'] = self.request.user
return kwargs
def get_context_data(self, **kwargs):
ctx = super(UserUpdateView, self).get_context_data(**kw | args)
ctx['profileform'] = kwargs.pop('form')
return ctx
def form_valid(self, form):
form.save()
messages.info(self.request, _('user details updated'))
return HttpResponseRedirect('/')
def addInfoMessage(method, info):
def addInfo(request, **kwargs):
| retval = method(request, **kwargs)
if isinstance(retval, HttpResponseRedirect):
messages.info(request, info)
return retval
return addInfo |
brendanzhao/ProjectEuler | src/P035.py | Python | mit | 719 | 0.026426 | import math
def sieve(limit):
primes_set = set()
primes = [True] * limit
primes[0] = primes[1] = False
for (i, is_prime) in enumerate(primes):
if is_prime:
primes_set.add(i)
for n in xrange(i*i, limit, i):
primes[n] = False
return primes_set
def P035():
limit = 1000000
prim | e_set = sieve(limit)
count = 0
for prime in prime_set:
rotating_prime = prime
rotation_count = int(math.log10(prime))
for _ in xrange(rotation_count):
rotating_prime, digit = divmod(rotating_prime, 10)
rotating_pr | ime += digit * 10 ** (rotation_count)
if rotating_prime not in prime_set:
count += 1
break
return len(prime_set) - count
print P035() |
FHIBioGroup/fafoom-dev | examples/ga.py | Python | gpl-3.0 | 8,274 | 0.000121 | import numpy as np
import sys
from fafoom import MoleculeDescription, Structure, selection, print_output,\
remover_dir, set_default, file2dict
import fafoom.run_utilities as run_util
# Decide for restart or a simple run.
opt | = run_util.simple_or_restart()
p_file = sys.argv[1]
# Build a dictionary from two section of the parameter file.
params = file2dict(p_file, ['GA settings', 'Run settings'])
dict_default = {'energy_var': 0.001, 'selection': "roulette_wheel",
'fitness_sum_limit': 1.2, 'popsize': 10,
'prob_for_crossing': 1.0, 'max_iter': 30,
| 'iter_limit_conv': 20, 'energy_diff_conv': 0.001}
# Set defaults for parameters not defined in the parameter file.
params = set_default(params, dict_default)
energy_function = run_util.detect_energy_function(params)
cnt_max = 200
population, blacklist = [], []
min_energy = []
if opt == "simple":
mol = MoleculeDescription(p_file)
# Assign the permanent attributes to the molecule.
mol.get_parameters()
mol.create_template_sdf()
# Check for potential degree of freedom related parameters.
linked_params = run_util.find_linked_params(mol, params)
print_output("Number of atoms: "+str(mol.atoms))
print_output("Number of bonds: "+str(mol.bonds))
for dof in mol.dof_names:
print_output("Number of identified "+str(dof)+": " +
str(len(getattr(mol, dof))))
print_output("Identified "+str(dof)+": "+str(getattr(mol, dof)))
print_output("___Initialization___")
cnt = 0
# Generate sensible and unique 3d structures.
while len(population) < params['popsize'] and cnt < cnt_max:
print_output("New trial")
str3d = Structure(mol)
str3d.generate_structure()
if not str3d.is_geometry_valid():
print_output("The geometry of "+str(str3d)+" is invalid.")
cnt += 1
continue
if str3d not in blacklist:
name = "initial_%d" % (len(population))
# Perform the local optimization
run_util.optimize(str3d, energy_function, params, name)
run_util.check_for_kill()
str3d.send_to_blacklist(blacklist)
population.append(str3d)
print_output(str(str3d)+", energy: "+str(float(str3d)) +
", was added to the population")
run_util.relax_info(str3d)
cnt += 1
else:
print_output("Geomerty of "+str(str3d)+" is fine, but already "
"known.")
cnt += 1
if cnt == cnt_max:
print_output("The allowed number of trials for building the "
"population has been exceeded. The code terminates.")
sys.exit(0)
print_output("___Initialization completed___")
population.sort()
print_output("Initial population after sorting: ")
for i in range(len(population)):
print_output(str(population[i])+" "+str(float(population[i])))
min_energy.append(population[0].energy)
print_output("Blacklist: " + ', '.join([str(v) for v in blacklist]))
iteration = 0
if opt == "restart":
# Reconstruct the molecule, population, blacklist and the state of the run.
print_output(" \n ___Restart will be performed___")
with open("backup_mol.dat", 'r') as inf:
mol = eval(inf.readline())
inf.close()
with open("backup_population.dat", 'r') as inf:
for line in inf:
population.append(eval(line))
inf.close()
with open("backup_blacklist.dat", 'r') as inf:
for line in inf:
blacklist.append(eval(line))
inf.close()
with open("backup_min_energy.dat", 'r') as inf:
for line in inf:
min_energy.append(eval(line))
inf.close()
with open("backup_iteration.dat", 'r') as inf:
iteration_tmp = eval(inf.readline())
inf.close()
linked_params = run_util.find_linked_params(mol, params)
population.sort()
for i in range(len(population)):
print_output(str(population[i])+" "+str(float(population[i])))
print_output("Blacklist: " + ', '.join([str(v) for v in blacklist]))
iteration = iteration_tmp+1
print_output(" \n ___Reinitialization completed___")
remover_dir('generation_'+str(iteration)+'_child1')
remover_dir('generation_'+str(iteration)+'_child2')
def mutate_and_relax(candidate, name, iteration, cnt_max, **kwargs):
print_output("__%s__" % name)
found = False
cnt = 0
while found is False and cnt < cnt_max:
candidate_backup = Structure(candidate)
candidate.mutate(**kwargs)
print_output("%s after mutation: " % name + str(candidate))
run_util.str_info(candidate)
if not candidate.is_geometry_valid():
print_output(" The geometry of %s is invalid." % name)
cnt += 1
# Rebuild the structure
candidate = candidate_backup
continue
if candidate not in blacklist:
name = "generation_%d_%s" % (iteration, name)
run_util.optimize(candidate, energy_function, params, name)
run_util.check_for_kill()
candidate.send_to_blacklist(blacklist)
print_output(str(candidate)+":, energy: "+str(float(
candidate))+", is temporary added to the population")
run_util.relax_info(candidate)
found = True
population.append(candidate)
else:
print_output("Geomerty of "+str(candidate)+" is fine, but already "
"known.")
cnt += 1
candidate = candidate_backup
if cnt == cnt_max:
raise Exception("The allowed number of trials for generating"
" a unique child has been exceeded.")
while iteration < params['max_iter']:
print_output(" \n ___Start of iteration " + str(iteration) + "___")
(parent1, parent2, fitness) = selection(population, params['selection'],
params['energy_var'],
params['fitness_sum_limit'])
param = np.random.rand()
cnt = 0
while param < params['prob_for_crossing'] and cnt < cnt_max:
child1, child2 = Structure.crossover(parent1, parent2)
if child1.is_geometry_valid() and child2.is_geometry_valid():
print_output("Crossover outcome: "+str(child1)+(", ")+str(child2))
break
else:
print_output("The geometries created via crossover are invalid.")
cnt += 1
continue
else:
child1, child2 = Structure(parent1), Structure(parent2)
print_output("No crossover was performed. Children are copies of "
"parents: " + str(child1) + (": ") + str(child1) +
(", ") + str(child2) + (": ") + str(child2))
# Delete inherited attributes.
for child in child1, child2:
attr_list = ["initial_sdf_string", "energy"]
for attr in attr_list:
delattr(child, attr)
for dof in child.dof:
delattr(dof, "initial_values")
run_util.str_info(child1)
run_util.str_info(child2)
try:
mutate_and_relax(child1, "child1", iteration, cnt_max, **linked_params)
except Exception as exc:
print_output(exc)
sys.exit(0)
try:
mutate_and_relax(child2, "child2", iteration, cnt_max, **linked_params)
except Exception as exc:
print_output(exc)
sys.exit(0)
population.sort()
print_output("Sorted population: " + ', '.join([
str(v) for v in population]))
del population[-1]
del population[-1]
print_output("Sorted population after removing two structures with highest"
" energy: " + ', '.join([str(v) for v in population]))
min_energy.append(population[0].energy)
print_output("Lowest energy of the population: %.3f" % min_energy[-1])
print_output("Lowest energies in run: "+str(min_energy))
run_util.perform_backup(mol, population, blacklist, iteration, min_energy)
run_util.check_fo |
janastu/audio-tagger | servers/audioApp.py | Python | mit | 3,589 | 0.000279 | from flask import (Flask, session, render_template, request, redirect,
url_for, make_response, Blueprint, current_app)
import requests
import json
from datetime import datetime, timedelta
from flask.ext.cors import CORS, cross_origin
bp = Blueprint('audioTag', __name__)
def create_app(blueprint=bp):
app = Flask(__name__)
app.register_blueprint(blueprint)
app.config.from_pyfile('config.py')
CORS(app, allow_headers=('Content-Type', 'Authorization'))
return app
@bp.route('/', methods=['GET'])
@cross_origin()
def index():
# if auth_tok is in session already..
if 'auth_tok' in session:
auth_tok = session['auth_tok']
# check if it has expired
oauth_token_expires_in_endpoint = current_app.config.get(
'SWTSTORE_URL')+'/oauth/token-expires-in'
resp = requests.get(oauth_token_expires_in_endpoint)
expires_in = json.loads(resp.text)['expires_in']
# added for backwared compatibility. previous session stores did not
# have issued key
try:
check = datetime.utcnow() - auth_tok['issued']
if check > timedelta(seconds=expires_in):
# TODO: try to refresh the token before signing out the user
auth_tok = {'access_token': '', 'refresh_token': ''}
else:
"""access token did not expire"""
pass
# if issued key is not there, reset the session
except KeyError:
auth_tok = {'access_token': '', 'refresh_token': ''}
else:
auth_tok = {'access_token': '', 'refresh_token': ''}
# print 'existing tokens'
# print auth_tok
# payload = {'what': 'img-anno',
# 'access_token': auth_tok['access_token']}
# req = requests.get(current_app.config.get(
# 'SWTSTORE_URL', 'SWTSTORE_URL') + '/api/sweets/q', params=payload)
# sweets = req.json()
return render_template('index.html', access_token=auth_tok['access_token'],
refresh_token=auth_tok['refresh_token'],
config=current_app.config,
url=request.args.get('where'))
@bp.route('/authenticate', methods=['GET'])
def authenticateWithOAuth():
auth_tok = None
code = request.args.get('code')
# prepare the payload
payload = {
'scopes': 'email context',
'client_secret': current_app.config.get('APP_SECRET'),
'code': code,
'redirect_uri': current_app.config.get('REDIRECT_URI'),
'grant_type': 'authorization_code',
'client_id': current_app.config.get('APP_ID')
}
# token exchange endpoint
oauth_token_x_endpoint = current_app.config.get(
'SWTSTORE_URL', 'SWTSTORE_URL') + '/oauth/token'
resp = requests.post(oauth_token_x_endpoint, data=payload)
auth_tok = json.loads(resp.text)
if 'error' in auth_tok:
return make_response(auth_tok['error'], 200)
# set sessions etc
session['auth_tok'] = auth_tok
session['auth_tok']['issued'] = d | atetime.utcnow()
return redirect(url_for('audioTag.index'))
@bp.route('/admin', methods=['GET', 'POST'])
def admin():
if request.method == 'POST':
phone = request.form.get('usertel')
print repr(phone)
return render_template('admin.html')
@bp.route('/upl | oad', methods=['GET', 'POST'])
def upload():
return render_template('upload_url.html')
if __name__ == '__main__':
app = create_app()
app.run(debug=app.config.get('DEBUG'),
host=app.config.get('HOST'))
|
guiguiabloc/api-domogeek | Holiday.py | Python | gpl-2.0 | 6,861 | 0.055386 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Source : Les recettes Python de Tyrtamos
http://python.jpvweb.com/mesrecettespython/doku.php?id=date_de_paques
"""
class jourf | erie:
def datepaques(self,an):
"""Calcule la date de Pâques d'une année donnée an (=nombre entier)"""
a=an//100
b=an%100
c=(3*(a+25))//4
d=(3*(a+25))%4
e=(8*(a+11))//25
f=(5*a+b)%19
g=(19*f+c-e)%30
h=(f+11*g)//319
j=(60* | (5-d)+b)//4
k=(60*(5-d)+b)%4
m=(2*j-k-g+h)%7
n=(g-h+m+114)//31
p=(g-h+m+114)%31
jour=p+1
mois=n
return [jour, mois, an]
def dateliste(self,c, sep='/'):
"""Transforme une date chaîne 'j/m/a' en une date liste [j,m,a]"""
j, m, a = c.split(sep)
return [int(j), int(m), int(a)]
def datechaine(self,d, sep='/'):
"""Transforme une date liste=[j,m,a] en une date chaîne 'jj/mm/aaaa'"""
return ("%02d" + sep + "%02d" + sep + "%0004d") % (d[0], d[1], d[2])
def jourplus(self,d, n=1):
"""Donne la date du nième jour suivant d=[j, m, a] (n>=0)"""
j, m, a = d
fm = [0,31,28,31,30,31,30,31,31,30,31,30,31]
if (a%4==0 and a%100!=0) or a%400==0: # bissextile?
fm[2] = 29
for i in xrange(0,n):
j += 1
if j > fm[m]:
j = 1
m += 1
if m>12:
m = 1
a += 1
return [j,m,a]
def jourmoins(self,d, n=-1):
"""Donne la date du nième jour précédent d=[j, m, a] (n<=0)"""
j, m, a = d
fm = [0,31,28,31,30,31,30,31,31,30,31,30,31]
if (a%4==0 and a%100!=0) or a%400==0: # bissextile?
fm[2] = 29
for i in xrange(0,abs(n)):
j -= 1
if j < 1:
m -= 1
if m<1:
m = 12
a -= 1
j = fm[m]
return [j,m,a]
def numjoursem(self,d):
"""Donne le numéro du jour de la semaine d'une date d=[j,m,a]
lundi=1, mardi=2, ..., dimanche=7
Algorithme de Maurice Kraitchik (1882?1957)"""
j, m, a = d
if m<3:
m += 12
a -= 1
n = (j +2*m + (3*(m+1))//5 +a + a//4 - a//100 + a//400 +2) % 7
return [6, 7, 1, 2, 3, 4, 5][n]
def joursem(self,d):
"""Donne le jour de semaine en texte à partir de son numéro
lundi=1, mardi=2, ..., dimanche=7"""
return ["", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi",
"dimanche"][self.numjoursem(d)]
def joursferiesliste(self,an, sd=0):
"""Liste des jours fériés France en date-liste de l'année an (nb entier).
sd=0 (=defaut): tous les jours fériés.
sd=1: idem sans les sammedis-dimanches.
sd=2: tous + les 2 jours fériés supplémentaires d'Alsace-Moselle.
sd=3: idem sd=2 sans les samedis-dimanches"""
F = [] # =liste des dates des jours feries en date-liste d=[j,m,a]
L = [] # =liste des libelles du jour ferie
dp = self.datepaques(an)
# Jour de l'an
d = [1,1,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Jour de l'an")
# Vendredi saint (pour l'Alsace-Moselle)
d = self.jourmoins(dp, -2)
if (sd==0) or (sd==2):
#if sd>=2:
F.append(d)
L.append(u"Vendredi saint (Alsace-Moselle)")
# Dimanche de Paques
d = dp
if (sd==0) or (sd==2):
F.append(d)
L.append(u"Dimanche de Paques")
# Lundi de Paques
d = self.jourplus(dp, +1)
F.append(d)
L.append(u"Lundi de Paques")
# Fête du travail
d = [1,5,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Fete du travail")
# Victoire des allies 1945
d = [8,5,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Victoire des allies 1945")
# Jeudi de l'Ascension
d = self.jourplus(dp, +39)
F.append(d)
L.append(u"Jeudi de l'Ascension")
# Dimanche de Pentecote
d = self.jourplus(dp, +49)
if (sd==0) or (sd==2):
F.append(d)
L.append(u"Dimanche de Pentecote")
# Lundi de Pentecote
d = self.jourplus(d, +1)
F.append(d)
L.append(u"Lundi de Pentecote")
# Fete Nationale
d = [14,7,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Fete Nationale")
# Assomption
d = [15,8,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Assomption")
# Toussaint
d = [1,11,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Toussaint")
# Armistice 1918
d = [11,11,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Armistice 1918")
# Jour de Noel
d = [25,12,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Jour de Noel")
# Saint Etienne Alsace
d = [26,12,an]
nj = self.numjoursem(d)
if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6):
F.append(d)
L.append(u"Saint-Etienne (Alsace)")
return F, L
def joursferies(self,an, sd=0, sep='/'):
"""Liste des jours fériés France en date-chaine de l'année an (nb entier).
sd=0 (=defaut): tous les jours fériés.
sd=1: idem sans les sammedis-dimanches.
sd=2: tous + les 2 jours fériés supplémentaires d'Alsace-Moselle.
sd=3: idem sd=2 sans les samedis-dimanches"""
C = []
J = []
F, L = self.joursferiesliste(an, sd)
for i in xrange(0,len(F)):
C.append(self.datechaine(F[i])) # conversion des dates-liste en dates-chaine
J.append(self.joursem(F[i])) # ajout du jour de semaine
return C, J, L
def estferie(self,d,sd=0):
"""estferie(d,sd=0): => dit si une date d=[j,m,a] donnée est fériée France
si la date est fériée, renvoie son libellé
sinon, renvoie une chaine vide"""
j,m,a = d
F, L = self.joursferiesliste(a, sd)
for i in xrange(0, len(F)):
if j==F[i][0] and m==F[i][1] and a==F[i][2]:
return L[i]
return "False"
|
Fokko/incubator-airflow | airflow/hooks/mysql_hook.py | Python | apache-2.0 | 8,067 | 0.000992 | # -*- coding: utf-8 -*-
#
# 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.
import json
import MySQLdb
import MySQLdb.cursors
from airflow.hooks.dbapi_hook import DbApiHook
class MySqlHook(DbApiHook):
"""
Interact with MySQL.
You can specify charset in the extra field of your connection
as ``{"charset": "utf8"}``. Also you can choose c | ursor as
``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details.
Note: For AWS IAM authentication, use iam in the extra connection parameters
and set it to true. Leave the password field empty. This will use the
"aws_default" connection to get the temporary token unless you override
in extras.
extras example: ``{"iam":true, "aws_conn_id":"my_aws_conn"}``
"""
conn_name_attr = 'mysql_conn_id'
default_conn_name = 'mysql_default'
supports_autoco | mmit = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.schema = kwargs.pop("schema", None)
self.connection = kwargs.pop("connection", None)
def set_autocommit(self, conn, autocommit):
"""
MySql connection sets autocommit in a different way.
"""
conn.autocommit(autocommit)
def get_autocommit(self, conn):
"""
MySql connection gets autocommit in a different way.
:param conn: connection to get autocommit setting from.
:type conn: connection object.
:return: connection autocommit setting
:rtype: bool
"""
return conn.get_autocommit()
def get_conn(self):
"""
Returns a mysql connection object
"""
conn = self.connection or self.get_connection(self.mysql_conn_id)
conn_config = {
"user": conn.login,
"passwd": conn.password or '',
"host": conn.host or 'localhost',
"db": self.schema or conn.schema or ''
}
# check for authentication via AWS IAM
if conn.extra_dejson.get('iam', False):
conn_config['passwd'], conn.port = self.get_iam_token(conn)
conn_config["read_default_group"] = 'enable-cleartext-plugin'
if not conn.port:
conn_config["port"] = 3306
else:
conn_config["port"] = int(conn.port)
if conn.extra_dejson.get('charset', False):
conn_config["charset"] = conn.extra_dejson["charset"]
if (conn_config["charset"]).lower() == 'utf8' or\
(conn_config["charset"]).lower() == 'utf-8':
conn_config["use_unicode"] = True
if conn.extra_dejson.get('cursor', False):
if (conn.extra_dejson["cursor"]).lower() == 'sscursor':
conn_config["cursorclass"] = MySQLdb.cursors.SSCursor
elif (conn.extra_dejson["cursor"]).lower() == 'dictcursor':
conn_config["cursorclass"] = MySQLdb.cursors.DictCursor
elif (conn.extra_dejson["cursor"]).lower() == 'ssdictcursor':
conn_config["cursorclass"] = MySQLdb.cursors.SSDictCursor
local_infile = conn.extra_dejson.get('local_infile', False)
if conn.extra_dejson.get('ssl', False):
# SSL parameter for MySQL has to be a dictionary and in case
# of extra/dejson we can get string if extra is passed via
# URL parameters
dejson_ssl = conn.extra_dejson['ssl']
if isinstance(dejson_ssl, str):
dejson_ssl = json.loads(dejson_ssl)
conn_config['ssl'] = dejson_ssl
if conn.extra_dejson.get('unix_socket'):
conn_config['unix_socket'] = conn.extra_dejson['unix_socket']
if local_infile:
conn_config["local_infile"] = 1
conn = MySQLdb.connect(**conn_config)
return conn
def bulk_load(self, table, tmp_file):
"""
Loads a tab-delimited file into a database table
"""
conn = self.get_conn()
cur = conn.cursor()
cur.execute("""
LOAD DATA LOCAL INFILE '{tmp_file}'
INTO TABLE {table}
""".format(tmp_file=tmp_file, table=table))
conn.commit()
def bulk_dump(self, table, tmp_file):
"""
Dumps a database table into a tab-delimited file
"""
conn = self.get_conn()
cur = conn.cursor()
cur.execute("""
SELECT * INTO OUTFILE '{tmp_file}'
FROM {table}
""".format(tmp_file=tmp_file, table=table))
conn.commit()
@staticmethod
def _serialize_cell(cell, conn):
"""
MySQLdb converts an argument to a literal
when passing those separately to execute. Hence, this method does nothing.
:param cell: The cell to insert into the table
:type cell: object
:param conn: The database connection
:type conn: connection object
:return: The same cell
:rtype: object
"""
return cell
def get_iam_token(self, conn):
"""
Uses AWSHook to retrieve a temporary password to connect to MySQL
Port is required. If none is provided, default 3306 is used
"""
from airflow.contrib.hooks.aws_hook import AwsHook
aws_conn_id = conn.extra_dejson.get('aws_conn_id', 'aws_default')
aws_hook = AwsHook(aws_conn_id)
if conn.port is None:
port = 3306
else:
port = conn.port
client = aws_hook.get_client_type('rds')
token = client.generate_db_auth_token(conn.host, port, conn.login)
return token, port
def bulk_load_custom(self, table, tmp_file, duplicate_key_handling='IGNORE', extra_options=''):
"""
A more configurable way to load local data from a file into the database.
.. warning:: According to the mysql docs using this function is a
`security risk <https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html>`_.
If you want to use it anyway you can do so by setting a client-side + server-side option.
This depends on the mysql client library used.
:param table: The table were the file will be loaded into.
:type table: str
:param tmp_file: The file (name) that contains the data.
:type tmp_file: str
:param duplicate_key_handling: Specify what should happen to duplicate data.
You can choose either `IGNORE` or `REPLACE`.
.. seealso::
https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-duplicate-key-handling
:type duplicate_key_handling: str
:param extra_options: More sql options to specify exactly how to load the data.
.. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html
:type extra_options: str
"""
conn = self.get_conn()
cursor = conn.cursor()
cursor.execute("""
LOAD DATA LOCAL INFILE '{tmp_file}'
{duplicate_key_handling}
INTO TABLE {table}
{extra_options}
""".format(
tmp_file=tmp_file,
table=table,
duplicate_key_handling=duplicate_key_handling,
extra_options=extra_options
))
cursor.close()
conn.commit()
|
yhat/db.py | db/column.py | Python | bsd-2-clause | 7,909 | 0.001897 | from prettytable import PrettyTable
import pandas as pd
class Column(object):
"""
A Columns is an in-memory reference to a column in a particular table. You
can use it to do some basic DB exploration and you can also use it to
execute simple queries.
"""
def __init__(self, con, query_templates, schema, table, name, dtype, keys_per_column):
self._con = con
self._query_templates = query_templates
self.schema = schema
self.table = table
self.name = name
self.type = dtype
self.keys_per_column = keys_per_column
self.foreign_keys = []
self.ref_keys = []
def __repr__(self):
tbl = PrettyTable(["Table", "Name", "Type", "Foreign Keys",
"Reference Keys"])
tbl.add_row([self.table, self.name, self.type, self._str_foreign_keys(),
self._str_ref_keys()])
return str(tbl)
def __str__(self):
return "Column({0})<{1}>".format(self.name, self.__hash__())
def _repr_html_(self):
tbl = PrettyTable(["Table", "Name", "Type"])
tbl.add_row([self.table, self.name, self.type])
return tbl.get_html_string()
def _str_foreign_keys(self):
keys = []
for col in self.foreign_keys:
keys.appe | nd("%s.%s" % (col.table, col.name))
if self.keys_per_column is not None and len(keys) > self.keys_per_column:
keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)]
return ", ".join(keys)
def _str_ref_keys(self):
keys = []
for col in self.ref_keys:
keys.append("%s.%s" % (col.table, col.name))
if self.ke | ys_per_column is not None and len(keys) > self.keys_per_column:
keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)]
return ", ".join(keys)
def head(self, n=6):
"""
Returns first n values of your column as a DataFrame. This is executing:
SELECT
<name_of_the_column>
FROM
<name_of_the_table>
LIMIT <n>
Parameters
----------
n: int
number of rows to return
Examples
--------
>>> from db import DemoDB
>>> db = DemoDB()
>>> db.tables.Customer.City.head()
0 Sao Jose dos Campos
1 Stuttgart
2 Montreal
3 Oslo
4 Prague
5 Prague
Name: City, dtype: object
>>> db.tables.Customer.City.head(2)
0 Sao Jose dos Campos
1 Stuttgart
Name: City, dtype: object
"""
q = self._query_templates['column']['head'].format(column=self.name, schema=self.schema,
table=self.table, n=n)
return pd.read_sql(q, self._con)[self.name]
def all(self):
"""
Returns entire column as a DataFrame. This is executing:
SELECT
DISTINCT
<name_of_the_column>
FROM
<name_of_the_table>
Examples
--------
>>> from db import DemoDB
>>> db = DemoDB()
>>> db.tables.Customer.Email.all().head()
0 luisg@embraer.com.br
1 leonekohler@surfeu.de
2 ftremblay@gmail.com
3 bjorn.hansen@yahoo.no
4 frantisekw@jetbrains.com
Name: Email, dtype: object
>>> df = db.tables.Customer.Email.all()
>>> len(df)
59
"""
q = self._query_templates['column']['all'].format(column=self.name, schema=self.schema,
table=self.table)
return pd.read_sql(q, self._con)[self.name]
def unique(self):
"""
Returns all unique values as a DataFrame. This is executing:
SELECT
DISTINCT
<name_of_the_column>
FROM
<name_of_the_table>
Examples
--------
>>> from db import DemoDB
>>> db = DemoDB()
>>> db.tables.Customer.FirstName.unique().head(10)
0 Luis
1 Leonie
2 Francois
3 Bjorn
4 Franti\u0161ek
5 Helena
6 Astrid
7 Daan
8 Kara
9 Eduardo
Name: FirstName, dtype: object
>>> len(db.tables.Customer.LastName.unique())
59
"""
q = self._query_templates['column']['unique'].format(column=self.name, schema=self.schema,
table=self.table)
return pd.read_sql(q, self._con)[self.name]
def sample(self, n=10):
"""
Returns random sample of n rows as a DataFrame. This is executing:
SELECT
<name_of_the_column>
FROM
<name_of_the_table>
ORDER BY
RANDOM()
LIMIT <n>
Parameters
----------
n: int
number of rows to sample
Examples (removed from doctest as we can't predict random names...)
--------
from db import DemoDB
db = DemoDB()
db.tables.Artist.Name.sample(10)
0 Pedro Luis & A Parede
1 Santana Feat. Eric Clapton
2 Os Mutantes
3 Banda Black Rio
4 Adrian Leaper & Doreen de Feis
5 Chicago Symphony Orchestra & Fritz Reiner
6 Smashing Pumpkins
7 Spyro Gyra
8 Aaron Copland & London Symphony Orchestra
9 Sir Georg Solti & Wiener Philharmoniker
Name: Name, dtype: object
>>> from db import DemoDB
>>> db = DemoDB()
>>> df = db.tables.Artist.Name.sample(10)
>>> len(df)
10
"""
q = self._query_templates['column']['sample'].format(column=self.name, schema=self.schema,
table=self.table, n=n)
return pd.read_sql(q, self._con)[self.name]
def to_dict(self):
"""
Serialize representation of the column for local caching.
"""
return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type}
class ColumnSet(object):
"""
Set of Columns. Used for displaying search results in terminal/ipython
notebook.
"""
def __init__(self, columns):
self.columns = columns
self.pretty_tbl_cols = ["Table", "Column Name", "Type"]
self.use_schema = False
for col in columns:
if col.schema and not self.use_schema:
self.use_schema = True
self.pretty_tbl_cols.insert(0, "Schema")
def __getitem__(self, i):
return self.columns[i]
def _tablify(self):
tbl = PrettyTable(self.pretty_tbl_cols)
for col in self.pretty_tbl_cols:
tbl.align[col] = "l"
for col in self.columns:
row_data = [col.table, col.name, col.type]
if self.use_schema:
row_data.insert(0, col.schema)
tbl.add_row(row_data)
return tbl
def __repr__(self):
tbl = str(self._tablify())
return tbl
def _repr_html_(self):
return self._tablify().get_html_string()
def to_dict(self):
"""Serialize representation of the tableset for local caching."""
return {'columns': [col.to_dict() for col in self.columns]}
|
pmghalvorsen/gramps_branch | gramps/plugins/tool/dateparserdisplaytest.py | Python | gpl-2.0 | 11,654 | 0.011327 | # -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Martin Hawlisch, Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Validate localized date parser and displayer.
Tools/Debug/Check Localized Date Parser and Displayer
"""
#-------------------------------------------------------------------------
#
# standard python modules
#
#-------------------------------------------------------------------------
import traceback
import sys
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from gramps.gen.lib import Date, Event, EventRef, EventType, Name, Person, Surname, Tag
from gramps.gen.db import DbTxn
from gramps.gui.plug import tool
from gramps.gui.utils import ProgressMeter
from gramps.gui.dialog import QuestionDialog
from gramps.gen.datehandler import parser as _dp
from gramps.gen.datehandler import displayer as _dd
#-------------------------------------------------------------------------
#
#
#
#-------------------------------------------------------------------------
class DateParserDisplayTest(tool.Tool):
def __init__(self, dbstate, user, options_class, name, callback=None):
uistate = user.uistate
tool.Tool.__init__(self, dbstate, options_class, name)
if uistate:
# Running with gui -> Show message
QuestionDialog(_("Start date test?"),_("This test will create many persons and events in the current database. Do you really want to run this test?"),_("Run test"),self.run_tool)
else:
self.run_tool()
def run_tool(self):
self.progress = ProgressMeter(_('Running Date Test'),'')
self.progress.set_pass(_('Generating dates'),
4)
dates = []
# first some valid dates
calendar = Date.CAL_GREGORIAN
for quality in (Date.QUAL_NONE, Date.QUAL_ESTIMATED,
Date.QUAL_CALCULATED):
for modifier in (Date.MOD_NONE, Date.MOD_BEFORE,
Date.MOD_AFTER, Date.MOD_ABOUT):
for slash1 in (False,True):
for month in range(0,13):
for day in (0,5,27):
if not month and day:
continue
d = Date()
d.set(quality,modifier,calendar,(day,month,1789,slash1),"Text comment")
dates.append( d)
for modifier in (Date.MOD_RANGE, Date.MOD_SPAN):
for slash1 in (False,True):
for slash2 in (False,True):
for month in range(0,13):
for day in (0,5,27):
if not month and day:
continue
d = Date()
d.set(quality,modifier,calendar,(day,month,1789,slash1,day,month,1876,slash2),"Text comment")
dates.append( d)
if not month:
continue
d = Date()
d.set(quality,modifier,calendar,(day,month,1789,slash1,day,13-month,1876,slash2),"Text comment")
dates.append( d)
if not day:
continue
d = Date()
d.set(quality,modifier,calendar,(day,month,1789,slash1,32-day,month,1876,slash2),"Text comment")
dates.append( d)
d = Date()
d.set(quality,modifier,calendar,(day,month,1789,slash1,32-day,13-month,1876,slash2),"Text comment")
dates.append( d)
modifier = Date.MOD_TEXTONLY
d = Date()
d.set(quality,modifier,calendar,Date.EMPTY,
"This is a textual date")
dates.append( d)
self.progress.step()
# test invalid dates
#dateval = (4,7,1789,False,5,8,1876,False)
#for l in range(1,len(dateval)):
# d = Date()
# try:
# d.set(Date.QUAL_NONE,Date.MOD_NONE,
# Date.CAL_GREGORIAN,dateval[:l],"Text comment")
# dates.append( d)
# except DateError, e:
# d.set_as_text("Date identified value correctly as invalid.\n%s" % e)
# dates.append( d)
# except:
# d = Date()
# d.set_as_text("Date.set Exception %s" % ("".join(traceback.format_exception(*sys.exc_info())),))
# dates.append( d)
#for l in range(1,len(dateval)):
# d = Date()
# try:
# d.set(Date.QUAL_NONE,Date.MOD_SPAN,Date.CAL_GREGORIAN,dateval[:l],"Text comment")
# dates.append( d)
# except DateError, e:
# d.set_as_text("Date identified value correctly as invalid.\n%s" % e)
# dates.append( d)
# except:
# d = Date()
# d.set_as_text("Date.set Exception %s" % ("".join(traceback.format_exception(*sys.exc_info())),))
# dates.append( d)
#self.progress.step()
# | d = Date()
#d.set(Date.QUAL_NONE,Date.MOD_NONE,
# Date.CAL_GREGORIAN,(44,7,1789,False),"Text comment")
#dates.append( d)
#d = Date()
#d.set(Date.QUAL_NONE,Date.MOD_NONE,
# Date.CAL_GREGORIAN,(4,77,1789,False),"Text comment")
#d | ates.append( d)
#d = Date()
#d.set(Date.QUAL_NONE,Date.MOD_SPAN,
# Date.CAL_GREGORIAN,
# (4,7,1789,False,55,8,1876,False),"Text comment")
#dates.append( d)
#d = Date()
#d.set(Date.QUAL_NONE,Date.MOD_SPAN,
# Date.CAL_GREGORIAN,
# (4,7,1789,False,5,88,1876,False),"Text comment")
#dates.append( d)
with DbTxn(_("Date Test Plugin"), self.db, batch=True) as self.trans:
self.db.disable_signals()
self.progress.set_pass(_('Generating dates'),
len(dates))
# create pass and fail tags
pass_handle = self.create_tag(_('Pass'), '#0000FFFF0000')
fail_handle = self.create_tag(_('Fail'), '#FFFF00000000')
# now add them as birth to new persons
i = 1
for dateval in dates:
person = Person()
surname = Surname()
surname.set_surname("DateTest")
name = Name()
name.add_surname(surname)
name.set_first_name("Test %d" % i)
person.set_primary_name(name)
self.db.add_person(person, self.trans)
bevent = Event()
bevent.set_type(EventType.BIRTH)
bevent.set_date_object(dateval)
bevent.set_description("Date Test %d (source)" % i)
bevent_h = self.db.add_event(bevent, self.trans)
|
Winterflower/khmer | scripts/fastq-to-fasta.py | Python | bsd-3-clause | 2,268 | 0.000441 | #! /usr/bin/env python
#
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) Michigan State University, 2009-2015. It is licensed under
# the three-clause BSD license; see LICENSE.
# Contact: khmer-project@idyll.org
#
# pylint: disable=invalid-name,missing-docstring
"""
Convert FASTQ files to FASTA format.
% python scripts/fastq-to-fasta.py [ -n -o ] <fastq_name>
Use '-h' for parameter help.
"""
from __future__ import print_function
import sys
import argparse
import screed
def get_parser():
parser = argparse.ArgumentParser(
description='Converts FASTQ format (.fq) files to FASTA format (.f | a).',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('input_sequence', help='The name of the input'
' FASTQ sequence file.')
parser.add_argument('-o', '--output', metavar="filename",
help='The name of the output'
' FASTA sequence file.',
type=argparse.FileType('w'),
default=sys.stdout)
parser.add_argument('-n', '--n_keep', default=False | , action='store_true',
help='Option to drop reads containing \'N\'s in ' +
'input_sequence file.')
return parser
def main():
args = get_parser().parse_args()
print(('fastq from ', args.input_sequence), file=sys.stderr)
n_count = 0
for n, record in enumerate(screed.open(args.input_sequence,
parse_description=False)):
if n % 10000 == 0:
print('...', n, file=sys.stderr)
sequence = record['sequence']
name = record['name']
if 'N' in sequence:
if not args.n_keep:
n_count += 1
continue
args.output.write('>' + name + '\n')
args.output.write(sequence + '\n')
print('\n' + 'lines from ' + args.input_sequence, file=sys.stderr)
if not args.n_keep:
print(str(n_count) + ' lines dropped.', file=sys.stderr)
else:
print('No lines dropped from file.', file=sys.stderr)
print('Wrote output to', args.output, file=sys.stderr)
if __name__ == '__main__':
main()
|
Anlim/decode-Django | Django-1.5.1/django/dispatch/saferef.py | Python | gpl-2.0 | 10,971 | 0.004523 | """
"Safe weakrefs", originally from pyDispatcher.
Provides a way to safely weakref any function, including bound methods (which
aren't handled by the core weakref module).
"""
import traceback
import weakref 弱引用
def safeRef(target, onDelete = None):
"""Return a *safe* weak reference to a callable target
target -- the object to be weakly referenced, if it's a
bound method reference, will create a BoundMethodWeakref,
otherwise creates a simple weakref.
onDelete -- if provided, will have a hard reference stored
to the callable to be called after the safe reference
goes out of scope with the reference object, (either a
weakref or a BoundMethodWeakref) as argument.
"""
if hasattr(target, '__self__'):
if target.__self__ is not None:
# Turn a bound method into a BoundMethodWeakref instance.
# Keep track of these instances for lookup by disconnect().
assert hasattr(target, '__func__'), """safeRef target %r has __self__, but no __func__, don't know how to create reference"""%( target,)
reference = get_bound_method_weakref(
target=target,
onDelete=onDelete
)
return reference
if callable(onDelete):
return weakref.ref(target, onDelete)
else:
return weakref.ref( target ) 返回 target 的弱引用对象
class BoundMethodWeakref(object):
"""'Safe' and reusable weak references to instance methods
BoundMethodWeakref objects provide a mechanism for
referencing a bound method without requiring that the
method object itself (which is normally a transient
object) is kept alive. Instead, the BoundMethodWeakref
object keeps weak references to both the object and the
function which together define the instance method.
Attributes:
key -- the identity key for the reference, calculated
by the class's calculateKey method applied to the
target instance method
deletionMethods -- sequence of callable objects taking
single argument, a reference to this object which
will be called when *either* the target object or
target function is garbage collected (i.e. when
this object becomes invalid). These are specified
as the onDelete parameters of safeRef calls.
weakSelf -- weak reference to the target object
weakFunc -- weak reference to the target function
Class Attributes:
_allInstances -- class attribute pointing to all live
BoundMethodWeakref objects indexed by the class's
calculateKey(target) method applied to the target
objects. This weak value dictionary is used to
short-circuit creation so that multiple references
to the same (object, function) pair produce the
same BoundMethodWeakref instance.
"""
_allInstances = weakref.WeakValueDictionary()
def __new__( cls, target, onDelete=None, *arguments,**named ):
"""Create new instance or return current instance
Basically this method of construction allows us to
short-circuit creation of references to already-
referenced instance methods. The key corresponding
to the target is calculated, and if there is already
an existing reference, that is returned, with its
deletionMethods attribute updated. Otherwise the
new instance is created and registered in the table
of already-referenced methods.
"""
key = cls.calculateKey(target)
current =cls._allInstances.get(key)
if current is not None: 存在
current.deletionMethods.append( onDelete)
return current
else:不存在, 需要新建和插入
base = super( BoundMethodWeakref, cls).__new__( cls )
cls._allInstances[key] = base
base.__init__( target, onDelete, *arguments,**named) 调用初始化函数
return base
def __init__(self, target, onDelete=None):
"""Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have __self__ and __func__ attributes
and be reconstructable via:
target.__func__.__get__( target.__self__ )
which is true of built-in instance methods.
onDelete -- optional callback which will be called
when this weak reference ceases to be valid
(i.e. either the object or the function is garbage
collected). Should take a single argument,
which will be passed a pointer to this object.
"""
def remove(weak, self=self):
"""Set self.isDead to true when method or instance is destroyed"""
methods = self.deletionMethods[:]
del self.deletionMethods[:]
try:
del self.__class__._allInstances[ self.key ]
except KeyError:
pass
for function in methods:
try:
if callable( function ):
function( self ) 如果可以调用, 调用
except Exception as e:
try:
traceback.print_exc()
except AttributeError:
print('Exception during saferef %s cleanup function %s: %s' % (
self, function, e)
)
self.deletionMethods = [onDelete] 替换
self.key = self.calculateKey( target )
self | .weakSelf = weakref.ref(target.__self__, remove)
self.weakFunc = weakref.ref(target.__func__, | remove)
self.selfName = str(target.__self__)
self.funcName = str(target.__func__.__name__)
def calculateKey( cls, target ): 这不是一个类方法, 因为没有 self
"""Calculate the reference key for this reference
Currently this is a two-tuple of the id()'s of the
target object and the target function respectively.
"""
return (id(target.__self__),id(target.__func__)) 所有要求 target 必须要有 __self__ 和 __func__ 两个属性
calculateKey = classmethod( calculateKey )
def __str__(self):
"""Give a friendly representation of the object"""
return """%s( %s.%s )"""%(
self.__class__.__name__,
self.selfName,
self.funcName,
)
__repr__ = __str__
def __hash__(self):
return hash(self.key)
def __bool__( self ):
"""Whether we are still a valid reference"""
return self() is not None
def __nonzero__(self): # Python 2 compatibility
return type(self).__bool__(self)
def __eq__(self, other):
"""Compare with another reference"""
if not isinstance(other, self.__class__):
return self.__class__ == type(other)
return self.key == other.key
def __call__(self):
"""Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.
"""
target = self.weakSelf()
if target is not None:
function = self.weakFunc()
if function is not None:
return function.__get__(target) function 是 self.weakFunc = weakref.ref(target.__func__, remove) 的结果
return None
class BoundNonDescriptorMethodWeakref(BoundMethodWeakref):
"""A specialized BoundMethodWeakref, for platforms where instance methods
are not descriptors.
It assumes that the function name and the target attribute name are the
same, instead of assuming that the function is a descriptor. This approach
is equally fast, but not 100% reliable because functions can be stored on an
attribute named differenty than the function's name such as in:
class A: pass
def foo(self): return "foo"
A.bar = foo
But this shouldn't be a com |
XiKuuKy/Stack2 | Stack2.py | Python | mit | 1,481 | 0.00135 | """
By Simon Harms.
Copyright 2015 Simon Harms, MIT LICENSE
Name: Stack2
Summary: Stack Version 2
"""
class Stack:
"""
Python Stack V2 with view and change.
"""
def __init__(self):
"""
Initialize the Stack.
"""
self.__storage = []
def is_empty(self):
"""
Returns if the Stack is empty.
"""
return len(self.__storage) == 0
def push(self, pushed):
"""
Add to the Stack.
"""
self.__storage.append(pushed)
def pop(self):
"""
Delete the top element.
"""
return self.__storage.pop()
def view(self):
"""
Return the Topmost item in the Stack.
"""
return self.__storage[-1]
def change(self, new):
"""
Make edits to the Topmost item in the Stack.
"""
self.__storage[-1] = new
def get_len(self):
"""
Return the length of the stack.
"""
return len(self.__storage)
def get_stack(self):
"""
Return the stack. (Can't edit it though. It is just a getter.)
"""
return self.__storage
def set_stack(self, new_stack):
"""
Set the stack as the stack pased i | n. (use the newStacks getStack function.)
"""
self.__storage = new_stack
def get_str | ing(self):
"""
Get a string of the stack.
"""
return "".join(self.__storage)
|
MarxMustermann/OfMiceAndMechs | src/itemFolder/plants/poisonBloom.py | Python | gpl-3.0 | 1,539 | 0.001949 | import src
class PoisonBloom(src.items.Item):
"""
a poisonous plant
"""
type = "PoisonBloom"
name = "poison bloom"
description = "Its spore sacks shriveled and are covered in green slime"
usageInfo = """
You can eat it to die.
"""
walkable = True
dead = False
bolted = False
def __init__(self):
"""
initialise internal state
"""
super().__init__(display=src.canvas.displayChars.poisonBloom)
self.attributesToStore.extend(["dead"])
def apply(self, character):
"""
handle a character trying to use this item
by killing the character
Parameters:
character: the character trying to use the item
"""
if | not self.contai | ner:
self.dead = True
character.die()
if not self.dead:
new = src.items.itemMap["PoisonBush"]()
self.container.addItem(new,self.getPosition())
character.addMessage("you eat the poison bloom and die")
self.destroy(generateScrap=False)
def pickUp(self, character):
"""
handle getting picked up by a character
Parameters:
character: the character picking up the item
"""
self.dead = True
self.charges = 0
super().pickUp(character)
def destroy(self, generateScrap=True):
"""
destroy the item without leaving residue
"""
super().destroy(generateScrap=False)
src.items.addType(PoisonBloom)
|
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_12_01/aio/operations/_gallery_images_operations.py | Python | mit | 25,178 | 0.004885 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._gallery_images_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_gallery_request, build_update_request_initial
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class GalleryImagesOperations:
"""GalleryImagesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.compute.v2019_12_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _create_or_update_initial(
self,
resource_group_name: str,
gallery_name: str,
gallery_image_name: str,
gallery_image: "_models.GalleryImage",
**kwargs: Any
) -> "_models.GalleryImage":
cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImage"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(gallery_image, 'GalleryImage')
request = build_create_or_update_request_initial(
subscription_id=self._config.subscription_id,
resource_group_name=resource_group_name,
gallery_name=gallery_name,
gallery_image_name=gallery_image_name,
content_type=content_type,
json=_json,
template_url=self._create_or_update_initial.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('GalleryImage', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('GalleryImage', pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize('GalleryImage', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}'} # type: ignore
@distributed_trace_async
async def begin_create_or_update(
self,
resource_group_name: str,
gallery_name: str,
gallery_image_name: str,
gallery_image: "_models.GalleryImage",
**kwargs: Any
) -> AsyncLROPoller["_models.GalleryImage"]:
"""Create or update a gallery Image Definition.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param gallery_name: The name of the Shared Image Gallery in which the Image Definition is to
be created.
:type gallery_name: str
:param gallery_image_name: The name of the gallery Image Definition to be created or updated.
The allowed characters are alphabets and numbers with dots, dashes, and periods allowed in the
middle. The maximum length is 80 characters.
:type gallery_image_name: str
:param gallery_image: Parameters supplied to the create or update gallery image operation.
:type gallery_image: ~azure.mgmt.compute.v2019_12_01.models.GalleryImage
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keywo | rd polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls | for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either GalleryImage or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2019_12_01.models.GalleryImage]
:raises: ~azure.core.exceptions.HttpResponseError
"""
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImage"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
gallery_name=gallery_name,
gallery_image_name=gallery_image_name,
gallery_image=gallery_image,
content_type=content_type,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('GalleryImage', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: pollin |
cojacoo/testcases_echoRD | gen_test1110k.py | Python | gpl-3.0 | 431 | 0.044084 | mcinif='mcini_gen1'
runname='gen_test11 | 10k'
mcpick='gen_test1.pickle'
pathdir='/beegfs/work/ka_oj4748/echoRD'
wdir='/beegfs/work/ka_oj4748/gen_tests'
update_prec=0.01
update_mf='False'
update_part=100
import sys
sys.path.append(pathdir)
import run_echoRD as rE
rE.echoRD_job(mcinif=mcinif,mcpick=mcpick,runname=runname,wdir=wdir,pa | thdir=pathdir,update_prec=update_prec,update_mf=update_mf,update_part=update_part,hdf5pick=False)
|
jeffmahoney/supybot | plugins/Seen/plugin.py | Python | bsd-3-clause | 13,345 | 0.001499 | ###
# Copyright (c) 2002-2004, Jeremiah Fincher
# Copyright (c) 2010-2011, 2013, James McCoy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import re
import time
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
import supybot.ircdb as ircdb
from supybot.commands import *
import supybot.irclib as irclib
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
class IrcStringAndIntDict(utils.InsensitivePreservingDict):
def key(self, x):
if isinstance(x, int):
return x
else:
return ircutils.toLower(x)
class SeenDB(plugins.ChannelUserDB):
IdDict = IrcStringAndIntDict
def serialize(self, v):
return list(v)
def deserialize(self, channel, id, L):
(seen, saying) = L
return (float(seen), saying)
def update(self, channel, nickOrId, saying):
seen = time.time()
self[channel, nickOrId] = (seen, saying)
self[channel, '<last>'] = (seen, saying)
def seenWildcard(self, channel, nick):
nicks = ircutils.IrcSet()
nickRe = re.compile('^%s$' % '.*'.join(nick.split('*')), re.I)
for (searchChan, searchNick) in self.keys():
#print 'chan: %s ... nick: %s' % (searchChan, searchNick)
if isinstance(searchNick, int):
# We need to skip the reponses that are keyed by id as they
# apparently duplicate the responses for the same person that
# are keyed by nick-string
continue
if ircutils.strEqual(searchChan, channel):
if nickRe.search(searchNick) is not None:
nicks.add(searchNick)
L = [[nick, self.seen(channel, nick)] for nick in nicks]
def negativeTime(x):
return -x[1][0]
utils.sortBy(negativeTime, L)
return L
def seen(self, channel, nickOrId):
return self[channel, nickOrId]
filename = conf.supybot.directories.data.dirize('Seen.db')
anyfilename = conf.supybot.directories.data.dirize('Seen.any.db')
class Seen(callbacks.Plugin):
noIgnore = True
def __init__(self, irc):
self.__parent = super(Seen, self)
self.__parent.__init__(irc)
self.db = SeenDB(filename)
self.anydb = SeenDB(anyfilename)
self.lastmsg = {}
self.ircstates = {}
world.flushers.append(self.db.flush)
world.flushers.append(self.anydb.flush)
def die(self):
if self.db.flush in world.flushers:
world.flushers.remove(self.db.flush)
else:
self.log.debug('Odd, no flush in flushers: %r', world.flushers)
self.db.close()
if self.anydb.flush in world.flushers:
world.flushers.remove(self.anydb.flush)
else:
self.log.debug('Odd, no flush in flushers: %r', world.flushers)
self.anydb.close()
self.__parent.die()
def __call__(self, irc, msg):
try:
if irc not in self.ircstates:
self._addIrc(irc)
self.ircstates[irc].addMsg(irc, self.lastmsg[irc])
finally:
self.lastmsg[irc] = msg
self.__parent.__call__(irc, msg)
def _addIrc(self, irc):
# Let's just be extra-special-careful here.
if irc not in self.ircstates:
self.ircstates[irc] = irclib.IrcState()
if irc not in self.lastmsg:
self.lastmsg[irc] = ircmsgs.ping('this is just | a fake message')
if not world.testing:
for channel in irc.state.channels:
irc.queueMsg(ircmsgs.who(channel))
irc.queueMsg(ircmsgs.names(channel))
def doPrivmsg(self, irc, msg):
if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
return
| if irc.isChannel(msg.args[0]):
channel = msg.args[0]
said = ircmsgs.prettyPrint(msg)
self.db.update(channel, msg.nick, said)
self.anydb.update(channel, msg.nick, said)
try:
id = ircdb.users.getUserId(msg.prefix)
self.db.update(channel, id, said)
self.anydb.update(channel, id, said)
except KeyError:
pass # Not in the database.
def doPart(self, irc, msg):
channel = msg.args[0]
said = ircmsgs.prettyPrint(msg)
self.anydb.update(channel, msg.nick, said)
try:
id = ircdb.users.getUserId(msg.prefix)
self.anydb.update(channel, id, said)
except KeyError:
pass # Not in the database.
doJoin = doPart
doKick = doPart
def doQuit(self, irc, msg):
said = ircmsgs.prettyPrint(msg)
if irc not in self.ircstates:
return
try:
id = ircdb.users.getUserId(msg.prefix)
except KeyError:
id = None # Not in the database.
for channel in self.ircstates[irc].channels:
if msg.nick in self.ircstates[irc].channels[channel].users:
self.anydb.update(channel, msg.nick, said)
if id is not None:
self.anydb.update(channel, id, said)
doNick = doQuit
def doMode(self, irc, msg):
# Filter out messages from network Services
if msg.nick:
self.doQuit(irc, msg)
doTopic = doMode
def _seen(self, irc, channel, name, any=False):
if any:
db = self.anydb
else:
db = self.db
try:
results = []
if '*' in name:
results = db.seenWildcard(channel, name)
else:
results = [[name, db.seen(channel, name)]]
if len(results) == 1:
(nick, info) = results[0]
(when, said) = info
irc.reply(format('%s was last seen in %s %s ago: %s',
nick, channel,
utils.timeElapsed(time.time()-when), said))
elif len(results) > 1:
L = []
for (nick, info) in results:
(when, said) = info
L.append(format('%s (%s ago)', nick,
utils.timeElapsed(time.time()-when)))
irc.reply(format('%s could be %L', name, (L, 'or')))
else:
irc.reply(format('I haven\'t seen anyone matching %s.', name))
except KeyError:
irc.reply(format('I have not seen %s.', name))
def seen(self, irc, msg, args, channel, name):
|
frekenbok/frekenbok | frekenbot/apps.py | Python | mit | 95 | 0 | from dja | ngo.apps import AppConfig
class TelegramBotConfig(AppConfig):
name = 'frekenbot' | |
oudalab/phyllo | phyllo/extractors/tungerDB.py | Python | apache-2.0 | 3,235 | 0.007112 | import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup, NavigableString
from phyllo.phyllo_logger import logger
import nltk
from itertools import cycle
nltk.download('punkt')
from nltk import sent_tokenize
# Case 1: Sections split by numbers (Roman or not) followed by a period, or bracketed. Subsections split by <p> tags
def parsecase1(ptags, c, colltitle, title, author, date, URL):
# ptags contains all <p> tags. c is the cursor object.
chapter = '-1'
verse = 1
for p in ptags:
# make sure it's not a paragraph without the main text
try:
if p['class'][0].lower() in ['border', 'pagehead', 'shortborder', 'smallboarder', 'margin',
'internal_navigation']: # these are not part of the main t
continue
except:
pass
passage = ''
text = p.get_text().strip()
# Skip empty paragraphs. and skip the last part with the collection link.
if len(text) <= 0 or text.startswith('Neo\n'):
continue
text = re.split('^([IVX]+)\.\s|^([0-9]+)\.\s|^\[([IVXL]+)\]\s|^\[([0-9]+)\]\s', text)
for element in text:
if element is None or element == '' or element.isspace():
text.remove(element)
# The split should not alter sections with no prefixed roman numeral.
if len(text) > 1:
i = 0
while text[i] is None:
i += 1
chapter = text[i]
i += 1
while text[i] is None:
i += 1
passage = text[i].strip()
verse = 1
else:
passage = text[0]
verse += 1
# check for that last line with the author name that doesn't need to be here
if passage.startswith('Neo'):
continue
c.execute("INSERT INTO texts VALUES (?,?,?,?,?,?,?, ?, ?, ?, ?)",
(None, colltitle, title, 'Latin', author, date, chapter,
verse, passage.strip(), URL, 'prose'))
def main():
# The collection URL below. In this example, we have a link to Cicero.
collURL = 'http://www.thelatinlibrary.com/tunger.html'
collOpen = urllib.request.urlopen(collURL)
collSOUP = BeautifulSoup(collOpen, 'html5lib')
author = collSOUP.title.string.strip()
colltitle = author.upper()
date = "1486"
textsURL = [collURL]
with sqlite3.connect('texts.db') as db:
c = db.cursor()
c.execute(
'CREATE TABLE IF NOT EXISTS texts (id INTEGER PRIMARY KEY, title TEXT, book TEXT,'
' language TEXT, author TEXT, date TEXT, chapter TEXT, verse TEXT, passa | ge TEXT,'
' link TEXT, documentType TEXT)')
c.execute("DELETE FROM texts WHERE author='Augustin Tünger'")
for url in textsURL:
openurl = urllib.request.urlopen(url)
textsoup = BeautifulSoup(openurl, 'html5lib')
title = 'FACETIAE LATINAE ET GERMANICAE'
getp = textsoup.find_all('p')
parsecase1(getp, c, colltitle, title | , author, date, url)
logger.info("Program runs successfully.")
if __name__ == '__main__':
main()
|
FreshXOpenSource/wallaby-base | wallaby/pf/peer/ping.py | Python | bsd-2-clause | 353 | 0.008499 | # Copyrig | ht (c) by it's authors.
# Some rights reserved. See LICENSE, AUTHORS.
from peer import *
class Ping(Peer):
Ping = Pillow.InOut
def __init__(self, *args):
Peer. | __init__(self, *args)
self._catch(Ping.In.Ping, self.message)
def message(self, pillow, feathers):
self._throw(Ping.Out.Ping, int(feathers)+1);
|
jmvrbanac/barbican | barbican/common/resources.py | Python | apache-2.0 | 1,430 | 0 | # Copyright (c) 2013-2014 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 CONDITI | ONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Shared business logic.
"""
from barbican.common import utils
from barbican.model import models
LOG = utils.getLogger(__name__)
def get_or_create_project(project_id, project_repo):
"""Returns project with matching project_id.
Creates it if | it does not exist.
:param project_id: The external-to-Barbican ID for this project.
:param project_repo: Project repository.
:return: Project model instance
"""
project = project_repo.find_by_external_project_id(project_id,
suppress_exception=True)
if not project:
LOG.debug('Creating project for %s', project_id)
project = models.Project()
project.external_id = project_id
project.status = models.States.ACTIVE
project_repo.create_from(project)
return project
|
lightmare/mapnik | scons/scons-local-4.1.0/SCons/Tool/rpm.py | Python | lgpl-2.1 | 4,494 | 0.007121 | """SCons.Tool.rpm
Tool-specific initialization for rpm.
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.
The rpm tool calls the rpmbuild command. The first and only argument should a
tar.gz consisting of the source file and a specfile.
"""
#
# __COPYRIGHT__
#
# 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.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
import re
import shutil
import subprocess
import SCons.Builder
import SCons.Node.FS
import SCons.Util
import SCons.Action
import SCons.Defaults
def get_cmd(source, env):
tar_file_with_included_specfile = source
if SCons.Util.is_List(source):
tar_file_with_included_specfile = source[0]
return "%s %s %s"%(env['RPM'], env['RPMFLAGS'],
tar_file_with_included_specfile.get_abspath())
def build_rpm(target, source, env) | :
# create a temporary rpm build root.
tmpdir = os.path.join(os.path.dirname(target[0].get_abspath()), 'rpmtemp')
if os.path.exists(tmpdir):
| shutil.rmtree(tmpdir)
# now create the mandatory rpm directory structure.
for d in ['RPMS', 'SRPMS', 'SPECS', 'BUILD']:
os.makedirs(os.path.join(tmpdir, d))
# set the topdir as an rpmflag.
env.Prepend(RPMFLAGS = '--define \'_topdir %s\'' % tmpdir)
# now call rpmbuild to create the rpm package.
handle = subprocess.Popen(get_cmd(source, env),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True)
with handle.stdout:
output = SCons.Util.to_str(handle.stdout.read())
status = handle.wait()
if status:
raise SCons.Errors.BuildError(node=target[0],
errstr=output,
filename=str(target[0]))
else:
# XXX: assume that LC_ALL=C is set while running rpmbuild
output_files = re.compile('Wrote: (.*)').findall(output)
for output, input in zip(output_files, target):
rpm_output = os.path.basename(output)
expected = os.path.basename(input.get_path())
assert expected == rpm_output, "got %s but expected %s" % (rpm_output, expected)
shutil.copy(output, input.get_abspath())
# cleanup before leaving.
shutil.rmtree(tmpdir)
return status
def string_rpm(target, source, env):
try:
return env['RPMCOMSTR']
except KeyError:
return get_cmd(source, env)
rpmAction = SCons.Action.Action(build_rpm, string_rpm)
RpmBuilder = SCons.Builder.Builder(action = SCons.Action.Action('$RPMCOM', '$RPMCOMSTR'),
source_scanner = SCons.Defaults.DirScanner,
suffix = '$RPMSUFFIX')
def generate(env):
"""Add Builders and construction variables for rpm to an Environment."""
try:
bld = env['BUILDERS']['Rpm']
except KeyError:
bld = RpmBuilder
env['BUILDERS']['Rpm'] = bld
env.SetDefault(RPM = 'LC_ALL=C rpmbuild')
env.SetDefault(RPMFLAGS = SCons.Util.CLVar('-ta'))
env.SetDefault(RPMCOM = rpmAction)
env.SetDefault(RPMSUFFIX = '.rpm')
def exists(env):
return env.Detect('rpmbuild')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
Astoriane/jCrunchyroll | lib/crunchy-xml-decoder/crunchyDec.py | Python | lgpl-3.0 | 4,061 | 0.02167 | import gzip, lxml, math, sha, zlib
from Base64Decoder import Base64Decoder
from binascii import hexlify, unhexlify
from bs4 import BeautifulSoup
from Common import Common
from crypto.cipher.aes_cbc import AES_CBC
from crypto.cipher.base import noPadding, padWithPadLen
class crunchyDec:
def __init__(self):
pass
def returnSubs(self, xml):
_id, _iv, _data = self.strainSoup(xml)
print "Attempting to decrypt subtitles..."
decryptedSubs = self.decodeSubtitles(_id, _iv, _data)
formattedSubs = self.convertToASS(decryptedSubs)
print "Success! Subtitles decrypted."
return formattedSubs
def strainSoup(self, xml):
soup = BeautifulSoup(xml)
subtitle = soup.find('subtitle', attrs={'link': None})
if subtitle:
_id = int(subtitle['id'])
_iv = subtitle.find('iv').contents[0]
_data = subtitle.data.string
return _id, _iv, _data
else:
print "Couldn't parse XML file."
def convertToASS(self, script):
soup = BeautifulSoup(script, 'xml')
header = soup.find('subtitle_script')
header = "[Script Info]\nTitle: "+header['title']+"\nScriptType: v4.00+\nWrapStyle: "+header['wrap_style']+"\nPlayResX: 656\nPlayResY: 368\n\n";
styles = "[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n";
events = "\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n";
stylelist = soup.findAll('style')
eventlist = soup.findAll('event')
for style in stylelist:
styles += "Style: " + style['name'] + "," + style['font_name'] + "," + style['font_size'] + "," + style['primary_colour'] + "," + style['secondary_colour'] + "," + style['outline_colour'] + "," + style['back_colour'] + "," + style['bold'] + "," + style['italic'] + "," + style['underline'] + "," + style['strikeout'] + "," + style['scale_x'] + "," + style['scale_y'] + "," + style['spacing'] + "," + style['angle'] + "," + style['border_style'] + "," + style['outline'] + "," + style['shadow'] + "," + style['alignment'] + "," + style['margin_l'] + "," + style['margin_r'] + "," + style['margin_v'] + "," + style['encoding'] + | "\n"
for event in eventlist:
events += "Dialogue: 0,"+event['start']+","+event['end']+","+event['style']+","+event['name']+","+event['margin_l']+","+event['margin_r']+","+event['margin_v']+","+event['effect']+","+event['text']+"\n"
formattedSubs = header+styles+events
return formattedSubs
# ---- CRYPTO -----
def generateKey(self, mediaid, size = 32):
# Be | low: Do some black magic
eq1 = int(int(math.floor(math.sqrt(6.9) * math.pow(2, 25))) ^ mediaid)
eq2 = int(math.floor(math.sqrt(6.9) * math.pow(2, 25)))
eq3 = (mediaid ^ eq2) ^ (mediaid ^ eq2) >> 3 ^ eq1 * 32
# Below: Creates a 160-bit SHA1 hash
shaHash = sha.new(self.createString([20, 97, 1, 2]) + str(eq3))
finalHash = shaHash.digest()
hashArray = Common().createByteArray(finalHash)
# Below: Pads the 160-bit hash to 256-bit using zeroes, incase a 256-bit key is requested
padding = [0]*4*3
hashArray.extend(padding)
keyArray = [0]*size
# Below: Create a string of the requested key size
for i, item in enumerate(hashArray[:size]):
keyArray[i] = item
return Common().ByteArrayToString(keyArray)
def createString(self, args):
i = 0
argArray = [args[2], args[3]]
while(i < args[0]):
argArray.append(argArray[-1] + argArray[-2])
i = i + 1
finalString = ""
for arg in argArray[2:]:
finalString += chr(arg % args[1] + 33)
return finalString
def decodeSubtitles(self, id, iv, data):
compressed = True
key = self.generateKey(id)
iv = Common().ByteArrayToString(Base64Decoder().decode(iv))
data = Common().ByteArrayToString(Base64Decoder().decode(data))
data = iv+data
cipher = AES_CBC(key, padding=noPadding(), keySize=32)
decryptedData = cipher.decrypt(data)
if compressed:
return zlib.decompress(decryptedData)
else:
return decryptedData
|
TariqEE/PrivEx | S2/S2-netified/noise.py | Python | bsd-3-clause | 345 | 0.008696 | import numpy
import random
impor | t math
from exit_weight import *
from privexUtils import resolution
#def Noise(sensitivity, epsilon, delta, fingerprint, sigma):
def Noise(sigma, fingerprint, sum_of_sq, p_exit):
sigma_i = p_exit*sigma/math.sqrt(sum_of_sq)
random_sample = random.gauss(0,sigma_i)
return random_sample
# | return 0
|
torgeirl/tradingpost-beepboop | bot/slack_bot.py | Python | mit | 2,852 | 0.002805 | import time
import logging
import traceback
from slack_clients import SlackClients
from messenger import Messenger
from event_handler import RtmEventHandler
logger = logging.getLogger(__name__)
def spawn_bot():
return SlackBot()
class SlackBot(object):
def __init__(self, token=None):
"""Creates Slacker Web and RTM clients with API Bot User token.
Args:
token (str): Slack API | Bot User token (for development token set in env)
| """
self.last_ping = 0
self.keep_running = True
if token is not None:
self.clients = SlackClients(token)
def start(self, resource):
"""Creates Slack Web and RTM clients for the given Resource
using the provided API tokens and configuration, then connects websocket
and listens for RTM events.
Args:
resource (dict of Resource JSON): See message payloads - https://beepboophq.com/docs/article/resourcer-api
"""
logger.debug('Starting bot for resource: {}'.format(resource))
if 'resource' in resource and 'SlackBotAccessToken' in resource['resource']:
res_access_token = resource['resource']['SlackBotAccessToken']
self.clients = SlackClients(res_access_token)
if self.clients.rtm.rtm_connect():
logging.info(u'Connected {} to {} team at https://{}.slack.com'.format(
self.clients.rtm.server.username,
self.clients.rtm.server.login_data['team']['name'],
self.clients.rtm.server.domain))
msg_writer = Messenger(self.clients)
event_handler = RtmEventHandler(self.clients, msg_writer)
while self.keep_running:
for event in self.clients.rtm.rtm_read():
try:
event_handler.handle(event)
except:
err_msg = traceback.format_exc()
logging.error(u'Unexpected error: {}'.format(err_msg))
msg_writer.write_error(event['channel'], err_msg)
continue
self._auto_ping()
time.sleep(.1)
else:
logger.error(u'Failed to connect to RTM client with token: {}'.format(self.clients.token))
def _auto_ping(self):
# hard code the interval to 3 seconds
now = int(time.time())
if now > self.last_ping + 3:
self.clients.rtm.server.ping()
self.last_ping = now
def stop(self, resource):
"""Stop any polling loops on clients, clean up any resources,
close connections if possible.
Args:
resource (dict of Resource JSON): See message payloads - https://beepboophq.com/docs/article/resourcer-api
"""
self.keep_running = False
|
mdg/pygrate | pygration/db.py | Python | apache-2.0 | 2,877 | 0.012165 | import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import mapper, sessionmaker
import subprocess
class PygrationState(object):
'''Python object representing the state table'''
def __init__(self, migration=None, step_id=None, step_name=None):
self.migration = migration
self.step_id = step_id
self.step_name = step_name
self.sequence = None
self.add_state = None
self.simdrop_state = None
self.drop_state = None
def __repr__(self):
return "<PygrationState(%s, %s)>" % (self.migration, self.step_id)
class Table(object):
metadata = sqlalchemy.MetaData()
engine = None
pygration_state = None
@classmethod
def define(cls, schema=None):
cls.pygration_state = sqlalchemy.Table('pygration_state', cls.metadata
, Column('migration', String(length=160), primary_key=True)
, Column('step_id', String(length=160), primary_key=True)
, Column('step_name', String(length=160))
, Column('sequence', Integer)
, Column('add_state', String(length=16))
, Column('simdrop_state', String(length=16))
, Column('drop_state', String(length=16))
, schema=schema
)
class FileLoader(object):
'''Object for running SQL from a file on the file system'''
def __init__(self, binary, args = [], formatt | ing_dict = {}):
self._binary = binary
self._args = [arg.format(filename="{filename}", **formatting_dict) for arg in args]
def __call__(self, filename):
args = [arg.format(filename=filename) for arg in self._args]
print self._binary, args
subprocess.check_call([self._binary] + args)
def open(url=None, drivername=None, schema=None, username=None,
password=None, host=None, port=None, database=None, query=None):
"""Open the DB through | a SQLAlchemy engine.
Returns an open session.
"""
if url is None and drivername is None:
raise Exception("Either a url or a driver name is required to open a db connection")
if url is None:
url = sqlalchemy.engine.url.URL(drivername = drivername,
username = username,
password = password,
host = host,
port = port,
database = database,
query = query)
Table.engine = sqlalchemy.create_engine(url)
Table.metadata.bind = Table.engine
Session = sessionmaker()
Session.configure(bind=Table.engine)
session = Session()
Table.define(schema)
mapper(PygrationState, Table.pygration_state)
return session
|
tao12345666333/tornado-zh | tornado/simple_httpclient.py | Python | mit | 23,983 | 0.000375 | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
from tornado.escape import utf8, _unicode
from tornado import gen
from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tornado.iostream import StreamClosedError
from tornado.netutil import Resolver, OverrideResolver, _client_ssl_defaults
from tornado.log import gen_log
from tornado import stack_context
from tornado.tcpclient import TCPClient
import base64
import collections
import copy
import functools
import re
import socket
import sys
from io import BytesIO
try:
| import urlparse # py2
except ImportError:
import urllib.parse as urlparse # py3
try:
import ssl
except ImportError:
# ssl is not available on Google App Engine.
ssl = None
try:
import certifi
except ImportE | rror:
certifi = None
def _default_ca_certs():
if certifi is None:
raise Exception("The 'certifi' package is required to use https "
"in simple_httpclient")
return certifi.where()
class SimpleAsyncHTTPClient(AsyncHTTPClient):
"""Non-blocking HTTP client with no external dependencies.
This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
Some features found in the curl-based AsyncHTTPClient are not yet
supported. In particular, proxies are not supported, connections
are not reused, and callers cannot select the network interface to be
used.
"""
def initialize(self, io_loop, max_clients=10,
hostname_mapping=None, max_buffer_size=104857600,
resolver=None, defaults=None, max_header_size=None,
max_body_size=None):
"""Creates a AsyncHTTPClient.
Only a single AsyncHTTPClient instance exists per IOLoop
in order to provide limitations on the number of pending connections.
``force_instance=True`` may be used to suppress this behavior.
Note that because of this implicit reuse, unless ``force_instance``
is used, only the first call to the constructor actually uses
its arguments. It is recommended to use the ``configure`` method
instead of the constructor to ensure that arguments take effect.
``max_clients`` is the number of concurrent requests that can be
in progress; when this limit is reached additional requests will be
queued. Note that time spent waiting in this queue still counts
against the ``request_timeout``.
``hostname_mapping`` is a dictionary mapping hostnames to IP addresses.
It can be used to make local DNS changes when modifying system-wide
settings like ``/etc/hosts`` is not possible or desirable (e.g. in
unittests).
``max_buffer_size`` (default 100MB) is the number of bytes
that can be read into memory at once. ``max_body_size``
(defaults to ``max_buffer_size``) is the largest response body
that the client will accept. Without a
``streaming_callback``, the smaller of these two limits
applies; with a ``streaming_callback`` only ``max_body_size``
does.
.. versionchanged:: 4.2
Added the ``max_body_size`` argument.
"""
super(SimpleAsyncHTTPClient, self).initialize(io_loop,
defaults=defaults)
self.max_clients = max_clients
self.queue = collections.deque()
self.active = {}
self.waiting = {}
self.max_buffer_size = max_buffer_size
self.max_header_size = max_header_size
self.max_body_size = max_body_size
# TCPClient could create a Resolver for us, but we have to do it
# ourselves to support hostname_mapping.
if resolver:
self.resolver = resolver
self.own_resolver = False
else:
self.resolver = Resolver(io_loop=io_loop)
self.own_resolver = True
if hostname_mapping is not None:
self.resolver = OverrideResolver(resolver=self.resolver,
mapping=hostname_mapping)
self.tcp_client = TCPClient(resolver=self.resolver, io_loop=io_loop)
def close(self):
super(SimpleAsyncHTTPClient, self).close()
if self.own_resolver:
self.resolver.close()
self.tcp_client.close()
def fetch_impl(self, request, callback):
key = object()
self.queue.append((key, request, callback))
if not len(self.active) < self.max_clients:
timeout_handle = self.io_loop.add_timeout(
self.io_loop.time() + min(request.connect_timeout,
request.request_timeout),
functools.partial(self._on_timeout, key))
else:
timeout_handle = None
self.waiting[key] = (request, callback, timeout_handle)
self._process_queue()
if self.queue:
gen_log.debug("max_clients limit reached, request queued. "
"%d active, %d queued requests." % (
len(self.active), len(self.queue)))
def _process_queue(self):
with stack_context.NullContext():
while self.queue and len(self.active) < self.max_clients:
key, request, callback = self.queue.popleft()
if key not in self.waiting:
continue
self._remove_timeout(key)
self.active[key] = (request, callback)
release_callback = functools.partial(self._release_fetch, key)
self._handle_request(request, release_callback, callback)
def _connection_class(self):
return _HTTPConnection
def _handle_request(self, request, release_callback, final_callback):
self._connection_class()(
self.io_loop, self, request, release_callback,
final_callback, self.max_buffer_size, self.tcp_client,
self.max_header_size, self.max_body_size)
def _release_fetch(self, key):
del self.active[key]
self._process_queue()
def _remove_timeout(self, key):
if key in self.waiting:
request, callback, timeout_handle = self.waiting[key]
if timeout_handle is not None:
self.io_loop.remove_timeout(timeout_handle)
del self.waiting[key]
def _on_timeout(self, key):
request, callback, timeout_handle = self.waiting[key]
self.queue.remove((key, request, callback))
timeout_response = HTTPResponse(
request, 599, error=HTTPError(599, "Timeout"),
request_time=self.io_loop.time() - request.start_time)
self.io_loop.add_callback(callback, timeout_response)
del self.waiting[key]
class _HTTPConnection(httputil.HTTPMessageDelegate):
_SUPPORTED_METHODS = set(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
def __init__(self, io_loop, client, request, release_callback,
final_callback, max_buffer_size, tcp_client,
max_header_size, max_body_size):
self.start_time = io_loop.time()
self.io_loop = io_loop
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.tcp_client = tcp_client
self.max_header_size = max_header_size
self.max_body_size = max_body_size
self.code = None
self.headers = None
self.chunks = []
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None
self._sockaddr = None
with stack_context.ExceptionStackContext(self._handle_exception):
self.parsed = urlparse.urlsplit(_unicode(self.request.url))
if self.parsed.scheme not in ("http", "https"):
raise ValueError( |
luv/webdav_tests | test_suite_09_limits.py | Python | gpl-3.0 | 3,365 | 0.01367 | import subprocess
import cfg
import util
import shutil
import os
import time
import tempfile
import easywebdav
import filecmp
from nose.tools import with_setup
from nose.tools import assert_raises
#
# NOTE: following tests have been implemented using easywebdav instead of davfs2
#
pjoin | = os.path.join
assert sub | process # pyflakes
assert cfg # pyflakes
@with_setup(util.setup_func, util.teardown_func)
def test_case_01_deep():
client = util.connect_easywebdav()
rel_dir_path = "x/" * 300
rel_file_path = pjoin(rel_dir_path,"test_file")
dir_path_dest = pjoin(cfg.webdav_backend_directory, rel_dir_path)
file_path_dest = pjoin(cfg.webdav_backend_directory, rel_file_path)
subprocess.call(["mkdir","-p", dir_path_dest])
with open(file_path_dest,"w") as f:
f.write("sample content")
assert len(client.ls(rel_dir_path) ) == 2
with tempfile.TemporaryFile() as f:
client.download( rel_file_path, f)
f.seek(0)
assert f.readlines() == ["sample content"]
@with_setup(util.setup_func, util.teardown_func)
def test_case_02_deep_client():
client = util.connect_easywebdav()
rel_dir_path = "x/" * 300
rel_file_path = pjoin(rel_dir_path,"test_file")
client.mkdirs(rel_dir_path)
with tempfile.TemporaryFile() as f:
f.write("sample content")
f.seek(0)
client.upload(f, rel_file_path)
dir_path_dest = pjoin(cfg.webdav_backend_directory, rel_dir_path)
file_path_dest = pjoin(cfg.webdav_backend_directory, rel_file_path)
assert os.path.isdir( dir_path_dest )
assert os.path.isfile( file_path_dest )
with open(file_path_dest,"r") as f:
assert f.readlines() == ["sample content"]
client.delete( rel_file_path )
assert not os.path.isfile( file_path_dest )
client.rmdir( rel_dir_path )
assert not os.path.isdir( dir_path_dest )
@with_setup(util.setup_func, util.teardown_func)
def test_case_03_4gb():
full_name_src = pjoin(cfg.webdav_backend_directory, "foo")
full_name_dest = pjoin(cfg.webdav_mounted_directory, "foo")
subprocess.call(["dd","if=/dev/zero",'of=%s' % full_name_src,"bs=100kB","count=45000"],
stderr=util.FNULL)
time.sleep(cfg.dir_refresh)
assert filecmp.cmp(full_name_src, full_name_dest)
@with_setup(util.setup_func, util.teardown_func)
def test_case_04_4gb_client():
full_name_src = pjoin(cfg.webdav_mounted_directory, "foo")
full_name_dest = pjoin(cfg.webdav_backend_directory, "foo")
subprocess.call(["dd","if=/dev/zero",'of=%s' % full_name_src,"bs=100kB","count=45000"],
stderr=util.FNULL)
time.sleep(cfg.delay_upload)
assert filecmp.cmp(full_name_src, full_name_dest)
@with_setup(util.setup_func, util.teardown_func)
def test_case_05_long_filename():
client = util.connect_easywebdav()
with tempfile.TemporaryFile() as f:
f.write("sample content")
f.seek(0)
client.upload(f, "a"*255)
with tempfile.TemporaryFile() as f:
client.download("a"*255, f)
f.seek(0)
assert f.readlines() == ["sample content"]
assert os.path.isfile( pjoin(cfg.webdav_backend_directory, "a"*255) )
client.delete("a"*255)
assert_raises(easywebdav.OperationFailed,
client.ls, "a"*255 )
assert not os.path.isfile( pjoin(cfg.webdav_backend_directory, "a"*255) )
|
redhat-openstack/neutron | neutron/plugins/linuxbridge/agent/arp_protect.py | Python | apache-2.0 | 5,344 | 0 | # Copyright (c) 2015 Mirantis, 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 netaddr
from oslo.config import cfg
from neutron.agent.linux import ip_lib
from neutron.openstack.common import lockutils
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
SPOOF_CHAIN_PREFIX = 'neutronARP-'
def setup_arp_spoofing_protection(vif, port_details):
current_rules = ebtables(['-L']).splitlines()
if not port_details.get('port_security_enabled', True):
# clear any previous entries related to this port
delete_arp_spoofing_protection([vif], current_rules)
LOG.info(_("Skipping ARP spoofing rules for port '%s' because "
"it has port security disabled"), vif)
return
if port_details['device_owner'].startswith('network:'):
# clear any previous entries related to this port
delete_arp_spoofing_protection([vif], current_rules)
LOG.debug("Skipping ARP spoofing rules for network owned port "
"'%s'.", vif)
return
# collect all of the addresses and cidrs that belong to the port
addresses = set(f['ip_address'] for f in port_details['fixed_ips'])
if port_details.get('allowed_address_pairs'):
addresses |= set(p['ip_address']
for p | in port_details['allowed_address_pairs'])
addresses = set | (ip for ip in addresses
if netaddr.IPNetwork(ip).version == 4)
if any(netaddr.IPNetwork(ip).prefixlen == 0 for ip in addresses):
# don't try to install protection because a /0 prefix allows any
# address anyway and the ARP_SPA can only match on /1 or more.
return
install_arp_spoofing_protection(vif, addresses, current_rules)
def chain_name(vif):
# start each chain with a common identifer for cleanup to find
return '%s%s' % (SPOOF_CHAIN_PREFIX, vif)
@lockutils.synchronized('ebtables')
def delete_arp_spoofing_protection(vifs, current_rules=None):
if not current_rules:
current_rules = ebtables(['-L']).splitlines()
# delete the jump rule and then delete the whole chain
jumps = [vif for vif in vifs if vif_jump_present(vif, current_rules)]
for vif in jumps:
ebtables(['-D', 'FORWARD', '-i', vif, '-j',
chain_name(vif), '-p', 'ARP'])
for vif in vifs:
if chain_exists(chain_name(vif), current_rules):
ebtables(['-X', chain_name(vif)])
def delete_unreferenced_arp_protection(current_vifs):
# deletes all jump rules and chains that aren't in current_vifs but match
# the spoof prefix
output = ebtables(['-L']).splitlines()
to_delete = []
for line in output:
# we're looking to find and turn the following:
# Bridge chain: SPOOF_CHAIN_PREFIXtap199, entries: 0, policy: DROP
# into 'tap199'
if line.startswith('Bridge chain: %s' % SPOOF_CHAIN_PREFIX):
devname = line.split(SPOOF_CHAIN_PREFIX, 1)[1].split(',')[0]
if devname not in current_vifs:
to_delete.append(devname)
LOG.info(_("Clearing orphaned ARP spoofing entries for devices %s"),
to_delete)
delete_arp_spoofing_protection(to_delete, output)
@lockutils.synchronized('ebtables')
def install_arp_spoofing_protection(vif, addresses, current_rules):
# make a VIF-specific ARP chain so we don't conflict with other rules
vif_chain = chain_name(vif)
if not chain_exists(vif_chain, current_rules):
ebtables(['-N', vif_chain, '-P', 'DROP'])
# flush the chain to clear previous accepts. this will cause dropped ARP
# packets until the allows are installed, but that's better than leaked
# spoofed packets and ARP can handle losses.
ebtables(['-F', vif_chain])
for addr in addresses:
ebtables(['-A', vif_chain, '-p', 'ARP', '--arp-ip-src', addr,
'-j', 'ACCEPT'])
# check if jump rule already exists, if not, install it
if not vif_jump_present(vif, current_rules):
ebtables(['-A', 'FORWARD', '-i', vif, '-j',
vif_chain, '-p', 'ARP'])
def chain_exists(chain, current_rules):
for rule in current_rules:
if rule.startswith('Bridge chain: %s' % chain):
return True
return False
def vif_jump_present(vif, current_rules):
searches = (('-i %s' % vif), ('-j %s' % chain_name(vif)), ('-p ARP'))
for line in current_rules:
if all(s in line for s in searches):
return True
return False
# Used to scope ebtables commands in testing
NAMESPACE = None
def ebtables(comm):
execute = ip_lib.IPWrapper(root_helper=cfg.CONF.AGENT.root_helper,
namespace=NAMESPACE).netns.execute
return execute(['ebtables'] + comm)
|
CoRfr/testman4trac | tracgenericworkflow/trunk/setup.py | Python | gpl-3.0 | 2,209 | 0.010865 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2012 Roberto Longobardi
#
# This file is part of the Test Manager plugin for Trac.
#
# The Test Manager plugin for Trac 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.
#
# The Test Manager plugin for Trac 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 the Test Manager plugin for Trac. See the file LICENSE.txt.
# If not, see <http://www.gnu.org/licenses/>.
#
from setuptools import setup
setup(
name='TracGenericWorkflow',
version='1.0.4',
packages=['tracgenericworkflow','tracgenericworkflow.upgrades'],
package_data={'tracgenericworkflow' : ['*.txt', 'templates/*.html', 'htdocs/*.*', 'htdocs/js/*.js', 'htdocs/css/*.css', 'htdocs/images/*.*']},
author = 'Roberto Longobardi',
author_email='otrebor.dev@gmail.com',
license='GPL v. 3. See the file LICENSE.txt contained in the package.',
url='http://trac-hacks.org/wiki/TestManagerForTracPlugin',
download_url='https://sourceforge.net/projects/testman4trac/files/',
description='Test management plugin for Trac - Generic Workflow Engine component',
long_description='A Trac plugin to create | Test Cases, organize them in catalogs and track their execution status and outcome. This module provides a generic workflow engine working on any Trac Resource.',
keywords='trac plugi | n test case management workflow engine resource project quality assurance statistics stats charts charting graph',
entry_points = {'trac.plugins': ['tracgenericworkflow = tracgenericworkflow']},
dependency_links=['http://svn.edgewall.org/repos/genshi/trunk#egg=Genshi-dev', 'http://trac-hacks.org/wiki/TestManagerForTracPluginGenericClass'],
install_requires=['Genshi >= 0.6', 'TracGenericClass >= 1.1.5']
)
|
0nkery/django-websocket-redis3 | ws4redis/exceptions.py | Python | mit | 517 | 0 | from socket import error as socket_error
from django.http import BadHeaderError
class WebSocketError(socket_error):
"""
Raised when an active websocket encounters a problem.
"""
class FrameTooLargeException(WebSocketError):
"""
Raised if a received | frame is too large | .
"""
class HandshakeError(BadHeaderError):
"""
Raised if an error occurs during protocol handshake.
"""
class UpgradeRequiredError(HandshakeError):
"""
Raised if protocol must be upgraded.
"""
|
mvidalgarcia/indico | indico/core/db/sqlalchemy/review_comments.py | Python | mit | 2,710 | 0.000738 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from sqlalchemy.ext.declarative import declared_attr
from indico.core.db import db
from indico.core.db.sqlalchemy import UTCDateTime
from indico.core.db.sqlalchemy.descriptions import RenderMode, RenderModeMixin
from indico.util.date_time import now_utc
class ReviewCommentMixin(RenderModeMixin):
possible_render_modes = {RenderMode.markdown}
default_render_mode = RenderMode.markdown
user_backref_name = None
user_modified_backref_name = None
TIMELINE_TYPE = 'comment'
@declared_attr
def id(cls):
return db.Column(
db.Integer,
primary_key=True
)
@declared_attr
def user_id(cls):
return db.Column(
db.Integer,
db.ForeignKey('users.users.id'),
index=True,
nullable=False
)
@declared_attr
def _text(cls):
return db.Column(
'text',
db.Text,
nullable=False
)
@declared_attr
def modified_by_id(cls):
return db.Column(
db.Integer,
db.ForeignKey('users.users.id'),
index=True,
nullable=True
)
@declared_attr
def created_dt(cls):
return db.Column(
UTCDateTime,
nullable=False,
default=now_utc
)
@declared_attr
def modified_dt(cls):
return db.Column(
UTCDateTime,
nullable=True
)
@declared_attr
def is_deleted(cls):
return db.Column(
db.Boolean,
nullable=False,
default=False
)
@declared_attr
def user(cls):
return db.relationship(
'User',
lazy=True,
foreign_keys=cls.user_id,
backref=db.backref(
cls.user_backref_name,
primaryjoin='({0}.user_id == User.id) & ~{0}.is_deleted'.format(cls.__name__),
lazy='dynamic'
)
)
@declar | ed_attr
def modified_by(cls):
return db.relations | hip(
'User',
lazy=True,
foreign_keys=cls.modified_by_id,
backref=db.backref(
cls.user_modified_backref_name,
primaryjoin='({0}.modified_by_id == User.id) & ~{0}.is_deleted'.format(cls.__name__),
lazy='dynamic'
)
)
text = RenderModeMixin.create_hybrid_property('_text')
|
rochefort-lab/fissa | fissa/tests/test_readimagejrois.py | Python | gpl-3.0 | 5,999 | 0.0015 | """
Tests for readimagejrois.py.
"""
import json
import os
import sys
import unittest
import numpy as np
from .. import readimagejrois
from .base_test import BaseTestCase
class TestReadImageJRois(BaseTestCase):
"""readimagejrois testing class."""
def __init__(self, *args, **kw):
super(TestReadImageJRois, self).__init__(*args, **kw)
self.data_dir = os.path.join(self.test_directory, "resources", "rois")
def check_polygon(self, name):
desired_arr = np.load(os.path.join(self.data_dir, name + ".npy"))
desired = {"polygons": desired_arr}
actual = readimagejrois.parse_roi_file(
os.path.join(self.data_dir, name + ".roi")
)
self.assert_equal_dict_of_array(actual, desired)
def check_mask(self, name):
desired_arr = np.load(os.path.join(self.data_dir, name + ".npy"))
desired = {"mask": desired_arr}
actual = readimagejrois.parse_roi_file(
os.path.join(self.data_dir, name + ".roi")
)
self.assert_equal_dict_of_array(actual, desired)
def test_all(self):
self.check_polygon("all")
def test_brush(self):
self.check_polygon("brush")
def test_composite(self):
# This is a retangle with a shape cut out of it, but still contiguous.
# The type is displayed as "trace".
self.check_polygon("composite-rectangle")
def test_freehand(self):
self.check_polygon("freehand")
def test_freeline(self):
self.check_polygon("freeline")
@unittest.skipIf(
sys.version_info < (3, 0), "multipoint rois only supported on Python 3"
)
def test_multipoint(self):
self.check_polygon("multipoint")
@unittest.skipIf(
sys.version_info >= (3, 0), "multipoint rois are supported on Python 3"
)
def test_multipoint_py2_raises(self):
with self.assertRaises(ValueError):
self.check_polygon("multipoint")
def test_polygon(self):
self.check_polygon("polygon")
def test_polygon_left(self):
self.check_polygon("polygon-left")
def test_polygon_top(self):
self.check_polygon("polygon-top")
def test_polygon_right(self):
self.check_polygon("polygon-right")
def test_polygon_bottom(self):
self.check_polygon("polygon-bottom")
def test_polygon_left_offscreen(self):
name = "polygon-left-offscreen"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.data_dir, name + ".roi"))
def test_polygon_top_offscreen(self):
name = "polygon-top-offscreen"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.data_dir, name + ".roi"))
def test_polygon_right_offscreen(self):
self.check_polygon("polygon-right-offscreen")
def test_polygon_bottom_offscreen(self):
self.check_polygon("polygon-bottom-offscreen")
def test_polyline(self):
self.check_polygon("polyline")
def test_rectangle(self):
self.check_polygon("rectangle")
@unittest.skipIf(
sys.version_info < (3, 0), "Rotated rectangle rois only supported on Python 3"
)
def test_rectangle_rotated(self):
self.check_polygon("rectangle-rotated")
@unittest.skipIf(
sys.version_info >= (3, 0), "Rotated rectangle rois are supported on Python 3"
)
def test_rectangle_rotated_py2_raises(self):
with self.assertRaises(ValueError):
self.check_polygon("rectangle-rotated")
def test_rectangle_rounded(self):
# We ignore the 'arc_size' parameter, and treat it like a regular
# rectangle.
self.check_polygon("rectangle-rounded")
def test_oval(self):
self.check_mask("oval-center")
def test_oval_full(self):
self.check_mask("oval-full")
def test_oval_left(self):
self.check_mask("oval-left")
def test_oval_top(self):
self.check_mask("oval-top")
def test_oval_right(self):
self.check_mask("oval-right")
def test_oval_bottom(self):
self.check_mask("oval-bottom")
def test_oval_left_offscreen(self):
name = "oval-left-offscreen"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.data_dir, name + ".roi"))
def test_oval_top_offscreen(self):
name = "oval-top-offscreen"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.data_dir, name + ".roi"))
def test_oval_right_offscreen(self):
self.check_mask("oval-right-offscreen")
def test_oval_bottom_offscreen(self):
self.check_mask("oval-bottom-offscreen")
def test_ellipse(self):
self.check_mask("ellipse-center")
def test_ellipse_left(self):
self.check_mask("ellipse-left")
def test_ellipse_top(self):
self.check_mask("ellipse-top")
def test_ellipse_right(self):
self.check_mask("ellipse-right")
def test_ellipse_bottom(self):
self.check_mask("ellipse-bottom")
def test_ellipse_left_offscreen(self):
name = "ellipse-left-offscreen"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.data_dir, name + ".roi"))
def test_ellipse_top_offscreen(self):
name = "ellipse-top-offscreen"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.da | ta_dir, name + ".roi"))
def test_ellipse_right_offscreen(self):
self.check_mask("ellipse-right-offscreen")
def test_ellipse_bottom_offscreen(self):
self.check_mask("ellipse-bottom-offscreen")
def test_ellipse_tiny(self):
# ROI which is too small to cover a single pixel
name = "ellipse-tiny"
with self.assertRaises(ValueError):
readimagejrois.parse_roi_file(os.path.join(self.data_ | dir, name + ".roi"))
|
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/copy.py | Python | unlicense | 11,818 | 0.002623 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: copy.py
"""Generic (shallow and deep) copying operations.
Interface summary:
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
For module specific errors, copy.Error is raised.
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances).
- A shallow copy constructs a new compound object and then (to the
extent possible) inserts *the same objects* into it that the
original contains.
- A deep copy constructs a new compound object and then, recursively,
inserts *copies* into it of the objects found in the original.
Two problems often exist with deep copy operations that don't exist
with shallow copy operations:
a) recursive objects (compound objects that, directly or indirectly,
contain a reference to themselves) may cause a recursive loop
b) because deep copy copies *everything* it may copy too much, e.g.
administrative data structures that should be shared even between
copies
Python's deep copy operation avoids these problems by:
a) keeping a table of objects already copied during the current
copying pass
b) letting user-defined classes override the copying operation or the
set of components copied
This version does not copy types like module, class, function, method,
nor stack trace, stack frame, nor file, socket, window, nor array, nor
any similar types.
Classes can use the same interfaces to control copying that they use
to control pickling: they can define methods called __getinitargs__(),
__getstate__() and __setstate__(). See the documentation for module
"pickle" for information on these methods.
"""
import types
import weakref
from copy_reg import dispatch_table
class Error(Exception):
pass
error = Error
try:
from org.python.core import PyStringMap
except ImportError:
PyStringMap = None
__all__ = ['Error', 'copy', 'deepcopy']
def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
if copier:
return copier(x)
else:
copier = getattr(cls, '__copy__', None)
if copier:
return copier(x)
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, '__reduce_ex__', None)
if reductor:
rv = reductor(2)
else:
reductor = getattr(x, '__reduce__', None)
if reductor:
rv = reductor()
else:
raise Error('un(shallow)copyable object of type %s' % cls)
return _reconstruct(x, rv, 0)
_copy_dispatch = d = {}
def _copy_immutable(x):
return x
for t in (type(None), int, long, float, bool, str, tuple,
frozenset, type, xrange, types.ClassType,
types.BuiltinFunctionType, type(Ellipsis),
types.FunctionType, weakref.ref):
d[t] = _copy_immutable
for name in ('ComplexType', 'UnicodeType', 'CodeType'):
t = getattr(types, name, None)
if t is not None:
d[t] = _copy_immutable
def _copy_with_constructor(x):
return type(x)(x)
for t in (list, dict, set):
d[t] = _copy_with_constructor
def _copy_with_copy_method(x):
return | x.cop | y()
if PyStringMap is not None:
d[PyStringMap] = _copy_with_copy_method
def _copy_inst(x):
if hasattr(x, '__copy__'):
return x.__copy__()
if hasattr(x, '__getinitargs__'):
args = x.__getinitargs__()
y = x.__class__(*args)
else:
y = _EmptyClass()
y.__class__ = x.__class__
if hasattr(x, '__getstate__'):
state = x.__getstate__()
else:
state = x.__dict__
if hasattr(y, '__setstate__'):
y.__setstate__(state)
else:
y.__dict__.update(state)
return y
d[types.InstanceType] = _copy_inst
del d
def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
if memo is None:
memo = {}
d = id(x)
y = memo.get(d, _nil)
if y is not _nil:
return y
else:
cls = type(x)
copier = _deepcopy_dispatch.get(cls)
if copier:
y = copier(x, memo)
else:
try:
issc = issubclass(cls, type)
except TypeError:
issc = 0
if issc:
y = _deepcopy_atomic(x, memo)
else:
copier = getattr(x, '__deepcopy__', None)
if copier:
y = copier(memo)
else:
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, '__reduce_ex__', None)
if reductor:
rv = reductor(2)
else:
reductor = getattr(x, '__reduce__', None)
if reductor:
rv = reductor()
else:
raise Error('un(deep)copyable object of type %s' % cls)
y = _reconstruct(x, rv, 1, memo)
memo[d] = y
_keep_alive(x, memo)
return y
_deepcopy_dispatch = d = {}
def _deepcopy_atomic(x, memo):
return x
d[type(None)] = _deepcopy_atomic
d[type(Ellipsis)] = _deepcopy_atomic
d[int] = _deepcopy_atomic
d[long] = _deepcopy_atomic
d[float] = _deepcopy_atomic
d[bool] = _deepcopy_atomic
try:
d[complex] = _deepcopy_atomic
except NameError:
pass
d[str] = _deepcopy_atomic
try:
d[unicode] = _deepcopy_atomic
except NameError:
pass
try:
d[types.CodeType] = _deepcopy_atomic
except AttributeError:
pass
d[type] = _deepcopy_atomic
d[xrange] = _deepcopy_atomic
d[types.ClassType] = _deepcopy_atomic
d[types.BuiltinFunctionType] = _deepcopy_atomic
d[types.FunctionType] = _deepcopy_atomic
d[weakref.ref] = _deepcopy_atomic
def _deepcopy_list(x, memo):
y = []
memo[id(x)] = y
for a in x:
y.append(deepcopy(a, memo))
return y
d[list] = _deepcopy_list
def _deepcopy_tuple(x, memo):
y = []
for a in x:
y.append(deepcopy(a, memo))
d = id(x)
try:
return memo[d]
except KeyError:
pass
for i in range(len(x)):
if x[i] is not y[i]:
y = tuple(y)
break
else:
y = x
memo[d] = y
return y
d[tuple] = _deepcopy_tuple
def _deepcopy_dict(x, memo):
y = {}
memo[id(x)] = y
for key, value in x.iteritems():
y[deepcopy(key, memo)] = deepcopy(value, memo)
return y
d[dict] = _deepcopy_dict
if PyStringMap is not None:
d[PyStringMap] = _deepcopy_dict
def _deepcopy_method(x, memo):
return type(x)(x.im_func, deepcopy(x.im_self, memo), x.im_class)
_deepcopy_dispatch[types.MethodType] = _deepcopy_method
def _keep_alive(x, memo):
"""Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone tries to deepcopy
the memo itself...
"""
try:
memo[id(memo)].append(x)
except KeyError:
memo[id(memo)] = [
x]
def _deepcopy_inst(x, memo):
if hasattr(x, '__deepcopy__'):
return x.__deepcopy__(memo)
if hasattr(x, '__getinitargs__'):
args = x.__getinitargs__()
args = deepcopy(args, memo)
y = x.__class__(*args)
else:
y = _EmptyClass()
y.__class__ = x.__class__
memo[id(x)] = y
if hasattr(x, '__getstate__ |
kennethreitz/pipenv | pipenv/vendor/passa/cli/install.py | Python | mit | 598 | 0.003344 | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from ..actions.install import install
from ._base import BaseCommand
from .options import dev, no_check, no_clean
class Command(BaseCommand):
name = "install"
desc | ription = "Generate Pipfile.lock to synchronize the environment."
arguments = [no_check, dev, no_clean]
def run(self, options):
return install(project=options.project, che | ck=options.check, dev=options.dev,
clean=options.clean)
if __name__ == "__main__":
Command.run_parser()
|
dathath/IJCAI_2017_SD | proteus/svm_classifier.py | Python | bsd-2-clause | 1,509 | 0.095427 | from oct2py import octave
from cvxopt import matrix, solvers
from cvxpy import *
import numpy as np
def svm_classifier(X, y, | mode):
[num_sample,d]=X.shape
mode_control=np.ones((num_sample,1))
for i in range(num_sample):
if(mode==1):
if(y[i]==-1):
mode_control[i]=0;
if(mode==2):
if(y[i]==1):
mode_control[i]=0;
if(mode==4):
mode_control[i]=0;
#[G,bet | a]= octave.PWL_feature(X, M, beta_type);
A=np.array([[]])
for i in range(num_sample):
s=np.zeros((1,num_sample));
s[0,i]=1;
temp_1=y[i]*np.concatenate((np.array([[1]]),[X[i,:]]),axis=1)
temp_a=-np.concatenate((temp_1,s),axis=1)
if(i==0):
A=temp_a
else:
A=np.concatenate((A,temp_a),axis=0)
dum_concat=-np.concatenate((np.zeros((num_sample,d+1)),np.eye(num_sample)),axis=1)
A=np.concatenate((A,dum_concat),axis=0);
beq=np.zeros((1+d+num_sample,1));
Aeq=np.concatenate((np.zeros((d+1,1)),np.ones((num_sample,1))-mode_control),axis=0);
Aeq=np.diag(Aeq[:,0]);
b=np.concatenate((-np.ones((num_sample,1)), np.zeros((num_sample,1))),axis=0);
gamma=1;
x=Variable(d+num_sample+1,1)
constraints=[A*x<=b, Aeq*x==0]
obj=Minimize(( 0.5*(norm(x[0:d+1:1,0])**2) )+100*(sum_entries(x[d+1:d+1+num_sample:1,0])) )
prob = Problem(obj, constraints)
prob.solve()
x_val=x.value
ypredicted = x_val[0,0]+(X*x_val[1:1+d,0]);
ypredicted=np.sign(ypredicted);
error=np.zeros(y.shape[0]);
for i in range(y.shape[0]):
error[i]=(y[i]-ypredicted[i,0])/2
return (error,x.value[0:d+1],ypredicted)
|
sclamons/murraylab_tools | examples/biotektests.py | Python | mit | 999 | 0.029029 | import murraylab_tools.biotek as mt_biotek
import os
gitexamplepath = "C:\\Users\\Andrey\\Documents\\GitHub\\"+\
"murraylab_tools\\examples\\biotek_examples\\"
data_filename = gitexamplepath+\
"180515_big384wellplate.csv"
supplementary_filename = gitexamplepath+\
"supp_inductiongrid.csv"
#mt_biotek.tidy_biotek_data(data_filename, supplementary_filename, convert_to_uM = F | alse)
import pandas as pd
tidy_filename | = gitexamplepath+"180515_big384wellplate_tidy.csv"
df = pd.read_csv(tidy_filename)
#df.head()
#df.head()
#gdf = df.groupby(["Channel", "Gain", "Well"])
#gdf.head()
#df[df.Channel == "GFP"].head()
normdf = mt_biotek.normalize(df,norm_channel= "OD")
#normdf[normdf.Gain==100].head()
end_df = mt_biotek.window_averages(normdf,15,17,"hours")
end_df.Excitation.unique()
slicedf = end_df[(end_df.Gain == 100 )&(end_df.Construct=="pQi41")&(end_df.aTC==250)]
end_df[(end_df.Gain == 100 )&(end_df.Construct=="pQi41")&(end_df.aTC==250)].head()
|
google/makani | config/m600/control/trans_in.py | Python | apache-2.0 | 13,367 | 0.001795 | # Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Transition-in controller parameters."""
from makani.analysis.control import simple_aero
from makani.config import mconfig
from makani.config.m600.control import trans_in_controllers
import numpy as np
@mconfig.Config(deps={
'phys': 'common.physical_constants',
'rotors': mconfig.WING_MODEL + '.rotors',
'tether': mconfig.WING_MODEL + '.tether',
'wing': mconfig.WING_MODEL + '.wing',
'wing_serial': 'common.wing_serial',
})
def MakeParams(params):
controllers = trans_in_controllers.GetControllers(params['wing_serial'])
flap_offset = np.deg2rad(-11.5)
simple_aero_model = {
'dCL_dalpha': 7.23857325,
'CL_0': 1.69398499,
'base_flaps': [flap_offset, flap_offset, flap_offset, flap_offset,
flap_offset, flap_offset, 0.0, 0.0],
'dCL_dflap': [0.31226199, 0.37013073, 0.37070369, 0.37013073,
0.36783890, 0.31111608, 0.54488286, 0.00229183],
'dCY_dbeta': -1.419025,
'CY_0': -0.051620,
'dCD_dalpha': 0.68301,
'CD_0': 0.076590,
}
simple_aero.CheckSimpleAeroModel(
'm600/m600_aswing_baseline_zero_angular_rate.json',
simple_aero_model, 1e-3, flap_offset=flap_offset)
# Maximum aerodynamic climb angle [rad] commanded by the
# longitudinal loop. This value is also used to provide a lower
# limit on the expected lift in lateral control.
max_aero_climb_angle_cmd = np.deg2rad(55.0)
# Compute the maximum CL.
max_delta_flap_cmd = np.deg2rad(10.0)
max_angle_of_attack_cmd = np.deg2rad(1.0)
# TODO: Consider whether trans-in should use the dCL_dflap that was
# added to the simple aero model.
CL_max = (simple_aero_model['CL_0']
+ controllers['dCL_dflap'] * max_delta_flap_cmd
+ simple_aero_model['dCL_dalpha'] * max_angle_of_attack_cmd)
# Calculate the angle [rad] between the body x-axis and the total
# thrust line.
thrust_axis_b = np.zeros((3,))
for i in range(len(params['rotors'])):
thrust_axis_b += params['rotors'][i]['axis']
thrust_axis_b /= len(params['rotors'])
assert thrust_axis_b[1] == 0.0
thrust_pitch = np.arctan2(-thrust_axis_b[2], thrust_axis_b[0])
return {
# Airspeed bias [m/s] and thresholds [m/s] for handling propeller inflow.
#
# We subtract a bias from the airspeed measurement to account for the
# effect of propeller inflow on the Pitot sensor.
'prop_inflow_airspeed_bias': 1.4,
'prop_inflow_low_airspeed': 20.0,
'prop_inflow_high_airspeed': 50.0,
# X position [m] at which to start an early turn.
'turn_start_pos_ti_x': -params['tether']['length'] * np.cos(np.pi/ 4.0),
# Turning radius [m] for the early turn.
'turn_radius': 200.0,
# Course angle [rad] at which to resume straight flight.
'turn_course_angle': -np.pi / 6.0,
'mode': {
# Minimum estimated dynamic pressure [Pa] before starting trans-in.
# TODO: This value sets a minimum airspeed above which
# we can reasonably trust the Pitot pressure sensors.
#
# This threshold was reduced to avoid entering trans-out.
'min_dynamic_pressure': 30.0,
# Minimum time [s] spent in kFlightModeHoverAccel before a
# transition is allowed.
'min_time_in_accel': 2.5,
# Measured acceleration [m/s^2] threshold and time to keep
# accelerating [s]. Transition to kFlightModeTransIn
# requires the measured specific force to drop below this
# value or for max_time_keep_accelerating time to elapse.
'acc_stopped_accelerating_threshold': params['phys']['g'] * 1.05,
'max_time_keep_accelerating': 5.0,
# Minimum pitch angle [rad] before forcing a transition from
# kFlightModeHoverAccel to kFlightModeTransIn.
'min_pitch_angle': -0.5
},
'longitudinal': {
# Aerodynamic climb angle limits [rad].
'min_aero_climb_angle_cmd': np.deg2rad(-10.0),
'max_aero_climb_angle_cmd': max_aero_climb_angle_cmd,
# Angle [rad] between the body x-axis and the thrust line.
'thrust_pitch': thrust_pitch,
# Minimum airspeed [m/s]. Below this airspeed, a linear
# gain is applied to pitch the kite forward.
#
# TODO: This should be a dynamic pressure.
'min_airspeed': 24.5,
# Natural frequency [Hz] for the position loop.
'radial_tracking_freq_hz': 0.1,
# Damping ratio for the radial tracking loop.
'radial_tracking_damping_ratio': 1.25,
# Threshold [m] on the radial error below which additional
# normal force is applied to establish tension.
'tension_control_radial_error_threshold': 20.0,
# Threshold [rad] on the elevation angle above which additional
# normal force is applied to establish tension.
'tension_control_elevation_angle_threshold': 0.7,
# Desired tension [N] on the tether sphere.
'min_tension_cmd': 6000.0,
# Zero angle-of-attack lift coefficient [#], lift slope
# [#/rad] with respect to change in angle-of-attack and flap
# commands.
'CL_0': simple_aero_model['CL_0'],
'dCL_dalpha': simple_aero_model['dCL_dalpha'],
'dCL_dflap': controllers['dCL_dflap'],
# Minimum and maximum delta flap command [rad].
'min_delta_flap_cmd': np.deg2rad(-10.0),
'max_delta_flap_cmd': max_delta_flap_cmd,
# Minimum and maximum angle-of-attack command [rad].
'min_angle_of_attack_cmd': np.deg2rad(-6.0),
'max_angle_of_attack_cmd': max_angle_of_attack_cmd,
# Maximum absolute feed-forward pitch rate [rad/s] to be commanded.
'max_pitch_rate_b_cmd': 0.5,
# Maximum thrust [N].
#
# This thrust command attempts to saturate thrust assuming
# Rev3 propellers, an 800 N-m torque limit, a per-motor
# power limit of 108 kW and a total aerodynamic power limit
# of 730 kW.
'thrust_cmd': 28000.0,
},
'lateral': {
# | Maximum expected lift coefficient [#].
'CL_max': CL_max,
'max_aero_climb_angle': max_aero_climb_angle_cmd,
# Reference length [m] for the lateral tracking loop.
#
| # The desired lateral tracking bandwidth is given by
# airspeed / (2.0 * pi * lateral_tracking_ref_length).
'lateral_tracking_ref_length': 150.0,
# Maximum bandwidth [Hz] for the lateral tracking loop.
'max_lateral_tracking_freq_hz': 0.035,
# Damping ratio [#] for the desired wing lateral position
# response.
'lateral_tracking_damping_ratio': 0.5,
# Maximum lateral position error [m].
'max_pos_ti_y_err': 30.0,
# Maximum feed-forward yaw-rate [rad/s] that can be commanded.
'max_yaw_rate_ti_cmd': 0.3,
# Maximum absolute roll angle command [rad].
'max_delta_roll_ti_cmd': 0.3,
# Trim angle-of-sideslip, roll angle and yaw angle [rad] in
# the transition-in frame.
'angle_of_sideslip_cmd': controllers['angle_of_sideslip_cmd'],
'roll_ti_cmd': controllers['roll_ti_cmd'],
'yaw_ti_cmd': controllers['yaw_ti_cmd']
},
'attitude': {
# Minimum feed-forward pitch moment [N-m] to carry-over from
# the final kFlightModeHoverAccel commands. The upper bound
|
liyao001/BioQueue | worker/ml_collector.py | Python | apache-2.0 | 3,685 | 0.002171 | #!/usr/local/bin python
from __future__ import print_function
import psutil
import time
import getopt
import sys
import django_initial
from QueueDB.models import Training
vrt_mem_list = []
mem_list = []
cpu_list = []
read_list = []
write_list = []
def get_mem(pid):
running_process = psutil.Process(pid)
if running_process.is_running():
mem = running_process.memory_info()
return mem[0], mem[1]
else:
return 0, 0
def get_cpu(pid):
running_process = psutil.Process(pid)
if running_process.is_running():
cpu = running_process.cpu_percent(interval=1)
return cpu
else:
return 0
def get_io(pid):
running_process = psutil.Process(pid)
if running_process.is_running():
io = running_process.io_counters()
return io[2], io[3]
else:
return 0
def get_cpu_mem(cpu_list, mem_list, virt_mem_list):
"""
Get CPU and memory usage
:param cpu_list: list, cpu usage info
:param mem_list: list, memory usage info
:return: tuple, cpu_usage and mem_usage
"""
if len(mem_list) > 0:
mem_usage = max(mem_list)
else:
mem_usage = -1
if len(virt_mem_list) > 0:
virt_mem_usage = max(virt_mem_list)
else:
virt_mem_usage = -1
if len(cpu_list) > 2:
samples = int(round(len(cpu_list) * 0.5))
cpu_list.sort(reverse=True)
cpu_usage = sum(cpu_list[0:samples]) / samples
elif len(cpu_list) > 0:
cpu_usage = sum(cpu_list) / len(cpu_list)
else:
cpu_usage = -1
return cpu_usage, mem_usage, virt_mem_usage
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "n:p:j:", ["protocolStep=", "pid=", "job_id="])
except getopt.GetoptError as err:
print(str(err))
sys.exit()
if len(opts) == 0:
sys.exit()
step_hash = ''
process_id = 0
job_id = 0
for o, a in opts:
if o in ("-n", "--protocolStep"):
step_hash = a
elif o in ("-p", "--pid"):
process_id = int(a)
elif o in ("-j", "--job_id"):
job_id = int(a)
if step_hash != '' and process_id != 0:
while True:
if process_id in psutil.pids():
process_info = psutil.Process(process_id)
if process_info.is_running():
try:
total_memory_usage, vrt = get_mem(proce | ss_id)
| total_cpu_usage = get_cpu(process_id)
children = process_info.children()
for child in children:
t1, t2 = get_mem(child.pid)
total_memory_usage += t1
vrt += t2
total_cpu_usage += get_cpu(child.pid)
mem_list.append(total_memory_usage)
vrt_mem_list.append(vrt)
cpu_list.append(total_cpu_usage)
time.sleep(30)
except Exception as e:
print(e)
break
else:
break
else:
break
cpu_usage, mem_usage, vrt_mem_usage = get_cpu_mem(cpu_list, mem_list, vrt_mem_list)
try:
training_item = Training.objects.get(id=job_id)
training_item.mem = mem_usage
training_item.vrt_mem = vrt_mem_usage
training_item.cpu = cpu_usage
training_item.save()
except:
pass
else:
sys.exit()
if __name__ == '__main__':
main()
|
saltstack/salt | salt/client/ssh/client.py | Python | apache-2.0 | 8,181 | 0.000733 | import copy
import logging
import os
import random
import salt.client.ssh
import salt.config
import salt.syspaths
import salt.utils.args
from salt.exceptions import SaltClientError
log = logging.getLogger(__name__)
class SSHClient:
"""
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
"""
def __init__(
self,
c_path=os.path.join(salt.syspaths.CONFIG_DIR, "master"),
mopts=None,
disable_custom_roster=False,
):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
"%s expects a file path not a directory path(%s) to "
"its 'c_path' keyword argument",
self.__class__.__name__,
c_path,
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts["__disable_custom_roster"] = disable_custom_roster
def sanitize_kwargs(self, kwargs):
roster_vals = [
("host", str),
("ssh_user", str),
("ssh_passwd", str),
("ssh_port", int),
("ssh_sudo", bool),
("ssh_sudo_user", str),
("ssh_priv", str),
("ssh_priv_passwd", str),
("ssh_identities_only", bool),
("ssh_remote_port_forwards", str),
("ssh_options", list),
("ssh_max_procs", int),
("ssh_askpass", bool),
("ssh_key_deploy", bool),
("ssh_update_roster", bool),
("ssh_scan_ports", str),
("ssh_scan_timeout", int),
("ssh_timeout", int),
("ssh_log_file", str),
("raw_shell", bool),
("refresh_cache", bool),
("roster", str),
("roster_file", str),
("rosters", list),
("ignore_host_keys", bool),
("raw_shell", bool),
("extra_filerefs", str),
("min_extra_mods", str),
("thin_extra_mods", str),
("verbose", bool),
("static", bool),
("ssh_wipe", bool),
("rand_thin_dir", bool),
("regen_thin", bool),
("ssh_run_pre_flight", bool),
("no_host_keys", bool),
("saltfile", str),
]
sane_kwargs = {}
for name, kind in roster_vals:
if name not in kwargs:
continue
try:
val = kind(kwargs[name])
except ValueError:
log.warning("Unable to cast kwarg %s", name)
continue
if kind is bool or kind is int:
sane_kwargs[name] = val
elif kind is str:
if val.find("ProxyCommand") != -1:
log.warning("Filter unsafe value for kwarg %s", name)
continue
sane_kwargs[name] = val
elif kind is list:
sane_val = []
for item in val:
# This assumes the values are strings
if item.find("ProxyCommand") != -1:
log.warning("Filter unsafe value for kwarg %s", name)
continue
sane_val.append(item)
sane_kwargs[name] = sane_val
return sane_kwargs
def _prep_ssh(
self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs
):
"""
Prepare the arguments
"""
kwargs = self.sanitize_kwargs(kwargs)
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts["timeout"] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts["argv"] = [fun] + arg
opts["selected_target_option"] = tgt_type
opts["tgt"] = tgt
opts["arg"] = arg
return salt.client.ssh.SSH(opts)
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type="glob",
ret="",
kwarg=None,
**kwargs
):
"""
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
"""
ssh = self._prep_ssh(tgt, fun, arg, timeout, tgt_type, kwarg, **kwargs)
yield from ssh.run_iter(jid=kwargs.get("jid", None))
def cmd(
self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs
):
"""
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
"""
ssh = self._prep_ssh(tgt, fun, arg, timeout, tgt_type, kwarg, **kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get("jid", None)):
final.update(ret)
return final
def cmd_sync(self, low):
"""
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
"""
kwargs = copy.deepcopy(low)
for ignore in ["tgt", "fun", "arg", "timeout", "tgt_type", "kwarg"]:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(
low["tgt"],
low["fun"],
low.get("arg", []),
low.get("timeout"),
low.get("tgt_type"),
low.get("kwarg"),
**kwargs
)
def cmd_async(self, low, timeout=None):
"""
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
"""
# TODO Not implemented
raise SaltClientError
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type="glob",
ret="",
kwarg=None,
subset=3,
**kwargs
):
"""
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param subset: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', subset=1)
{'jerry': True}
.. versionadded:: 2017.7.0
"""
minion_ret = self.cmd(tgt, "sys.list_functions", tgt_type=tgt_type, **kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]["return"]:
f_tgt.append(minion)
if len(f_tgt) >= subset:
| break
return self.cmd_iter(
f_tgt, fun, arg, timeout, tgt_type="list", ret=ret, kwarg=kwarg, **kwargs
)
def destroy(self):
| """
API compatibility method with salt.client.LocalClient
"""
def __enter__(self):
"""
API compatibility method with salt.client.LocalClient
"""
return self
def __exit__(self, *args):
"""
API compatibility method with salt.client.LocalClient
"""
self.destroy() |
mosra/m.css | documentation/test_python/inspect_recursive/inspect_recursive/second.py | Python | mit | 358 | 0 | """Second module, imported as inspect_recursive.a, with no contents"""
i | mport inspect_recursive.first as a
import sys
if sys.version_info >= (3, 7):
# For some reason 3.6 says second doesn't exist yet. I get that, it's a
| # cyclic reference, but that works in 3.7.
import inspect_recursive.second as b
from inspect_recursive import Foo as Bar
|
CVL-dev/cvl-fabric-launcher | LauncherOptionsDialog.py | Python | gpl-3.0 | 4,921 | 0.013818 | import wx
import sys
import IconPys.MASSIVElogoTransparent64x64
class LauncherOptionsDialog(wx.Dialog):
def __init__(self, parent, message, title, ButtonLabels=['OK'],onHelp=None,helpEmailAddress="help@massive.org.au",**kw):
wx.Dialog.__init__(self, parent, style=wx.DEFAULT_DIALOG_STYLE, **kw)
if parent!=None:
self.CenterOnParent()
else:
self.Centre()
self.helpEmailAddress = helpEmailAddress
if not sys.platform.startswith("darwin"):
self.SetTitle(title)
if sys.platform.startswith("win"):
_icon = wx.Icon('MASSIVE.ico', wx.BITMAP_TYPE_ICO)
self.SetIcon(_icon)
elif sys.platform.startswith("linux"):
import MASSIVE_icon
self.SetIcon(MASSIVE_icon.getMASSIVElogoTransparent128x128Icon())
self.dialogPanel = wx.Panel(self, wx.ID_ANY)
self.dialogPanel.SetSizer(wx.FlexGridSizer(cols=2,rows=2))
#self.dialogPanel.SetSizer(wx.BoxSizer(wx.VERTICAL))
self.ButtonLabels=ButtonLabels
self.onHelp=onHelp
iconAsBitmap = IconPys.MASSIVElogoTransparent64x64.getMASSIVElogoTransparent64x64Bitmap()
self.iconBitmap = wx.S | taticBitmap(self.dialogPanel, wx.ID_ANY, iconAsBitmap, pos=(25,15), size=(64,64))
smallFont = wx.Syst | emSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
if sys.platform.startswith("darwin"):
smallFont.SetPointSize(11)
self.messagePanel = wx.Panel(self.dialogPanel)
if sys.platform.startswith("darwin"):
self.messagePanel.SetSizer(wx.FlexGridSizer(cols=1,rows=2))
self.titleLabel = wx.StaticText(self.messagePanel, wx.ID_ANY, title)
titleFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
titleFont.SetWeight(wx.BOLD)
titleFont.SetPointSize(13)
self.titleLabel.SetFont(titleFont)
self.messagePanel.GetSizer().Add(self.titleLabel,flag=wx.BOTTOM,border=10)
else:
self.messagePanel.SetSizer(wx.FlexGridSizer(cols=1,rows=1))
messageWidth = 330
self.messageLabel = wx.StaticText(self.messagePanel, wx.ID_ANY, message)
self.messageLabel.SetForegroundColour((0,0,0))
self.messageLabel.SetFont(smallFont)
self.messageLabel.Wrap(messageWidth)
self.messagePanel.GetSizer().Add(self.messageLabel)
contactPanel = wx.Panel(self.dialogPanel)
contactPanel.SetSizer(wx.BoxSizer(wx.VERTICAL))
contactQueriesContactLabel = wx.StaticText(contactPanel, label = "For queries, please contact:")
contactQueriesContactLabel.SetFont(smallFont)
contactQueriesContactLabel.SetForegroundColour(wx.Colour(0,0,0))
contactPanel.GetSizer().Add(contactQueriesContactLabel)
contactEmailHyperlink = wx.HyperlinkCtrl(contactPanel, id = wx.ID_ANY, label = self.helpEmailAddress, url = "mailto:"+self.helpEmailAddress)
contactEmailHyperlink.SetFont(smallFont)
#hyperlinkPosition = wx.Point(self.contactQueriesContactLabel.GetPosition().x+self.contactQueriesContactLabel.GetSize().width+10,okButtonPosition.y)
#hyperlinkPosition = wx.Point(self.contactQueriesContactLabel.GetPosition().x+self.contactQueriesContactLabel.GetSize().width,buttonPosition.y)
#self.contactEmailHyperlink.SetPosition(hyperlinkPosition)
contactPanel.GetSizer().Add(contactEmailHyperlink)
contactPanel.Fit()
buttonPanel = wx.Panel(self.dialogPanel,wx.ID_ANY)
buttonPanel.SetSizer(wx.BoxSizer(wx.HORIZONTAL))
for label in ButtonLabels:
b = wx.Button(buttonPanel, wx.ID_ANY, label)
b.SetDefault()
b.Bind(wx.EVT_BUTTON,self.onClose)
buttonPanel.GetSizer().Add(b,flag=wx.ALL,border=5)
if self.onHelp is not None:
b = wx.Button(buttonPanel, wx.ID_ANY, 'Help')
b.Bind(wx.EVT_BUTTON,self.onHelp)
buttonPanel.GetSizer().Add(b,flag=wx.ALL,border=5)
buttonPanel.Fit()
self.dialogPanel.GetSizer().Add(self.iconBitmap,flag=wx.ALL,border=15)
self.dialogPanel.GetSizer().Add(self.messagePanel,flag=wx.ALL,border=15)
self.dialogPanel.GetSizer().Add(contactPanel,flag=wx.ALL,border=15)
self.dialogPanel.GetSizer().Add(buttonPanel,flag=wx.ALL,border=15)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.dialogPanel.Fit()
#self.SetClientSize(wx.Size(dialogPanelWidth,dialogPanelHeight))
self.Layout()
self.Fit()
def onClose(self, event):
obj=event.GetEventObject()
if (isinstance(obj,wx.Button)):
label=obj.GetLabel()
ln=0
for i in self.ButtonLabels:
if (label==i):
self.EndModal(ln)
else:
ln=ln+1
else:
self.EndModal(-1)
|
jxta/cc | vendor/boto/boto/ec2/keypair.py | Python | apache-2.0 | 4,210 | 0.0019 | # Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Keypair
"""
import os
from boto.ec2.ec2object import EC2Object
from boto.exception import BotoClientError
class KeyPair(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.name = None
self.fingerprint = None
self.material = None
def __repr__(self):
return 'KeyPair:%s' % self.name
def endElement(self, name, value, connection):
if name == 'keyName':
self.name = value
elif name == 'keyFingerprint':
self.fingerprint = value
elif name == 'keyMaterial':
self.material = value
else:
setattr(self, name, value)
def delete(self):
"""
Delete the KeyPair.
:rtype: bool
:return: True if successful, otherwise False.
"""
return self.connection.delete_key_pair(self.name)
def save(self, directory_path):
"""
Save the material (the unencrypted PEM encoded RSA private key)
of a newly created KeyPair to a local file.
:type directory_path: string
:param directory_path: The fully qualified path to the directory
in which the keypair will be saved. The
keypair file will be named using the name
of the keypair as the base name and .pem
for the fil | e extension. If a file of that
name already exists in the directory, an
exception will be raised and the old file
will not be overwritten.
:rtype: bool
:return: True if successful.
"""
if self.material:
file_path = os.path.join(directory_path, '%s.pem' % self.name)
if os.path.exists( | file_path):
raise BotoClientError('%s already exists, it will not be overwritten' % file_path)
fp = open(file_path, 'wb')
fp.write(self.material)
fp.close()
return True
else:
raise BotoClientError('KeyPair contains no material')
def copy_to_region(self, region):
"""
Create a new key pair of the same new in another region.
Note that the new key pair will use a different ssh
cert than the this key pair. After doing the copy,
you will need to save the material associated with the
new key pair (use the save method) to a local file.
:type region: :class:`boto.ec2.regioninfo.RegionInfo`
:param region: The region to which this security group will be copied.
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The new key pair
"""
if region.name == self.region:
raise BotoClientError('Unable to copy to the same Region')
conn_params = self.connection.get_params()
rconn = region.connect(**conn_params)
kp = rconn.create_key_pair(self.name)
return kp
|
j-carl/ansible | lib/ansible/parsing/mod_args.py | Python | gpl-3.0 | 13,925 | 0.002226 | # (c) 2014 Michael DeHaan, <michael@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ansible.constants as C
from ansible.errors import AnsibleParserError, AnsibleError, AnsibleAssertionError
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils._text import to_text
from ansible.parsing.splitter import parse_kv, split_args
from ansible.plugins.loader import module_loader, action_loader
from ansible.template import Templar
from ansible.utils.sentinel import Sentinel
# For filtering out modules correctly below
FREEFORM_ACTIONS = frozenset(C.MODULE_REQUIRE_ARGS)
RAW_PARAM_MODULES = FREEFORM_ACTIONS.union((
'include',
'include_vars',
'include_tasks',
'include_role',
'import_tasks',
'import_role',
'add_host',
'group_by',
'set_fact',
'meta',
))
BUILTIN_TASKS = frozenset((
'meta',
'include',
'include_tasks',
'include_role',
'import_tasks',
'import_role'
))
class ModuleArgsParser:
"""
There are several ways a module and argument set can be expressed:
# legacy form (for a shell command)
- action: shell echo hi
# common shorthand for local actions vs delegate_to
- local_action: shell echo hi
# most commonly:
- copy: src=a dest=b
# legacy form
- action: copy src=a dest=b
# complex args form, for passing structured data
- copy:
src: a
dest: b
# gross, but technically legal
- action:
module: copy
args:
src: a
dest: b
# Standard YAML form for command-type modules. In this case, the args specified
# will act as 'defaults' and will be overridden by any args specified
# in one of the other formats (complex args under the action, or
# parsed from the k=v string
- command: 'pwd'
args:
chdir: '/tmp'
This class has some of the logic to canonicalize these into the form
- module: <module_name>
delegate_to: <optional>
args: <args>
Args may also be munged for certain shell command parameters.
"""
def __init__(self, task_ds=None, collection_list=None):
task_ds = {} if task_ds is None else task_ds
if not isinstance(task_ds, dict):
raise AnsibleAssertionError("the type of 'task_ds' should be a dict, but is a %s" % type(task_ds))
self._task_ds = task_ds
self._collection_list = collection_list
# delayed local imports to prevent circular import
from ansible.playbook.task import Task
from ansible.playbook.handler import Handler
# store the valid Task/Handler attrs for quick access
self._task_attrs = set(Task._valid_attrs.keys())
self._task_attrs.update(set(Handler._valid_attrs.keys()))
# HACK: why are these not FieldAttributes on task with a post-validate to check usage?
self._task_attrs.update(['local_action', 'static'])
self._task_attrs = frozenset(self._task_attrs)
self.internal_redirect_list = []
def _split_module_string(self, module_string):
'''
when module names are expressed like:
action: copy src=a dest=b
the first part of the string is the name of the module
and the rest are strings pertaining to the arguments.
'''
tokens = split_args(module_string)
if len(tokens) > 1:
return (tokens[0].strip(), " ".join(tokens[1:]))
else:
return (tokens[0].strip(), "")
def _normalize_parameters(self, thing, action=None, additional_args=None):
'''
arguments can be fuzzy. Deal with all the forms.
'''
additional_args = {} if additional_args is None else additional_args
# final args are the ones we'll eventually return, so first update
# them with any additional args specified, which have lower priority
# than those which may be parsed/normalized next
final_args = dict()
if additional_args:
if isinstance(additional_args, string_types):
templar = Templar(loader=None)
if templar.is_template(additional_args):
final_args['_variable_params'] = additional_args
else:
raise AnsibleParserError("Complex args containing variables cannot use bare variables (without Jinja2 delimiters), "
"and must use the full variable style ('{{var_name}}')")
elif isinstance(additional_args, dict):
final_args.update(additional_args)
else:
raise AnsibleParserError('Complex args must be a dictionary or variable string ("{{var}}").')
# how we normalize depends if we figured out what | the module name is
# yet. If we have already figured it out, it's a 'new style' invocation.
# ot | herwise, it's not
if action is not None:
args = self._normalize_new_style_args(thing, action)
else:
(action, args) = self._normalize_old_style_args(thing)
# this can occasionally happen, simplify
if args and 'args' in args:
tmp_args = args.pop('args')
if isinstance(tmp_args, string_types):
tmp_args = parse_kv(tmp_args)
args.update(tmp_args)
# only internal variables can start with an underscore, so
# we don't allow users to set them directly in arguments
if args and action not in FREEFORM_ACTIONS:
for arg in args:
arg = to_text(arg)
if arg.startswith('_ansible_'):
raise AnsibleError("invalid parameter specified for action '%s': '%s'" % (action, arg))
# finally, update the args we're going to return with the ones
# which were normalized above
if args:
final_args.update(args)
return (action, final_args)
def _normalize_new_style_args(self, thing, action):
'''
deals with fuzziness in new style module invocations
accepting key=value pairs and dictionaries, and returns
a dictionary of arguments
possible example inputs:
'echo hi', 'shell'
{'region': 'xyz'}, 'ec2'
standardized outputs like:
{ _raw_params: 'echo hi', _uses_shell: True }
'''
if isinstance(thing, dict):
# form is like: { xyz: { x: 2, y: 3 } }
args = thing
elif isinstance(thing, string_types):
# form is like: copy: src=a dest=b
check_raw = action in FREEFORM_ACTIONS
args = parse_kv(thing, check_raw=check_raw)
elif thing is None:
# this can happen with modules which take no params, like ping:
args = None
else:
raise AnsibleParserError("unexpected parameter type in action: %s" % type(thing), obj=self._task_ds)
return args
def _normalize_old_style_args(self, thing):
'''
deals with fuzziness in old-style (action/local_action) module invocations
returns tuple of (module_name, dictionary_args)
possible example inputs:
{ 'shell' : 'echo hi' }
'shell echo hi'
{'module': 'ec2', 'x': 1 }
standardized outputs like:
('ec2', { 'x': 1} )
'''
acti |
mfrasca/bauble.classic | bauble/meta.py | Python | gpl-2.0 | 2,702 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2005,2006,2007,2008,2009 Brett Adams <brett@belizebotanic.org>
# Copyright (c) 2012-2015 Mario Frasca <mario@anche.no>
#
# This file is part of bauble.classic.
#
# bauble.classic is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lic | ense as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# bauble.classic 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 bauble.classic. If not, see <http://www.gnu.org/licenses/>.
#
# meta.py
#
from sqlalchemy import Unicode, UnicodeText, Column
import bauble.db as db
import bauble.utils as utils
VERSION_KEY = u'version'
CREATED_KEY = u'created'
REGISTRY_KEY = u'registry'
# date format strings:
# yy - short year
# yyyy - long year
# dd - number day, always two digits
# d - number day, two digits when necessary
# mm -number month, always two digits
# m - number month, two digits when necessary
DATE_FORMAT_KEY = u'date_format'
def get_default(name, default=None, session=None):
"""
Get a BaubleMeta object with name. If the default value is not
None then a BaubleMeta object is returned with name and the
default value given.
If a session instance is passed (session != None) then we
don't commit the session.
"""
commit = False
if not session:
session = db.Session()
commit = True
query = session.query(BaubleMeta)
meta = query.filter_by(name=name).first()
if not meta and default is not None:
meta = BaubleMeta(name=utils.utf8(name), value=default)
session.add(meta)
if commit:
session.commit()
# load the properties so that we can close the session and
# avoid getting errors when accessing the properties on the
# returned meta
meta.value
meta.name
if commit:
# close the session whether we added anything or not
session.close()
return meta
class BaubleMeta(db.Base):
"""
The BaubleMeta class is used to set and retrieve meta information
based on key/name values from the bauble meta table.
:Table name: bauble
:Columns:
*name*:
The name of the data.
*value*:
The value.
"""
__tablename__ = 'bauble'
name = Column(Unicode(64), unique=True)
value = Column(UnicodeText)
|
koditr/xbmc-tr-team-turkish-addons | plugin.video.hintfilmkeyfi/xbmctools.py | Python | gpl-2.0 | 3,303 | 0.038147 | # -*- coding: iso8859-9 -*-
import urllib2,urllib,re,HTMLParser,cookielib
import sys,os,base64,time
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urlresolver,json
__settings__ = xbmcaddon.Addon(id="plugin.video.hintfilmkeyfi")
#----------------------------------------------------------------------
xbmcPlayer = xbmc.Player()
playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
def name_prepare(videoTitle):
print 'DUZELTME ONCESI:',videoTitle
videoTitle=videoTitle.replace('Ýzle',"").replace('Türkçe',"").replace('Turkce',"").replace('Dublaj',"|TR|").replace('Altyazýlý'," [ ALTYAZILI ] ").replace('izle',"").replace('Full',"").replace('720p',"").replace('HD',"")
return videoTitle
def get_url(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
response = urllib2.urlopen(req)
link=response.read()
link=link.replace('\xFD',"i").replace('''',"\"").replace(''',"\'").replace('\xf6',"o").replace('&',"&").replace('\xd6',"O").replace('\xfc',"u").replace('\xdd',"I").replace('\xfd',"i").replace('\xe7',"c").replace('\xde',"s").replace('\xfe',"s").replace('\xc7',"c").replace('\xf0',"g")
link=link.replace('\xc5\x9f',"s").replace('&',"&").replace('’',"'").replace('\xc3\xbc',"u").replace('\xc3\x87',"C").replace('\xc4\xb1',"ý").replace('–',"-").replace('\xc3\xa7',"c").replace('\xc3\x96',"O").replace('\xc5\x9e',"S").replace('\xc3\xb6',"o").replace('\xc4\x9f',"g").replace('\xc4\xb0',"I").replace('\xe2\x80\x93',"-")
response.close()
return link
def addLink(name,url,iconimage):
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name } )
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
return ok
def addDir(name,url,mode,iconimage):
u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name } )
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
def magix_player(name,url):
UrlResolverPlayer = url
playList.clear()
media = urlresolver.HostedMediaFile(UrlResolverPlayer)
source = media
if source:
ur | l = source.resolve()
addLink(name,url,'')
playlist_yap(playList,name,url)
xbmcPlayer.play(playList)
def playlist_yap(playList,name,url):
listitem = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnail | Image="")
listitem.setInfo('video', {'name': name } )
playList.add(url,listitem=listitem)
return playList
def yeni4(name,url):
xbmcPlayer = xbmc.Player()
playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
playList.clear()
addLink(name,url,'')
listitem = xbmcgui.ListItem(name)
playList.add(url, listitem)
xbmcPlayer.play(playList)
|
aubreyrjones/libesp | scons_local/scons-local-2.3.0/SCons/Tool/f77.py | Python | mit | 2,068 | 0.003385 | """engine.SCons.Tool.f77
Tool-specific initialization for the generic Posix f77 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, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (t | he
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, mer | ge, 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/f77.py 2013/03/03 09:48:35 garyo"
import SCons.Defaults
import SCons.Scanner.Fortran
import SCons.Tool
import SCons.Util
from SCons.Tool.FortranCommon import add_all_to_env, add_f77_to_env
compilers = ['f77']
def generate(env):
add_all_to_env(env)
add_f77_to_env(env)
fcomp = env.Detect(compilers) or 'f77'
env['F77'] = fcomp
env['SHF77'] = 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:
|
akrherz/iem | htdocs/plotting/auto/scripts/p18.py | Python | mit | 7,957 | 0 | """Time series plot."""
import datetime
import pytz
import psycopg2.extras
import numpy as np
import pandas as pd
from pyiem.plot import figure_axes
from pyiem.util import get_autoplot_context, get_sqlalchemy_conn, get_dbconn
from pyiem.exceptions import NoDataFound
MDICT = dict(
[
("tmpf", "Air Temperature"),
("dwpf", "Dew Point Temperature"),
("feel", "Feels Like Temperature"),
("alti", "Pressure Altimeter"),
("relh", "Relative Humidity"),
("mslp", "Sea Level Pressure"),
]
)
UNITS = {
"tmpf": "°F",
"dwpf": "°F",
"alti": "inch",
"mslp": "mb",
"feel": "°F",
"relh": "%",
}
def get_description():
"""Return a dict describing how to call this plotter"""
desc = {}
ts = datetime.date.today() - datetime.timedelta(days=365)
desc["data"] = True
desc[
"description"
] = """This chart displays a simple time series of
an observed variable for a location of your choice. For sites in the
US, the daily high and low temperature climatology is presented as a
filled bar for each day plotted when Air Temperature is selected."""
desc["arguments"] = [
dict(
type="zstation",
name="zstation",
default="AMW",
network="IA_ASOS",
label="Select Station:",
),
dict(
type="date",
name="sdate",
default=ts.strftime("%Y/%m/%d"),
label="Start Date of Plot:",
min="1951/01/01",
), # Comes back to python as yyyy-mm-dd
dict(type="int", name="days", default="365", label="Days to Plot"),
dict(
type="select",
name="var",
options=MDICT,
default="tmpf",
label="Variable to Plot",
),
]
return desc
def highcharts(fdict):
"""Highcharts output"""
ctx = get_data(fdict)
ranges = []
now = ctx["sdate"]
oneday = datetime.timedelta(days=1)
while ctx["climo"] is not None and (now - oneday) <= ctx["edate"]:
ranges.append(
[
int(now.strftime("%s")) * 1000.0,
ctx["climo"][now.strftime("%m%d")]["low"],
ctx["clim | o"][now.strftime("%m%d")]["high"],
]
)
now += oneday
j = {}
j["title"] = dict(
text=("[%s] %s Time Series")
% (ctx["station"], ctx["_nt"].sts[ctx["station"]]["name"])
| )
j["xAxis"] = dict(type="datetime")
j["yAxis"] = dict(
title=dict(text="%s %s" % (MDICT[ctx["var"]], UNITS[ctx["var"]]))
)
j["tooltip"] = {
"crosshairs": True,
"shared": True,
"valueSuffix": " %s" % (UNITS[ctx["var"]],),
}
j["legend"] = {}
j["time"] = {"useUTC": False}
j["exporting"] = {"enabled": True}
j["chart"] = {"zoomType": "x"}
j["plotOptions"] = {"line": {"turboThreshold": 0}}
j["series"] = [
{
"name": MDICT[ctx["var"]],
"data": list(
zip(
ctx["df"].ticks.values.tolist(),
ctx["df"].datum.values.tolist(),
)
),
"zIndex": 2,
"color": "#FF0000",
"lineWidth": 2,
"marker": {"enabled": False},
"type": "line",
}
]
if ranges:
j["series"].append(
{
"name": "Climo Hi/Lo Range",
"data": ranges,
"type": "arearange",
"lineWidth": 0,
"color": "#ADD8E6",
"fillOpacity": 0.3,
"zIndex": 0,
}
)
if ctx["var"] in ["tmpf", "dwpf"]:
j["yAxis"]["plotLines"] = [
{
"value": 32,
"width": 2,
"zIndex": 1,
"color": "#000",
"label": {"text": "32°F"},
}
]
return j
def get_data(fdict):
"""Get data common to both methods"""
ctx = get_autoplot_context(fdict, get_description())
coop_pgconn = get_dbconn("coop")
ccursor = coop_pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
ctx["station"] = ctx["zstation"]
sdate = ctx["sdate"]
days = ctx["days"]
ctx["edate"] = sdate + datetime.timedelta(days=days)
today = datetime.date.today()
if ctx["edate"] > today:
ctx["edate"] = today
ctx["days"] = (ctx["edate"] - sdate).days
ctx["climo"] = None
if ctx["var"] == "tmpf":
ctx["climo"] = {}
ccursor.execute(
"SELECT valid, high, low from ncei_climate91 where station = %s",
(ctx["_nt"].sts[ctx["station"]]["ncei91"],),
)
for row in ccursor:
ctx["climo"][row[0].strftime("%m%d")] = dict(
high=row[1], low=row[2]
)
col = "tmpf::int" if ctx["var"] == "tmpf" else ctx["var"]
col = "dwpf::int" if ctx["var"] == "dwpf" else col
with get_sqlalchemy_conn("asos") as conn:
ctx["df"] = pd.read_sql(
"SELECT valid at time zone 'UTC' as valid, "
f"extract(epoch from valid) * 1000 as ticks, {col} as datum "
"from alldata WHERE station = %s and valid > %s and valid < %s "
f"and {ctx['var']} is not null and report_type = 2 "
"ORDER by valid ASC",
conn,
params=(
ctx["station"],
sdate,
sdate + datetime.timedelta(days=days),
),
index_col="valid",
)
if ctx["df"].empty:
raise NoDataFound("No data found.")
return ctx
def plotter(fdict):
"""Go"""
ctx = get_data(fdict)
title = "%s [%s]\n%s Timeseries %s - %s" % (
ctx["_nt"].sts[ctx["station"]]["name"],
ctx["station"],
MDICT[ctx["var"]],
ctx["sdate"].strftime("%d %b %Y"),
ctx["edate"].strftime("%d %b %Y"),
)
(fig, ax) = figure_axes(title=title, apctx=ctx)
xticks = []
xticklabels = []
now = ctx["sdate"]
cdates = []
chighs = []
clows = []
oneday = datetime.timedelta(days=1)
while ctx["climo"] is not None and (now - oneday) <= ctx["edate"]:
cdates.append(now)
chighs.append(ctx["climo"][now.strftime("%m%d")]["high"])
clows.append(ctx["climo"][now.strftime("%m%d")]["low"])
if now.day == 1 or (now.day % 12 == 0 and ctx["days"] < 180):
xticks.append(now)
fmt = "%-d"
if now.day == 1:
fmt = "%-d\n%b"
xticklabels.append(now.strftime(fmt))
now += oneday
while (now - oneday) <= ctx["edate"]:
if now.day == 1 or (now.day % 12 == 0 and ctx["days"] < 180):
xticks.append(now)
fmt = "%-d"
if now.day == 1:
fmt = "%-d\n%b"
xticklabels.append(now.strftime(fmt))
now += oneday
if chighs:
chighs = np.array(chighs)
clows = np.array(clows)
ax.bar(
cdates,
chighs - clows,
bottom=clows,
width=1,
align="edge",
fc="lightblue",
ec="lightblue",
label="Daily Climatology",
)
# Construct a local timezone x axis
x = (
ctx["df"]
.index.tz_localize(pytz.UTC)
.tz_convert(ctx["_nt"].sts[ctx["station"]]["tzname"])
.tz_localize(None)
)
ax.plot(x.values, ctx["df"]["datum"], color="r", label="Hourly Obs")
ax.set_ylabel("%s %s" % (MDICT[ctx["var"]], UNITS[ctx["var"]]))
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)
ax.set_xlim(ctx["sdate"], ctx["edate"] + oneday)
ax.set_ylim(top=ctx["df"].datum.max() + 15.0)
ax.legend(loc=2, ncol=2)
ax.axhline(32, linestyle="-.")
ax.grid(True)
return fig, ctx["df"]
if __name__ == "__main__":
plotter({})
|
Nextdoor/rightscale_rightlink10_rightscripts | tasks.py | Python | mit | 6,904 | 0.000579 | import sys
import os
from os import walk, chdir
import fnmatch
from invoke import run, task, Collection
from colorama import init, Fore
import yaml
import numpy
PEP8_IGNORE = 'E402,E266,F841'
init()
# These things don't pass syntax/lint checks and are external deps.
EXCLUDE_DIRS = ['nextdoor/lib/python/kingpin',
'nextdoor/lib/shell/storage-scripts']
def find_files(pattern, excludes=[]):
"""
Recursive find of files matching pattern starting at location of this script.
Args:
pattern (str): filename pattern to match
excludes: array of patterns for to exclude from find
Returns:
array: list of matching files
"""
matches = []
DEBUG = False
for root, dirnames, filenames in walk(os.path.dirname(__file__)):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
# Oh, lcomp sytnax...
for exclude in excludes:
matches = numpy.asarray(
[match for match in matches if exclude not in match])
if DEBUG:
print(Fore.YELLOW + "Matches in find_files is : {}".format(str(matches)))
return matches
def handle_repo(repo):
"""
Given a dictionary representing our repo settings, download and checkout.
"""
# These things are all required even though some of them could
# be defaulted.
required_keys = ('type', 'source', 'ref', 'destination')
if not all(key in repo for key in required_keys):
print(Fore.RED + str(repo))
print(Fore.RED + "repo spec must include: {}".format(
str(required_keys)))
sys.exit(-1)
# For now, just git repos. But who knows...whatever comes after git?
if 'git' != repo['type']:
print(Fore.RED + str(repo))
print(Fore.RED + "repo type must be 'git'!")
sys.exit(-1)
# Rather than try to play clever games with any existing dep caches,
# blow away what is in place and replace with a fresh clone + checkout.
# 'prep' task is *meant* to run only rarely anyway.
dest = str(repo['destination'])
if os.path.exists(dest):
print(Fore.BLUE + "{} already exists; removing...".format(dest))
result = run("rm -rf {}".format(dest), echo=True)
if result.failed:
print(Fore.RED + "Failed while removing {}".format(dest))
sys.exit(-1)
try:
os.makedirs(dest)
except os.OSError as e:
print(Fore.RED + "Failed creating directory '{}'".format(dest))
print(str(e))
# Fresh clone and checkout of the repo but *not* a submodule or subtree.
# The dep is cleansed of .git directory.
source = repo['source']
ref = repo['ref']
result = run("git clone {} {} && "
"(cd {} && git checkout {}) && "
" rm -rf {}/.git".format(source, dest, dest, ref, dest),
echo=True)
if result.failed:
print(Fore.RED + "Failed checking out repo: {} / {} to '{}'!".format(
source, ref, dest))
sys.exit(-1)
# If he 'prep' key is present, run this command as a way of setting up
# the external dep.
if 'prep' in repo:
prep = str(repo['prep'])
print(Fore.BLUE + "Executing specified 'prep' command: {}".format(prep))
result = run(prep, echo=True)
if result.failed:
print(Fore.RED + "Failed while prepping!")
sys.exit(-1)
# If the 'persist' key is False, remove the directory after 'prep'
if 'persist' in repo and False is repo['persist']:
cmd = "rm -rf {}".format(dest)
result = run(cmd, echo=True)
if result.failed:
print(Fore.RED + "Failed while removing non-persisted repo!")
@task
def prep():
"""
Download and place external dependencies as a way to avoid
git submodules/subtrees. Would | be nice if librarian could be leveraged...
"""
newcwd = sys.path[0]
if '' != newcwd:
# I'm not sure this is absolutely necessary but to be careful...
print(Fore.GREEN + "Changing cwd to {}".format(newcwd))
chdi | r(sys.path[0])
else:
print(Fore.Red + "I am very confused about our sys.path[0] of ''!")
sys.exit(-1)
deps = {}
with open('external_dependencies.yml') as deps:
try:
deps = yaml.load(deps)
except yaml.YAMLError as e:
print(Fore.RED + str(e))
sys.exit(-1)
if 'repos' in deps:
for repo in deps['repos']:
chdir(sys.path[0])
handle_repo(deps['repos'][repo])
@task
def syntax():
"""
Recursively syntax check various files.
"""
print(Fore.GREEN + "Syntax checking of YAML files...")
yaml_files = find_files('*.yaml') + find_files('*.yml')
for yaml_file in yaml_files:
with open(yaml_file, 'r') as f:
print(Fore.WHITE + yaml_file)
try:
yaml.load(f)
except yaml.YAMLError as e:
print(Fore.RED + str(e))
print(Fore.GREEN + "Syntax checking of Python files...")
python_files = find_files('*.py', excludes=EXCLUDE_DIRS)
cmd = "python -m py_compile {}".format(' '.join(python_files))
result = run(cmd, echo=True)
print(Fore.GREEN + "Syntax checking of Ruby files...")
ruby_files = find_files('*.rb')
cmd = "ruby -c {}".format(' '.join(ruby_files))
result = run(cmd, echo=True)
# won't get here unless things run clean
print(Fore.GREEN + "Exit code: {}".format(result.return_code))
@task
def lint_check():
"""
Recursively lint check Python files in this project using flake8.
"""
print(Fore.GREEN + "Lint checking of Python files...")
python_files = find_files('*.py', excludes=EXCLUDE_DIRS)
cmd = "flake8 --count --statistics --show-source --show-pep8"\
" --max-line-length=160 --ignore={} {}".format(
PEP8_IGNORE, ' '.join(python_files))
result = run(cmd, echo=True)
# won't get here unless things run clean
print(Fore.GREEN + "Exit code: {}".format(result.return_code))
@task
def lint_fix():
"""
Recursively lint check **and fix** Python files in this project using autopep8.
"""
print(Fore.GREEN + "Lint fixing Python files...")
python_files = find_files('*.py', excludes=EXCLUDE_DIRS)
cmd = "autopep8 -r --in-place --ignore={} {}".format(
PEP8_IGNORE, ' '.join(python_files))
result = run(cmd, echo=True)
# won't get here unless things run clean
print(Fore.GREEN + "Exit code: {}".format(result.return_code))
@task(syntax, lint_check)
def test():
"""
Run syntax + lint check.
"""
pass
ns = Collection('')
lint = Collection('lint')
lint.add_task(lint_check, 'check')
lint.add_task(lint_fix, 'fix')
ns.add_collection(lint)
ns.add_task(prep, 'prep')
ns.add_task(test, 'test')
ns.add_task(syntax, 'syntax')
|
zwChan/VATEC | ~/eb-virt/Lib/site-packages/pip/_vendor/requests/packages/urllib3/poolmanager.py | Python | apache-2.0 | 9,614 | 0.000312 | from __future__ import absolute_import
import logging
try: # Python 3
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from .connectionpool import port_by_scheme
from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown
from .request import RequestMethods
from .util.url import parse_url
from .util.retry import Retry
__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
log = logging.getLogger(__name__)
SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
'ssl_version', 'ca_cert_dir')
pool_classes_by_scheme = {
'http': HTTPConnectionPool,
'https': HTTPSConnectionPool,
}
class PoolManager(RequestMethods):
"""
Allows for arbitrary requests while transparently keeping track of
necessary connection pools for you.
:param num_pools:
Number of connection pools to cache before discarding the least
recently used pool.
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
:param \**connection_pool_kw:
Additional parameters are used to create fresh
:class:`urllib3.connectionpool.ConnectionPool` instances.
Example::
>>> manager = PoolManager(num_pools=2)
>>> r = manager.request('GET', 'http://google.com/')
>>> r = manager.request('GET', 'http://google.com/mail')
>>> r = manager.request('GET', 'http://yahoo.com/')
>>> len(manager.pools)
2
"""
proxy = None
def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
RequestMethods.__init__(self, headers)
self.connection_pool_kw = connection_pool_kw
self.pools = RecentlyUsedContainer(num_pools,
dispose_func=lambda p: p.close())
# Locally set the pool classes so other PoolManagers can override them.
self.pool_classes_by_scheme = pool_classes_by_scheme
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.clear()
# Return False to re-raise any potential exceptions
return False
def _new_pool(self, scheme, host, port):
"""
Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.
"""
pool_cls = self.pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs)
def clear(self):
"""
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
"""
self.pools.clear()
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
if not host:
raise LocationValueError("No host specified.")
scheme = scheme or 'http'
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
with self.pools.lock:
# If the scheme, host, or port doesn't match existing open
# connections, open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
pool = self._new_pool(scheme, host, port)
self.pools[pool_key] = pool
return pool
def connection_from_url(self, url):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
def urlopen(self, metho | d, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.hos | t, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw)
else:
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
# Support relative URLs for redirecting.
redirect_location = urljoin(url, redirect_location)
# RFC 7231, Section 6.4.4
if response.status == 303:
method = 'GET'
retries = kw.get('retries')
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
try:
retries = retries.increment(method, url, response=response, _pool=conn)
except MaxRetryError:
if retries.raise_on_redirect:
raise
return response
kw['retries'] = retries
kw['redirect'] = redirect
log.info("Redirecting %s -> %s", url, redirect_location)
return self.urlopen(method, redirect_location, **kw)
class ProxyManager(PoolManager):
"""
Behaves just like :class:`PoolManager`, but sends all requests through
the defined proxy, using the CONNECT method for HTTPS URLs.
:param proxy_url:
The URL of the proxy to be used.
:param proxy_headers:
A dictionary contaning headers that will be sent to the proxy. In case
of HTTP they are being sent with each request, while in the
HTTPS/CONNECT case they are sent only once. Could be used for proxy
authentication.
Example:
>>> proxy = urllib3.ProxyManager('http://localhost:3128/')
>>> r1 = proxy.request('GET', 'http://google.com/')
>>> r2 = proxy.request('GET', 'http://httpbin.org/')
>>> len(proxy.pools)
1
>>> r3 = proxy.request('GET', 'https://httpbin.org/')
>>> r4 = proxy.request('GET', 'https://twitter.com/')
>>> len(proxy.pools)
3
"""
def __init__(self, proxy_url, num_pools=10, headers=None,
proxy_headers=None, **connection_pool_kw):
if isinstance(proxy_url, HTTPConnectionPool):
proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
proxy_url.port)
proxy = parse_url(proxy_url)
if not proxy.port:
port = port_by_scheme.get(proxy.scheme, 80)
proxy = proxy._replace(port=port)
if proxy.scheme not in ("http", "https"):
raise ProxySchemeUnknown(proxy.scheme)
self.proxy = proxy
self.proxy_headers = proxy_headers or {}
connection_pool_kw['_proxy'] = self.proxy
connection_pool_kw['_proxy_headers'] = self.proxy_headers
super(ProxyManager, self).__init__(
num_pools, headers, **connection_pool_kw)
|
vertexproject/synapse | synapse/models/proj.py | Python | apache-2.0 | 6,668 | 0.00165 | import synapse.common as s_common
import synapse.lib.module as s_module
prioenums = (
(0, 'none'),
(10, 'lowest'),
(20, 'low'),
(30, 'medium'),
(40, 'high'),
(50, 'highest'),
)
statusenums = (
(0, 'new'),
(10, 'in validation'),
(20, 'in backlog'),
(30, 'in sprint'),
(40, 'in progress'),
(50, 'in review'),
(60, 'completed'),
(70, 'done'),
(80, 'blocked'),
)
class ProjectModule(s_module.CoreModule):
async def initCoreModule(self):
self.model.form('proj:project').onAdd(self._onAddProj)
self.model.form('proj:project').onDel(self._onDelProj)
async def _onAddProj(self, node):
# ref counts on authgates?
gateiden = node.ndef[1]
await self.core.auth.addAuthGate(node.ndef[1], 'storm:project')
useriden = node.snap.user.iden
rule = (True, ('project', 'admin'))
await node.snap.user.addRule(rule, gateiden=gateiden)
async def _onDelProj(self, node):
gateiden = node.ndef[1]
await self.core.auth.delAuthGate(gateiden)
def getModelDefs( | self):
return (
('proj', {
'types': (
('proj:epic', ('guid', {}), {}),
('proj:ticket', ('guid', {}), {}),
('proj:sprint', ('guid', {}), {}),
('proj:comment | ', ('guid', {}), {}),
('proj:project', ('guid', {}), {}),
('proj:attachment', ('guid', {}), {}),
),
'forms': (
('proj:project', {}, (
('name', ('str', {'lower': True, 'strip': True, 'onespace': True}), {
'doc': 'The project name.'}),
('desc', ('str', {}), {
'disp': {'hint': 'text'},
'doc': 'The project description.'}),
('creator', ('syn:user', {}), {
'doc': 'The synapse user who created the project.'}),
('created', ('time', {}), {
'doc': 'The time the project was created.'}),
)),
('proj:sprint', {}, (
('name', ('str', {'lower': True, 'strip': True, 'onespace': True}), {
'doc': 'The name of the sprint.'}),
('status', ('str', {'enums': 'planned,current,completed'}), {
'doc': 'The sprint status.'}),
('project', ('proj:project', {}), {
'doc': 'The project containing the sprint.'}),
('creator', ('syn:user', {}), {
'doc': 'The synapse user who created the sprint.'}),
('created', ('time', {}), {
'doc': 'The date the sprint was created.'}),
('period', ('ival', {}), {
'doc': 'The interval for the sprint.'}),
('desc', ('str', {}), {
'doc': 'A description of the sprint.'}),
)),
# TODO this will require a special layer storage mechanism
# ('proj:backlog', {}, (
('proj:comment', {}, (
('creator', ('syn:user', {}), {}),
('created', ('time', {}), {}),
('updated', ('time', {}), {}),
('ticket', ('proj:ticket', {}), {}),
('text', ('str', {}), {}),
# -(refs)> thing comment is about
)),
('proj:epic', {}, (
('name', ('str', {'strip': True, 'onespace': True}), {}),
('project', ('proj:project', {}), {}),
('creator', ('syn:user', {}), {}),
('created', ('time', {}), {}),
('updated', ('time', {'max': True}), {}),
)),
('proj:attachment', {}, (
('name', ('file:base', {}), {}),
('file', ('file:bytes', {}), {}),
('creator', ('syn:user', {}), {}),
('created', ('time', {}), {}),
('ticket', ('proj:ticket', {}), {}),
('comment', ('proj:comment', {}), {}),
)),
('proj:ticket', {}, (
('project', ('proj:project', {}), {}),
('ext:id', ('str', {'strip': True}), {
'doc': 'A ticket ID from an external system.'}),
('ext:url', ('inet:url', {}), {
'doc': 'A URL to the ticket in an external system.'}),
('epic', ('proj:epic', {}), {
'doc': 'The epic that includes the ticket.'}),
('created', ('time', {}), {
'doc': 'The time the ticket was created.'}),
('updated', ('time', {'max': True}), {
'doc': 'The last time the ticket was updated.'}),
('name', ('str', {'strip': True, 'onespace': True}), {
'doc': 'The name of the ticket.'}),
('desc', ('str', {}), {
'doc': 'A description of the ticket.'}),
('points', ('int', {}), {
'doc': 'Optional SCRUM style story points value.'}),
('status', ('int', {'enums': statusenums}), {
'doc': 'The ticket completion status.'}),
('sprint', ('proj:sprint', {}), {
'doc': 'The sprint that contains the ticket.'}),
('priority', ('int', {'enums': prioenums}), {
'doc': 'The priority of the ticket.'}),
('type', ('str', {'lower': True, 'strip': True}), {
'doc': 'The type of ticket. (eg story / bug)'}),
('creator', ('syn:user', {}), {
'doc': 'The synapse user who created the ticket.'}),
('assignee', ('syn:user', {}), {
'doc': 'The synapse user who the ticket is assigned to.'}),
)),
),
}),
)
|
itahsieh/sparx-alpha | preprocessor/presparx/Disk_cyl2d/model.py | Python | gpl-3.0 | 5,481 | 0.021164 | ####################################################
# The model of disk and envelope (Keto&Zhang 2010) #
####################################################
# Model Type : Function / Constant / TABLE / ZEUS
ModelType = 'Function'
# Molecule
molec = 'hco+'
# CMB temperature (Kelvin, outer B.C.)
T_cmb = 2.73
# inner Boundary condition
T_in = 0.0
# enable/disable disk model
disk = 1
# enable/disable envelope model
env = 1
# Physical pa | rameter
#parameters from Keto&Zhang
rho_e0 = 7.9e4 *1e6 # Envelope density at Rd (m^-3)
Rd = 6900./206260. # AU to pc
Ap = 5.1
Mt = 10.7 # stellar mass (Msun)
Rt = 26.*0.0046491/206260
p = -1
BT = 15.0
vk = 1.2 # Keplerian velocity (km/s)
rho_d0 = Ap*rho_e0
H0 = 0.01*Rt
Tt = 30000.
# unit converter
km2m=1e3
pc2m=30.857e15
pc2km=30.857e12
# mean mollecular mass (kg)
mean_molecular_mass = 2*1.67*1.67e-27 # kg
from math import sin,cos,pi,exp,sqrt,isnan,acos
Mar = rho_e0*4.*pi*Rd*Rd*vk*(mean_m | olecular_mass*pc2m**2*km2m) # mass accretion rate (kg/s)
G = 4.302e-3 # gravitational constant (pc Msun^-1 (km/s)^2)
sigma = 5.67037321e-8 # Stefan-Boltzmann constant (W m^-2 K^-4)
pp = 0.0
qq = 0.0
def CubicEq(x):
global pp,qq
return x*x*x + pp*x + qq
from scipy.optimize import brentq
class model:
def __init__(self, Rc, z):
self.Rc = Rc
self.z = z
self.r = sqrt( Rc*Rc + z*z )
self.sin_theta = Rc / self.r
self.cos_theta = z / self.r
self.theta = acos( self.cos_theta )
global pp,qq
pp = self.r / Rd - 1.
qq = -self.cos_theta * self.r / Rd
self.cos_theta0 = brentq(CubicEq, -1.,1.)
self._DensityCyl2D()
self._TgasCyl2D()
self._VeloCyl2D()
self._VtCyl2D()
self._MolecAbdCyl2D()
self._DustToGasCyl2D()
self._TdustCyl2D()
self._kappa_d_Cyl2D()
# Gas Density (number/m^3)
def _DensityCyl2D(self):
# envelope density
if (env == 1):
self.n_H2_env = rho_e0 * ((self.r/Rd)**(-1.5)) * ((1. + self.cos_theta / self.cos_theta0)**(-0.5)) * ((1 + ((self.r/Rd)**(-1)) * (3 * self.cos_theta0**2 - 1.0))**(-1))
else:
self.n_H2_env = 0.0
# disk density
if (self.r<=Rd and disk==1):
rho_0 = rho_d0*(Rd/self.Rc)**2.25
H=H0*(self.Rc/Rt)**1.2
self.n_H2_disc = rho_0 * exp(-(self.r*self.r-self.Rc*self.Rc)/(2.*H*H))
else:
self.n_H2_disc = 0.0
# total density
self.n_H2 = self.n_H2_env + self.n_H2_disc
# Temperature (Kelvin)
def _TgasCyl2D(self):
if ( self.n_H2 != 0.0 ):
T_env = Tt*(Rt/(2.*self.r))**(2./(4+p))
T_disc = BT * ( (3.*G*Mt*Mar/(4.*pi * pc2km*pc2km * (self.Rc**3) * sigma)) * (1.-sqrt(Rt/self.Rc)) )**0.25
self.T_k = ( self.n_H2_disc*T_disc + self.n_H2_env*T_env ) / self.n_H2
else:
self.T_k = 0.0
# Velocity (m/s)
def _VeloCyl2D(self):
# Keplerian velocity (km/s)
Vkep = sqrt(G*Mt/self.r)
# disk velocity (km/s)
Vp_disc = sqrt(G*Mt/self.Rc)
Vr_env = -Vkep * sqrt( 1. + self.cos_theta / self.cos_theta0 )
if self.sin_theta == 0. or self.cos_theta0 == 0.:
print self.r, self.theta, self.sin_theta, self.cos_theta0
import sys
sys.exit(0)
Vt_env = Vkep * ( (self.cos_theta0 - self.cos_theta)/ self.sin_theta ) * sqrt( 1. + self.cos_theta / self.cos_theta0 )
Vp_env = Vkep * ( sqrt( 1. - self.cos_theta0 * self.cos_theta0) / self.sin_theta ) * sqrt( 1. + self.cos_theta / self.cos_theta0 )
Vrc_env = Vr_env * self.sin_theta + Vt_env * self.cos_theta
Vz_env = Vr_env * self.cos_theta - Vt_env * self.sin_theta
if self.n_H2 != 0.:
Vrc = (self.n_H2_env * Vrc_env) / self.n_H2
Vz = (self.n_H2_env * Vz_env) / self.n_H2
Vp = (self.n_H2_env * Vp_env + self.n_H2_disc * Vp_disc) / self.n_H2
else:
Vrc = 0.0
Vz = 0.0
Vp = 0.0
self.V_cen = [ km2m*Vrc, km2m*Vp, km2m*Vz]
# turbulent speed (m/s)
def _VtCyl2D(self):
self.Vt = 200.
# Molecular Abundance (fraction)
def _MolecAbdCyl2D(self):
self.X_mol = 1e-9
# gas-to-dust ratio
def _DustToGasCyl2D(self):
self.dust_to_gas = 0.01
# Dust Temperature (Kelvin)
def _TdustCyl2D(self):
self.T_d = self.T_k
# dust kappa
def _kappa_d_Cyl2D( self):
self.kapp_d = 'table,jena_thin_e5'
#kappa_d = 'powerlaw, 1.874e+12, 2.300e-02,-2.0'
|
hankcs/HanLP | hanlp/metrics/chunking/sequence_labeling.py | Python | apache-2.0 | 14,144 | 0.002828 | # MIT License
#
# Copyright (c) 2018 chakki
#
# 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.
"""Metrics to assess performance on sequence labeling task given prediction
Functions named as ``*_score`` return a scalar value to maximize: the higher
the better
"""
from collectio | ns import defaultdict
import numpy as np
def iobes_to | _span(words, tags):
delimiter = ' '
if all([len(w) == 1 for w in words]):
delimiter = '' # might be Chinese
entities = []
for tag, start, end in get_entities(tags):
entities.append((delimiter.join(words[start:end]), tag, start, end))
yield entities
def get_entities(seq, suffix=False):
"""Gets entities from sequence.
Args:
seq(list): sequence of labels.
suffix: (Default value = False)
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
>>> from seqeval.metrics.sequence_labeling import get_entities
>>> seq = ['B-PER', 'I-PER', 'O', 'B-LOC']
>>> get_entities(seq)
[('PER', 0, 2), ('LOC', 3, 4)]
"""
# for nested list
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ['O']]
prev_tag = 'O'
prev_type = ''
begin_offset = 0
chunks = []
for i, chunk in enumerate(seq + ['O']):
if suffix:
tag = chunk[-1]
type_ = chunk[:-2]
else:
tag = chunk[0]
type_ = chunk[2:]
if end_of_chunk(prev_tag, tag, prev_type, type_):
chunks.append((prev_type, begin_offset, i))
if start_of_chunk(prev_tag, tag, prev_type, type_):
begin_offset = i
prev_tag = tag
prev_type = type_
return chunks
def end_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk ended between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_end: boolean.
"""
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': chunk_end = True
if prev_tag == 'I' and tag == 'S': chunk_end = True
if prev_tag == 'I' and tag == 'O': chunk_end = True
if prev_tag != 'O' and prev_tag != '.' and prev_type != type_:
chunk_end = True
return chunk_end
def start_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean.
"""
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
return chunk_start
def f1_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::
F1 = 2 * (precision * recall) / (precision + recall)
Args:
y_true: 2d array. Ground truth (correct) target values.
y_pred: 2d array. Estimated targets as returned by a tagger.
average: (Default value = 'micro')
suffix: (Default value = False)
Returns:
score: float.
Example:
>>> from seqeval.metrics import f1_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> f1_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
nb_true = len(true_entities)
p = nb_correct / nb_pred if nb_pred > 0 else 0
r = nb_correct / nb_true if nb_true > 0 else 0
score = 2 * p * r / (p + r) if p + r > 0 else 0
return score
def accuracy_score(y_true, y_pred):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Args:
y_true: 2d array. Ground truth (correct) target values.
y_pred: 2d array. Estimated targets as returned by a tagger.
Returns:
score: float.
Example:
>>> from seqeval.metrics import accuracy_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> accuracy_score(y_true, y_pred)
0.80
"""
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
nb_correct = sum(y_t == y_p for y_t, y_p in zip(y_true, y_pred))
nb_true = len(y_true)
score = nb_correct / nb_true
return score
def precision_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the precision.
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample.
The best value is 1 and the worst value is 0.
Args:
y_true: 2d array. Ground truth (correct) target values.
y_pred: 2d array. Estimated targets as returned by a tagger.
average: (Default value = 'micro')
suffix: (Default value = False)
Returns:
score: float.
Example:
>>> from seqeval.metrics import precision_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> precision_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pre |
vpramo/contrail-controller | src/config/api-server/vnc_perms.py | Python | apache-2.0 | 3,590 | 0.000279 | #
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
from cfgm_common import jsonutils as json
import string
from provision_defaults import *
from cfgm_common.exceptions import *
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
class VncPermissions(object):
mode_str = {PERMS_R: 'read', PERMS_W: 'write', PERMS_X: 'link'}
def __init__(self, server_mgr, args):
self._server_mgr = server_mgr
# end __init__
@property
def _multi_tenancy(self):
return self._server_mgr._args.multi_tenancy
# end
def validate_user_visible_perm(self, id_perms, is_admin):
return id_perms.get('user_visible', True) is not False or is_admin
# end
def validate_perms(self, request, uuid, mode=PERMS_R):
# retrieve object and permissions
try:
id_perms = self._server_mgr._db_conn.uuid_to_obj_perms(uuid)
except NoIdError:
return (True, '')
err_msg = (403, 'Permission Denied')
user, roles = self.get_user_roles(request)
is_admin = 'admin' in [x.lower() for x in roles]
owner = id_perms['permissions']['owner']
group = id_perms['permissions']['group']
perms = id_perms['permissions']['owner_access'] << 6 | \
id_perms['permissions | ']['group_access'] << | 3 | \
id_perms['permissions']['other_access']
# check perms
mask = 0
if user == owner:
mask |= 0700
if group in roles:
mask |= 0070
if mask == 0: # neither user nor group
mask = 07
mode_mask = mode | mode << 3 | mode << 6
ok = is_admin or (mask & perms & mode_mask)
if ok and mode == PERMS_W:
ok = self.validate_user_visible_perm(id_perms, is_admin)
return (True, '') if ok else (False, err_msg)
# end validate_perms
# retreive user/role from incoming request
def get_user_roles(self, request):
user = None
env = request.headers.environ
if 'HTTP_X_USER' in env:
user = env['HTTP_X_USER']
roles = None
if 'HTTP_X_ROLE' in env:
roles = env['HTTP_X_ROLE'].split(',')
return (user, roles)
# end get_user_roles
# set user/role in object dict from incoming request
# called from post handler when object is created
def set_user_role(self, request, obj_dict):
(user, roles) = self.get_user_roles(request)
if user:
obj_dict['id_perms']['permissions']['owner'] = user
if roles:
obj_dict['id_perms']['permissions']['group'] = roles[0]
# end set_user_role
def check_perms_write(self, request, id):
app = request.environ['bottle.app']
if app.config.auth_open:
return (True, '')
if not self._multi_tenancy:
return (True, '')
return self.validate_perms(request, id, PERMS_W)
# end check_perms_write
def check_perms_read(self, request, id):
app = request.environ['bottle.app']
if app.config.auth_open:
return (True, '')
if not self._multi_tenancy:
return (True, '')
return self.validate_perms(request, id, PERMS_R)
# end check_perms_read
def check_perms_link(self, request, id):
app = request.environ['bottle.app']
if app.config.auth_open:
return (True, '')
if not self._multi_tenancy:
return (True, '')
return self.validate_perms(request, id, PERMS_X)
# end check_perms_link
|
paddycarey/beardo-control | app/run-prospector.py | Python | mit | 715 | 0.001399 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Prospector runner for beardo-control
"""
# stdlib imports
import sys
# third-party imports
from prospector import run
# this looks like an unused import, but we're only using it to do some path
# manipulat | ion on import so you can safely ignore it (even | though your linter
# may complain)
import appengine_config
# setup our appengine environment so we can import the libs we need for our tests,
# we need to do this first so we can import the stubs from testbed
from nacelle.test.environ import setup_environ
setup_environ()
if __name__ == '__main__':
sys.argv = [sys.argv[0]]
sys.argv += ['--no-autodetect', '--ignore-paths', 'vendor']
run.main()
|
RevelSystems/revel-bootstrap | manage.py | Python | mit | 476 | 0.002101 | """
usage: manage.py [--help] <command> [<args>...]
The most commonly used git commands are:
syncdb Creates db models
dropdb Drop db models
"""
from database import init_db
from docopt import docopt
def main():
args = docopt(__doc__,
options_first=True)
if args['<command>'] == 'syncdb | ':
init_db()
else:
exit("%r is not a manage.py command. See 'mana | ge.py help'." % args['<command>'])
if __name__ == '__main__':
main()
|
hkff/AccLab | pyAAL/AALMetaModel.py | Python | gpl-3.0 | 66,923 | 0.002944 | """
AALMetaModel
Copyright (C) 2014 Walid Benghabrit
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/>.
"""
__author__ = 'walid'
'''
// AAL CORE
AALprogram ::= (Declaration | Clause | Comment | Macro | MacroCall | Loadlib | LtlCheck | CheckApply | Exec | Behavior)
Declaration ::= AgentDec | ServiceDec | DataDec | TypesDec | varDec
AgentDec ::= AGENT Id [TYPES '(' Type *')' REQUIRED'('service*')' PROVIDED'('service*')']
ServiceDec ::= SERVICE Id [TYPES '(' Type* ')'] [PURPOSE '(' Id* ')']
DataDec ::= DATA Id TYPES '(' Type* ')' [REQUIRED'('service*')' PROVIDED'('service*')'] SUBJECT agent
VarDec ::= Type_Id Id [att | r_Id '(' value* ')']*
Clause ::= CLAUSE Id '(' [Usage] [Audit Rectification] ')'
Usage ::= ActionExp
Audit ::= AUDITING Usage
Rectification ::= IF_VIOLATED_THEN Usage
ActionExp ::= Action | | NOT ActionExp | Modality ActionExp | Condition
| ActionExp (AND|OR|ONLYWHEN|UNTIL|UNLESS) ActionExp
| Author | Quant* | IF '(' ActionExp ')' THEN '{' ActionExp '}'
Exp ::= Variable | Constant | Variable.Attribute
Condition ::= [NOT] Exp | Exp ['==' | '!='] Exp | Condition (AND|OR) Condition
Author ::= (PERMIT | DENY) Action
Action ::= agent.service ['['[agent]']'] '('Exp')' [Time] [Purpose]
Quant ::= (FORALL | EXISTS) Var [WHERE Condition]
Variable ::= Var ':' Type
Modality ::= MUST | MUSTNOT | ALWAYS | NEVER | SOMETIME
Time ::= (AFTER | BEFORE) Date | Time (AND | OR) Time
Date ::= STRING
Type, var, val, attr Id, agent, Constant, Purpose ::= literal
// AAL Type extension
TypesDec ::= TYPE Id [EXTENDS '(' Type* ')'] ATTRIBUTES '(' AttributeDec* ')' ACTIONS '(' ActionDec* ')'
AttributeDec ::= Id ':' Type
ActionDec ::= Id
Type, Id ::= litteral
// Reflexion extension
Macro ::= MACRO Id '(' param* ')' '(' mcode ')'
MCode ::= """ Meta model api + Python3 code (subset) """
MCall ::= CALL Id '(' param* ')'
LoadLib ::= LOAD STRING;
Exec ::= EXEC MCode
// FOTL checking extension
LtlCheck ::= CHECK Id '(' param* ')' '(' check ')'
check ::= FOTL_formula + clause(Id) [.ue | .ae | .re]
CheckApply ::= APPLY Id '(' param* ')'
// Behavior extension
Behavior ::= BEHAVIOR Id '(' ActionExp ')'
'''
from enum import Enum
from FOTLOperators import *
from tools.color import Color
from tools.hottie import hot
# TODO: add until to modals
# TODO: handle quantifications scope
##########################
########## aalmm #########
##########################
# All meta model classes are prefixed by "m_"
class aalmm():
"""
AAL meta model class
Attributes
- errors: a list that contains all internal compiler error
- parsingErrors: a list that contains all semantics parsing errors
- aalprog: the aal program node
"""
def __init__(self):
self.errors = []
self.parsingErrors = []
self.aalprog = m_aalprog()
# Enable masking
def enable_masking():
"""
More funny with meta programming ;)
:return:
"""
def mask_decorator(f):
def g(*args, **kwargs):
if args[0].masked:
return "true"
else:
return f(*args, **kwargs)
return g
import inspect, sys
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj):
if issubclass(obj, aalmmnode):
obj.to_ltl = mask_decorator(obj.to_ltl)
obj.__str__ = mask_decorator(obj.__str__)
# Meta model node
class aalmmnode():
"""
AAL meta model node
Attributes
- name: node's name, used as Id by some nodes type
- parent: parent's node
"\n\t - aalprog " + "\t Get the AAL program instance" \
""\
"\n{autoblue} - Methods{/blue}" \
"\n\t - isDeclared(name, klass, ret=bool) " + "\t Check if element 'name' with type 'klass is declared" \
"\n\t - children() " + "\t " Get children nodes\
"\n\t - get_refs(pprint=bool) " + "\t " Get references\
"\n\t - walk(filters=bool, filter_type=bool) " + "\t " AST tree walker\
"\n\t - man() " + "\t Print this manual" \
"\n\t - to_ltl() " + "\t Translate to fotl"
"""
def __init__(self, name: str=None):
"""
:param name: Node name
:return:
"""
self.name = name
self.parent = None
self.masked = False
self.line = "0"
self.source_range = None
def mask(self):
self.masked = True
def unmask(self):
self.masked = False
def children(self):
""" return a list that contains node's children """
return []
def walk(self, filters: str=None, filter_type: type=None, pprint=False, depth=-1):
"""
Iterate tree in pre-order wide-first search order
:param filters: filter by python expression
:param filter_type: Filter by class
:return:
"""
children = self.children()
if children is None:
children = []
res = []
if depth == 0:
return res
elif depth != -1:
depth -= 1
for child in children:
if isinstance(child, aalmmnode) or isinstance(child, sEnum):
tmp = child.walk(filters=filters, filter_type=filter_type, pprint=pprint, depth=depth)
if tmp:
res.extend(tmp)
if filter_type is None:
if filters is not None:
if eval(filters) is True:
res.append(self)
else:
res.append(self)
elif isinstance(self, filter_type):
if filters is not None:
if eval(filters) is True:
res.append(self)
else:
res.append(self)
if pprint:
res = [str(x) + " " for x in res]
res = "\n".join(res)
return res
def remove(self):
"""
Remove child
:return:
"""
pass
def replace(self, child, node):
"""
Replace child
:param child: the child node
:param node: the replacement node
:return:
"""
pass
def get_refs(self, pprint=False):
""" Get all refs used in the node """
res = []
children = self.children()
if children is None:
children = []
for child in children:
if isinstance(child, aalmmnode) or isinstance(child, sEnum):
res.extend(child.get_refs())
if pprint:
res = [str(x.target) + " " for x in res]
res = "\n".join(res)
return res
def to_ltl(self):
""" Get LTL translation """
pass
def to_nnf(self, negated):
"""
Transform node to negative normal form
:param negated: true if action is not negated, false if action is negated
:return: negation propagated action
"""
return
def to_natural(self, kw=True):
"""
Get the natural language translation
:param kw:
:return:
"""
res = ""
children = self.child |
hfp/libxsmm | samples/deeplearning/sparse_training/fairseq/fairseq/modules/fairseq_dropout.py | Python | bsd-3-clause | 1,687 | 0.000593 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import List, Optional
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
class FairseqDropout(nn.Module):
def __init__(self, p, module_name=None):
super().__init__()
self.p = p
self.module_name = module_name
self.apply_during_inference = False
def forward(self, x, inplace: bool = False):
if self.training or self.apply_during_inference:
return F.dropout(x, p=self.p, training=True, inplace=inplace)
else:
return x
def make_generation_fast_(
self,
name: str,
retain_dropout: bool = False,
retain_dropout_modules: Optional[List[str]] = None,
**kwargs
):
if retain_dropout:
if retain_dropout_modules is not None and self.module_name is None:
logger.warning(
'Cannot enable dropout during inference for module {} '
'because module_name was | not set'.format(name)
)
elif (
retain_dropout_modules is None # if None, apply to all modules
or self.module_name in retain_dropout_modules
| ):
logger.info(
'Enabling dropout during inference for module: {}'.format(name)
)
self.apply_during_inference = True
else:
logger.info('Disabling dropout for module: {}'.format(name))
|
gustavofoa/pympm | apps/mpm/views/view_starratings.py | Python | apache-2.0 | 1,191 | 0.028547 | from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.cache import cache_control, cache_page
from ..models import Musica
import re
@csrf_exempt
def starratings_ajax(request):
id = request.POST.get('id', 0)
stars = request.POST.get('stars', 0)
if int(stars) > 0:
print("Rating ", stars, " to ", id)
if request.method == 'POST' and re.match('^[\w\d-]+$', id):
jsonObj = {}
jsonObj[id] = {}
jsonObj[id]["success"] = 1
jsonObj[id]["disable"] = "false"
musica = get_object_or_404(Musica, slug=id)
if stars != "0":
musica.add_rate(int(stars))
musica.save()
jsonObj[id]["disable"] = "true"
jsonObj[id]["fuel"] = musica.rating
jsonObj[id][ | "legend"] = musica.get_legend()
return JsonResponse(jsonObj)
return HttpResponse(str("0"))
@cache_control(max_age = 60 * 60)
@cache_page(60 * 5)#5 minutes
def stars(request):
musicas = Musica.objects.all()
jsonObj = {}
for musica in musicas:
jsonObj[musica.slug] = {"r": musica.ratin | g if musica.rating else 0, "v":musica.votes if musica.votes else 0}
return JsonResponse(jsonObj) |
minddistrict/doublespeak | src/doublespeak/message.py | Python | bsd-3-clause | 6,920 | 0.000578 | """Inspired by
http://trac.edgewall.org/attachment/ticket/6353/babel-l10n-js.diff#L590 """
import os
import glob
import distutils
import json
from babel._compat import StringIO
from babel._compat import string_types
from babel.messages import frontend as babel
from babel.messages.pofile import read_po
import gettext
TEMPLATE = '''\
/*jshint indent: 4 */
/*global window */
/*jshint -W069 */
if (typeof window.json_locale_data === 'undefined') {{
window.json_locale_data = {{}};
}}
window.json_locale_data['{domain}'] = {messages};
'''
def check_js_message_extractors(dist, name, value):
"""Validate the ``js_message_extractors`` keyword argument to ``setup()``.
:param dist: the distutils/setuptools ``Distribution`` object
:param name: the name of the keyword argument (should always be
"js_message_extractors")
:param value: the value of the keyword argument
:raise `DistutilsSetupError`: if the value is not valid
"""
assert name == 'js_message_extractors'
if not isinstance(value, dict):
raise distutils.errors.DistutilsSetupError(
'the value of the "js_message_extractors" parameter must be a '
'dictionary')
class extract_js_messages(babel.extract_messages):
"""Mostly a wrapper for Babel's extract_messages so that we can configure
it explicitly for JS files in setup.cfg
"""
def _get_mappings(self):
"""Override to check js_message_extractors keywords and not
message_extractors
"""
mappings = {}
if self.mapping_file:
mappings = babel.extract_messages._get_mappings(self)
elif getattr(self.distribution, 'js_message_extractors', None):
message_extractors = self.distribution.js_message_extractors
for dirname, mapping in message_extractors.items():
if isinstance(mapping, string_types):
method_map, options_map = \
babel.parse_mapping(StringIO(mapping))
else:
method_map, options_map = [], {}
for pattern, method, options in mapping:
method_map.append((pattern, method))
options_map[pattern] = options or {}
mappings[dirname] = method_map, options_map
else:
mappings = babel.extract_messages._get_mappings(self)
return mappings
class init_js_catalog(babel.init_catalog):
"""Wrapper for Babel's init_catalog so that we can configure it
explicitly for JS files in setup.cfg
"""
class update_js_catalog(babel.update_catalog):
"""Wrapper for Babel's update_catalog so that we can configure it
explicitly for JS files in setup.cfg
"""
class compile_js_catalog(distutils.cmd.Command):
"""Generating message javascripts command for use ``setup.py`` scripts.
"""
description = 'generate message javascript file from PO files'
user_options = [
('domain=', 'D',
"domain of PO file (default 'messages')"),
('input-dir=', 'I',
'path to base directory containing the catalogs'),
('output-dir=', 'o',
'path to the output directory'),
('output-prefix=', 'p',
'filename prefix for files in output directory'),
('fallback-locale=', 'l',
"fallback locale (default 'en')"),
('use-fuzzy', 'f',
'also include fuzzy translations'),
('statistics', None,
'print statistics about translations')
]
boolean_options = ['use-fuzzy', 'statistics']
def initialize_options(self):
self.domain = 'messages'
self.input_dir = None
self.output_dir = None
self.output_prefix = ''
self.fallback_locale = 'en'
self.use_fuzzy = False
self.statistics = False
def finalize_options(self):
pass
def run(self):
found_po_files = False
for in_dir in glob.glob(os.path.join(self.input_dir, '*')):
locale = in_dir.rstrip('/').split('/')[-1]
if not os.path.isdir(in_dir):
distutils.log.warn(
"can't generate JS for locale {} because the "
"directory {} doesn't exist".format(locale, in_dir))
continue
po_file = os.path.join(in_dir, 'LC_MESSAGES', self.domain + '.po')
if not os.path.exists(po_file):
distutils.log.warn(
"can't generate JS for locale \"{}\" because the file {}"
"doesn't exist".format(locale, po_file))
continue
found_po_files = True
infile = open(po_file, 'rb')
try:
catalog = read_po(infile, locale)
finally:
infile.close()
# statistics.
if self.statistics:
translated = 0
for message in list(catalog):
if message.id == '':
continue
if message.string:
translated +=1
percentage = 0
if len(catalog):
percentage = translated * 100 // len(catalog)
distutils.log.info('%d of %d messages (%d%%) translated in %r',
translated, len(catalog), percentage, po_file)
if catalog.fuzzy and not self.use_fuzzy:
distutils.log.warn('warning: catalog %r is marked as fuzzy, skipping', po_file)
continue
for message, errors in catalog.check():
for error in errors:
dist | utils.log.error(
'error: %s:%d: %s', po_file, message.lineno, error)
# Don't leak private information to the frontend.
messages = {'': [None, '']}
for message in list(cata | log):
# See comment above about not leaking private information to the
# frontend.
if message.id == '':
continue
if not self.use_fuzzy and message.fuzzy:
continue
# If you need pluralization here, make a pull request.
messages[message.id] = [None, message.string]
js_file_path = os.path.join(
self.output_dir,
'{}{}.js'.format(self.output_prefix, locale))
open(js_file_path, 'w').write(TEMPLATE.format(
messages=json.dumps(messages),
domain=self.domain
))
distutils.log.info(
'compiling Javascript catalog {} to {}.'.format(
po_file, js_file_path))
if not found_po_files:
raise distutils.errors.DistutilsOptionError(
'no compiled catalogs found')
|
goffersoft/common-utils-python | experimental/com/goffersoft/raw/rawhdr.py | Python | gpl-2.0 | 543 | 0.001842 | #! /usr/bin/python
from com.goffersoft.utils.utils import readonly
""" This Module Contains header types specific to raw
me | ssaging protocol
"""
class _RawMsgHdrType(type):
"""Raw Message Header Names"""
CONTENT = readonly('Content')
CONTENT_TYPE = readonly('Content-Type')
FROM = readonly('From')
TO = readonly('To')
REQ_ID = readonly('Req-Id')
RESP_ID = readonly('Resp-Id')
"""Raw Message Header Type"""
RawMsgHdrType = _RawMsgHdrType('RawMsgHdrType', (object,), {})
if __name__ == '__main__':
pas | s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.