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
nens/timeseries
setup.py
Python
gpl-3.0
1,079
0.00278
from setuptools import setup version = 'y.dev0' long_description = '\n\n'.join([ open('README.rst').
read(), open('TODO.rst').read(), open('CREDITS.rst').read(), open('CHANGES.rst'
).read(), ]) install_requires = [ 'pkginfo', 'setuptools', 'nens', ], tests_require = [ ] setup(name='timeseries', version=version, description="Package to implement time series and generic operations on time series.", long_description=long_description, # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[], keywords=[], author='Pieter Swinkels', author_email='pieter.swinkels@nelen-schuurmans.nl', url='', license='GPL', packages=['timeseries'], include_package_data=True, zip_safe=False, install_requires=install_requires, tests_require=tests_require, extras_require = {'test': tests_require}, entry_points={ 'console_scripts': [ 'ziprelease = adapter.ziprelease:main', ]}, )
ghostsquad/seasalt
src/tests/unit/test_container.py
Python
mit
5,504
0.001272
import pytest from seasalt import container from assertpy import assert_that from os import path def get_minimum_seasalt_kwargs(): return { 'image': 'test-image:latest' } def get_minimum_container(docker_fixture): kwargs = get_minimum_seasalt_kwargs() return container(docker_cli=docker_fixture, **kwargs) def get_container(docker_cli, kwargs=None): if not kwargs: kwargs = get_minimum_seasalt_kwargs() return container(docker_cli=docker_cli, **kwargs) def assert_single_call_get_kwargs(mocked_method): assert_that(mocked_method.call_count).is_equal_to(1) return mocked_method.call_args[1] def test_expect_container_runs_when_created(mock_docker_fixture): start_mock = mock_docker_fixture.start with get_minimum_container(mock_docker_fixture) as cn: expected_id = cn.id pass start_mock.assert_called_once_with(expected_id) def test_expect_container_removed_when_out_of_context(mock_docker_fixture): rm_cn_mock = mock_docker_fixture.remove_container with get_minimum_container(mock_docker_fixture) as cn: expected_id = cn.id assert_that(expected_id).is_not_empty() actual_kwargs = assert_single_call_get_kwargs(rm_cn_mock) (assert_that(actual_kwargs) .contains_entry({'container': expected_id}) .contains_entry({'force': True}) .contains_entry({'v': True})) def test_given_target_expect_runs_docker_with_image_and_tag(mock_docker_fixture): with get_minimum_container(mock_docker_fixture) as cn: expected_image_name = 'test-image:latest' expected_container_name = cn.name actual_kwargs = assert_single_call_get_kwargs(mock_docker_fixture.create_container) (assert_that(actual_kwargs) .contains_entry({'image': expected_image_name}) .contains_entry({'name': expected_container_name})) def test_given_default_source_paths_expect_mounted_with_readonly_access(mock_docker_fixture): # arrange kwargs = get_minimum_seasalt_kwargs() kwargs['cwd'] = '/path/on/host' create_host_config_mock = mock_docker_fixture.create_host_config expected_host_config_value = {'mocked_host_config': 'foobarbaz'} create_host_config_mock.return_value = expected_host_config_value # act with container(docker_cli=mock_docker_fixture, **
kwargs): pass # assert that the host_config was created in order to create the container expected_salt_path = '/path/on/host/salt' expected_pillar_path = '/path/on/host/pillar' expected_test_path = '/path/on/host/tests' expected_salt_bind = '{}:/srv/salt:ro'.format(expected_salt_path) expected_pillar_bind = '{}:/srv/pillar:ro'.format(expected_pillar_path) expected_test_bind = '{}:/srv/seasalt:ro'.form
at(expected_test_path) actual_kwargs = assert_single_call_get_kwargs(create_host_config_mock) assert_that(actual_kwargs).contains_key('binds') (assert_that(actual_kwargs['binds']) .contains(expected_salt_bind) .contains(expected_pillar_bind) .contains(expected_test_bind)) # assert that the container was created with the pre-setup mock host_config actual_kwargs = assert_single_call_get_kwargs(mock_docker_fixture.create_container) assert_that(actual_kwargs).contains_key('volumes') assert_that(actual_kwargs['volumes']) \ .contains('/srv/salt') \ .contains('/srv/pillar') \ .contains('/srv/seasalt') assert_that(actual_kwargs).contains_key('host_config') assert_that(actual_kwargs['host_config']).is_equal_to(expected_host_config_value) def test_container_network_mode_is_bridge(mock_docker_fixture): with get_minimum_container(mock_docker_fixture): pass actual_kwargs = assert_single_call_get_kwargs(mock_docker_fixture.create_host_config) assert_that(actual_kwargs).contains_entry({'network_mode': 'bridge'}) def test_exec_runs_command_in_container(mock_docker_fixture): expected_cmd = 'touch /this-is-a-test-file' expected_exec_id = '74213' expected_return_val = "done" exec_create_mock = mock_docker_fixture.exec_create exec_create_mock.return_value = {'Id': expected_exec_id} exec_start_mock = mock_docker_fixture.exec_start exec_start_mock.return_value = expected_return_val with get_minimum_container(mock_docker_fixture) as cn: expected_cn_id = cn.id result = cn.exec(expected_cmd) actual_kwargs = assert_single_call_get_kwargs(exec_create_mock) (assert_that(actual_kwargs) .contains_entry({'container': expected_cn_id}) .contains_entry({'cmd': expected_cmd})) actual_kwargs = assert_single_call_get_kwargs(exec_start_mock) assert_that(actual_kwargs).contains_entry({'exec_id': expected_exec_id}) assert_that(result).is_equal_to(expected_return_val) @pytest.mark.xfail(reason='need to implement mock file system to test tarring of file') def test_cp_copies_file_to_container(mock_docker_fixture): put_archive_mock = mock_docker_fixture.put_archive put_archive_mock.return_value = True with get_minimum_container(mock_docker_fixture) as cn: expected_id = cn.id cn.cp('/salt-tests') actual_kwargs = assert_single_call_get_kwargs(put_archive_mock) (assert_that(actual_kwargs) .contains_entry({'container': expected_id}) .contains_entry({path: '/srv/seasalt_tests'}) .contains_key('data')) print(type(actual_kwargs['data']))
yleo77/leetcode
Unique_Email_Addresses/answer.py
Python
mit
550
0
class Solution(object): def numUniqueEmails(self, emails): ret = set() for email in emails: local, rest = email.split("@") pos = local.find("+") if pos >= 0: local = local[0: pos] local = local.replace(".", "") ret.add(local + "@" + rest) return len(ret) emails = ["test.email+alex@leetcode.com", "test
.e.mail+bob.cathy@leetcode.com", "testemail+david@
lee.tcode.com"] sol = Solution() print(sol.numUniqueEmails(emails))
drbean/ultisnips
test/test_Plugin.py
Python
gpl-3.0
935
0.00107
import sys from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Plugin_SuperTab_SimpleTest(_VimTest): plugins = ["ervandew/supertab"] snippets = ("long", "Hello", "", "w") keys = ( "l
ongtextlongtext\n" + "longt" + EX + "\n" + "long" + EX # Should complete word ) # Should expand wanted = "longtextlongtext\nlongtextlongtext\nHello" def _before_test(self): # Make sure that UltiSnips has the keymap self.vim.send_to_vim(":call UltiSnips#map_keys#MapKeys()\n") def _extra_vim_config(self, vim_config): assert EX == "\t" # Otherwise this test needs changing. vim_config
.append('let g:SuperTabDefaultCompletionType = "<c-p>"') vim_config.append('let g:SuperTabRetainCompletionDuration = "insert"') vim_config.append("let g:SuperTabLongestHighlight = 1") vim_config.append("let g:SuperTabCrMapping = 0")
vitorio/pygrow
grow/client/client.py
Python
mit
1,209
0.008271
from apiclient import errors import httplib2 import json import requests HOST = '' root_url_format = '{}://{}/_ah/api' api = 'grow' version = 'v0.1' class Client(object): def __init__(self, host=None): self.host = host def rpc(self, path, body=None): if body is None: body = {} headers = { 'Content-Type': 'application/json', } url = 'http://{}/_api/{}'.format(self.host, path) resp = requests.post(url, data=json.dumps(body), headers=headers) if not (resp.status_code >= 200 and resp.status_code < 205): raise Exception(resp.text) return resp def upload_to_gcs(signed_url, file_path, content): files = {'file': (file_path, content)} payload = { 'GoogleAccessId': signed_url['google_access_id'], 'bucket': signed_url['bucket'], 'key': signed_url['filename'], 'policy': signed_url['policy'], 'signature': signed_url['signature'], # 'x-goog-meta-owner': signed_url['x_goog_meta_owner'], } resp = requests.post(signed_url['url'], data=payload, files=files) if not (
resp.status_code >= 200 and resp.status_code < 205): raise Exception(resp.text) print 'Uploaded: {}'.format(signed_url['
pod_path'])
DinoCow/airflow
airflow/providers/microsoft/azure/example_dags/example_local_to_adls.py
Python
apache-2.0
1,492
0.00067
# 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 os from airflow import models from airflow.providers.microsoft.azure.transfers.local_to_adls import LocalToAzureDataLakeStorageOperator from airflow.utils.dates import days_ago LOCAL_FILE_PATH = os.environ.get("LOCAL_FILE_PATH", 'localfile.txt') REMOTE_FILE_PATH = os.environ.get("REMOTE_LOCAL_PATH", 'remote') with models.DAG( "example_local_to_adls", start_date=days_ago(1), schedule_interv
al=None, tags=['example'], ) as dag: # [START howto_operator_local_to_adls] upload_file = LocalToAzureDataLakeStorageOperator( task_id='upload_task', local_path=LOCAL_FILE_PATH, remote_path=REMOTE_FILE_P
ATH, ) # [END howto_operator_local_to_adls]
jrafa/hotshot
settings_default.py
Python
mit
110
0
# -
*- coding: utf-8 -*- HOST = 'localhost' PORT
_REDIS = 6379 PORT_APP = 6500 PASSWORD = '' DEBUG = False
iulian787/spack
var/spack/repos/builtin/packages/r-cli/package.py
Python
lgpl-2.1
1,307
0.003826
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RCli(RPackage): """A suite of tools designed to build attractive command line interfaces ('CLIs'). Includes tools for drawing rules, boxes, trees, and 'Unicode' symbols with 'ASCII' alternatives.""" homepage = "https://github.com/r-lib/cli#readme" url = "https://cloud.r-project.org/src/contrib/cli_1.0.0.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/cli" version('2.0.2', sha256='490834e5b80eb036befa0e150996bcab1c4d5d168c3d45209926e52d0d5413b6') version('1.1.0', sha256='4fc00fcdf4fdbdf9b5792faee8c7cf1ed5c4f45b1221d961332cda82dbe60d0a') version('1.0.1', sha256='ef80fbcde15760fd55abbf9413b306e3971b2a7034ab8c415fb52dc0088c
5ee4') version('1.0.0', sha256='8fa3dbfc954ca61b8510f767ede9e8a365dac2ef95fe87c715a0f37d721b5a1d') depends_on('r@2.10:', type=('build', 'run')) depends_on('r-assertthat', type=('build',
'run')) depends_on('r-crayon@1.3.4:', type=('build', 'run')) depends_on('r-glue', when='@2:', type=('build', 'run')) depends_on('r-fansi', when='@2:', type=('build', 'run'))
DEVSENSE/PTVS
Python/Tests/TestData/WFastCgi/BadHeaders/myapp.py
Python
apache-2.0
1,130
0.007965
import sys import traceback def test_1(environment, start_response): try: start_response('200', []) raise Exception yield b'200 OK' except: # We get to start again as long as no data has been yielded start_response('500', [], sys.exc_info()) yield b'500 Error' def test_2(environment, start_response): try: start_response('200', []) yield b'200 OK' raise Exception except: # We don't get to start again because of the yield. # This will result in
a generic 500 error start_response('500', [], sys.exc_info()) def test_3(environment, start_response): start_response('200', []) try: start_response('200', []) yield b'Should have thrown when setting headers again' except: start_response('500'
, [], sys.exc_info()) yield traceback.format_exc() def test_4(environment, start_response): yield b'Should throw because we have not set headers' def handler(environment, start_response): return globals()[environment['PATH_INFO'].strip('/')](environment, start_response)
technologiescollege/Blockly-rduino-communication
scripts_XP/Lib/site-packages/autobahn/wamp/test/test_protocol_peer.py
Python
gpl-3.0
4,497
0.001557
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 # IMPLI
ED, 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. # #################################################
############################## from __future__ import absolute_import import os # we need to select a txaio subsystem because we're importing the base # protocol classes here for testing purposes. "normally" you'd import # from autobahn.twisted.wamp or autobahn.asyncio.wamp explicitly. import txaio if os.environ.get('USE_TWISTED', False): txaio.use_twisted() else: txaio.use_asyncio() from autobahn import wamp from autobahn.wamp import message from autobahn.wamp import exception from autobahn.wamp import protocol import unittest2 as unittest class TestPeerExceptions(unittest.TestCase): def test_exception_from_message(self): session = protocol.BaseSession() @wamp.error(u"com.myapp.error1") class AppError1(Exception): pass @wamp.error(u"com.myapp.error2") class AppError2(Exception): pass session.define(AppError1) session.define(AppError2) # map defined errors to user exceptions emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, AppError1) self.assertEqual(exc.args, ()) emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error2') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, AppError2) self.assertEqual(exc.args, ()) # map undefined error to (generic) exception emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, exception.ApplicationError) self.assertEqual(exc.error, u'com.myapp.error3') self.assertEqual(exc.args, ()) self.assertEqual(exc.kwargs, {}) emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3', args=[1, 2, u'hello']) exc = session._exception_from_message(emsg) self.assertIsInstance(exc, exception.ApplicationError) self.assertEqual(exc.error, u'com.myapp.error3') self.assertEqual(exc.args, (1, 2, u'hello')) self.assertEqual(exc.kwargs, {}) emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3', args=[1, 2, u'hello'], kwargs={u'foo': 23, u'bar': u'baz'}) exc = session._exception_from_message(emsg) self.assertIsInstance(exc, exception.ApplicationError) self.assertEqual(exc.error, u'com.myapp.error3') self.assertEqual(exc.args, (1, 2, u'hello')) self.assertEqual(exc.kwargs, {u'foo': 23, u'bar': u'baz'}) def test_message_from_exception(self): session = protocol.BaseSession() @wamp.error(u"com.myapp.error1") class AppError1(Exception): pass @wamp.error(u"com.myapp.error2") class AppError2(Exception): pass session.define(AppError1) session.define(AppError2) exc = AppError1() msg = session._message_from_exception(message.Call.MESSAGE_TYPE, 123456, exc) self.assertEqual(msg.marshal(), [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, "com.myapp.error1"])
pedro2d10/SickRage-FR
sickbeard/providers/elitetorrent.py
Python
gpl-3.0
6,480
0.003086
# coding=utf-8 # Author: CristianBB # # URL: https://sickrage.github.io # # 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 re from six.moves import urllib import traceback from sickbeard import logger, tvcache from sickbeard.bs4_parser import BS4Parser from sickrage.helper.common import try_int from sickrage.providers.torrent.TorrentProvider import TorrentProvider class elitetorrentProvider(TorrentProvider): def __init__(self): TorrentProvider.__init__(self, "EliteTorrent") self.onlyspasearch = None self.minseed = None self.minleech = None self.cache = tvcache.TVCache(self) # Only poll EliteTorrent every 20 minutes max self.urls = { 'base_url': 'http://www.elitetorrent.net', 'search': 'http://www.elitetorrent.net/torrents.php' } self.url = self.urls['base_url'] """ Search query: http://www.elitetorrent.net/torrents.php?cat=4&modo=listado&orden=fecha&pag=1&buscar=fringe cat = 4 => Shows modo = listado => display results mode orden = fecha => order buscar => Search show pag = 1 => page number """ self.search_params = { 'cat': 4, 'modo': 'listado', 'orden': 'fecha', 'pag': 1, 'buscar': '' } def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals, too-many-branches results = [] lang_info = '' if not ep_obj or not ep_obj.show else ep_obj.show.lang for mode in search_strings: items = [] logger.log(u"Search Mode: %s" % mode, logger.DEBUG) # Only search if user conditions are true if self.onlyspasearch and lang_info != 'es' and mode != 'RSS': logger.log(u"Show info is not spanish, skipping provider search", logger.DEBUG) continue for search_string in search_strings[mode]: if mode != 'RSS': logger.log(u"Search string: {search}".format(search=search_string.decode('utf-8')), logger.DEBUG) search_string = re.sub(r'S0*(\d*)E(\d*)', r'\1x\2', search_string) self.search_params['buscar'] = search_string.strip() if mode != 'RSS' else '' search_url = self.urls['search'] + '?' + urllib.parse.urlencode(self.search_params) logger.log(u"Search URL: %s" % search_url, logger.DEBUG) data = self.get_url(search_url, timeout=30) if not data: continue try: with BS4Parser(data, 'html5lib') as html: torrent_table = html.find('table', class_='fichas-listado') torrent_rows = [] if torrent_table is not None: torrent_rows = torrent_table.findAll('tr') if not torrent_rows: logger.log(u"Data returned from provider does not contain any torrents", logger.DEBUG) continue for row in torrent_rows[1:]: try: download_url = self.urls['base_url'] + row.find('a')['href'] title = self._processTitle(row.find('a', class_='nombre')['title']) seeders = try_int(row.find('td', class_='semillas').get_text(strip=True)) leechers = try_int(row.find('td', class_='clientes').get_text(strip=True)) # Provider does not provide size size = -1 except (AttributeError, TypeError, KeyError, ValueError): continue if not all([title, download_url]): continue # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers if mode != 'RSS': logger.log(u"Found result: %s wit
h %s seeders and %s leechers" % (title, seeders, leechers), logger.DEBUG) items.append(item) except Exception: logger.log(u"Failed parsing provider. Traceback: %s" % traceback.format_exc(), logger.WARNING) # For each search mode sort all the items by seeders if available
items.sort(key=lambda tup: tup[3], reverse=True) results += items return results @staticmethod def _processTitle(title): # Quality, if no literal is defined it's HDTV if 'calidad' not in title: title += ' HDTV x264' title = title.replace('(calidad baja)', 'HDTV x264') title = title.replace('(Buena calidad)', '720p HDTV x264') title = title.replace('(Alta calidad)', '720p HDTV x264') title = title.replace('(calidad regular)', 'DVDrip x264') title = title.replace('(calidad media)', 'DVDrip x264') # Language, all results from this provider have spanish audio, we append it to title (avoid to download undesired torrents) title += ' SPANISH AUDIO' title += '-ELITETORRENT' return title.strip() provider = elitetorrentProvider()
Hossein-Noroozpour/PyHGEE
core/HGEApplication.py
Python
mit
168
0
#!/usr/bin/pytho
n3.3 __author__ = 'Hossein Noroozpour Thany Abady' class Application(): def __init__(self): pass def render_loop(self): pass
fnp/prawokultury
prawokultury/settings.d/35-search.py
Python
agpl-3.0
277
0.00361
HAYSTACK_C
ONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/prawokultury' }, } HAYSTACK_DOCUMENT_FIELD = "text" #HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals
.RealtimeSignalProcessor'
WoLpH/EventGhost
eg/Classes/ActionBase.py
Python
gpl-2.0
6,104
0.000328
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2016 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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. # # EventGhost 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 EventGhost. If not, see <http://www.gnu.org/licenses/>. import wx # Local imports import eg class ActionBase(object): """ Base class of every action of a EventGhost plugin written in Python .. attribute:: name Set this to descriptive name in your class definition. It might get translated by :meth:`eg.PluginBase.AddAction` to the user's language if a translation is found. .. attribute:: description Set this to descriptive description in your class definition. It might get translated by :meth:`eg.PluginBase.AddAction` to the user's language if a translation is found. .. attribute:: iconFile Name of an icon file if any. Use a 16x16-PNG and drop it inside your plugin's folder. Only specify the name of the file without extension. .. attribute:: text Assign a class with text strings to this field to get them localised. For more information read the section about :ref:`internationalisation`. .. attribute:: plugin This will be set from :meth:`eg.PluginBase.AddAction` for convenience, so every action can access its own plugin instance through this member variable. .. attribute:: info Internally used house keeping data. Don't try to manipulate this yourself. """ name = None description = None iconFile = None # Don't try to manipulate these variables yourself. # Will be set later by AddAction. plugin = None info = None text = None Exceptions = None __docsort__ = ( "__call__, Configure, GetLabel, Compile, PrintError, Exception" ) # Exceptions class Exception(eg.Exception): pass def __call__(self, *args): """ Do the actual work. Will in most cases be overwritten in subclasses. """ # This Compile call is only here to support calls of pre-compiled # actions (see below) like PythonScript/PythonCommand actions. # Normally all actions will overwrite this __call__ method completely. if self.__class__.Compile != ActionBase.Compile: self.Compile(*args)() else: raise NotImplementedError( "Action has no __call__ method implemented." ) def Compile(self, *args): """ Implementation of pre-compiled parameters. An action class will only override this method, if it uses a special way to implement its action. An action receives a call to :meth:`!Compile` every time their parameters change (the user has reconfigured the action) or in the moment the configuration file is loaded and an action of this type is created because it was saved in the tree. The :meth:`!Compile` method should return a "callable" object, that can be called without any arguments. This "callable" will then be called instead of the the actions :meth:`!__call__` method. This way actions can be build that need considerable time to compute something out of the parameters but need less time for the actual execution of the action. One example of such action is the PythonScript action, that compiles the Python source every time it changes and then this compiled code object gets called instead of doing compile&run in the :meth:`!__call__` method. """ def CallWrapper(): return self(*args) return CallWrapper def Configure(self, *args): """ This should be overridden in a subclass, if the plugin wants to have a configuration dialog. When the plugin is freshly added by the user to the configuration tree there are no *\*args* and you must therefore supply sufficient default arguments. If the plugin is reconfigured by the user, this method will be called with the same arguments as the :meth:`!__start__` method would receive. """ panel = eg.ConfigPanel() p
anel.dialog.buttonRow.applyButton.Enable(False) label = p
anel.StaticText( eg.text.General.noOptionsAction, style=wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE ) panel.sizer.Add((0, 0), 1, wx.EXPAND) panel.sizer.Add(label, 0, wx.ALIGN_CENTRE) panel.sizer.Add((0, 0), 1, wx.EXPAND) while panel.Affirmed(): panel.SetResult() def GetLabel(self, *args): """ Returns the label that should be displayed in the configuration tree with the current arguments. The default method simply shows the action name and the first parameter if there is any. If you want to have a different behaviour, you can override it. This method gets called with the same parameters as the :meth:`!__call__` method. """ label = self.name if args: label += ': ' + unicode(args[0]) return label @classmethod def OnAddAction(cls): pass def PrintError(self, msg): """ Print an error message to the logger. Prefer to use :meth:`!self.PrintError` instead of :meth:`eg.PrintError`, since this method gives the user better information about the source of the error. """ eg.PrintError(msg)
openrobotics/openrobotics_thunderbot
pr3_teleop/talos_os/src/talos_smach/state_machines/follow_me_state_machine/no_user_detected_state.py
Python
mit
556
0.010791
## Author: Devon Ash ## Maitnainer: noobaca2@gmail.com import roslib import rospy import smach import smach_ros class NoUserDetectedState(smach.State): d
ef __init__(self): smach.State.__init__(self, outcomes=["UserDetected", "UserOffScreen", "UserOccluded", "TrackingWrongUser"]) self.counter = 0 def execute(self, userdata): rospy.loginfo("No user detected") user_detected = 1 if (user_detected): return "UserDetected" else: return "Tr
ackingWrongUser"
JaDogg/__py_playground
reference/parsley/examples/trace_visualiser.py
Python
mit
2,033
0.000492
fr
om tkinter.scrolledtext import ScrolledText import tkinter as tk from trace_json import traceparse from parsley_json import jsonGrammar jsonData = open('337141-steamcube.json').read() class Tracer(object): def __init__(self, grammarWin, inputWin, logWin, trace): self.grammarWin = grammarWin self.inputWin = inputWin
self.logWin = logWin self.trace = trace self.position = 0 def advance(self): if self.position < len(self.trace): self.position += 1 self.display() def rewind(self): if self.position > 0: self.position -= 1 self.display() def display(self): def updateHighlight(w, start, end=None): w.tag_remove("highlight", "1.0", tk.END) start = "1.0+%sc" % (start,) if end is not None: end = "1.0+%sc" % (end,) w.tag_add("highlight", start, end) w.tag_configure("highlight", background="yellow") _, (grammarStart, grammarEnd), inputPos = self.trace[self.position] updateHighlight(self.grammarWin, grammarStart, grammarEnd) updateHighlight(self.inputWin, inputPos) def display(grammar, src, trace): r = tk.Tk() f = tk.Frame(master=r) lt = ScrolledText(master=f) rt = ScrolledText(master=f) lt.pack(side="left", expand=True, fill="both") rt.pack(side="right", expand=True, fill="both") bot = ScrolledText(master=r, height=5) tracer = Tracer(lt, rt, bot, trace) toolbar = tk.Frame(master=r) tk.Button(toolbar, text="Next", width=5, command=tracer.advance).pack( side="left") tk.Button(toolbar, text="Prev", width=5, command=tracer.rewind).pack( side="left") f.pack(expand=1, fill="both") toolbar.pack(fill=tk.X) bot.pack(fill=tk.X) lt.insert(tk.END, grammar) rt.insert(tk.END, src) tracer.display() return r _, trace = traceparse(jsonData) root = display(jsonGrammar, jsonData, trace) root.mainloop()
ifduyue/sentry
src/sentry/south_migrations/0310_auto__add_field_savedsearch_owner.py
Python
bsd-3-clause
109,233
0.000861
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'SavedSearch.owner' db.add_column( 'sentry_savedsearch', 'owner', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')( to=orm['sentry.User'], null=True ), keep_default=False ) def backwards(self, orm): # Deleting field 'SavedSearch.owner' db.delete_column('sentry_savedsearch', 'owner_id') models = { 'sentry.activity': { 'Meta': { 'object_name': 'Activity' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'Tr
ue'
} ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ) }, 'sentry.apiapplication': { 'Meta': { 'object_name': 'ApiApplication' }, 'allowed_origins': ('django.db.models.fields.TextField', [], { 'null': 'True', 'blank': 'True' }), 'client_id': ( 'django.db.models.fields.CharField', [], { 'default': "'fe2733e3954542ac8f6cf90ffcbd3b79e389172515a24faeb7ed124ffd78c9e8'", 'unique': 'True', 'max_length': '64' } ), 'client_secret': ( 'sentry.db.models.fields.encrypted.EncryptedTextField', [], { 'default': "'e215d3d1ec6e44ef8cf5fd79620982ffc5dd33d7225643149e601a15046d8109'" } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'homepage_url': ('django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ( 'django.db.models.fields.CharField', [], { 'default': "'Nongenealogic Salvatore'", 'max_length': '64', 'blank': 'True' } ), 'owner': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'privacy_url': ('django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True' }), 'redirect_uris': ('django.db.models.fields.TextField', [], {}), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'terms_url': ('django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True' }) }, 'sentry.apiauthorization': { 'Meta': { 'unique_together': "(('user', 'application'),)", 'object_name': 'ApiAuthorization' }, 'application': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.ApiApplication']", 'null': 'True' } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'scope_list': ( 'sentry.db.models.fields.array.ArrayField', [], { 'of': ('django.db.models.fields.TextField', [], {}) } ), 'scopes': ('django.db.models.fields.BigIntegerField', [], { 'default': 'None' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.apigrant': { 'Meta': { 'object_name': 'ApiGrant' }, 'application': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.ApiApplication']" } ), 'code': ( 'django.db.models.fields.CharField', [], { 'default': "'aad6032d25614f529931584f529a0eaf'", 'max_length': '64', 'db_index': 'True' } ), 'expires_at': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime(2017, 3, 23, 0, 0)', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'redirect_uri': ('django.db.models.fields.CharField', [], { 'max_length': '255' }), 'scope_list': ( 'sentry.db.models.fields.array.ArrayField', [], { 'of': ('django.db.models.fields.TextField', [], {}) } ), 'scopes': ('django.db.models.fields.BigIntegerField', [], { 'default': 'None' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.apikey': { 'Meta': { 'object_name': 'ApiKey' }, 'allowed_origins': ('django.db.models.fields.TextField', [], { 'null': 'True', 'blank': 'True' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '32' }), 'label': ( 'django.db.models.fields.CharField', [], { 'default': "'Default'", 'max_length': '64',
izzygomez/cocoon
crypto/crypto.py
Python
mit
4,136
0.013781
from Crypto.Cipher import AES import base64 import hashlib import math BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[0:-ord(s[-1])] # pseudo-random function def PRF(key, plaintext): keyHash = hashlib.sha256(key).hexdigest() ptxtHash = hashlib.sha256(plaintext).hexdigest() return hashlib.sha256((ptxtHash + keyHash)).hexdigest() def CBC_MAC(key, iv, text): aes = AES.new(key, AES.MODE_CBC, iv) raw = aes.encrypt(pad(text)) hex_string = raw.encode('hex') hex_MAC = hex_string[-32:] raw_MAC = hex_MAC.decode('hex') return base64.b64encode(raw_MAC) def AES_Enc(key, iv, text): aes = AES.new(key, AES.MODE_CBC, iv) raw = aes.encrypt(pad(text)) return base64.b64encode(raw) def AES_Dec(key, iv, ctxt): aes = AES.new(key, AES.MODE_CBC, iv) raw = base64.b64decode(ctxt) return unpad(aes.decrypt(raw)) # index, inputSize are integers # key is a string # Return the permuted index def permute(index, inputSize, key): # Pad the index and inputSize to make sure they are a power of 2 bitLength = int(math.ceil(math.log(inputSize, 2))) paddedIndex = bin(index)[2:].zfill(bitLength) # Next, split into left and right # If there are an even amount of bits if bitLength % 2 == 0: leftHalf = paddedIndex[:bitLength/2] rightHalf = paddedIndex[bitLength/2:] rightRandom = hashBinary(rightHalf, key, bitLength/2) leftHalf = int(leftHalf, 2) rightRandom = int(rightRandom, 2) rightXor = leftHalf ^ rightRandom rightXor = bin(rightXor)[2:].zfill(bitLength/2) concatenation = rightHalf + rightXor return int(concatenation, 2) # In case there are an odd number of bits else: leftHalf = paddedIndex[:bitLength/2] rightHalf = paddedIndex[bitLength/2:] rightRandom = hashBinary(rightHalf[:bitLength/2+1], key, bitLength/2) leftHalf = int(leftHalf, 2) rightRandom = int(rightRandom, 2) rightXor = leftHalf ^ rightRandom rightXor = bin(rightXor)[2:].zfill(bitLength/2) concatenation = rightHalf + rightXor return int(concatenation, 2) # Takes in a value (binary), key (string), and length, and returns a hash # of the value of length length. def hashBinary(value, key, length): keyHash = hashlib.sha256(key.encode()).hexdigest() valueHash = hashlib.sha256(value.encode()).hexdigest() hashValue = hashlib.sha256((valueHash + keyHash).encode()).hexdigest() return bin(int(hashValue, 16))[2:length+2] # Similar to the above function def unpermute(permutedIndex, inputSize, key):
# Pad the index and inputSize to make sure they are a power of 2 bitLength = int(math.ceil(math.log(inputSize, 2))) paddedPermutedIndex = bin(permutedIndex)[2:].zfill(bitLength) # Next, split into left and right # If there are an even am
ount of bits if bitLength % 2 == 0: leftHalf = paddedPermutedIndex[:bitLength/2] rightHalf = paddedPermutedIndex[bitLength/2:] leftRandom = hashBinary(leftHalf, key, bitLength/2) rightHalf = int(rightHalf, 2) leftRandom = int(leftRandom, 2) leftXor = leftRandom ^ rightHalf leftXor = bin(leftXor)[2:].zfill(bitLength/2) concatenation = leftXor + leftHalf return int(concatenation, 2) else: leftHalf = paddedPermutedIndex[:bitLength/2 + 1] rightHalf = paddedPermutedIndex[bitLength/2 + 1:] leftRandom = hashBinary(leftHalf[:bitLength/2+1], key, bitLength/2) rightHalf = int(rightHalf, 2) leftRandom = int(leftRandom, 2) leftXor = leftRandom ^ rightHalf leftXor = bin(leftXor)[2:].zfill(bitLength/2) concatenation = leftXor + leftHalf return int(concatenation, 2) def permuteSecure(index, inputSize, key): firstRound = permute(index, inputSize, key) secondRound = permute(firstRound, inputSize, key) thirdRound = permute(secondRound, inputSize, key) return thirdRound def unpermuteSecure(permutedIndex, inputSize, key): firstRound = unpermute(permutedIndex, inputSize, key) secondRound = unpermute(firstRound, inputSize, key) thirdRound = unpermute(secondRound, inputSize, key) return thirdRound test = permuteSecure(5, 9, 'a') print unpermuteSecure(test, 9, 'a')
alexm92/sentry
src/sentry/rules/conditions/event_frequency.py
Python
bsd-3-clause
2,896
0
""" sentry.rules.conditions.event_frequency ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from datetime import timedelta from django import forms from django.utils import timezone from sentry.rules.conditions.base import EventCondition class Interval(object): ONE_MINUTE = '1m' ONE_HOUR = '1h' ONE_DAY = '1d' class EventFrequencyForm(forms.Form): interval = forms.ChoiceField(choices=( (Interval.ONE_MINUTE, 'one minute'), (Interval.ONE_HOUR, 'one hour'), (Interval.ONE_DAY, 'one day'), )) value = forms.IntegerField(widget=forms.TextInput(attrs={ 'placeholder': '100', 'type': 'number' })) class BaseEventFrequencyCondition(EventCondition): form_cls = EventFrequencyForm label = NotImplemented # subclass must implement def __init__(self, *args, **kwargs): from sentry.app import tsdb self.tsdb = kwargs.pop('tsdb', tsdb) super(BaseEventFrequencyCondition, self).__init__(*args, **kwargs) def passes(self, event, state): interval = self.get_option('interval') try: value = int(self.get_option('value')) except (TypeError, ValueError): return False if not interval: return False current_value = self.get_rate(event, interval) return current_value > value def query(self, event, start, end): """ """ raise NotImplementedError # subclass must implement def get_rate(self, event, interval): end = timezone.now() if interval == Interval.ONE_MINUTE: start = end - timedelta(minutes=1) elif interval == Interval.ONE_HOUR: start = end - timedelta(hours=1) elif interval == Interval.ONE_DAY: start = end - timedelta(hours=24) else: raise ValueError(interval) return self.query( event, start, end, ) class EventFrequencyCondition(BaseEventFrequencyCondition): label = 'An event is seen more than {value} times in {interval}' def query(self, event, start, end): return self.tsdb.get
_sums( model=self.tsdb.models.group, keys=[event.group_id], start=start, end=end, )[event.group_id] class EventUniqueUserFrequencyCondition(BaseEventFrequencyCondition): label = 'An event is seen by more than {value} users in {interval}' def query(self, event, start, end): return self.tsdb.get_distinct_counts_totals( model=self.tsdb.models.users_affected
_by_group, keys=[event.group_id], start=start, end=end, )[event.group_id]
yosshy/nova
nova/tests/unit/scheduler/filters/test_affinity_filters.py
Python
apache-2.0
8,801
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 from oslo_config import cfg from nova import objects from nova.scheduler.filters import affinity_filter from nova import test from nova.tests.unit.scheduler import fakes CONF = cfg.CONF CONF.import_opt('my_ip', 'nova.netconf') class TestDifferentHostFilter(test.NoDBTestCase): def setUp(self): super(TestDifferentHostFilter, self).setUp() self.filt_cls = affinity_filter.DifferentHostFilter() def test_affinity_different_filter_passes(self): host = fakes.FakeHostState('host1', 'node1', {}) inst1 = objects.Instance(uuid='different') host.instances = {inst1.uuid: inst1} f
ilter_properties = {'context': mock.sentinel.ctx,
'scheduler_hints': { 'different_host': ['same'], }} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_different_filter_no_list_passes(self): host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'different_host': 'same'}} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_different_filter_fails(self): inst1 = objects.Instance(uuid='same') host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {inst1.uuid: inst1} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'different_host': ['same'], }} self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_different_filter_handles_none(self): inst1 = objects.Instance(uuid='same') host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {inst1.uuid: inst1} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': None} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) class TestSameHostFilter(test.NoDBTestCase): def setUp(self): super(TestSameHostFilter, self).setUp() self.filt_cls = affinity_filter.SameHostFilter() def test_affinity_same_filter_passes(self): inst1 = objects.Instance(uuid='same') host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {inst1.uuid: inst1} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'same_host': ['same'], }} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_same_filter_no_list_passes(self): host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'same_host': 'same'}} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_same_filter_fails(self): inst1 = objects.Instance(uuid='different') host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {inst1.uuid: inst1} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'same_host': ['same'], }} self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_same_filter_handles_none(self): inst1 = objects.Instance(uuid='different') host = fakes.FakeHostState('host1', 'node1', {}) host.instances = {inst1.uuid: inst1} filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': None} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) class TestSimpleCIDRAffinityFilter(test.NoDBTestCase): def setUp(self): super(TestSimpleCIDRAffinityFilter, self).setUp() self.filt_cls = affinity_filter.SimpleCIDRAffinityFilter() def test_affinity_simple_cidr_filter_passes(self): host = fakes.FakeHostState('host1', 'node1', {}) host.host_ip = '10.8.1.1' affinity_ip = "10.8.1.100" filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'cidr': '/24', 'build_near_host_ip': affinity_ip}} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_simple_cidr_filter_fails(self): host = fakes.FakeHostState('host1', 'node1', {}) host.host_ip = '10.8.1.1' affinity_ip = "10.8.1.100" filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': { 'cidr': '/32', 'build_near_host_ip': affinity_ip}} self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_simple_cidr_filter_handles_none(self): host = fakes.FakeHostState('host1', 'node1', {}) affinity_ip = CONF.my_ip.split('.')[0:3] affinity_ip.append('100') affinity_ip = str.join('.', affinity_ip) filter_properties = {'context': mock.sentinel.ctx, 'scheduler_hints': None} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) class TestGroupAffinityFilter(test.NoDBTestCase): def _test_group_anti_affinity_filter_passes(self, filt_cls, policy): host = fakes.FakeHostState('host1', 'node1', {}) filter_properties = {} self.assertTrue(filt_cls.host_passes(host, filter_properties)) filter_properties = {'group_policies': ['affinity']} self.assertTrue(filt_cls.host_passes(host, filter_properties)) filter_properties = {'group_policies': [policy]} filter_properties['group_hosts'] = [] self.assertTrue(filt_cls.host_passes(host, filter_properties)) filter_properties['group_hosts'] = ['host2'] self.assertTrue(filt_cls.host_passes(host, filter_properties)) def test_group_anti_affinity_filter_passes(self): self._test_group_anti_affinity_filter_passes( affinity_filter.ServerGroupAntiAffinityFilter(), 'anti-affinity') def _test_group_anti_affinity_filter_fails(self, filt_cls, policy): host = fakes.FakeHostState('host1', 'node1', {}) filter_properties = {'group_policies': [policy], 'group_hosts': ['host1']} self.assertFalse(filt_cls.host_passes(host, filter_properties)) def test_group_anti_affinity_filter_fails(self): self._test_group_anti_affinity_filter_fails( affinity_filter.ServerGroupAntiAffinityFilter(), 'anti-affinity') def _test_group_affinity_filter_passes(self, filt_cls, policy): host = fakes.FakeHostState('host1', 'node1', {}) filter_properties = {} self.assertTrue(filt_cls.host_passes(host, filter_properties)) filter_properties = {'group_policies': ['anti-affinity']} self.assertTrue(filt_cls.host_passes(host, filter_properties)) filter_properties = {'group_policies': ['affinity'], 'group_hosts': ['host1']} self.assertTrue(filt_cls.host_passes(host, filter_properties)) def test_group_affinity_f
cgeoffroy/son-analyze
scripts/all.py
Python
apache-2.0
2,996
0
#! /usr/bin/env python3 # Copyright (c) 2015 SONATA-NFV, Thales Communications & Security # 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. # # Neither the name of the SONATA-NFV, Thales Communications & Security # nor the names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # This work has been performed in the framework of the SONATA project, # funded by the European Commission under Grant number 671517 through # the Horizon 2020 and 5G-PPP programmes. The authors would like to # acknowledge the contributions of their colleagues of the SONATA # partner consortium (www.sonata-nfv.eu). """all.py launch all the tests and checks for this project""" # pylint: disable=unsubscriptable-object import sys import subprocess import typing # noqa pylint: disable=unused-import from typing import List, Tuple from colorama import init, Fore, Style # type: ignore def launch_command(summaries: List[Tuple[str, int]], name: str, command: List[str]) -> None: # noqa pylint: disable=invalid-sequence-index """Start a command and adds its return code in summaries""" return_code = subprocess.call(command) summaries.append((name, return_code)) print() def print_summaries(summaries: List[Tuple[str, int]]) -> None: """Print on the console the summaries of the executed commands""" def text_summary(name: str, return_code: int) -> str: """Returns
a colorized string corresponding to the return code""" if return_code == 0: return '{} {}: commands succeeded{}'.format(Fore.GREEN, name, Style.RESET_ALL) return '{}ERROR, {}: commands failed{}'.format(Fore.RED, name, Style.RESET_ALL)
print('\n{0} summary {0}'.format('_'*35)) for summary in summaries: print(text_summary(*summary)) def main() -> None: """Main entrypoint""" init() args = sys.argv[1:] summaries = [] # type: List[Tuple[str, int]] commands = [('flake8', 'scripts/flake8.sh'), ('pylint', 'scripts/pylint.sh'), ('mypy', 'scripts/mypy.sh'), ('py.test', 'scripts/py.test.sh'), ] for (name, command) in commands: launch_command(summaries, name, [command] + args) print_summaries(summaries) if __name__ == '__main__': main()
neoatlantis/MTSAT-2-plotter
converter.py
Python
gpl-3.0
468
0.004274
#!/u
sr/bin/python import os from subprocess import * import sys from PIL import Image def convert(table, dimension, dataString): tableStr = ''.join([chr(i) for i in tabl
e]) print "Calling C converter..." proc = Popen(['./converter'], stdin=PIPE, stdout=PIPE, shell=True, bufsize=0) strout, strerr = proc.communicate(tableStr + dataString) print "C converter called..." endstr = strout[-2:] strout = strout[:-2] return strout
thisismyrobot/dnstwister
tests/test_exports.py
Python
unlicense
14,760
0.000678
"""Test the csv/json export functionality.""" import binascii import textwrap import dnstwister.tools import patches from dnstwister.core.domain import Domain def test_csv_export(webapp, monkeypatch): """Test CSV export""" monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999.999', False) ) domain = Domain('a.com') hexdomain = domain.to_hex() response = webapp.get('/search/{}/csv'.format(hexdomain)) assert response.headers['Content-Disposition'] == 'attachment; filename=dnstwister_report_a.com.csv' assert '\n'.join(sorted(response.text.strip().split('\n'))) == textwrap.dedent(""" Domain,Type,Tweak,IP,Error a.com,Addition,aa.com,999.999.999.999,False a.com,Addition,ab.com,999.999.999.999,False a.com,Addition,ac.com,999.999.999.999,False a.com,Addition,ad.com,999.999.999.999,False a.com,Addition,ae.com,999.999.999.999,False a.com,Addition,af.com,999.999.999.999,False a.com,Addition,ag.com,999.999.999.999,False a.com,Addition,ah.com,999.999.999.999,False a.com,Addition,ai.com,999.999.999.999,False a.com,Addition,aj.com,999.999.999.999,False a.com,Addition,ak.com,999.999.999.999,False a.com,Addition,al.com,999.999.999.999,False a.com,Addition,am.com,999.999.999.999,False a.com,Addition,an.com,999.999.999.999,False a.com,Addition,ao.com,999.999.999.999,False a.com,Addition,ap.com,999.999.999.999,False a.com,Addition,aq.com,999.999.999.999,False a.com,Addition,ar.com,999.999.999.999,False a.com,Addition,as.com,999.999.999.999,False a.com,Addition,at.com,999.999.999.999,False a.com,Addition,au.com,999.999.999.999,False a.com,Addition,av.com,999.999.999.999,False a.com,Addition,aw.com,999.999.999.999,False a.com,Addition,ax.com,999.999.999.999,False a.com,Addition,ay.com,999.999.999.999,False a.com,Addition,az.com,999.999.999.999,False a.com,Bitsquatting,c.com,999.999.999.999,False a.com,Bitsquatting,e.com,999.999.999.999,False a.com,Bitsquatting,i.com,999.999.999.999,False a.com,Bitsquatting,q.com,999.999.999.999,False a.com,Original*,a.com,999.999.999.999,False a.com,Replacement,1.com,999.999.999.999,False a.com,Replacement,2.com,999.999.999.999,False a.com,Replacement,s.com,999.999.999.999,False a.com,Replacement,w.com,999.999.999.999,False a.com,Replacement,y.com,999.999.999.999,False a.com,Replacement,z.com,999.999.999.999,False a.com,Various,acom.com,999.999.999.999,False a.com,Various,wwa.com,999.999.999.999,False a.com,Various,www-a.com,999.999.999.999,False a.com,Various,wwwa.com,999.999.999.999,False a.com,Vowel swap,o.com,999.999.999.999,False a.com,Vowel swap,u.com,999.999.999.999,False """).strip() def test_json_export(webapp, monkeypatch): """Test JSON export""" monkeypatch.setattr( 'dnstwister.tools.dnstwist.DomainFuzzer', patches.SimpleFuzzer ) monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999.999', False) ) domain = Domain('a.com') path = domain.to_hex() response = webapp.get('/search/{}/json'.format(path)) assert response.headers['Content-Disposition'] == 'attachment; filename=dnstwister_report_a.com.json' assert response.json == { u'a.com': { u'fuzzy_domains': [ { u'domain-name': u'a.com', u'fuzzer': u'Original*', u'hex': u'612e636f6d', u'resolution': { u'error': False, u'ip': u'999.999.999.999' } }, { u'domain-name': u'a.co', u'fuzzer': u'Pretend', u'hex': u'612e636f', u'resolution': { u'error': False, u'ip': u'999.999.999.999' } } ] } } def test_json_export_one_domain(webapp, monkeypatch): """Test JSON export when no reports""" monkeypatch.setattr( 'dnstwister.tools.dnstwist.DomainFuzzer', patches.SimpleFuzzer ) monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999.999', False) ) domains = ('a.com',) path = ','.join([Domain(d).to_hex() for d in domains]) response = webapp.get('/search/{}/json'.format(path)) assert response.headers['Content-Disposition'] == 'attachment; filename=dnstwister_report_a.com.json' assert response.json == { u'a.com': { u'fuzzy_domains': [ { u'domain-name': u'a.com', u'fuzzer': u'Original*', u'hex': u'612e636f6d', u'resolution': { u'error': False, u'ip': u'999.999.999.999' } }, { u'domain-name': u'a.co', u'fuzzer': u'Pretend', u'hex': u'612e636f', u'resolution': { u'error': False, u'ip': u'999.999.999.999' } } ] } } def test_json_export_no_fuzzy(webapp, monkeypatch): """Test JSON export when no fuzzy domains.""" monkeypatch.setattr( 'dnstwister.tools.dnstwist.DomainFuzzer', patches.NoFuzzer ) monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999.999', False) ) domains = ('a.com',) path = ','.join([Domain(d).to_hex() for d in domains]) response = webapp.get('/search/{}/json'.format(path)) assert response.headers['Content-Disposition'] == 'attachment; filename=dnstwister_re
port_a.com.json' assert response.json == { u'a.com': { u'fuzzy_domains': [ { u'domain-name': u'a.com', u'fuzzer': u'Original*', u'hex': u'612e636f6d', u'resolution': { u'error': False, u'ip': u'999.999.999.999' } } ] } } def test_json_export_formatting(webapp
, monkeypatch): """Test JSON export looks nice :)""" monkeypatch.setattr( 'dnstwister.tools.dnstwist.DomainFuzzer', patches.SimpleFuzzer ) monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999.999', False) ) domain = 'a.com' path = Domain(domain).to_hex() response = webapp.get('/search/{}/json'.format(path)) assert response.headers['Content-Disposition'] == 'attachment; filename=dnstwister_report_a.com.json' assert response.text.strip() == textwrap.dedent(""" { "a.com": { "fuzzy_domains": [ { "domain-name": "a.com", "fuzzer": "Original*", "hex": "612e636f6d", "resolution": { "error": false, "ip": "999.999.999.999" } }, { "domain-name": "a.co", "fuzzer": "Pretend", "hex": "612e636f", "resolution": { "error": false, "ip": "999.999.999.999" } } ] } } """).strip() def test_failed_export(webapp): """Test unknown-format export""" domain = 'a.com' hexdomain = Domain(domain).to_hex() response = webapp.get('/search/{}/xlsx'.format(hexdomain), expect_errors=True) assert response.statu
hsoft/jobprogress
jobprogress/job.py
Python
bsd-3-clause
6,167
0.006162
# Created By: Virgil Dupras # Created On: 2004/12/20 # Copyright 2011 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license class JobCancelled(Exception): "The user has cancelled the job" class JobInProgressError(Exception): "A job is already being performed, you can't perform more than one at the same time." class JobCountError(Exception): "The number of jobs started have exceeded the number of jobs allowed" class Job: """Manages a job's progression and return it's progression through a callback. Note that this class is not foolproof. For example, you could call start_subjob, and then call add_progress from the parent job, and nothing would stop you from doing it. However, it would mess your progression because it is the sub job that is supposed to drive the progression. Another example would be to start a subjob, then start another, and call add_progress from the old subjob. Once again, it would mess your progression. There are no stops because it would remove the lightweight aspect of the class (A Job would need to have a Parent instead of just a callback, and the parent could be None. A lot of checks for nothing.). Another one is that nothing stops you from calling add_progress right after SkipJob. """ #---Magic functions def __init__(self, job_proportions, callback): """Initialize the Job with 'jobcount' jobs. Start every job with start_job(). Every time the job progress is updated, 'callback' is called 'callback' takes a 'progress' int param, and a optional 'desc' parameter. Callback must return false if the job must be cancelled. """ if not hasattr(callback, '__call__'): raise TypeError("'callback' MUST be set when creating a Job") if isinstance(job_proportions, int): job_proportions = [1] * job_proportions self._job_proportions = list(job_proportions) self._jobcount = sum(job_proportions) self._callback = callback self._current_job = 0 self._passed_jobs = 0 self._progress = 0 self._currmax = 1 #---Private def _subjob_callback(self, progress, desc=''): """This is the callback passed to children jobs. """ self.set_progress(progress, desc) return True #if JobCancelled has to be raised, it will be at the highest level def _do_update(self, desc): """Calls the callback function with a % progress as a parameter. The parameter is a int in the 0-100 range. """ if self._current_job: passed_progress = self._passed_jobs * self._currmax current_progress = self._current_job * self._progress total_progress = self._jobcount * self._currmax progress = ((passed_progress + current_progress) * 100) // total_progress else: progress = -1 # indeterminate # It's possible that callback doesn't support a desc arg result = self._callback(progress, desc) if desc else self._callback(progress) if not result: raise JobCancelled() #---Public def add_progress(self, progress=1, desc=''): self.set_progress(self._progress + progress, desc) def check_if_cancelled(self): self._do_update('') def iter_with_progress(self, sequence, desc_format=None, every=1):
''' Iterate through sequence while automatically adding progress. ''' desc = '' if desc_format: desc = desc_format % (0, len(sequence)) self.start_job(len(sequence), desc) for i, element in enumerate(sequence, start=1): yield element if i % every == 0: if desc_format: desc = desc_format % (i, len(sequence)) self.add_progress(progress=every, desc=desc) if desc_format:
desc = desc_format % (len(sequence), len(sequence)) self.set_progress(100, desc) def start_job(self, max_progress=100, desc=''): """Begin work on the next job. You must not call start_job more than 'jobcount' (in __init__) times. 'max' is the job units you are to perform. 'desc' is the description of the job. """ self._passed_jobs += self._current_job try: self._current_job = self._job_proportions.pop(0) except IndexError: raise JobCountError() self._progress = 0 self._currmax = max(1, max_progress) self._do_update(desc) def start_subjob(self, job_proportions, desc=''): """Starts a sub job. Use this when you want to split a job into multiple smaller jobs. Pretty handy when starting a process where you know how many subjobs you will have, but don't know the work unit count for every of them. returns the Job object """ self.start_job(100, desc) return Job(job_proportions, self._subjob_callback) def set_progress(self, progress, desc=''): """Sets the progress of the current job to 'progress', and call the callback """ self._progress = progress if self._progress > self._currmax: self._progress = self._currmax if self._progress < 0: self._progress = 0 self._do_update(desc) class NullJob: def __init__(self, *args, **kwargs): pass def add_progress(self, *args, **kwargs): pass def check_if_cancelled(self): pass def iter_with_progress(self, sequence, *args, **kwargs): return iter(sequence) def start_job(self, *args, **kwargs): pass def start_subjob(self, *args, **kwargs): return NullJob() def set_progress(self, *args, **kwargs): pass nulljob = NullJob()
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/terminal/iosxr.py
Python
bsd-3-clause
1,889
0.000529
# # (c) 2016 Red Hat Inc. # # 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 WITHO
UT 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/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from ansible.plugins.terminal import TerminalBase from ansible.errors import AnsibleConnectionFailure class TerminalModule(TerminalBase): terminal_stdout_re = [ re.compile(br"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"), re.compile(br"\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$"), re.compile(br']]>]]>[\r\n]?') ] terminal_stderr_re = [ re.compile(br"% ?Error"), re.compile(br"% ?Bad secret"), re.compile(br"invalid input", re.I), re.compile(br"(?:incomplete|ambiguous) command", re.I), re.compile(br"connection timed out", re.I), re.compile(br"[^\r\n]+ not found", re.I), re.compile(br"'[^']' +returned error code: ?\d+"), re.compile(br"Failed to commit", re.I) ] def on_open_shell(self): try: for cmd in (b'terminal length 0', b'terminal width 512', b'terminal exec prompt no-timestamp'): self._exec_cli_command(cmd) except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to set terminal parameters')
attojeon/learnsteam.node.js
gpio/dht11Run.py
Python
gpl-2.0
410
0.036585
import RPi.GPIO as GPIO import dht11 import time # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() instance = dht11.DHT
11(pin = 23) while( 1 ) : result = instance.read() if result.is_valid(): print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity)
else: continue # print("Error: %d" % result.error_code) time.sleep(0.5)
Positliver/Salmon
src/config.py
Python
bsd-3-clause
1,728
0.013657
''' Created on 2015-7-11 @author: livepc ''' #encoding=utf-8 import os DownloadDataDir = os.path.join(os.path.dirname(__file__), 'stockdata/') # os.path.pardir: 上级目录 DownloadCodeDir = os.path.join(os.path.dirname(__file__), 'stockcode/') HS300_CodePath =os.path.join(DownloadCodeDir, 'HS300S.csv') SZ50_CodePath =os.path.join(DownloadCodeDir, 'SZ50S.csv') ZZ500_CodePath =os.path.join(DownloadCodeDir, 'ZZ500S.csv') MAX_SELECT_STOCK_COUNT = 5 MAXDISTANCE_DAYS = 7 PRE_PRE_pCHANGE_WETIGHT = 1 # 前二天的跌幅所占的权重 PRE_pCHANGE_WETIGHT = 1 #前一天的跌幅 所占的权重 CURRENT_pCHANGE_WETIGHT = 1 #今天跌幅 所占的权重 OCDistance_PREDATE_WETIGHT = 2 # 前一天价格差 所占的权重 OCDistance_CURRENTDATE_WETIGHT = 5 # 今天价格差 所占的权重 KAIPAN_DELEGATESAIL_S
CALE_0 = 1.02 #没有补过仓的开盘卖价 KAIPAN_DELEGATESAIL_SCALE_1 = 1.01 #补过一次仓的卖价 KAIPAN_DELEGATESAIL_SCALE_2 = 1.00 #补过两次仓的卖价 PANZHONG_BUCANG_SCALE_0 = 0.92 # 盘中相对于今天开盘价的跌8个点 补仓。 WEIPAN_BUCANG_SCALE_0 = 1.02 # 尾盘时 计算是否可以补仓, 当跌幅超过2个点的时候,可以补仓 # KAIPAN_DELEGATEBUY_SCALE_1 = 0.92 #开盘没有卖出,基本判定需要补仓 # KAIPAN_DELEGATEBUY_SCALE_1 = 0.96 #第二次
进行开盘没有卖出的补仓 GEROU_SCALE_0 = 0.95 # 触发割肉条件,成本价跌5个点。 MOST_DAYS_CHIGU = 5 # 触发割肉 超过5天必须持股天数 INITIAL_MONEY= 100000 # 初始资金 CHICANG_BILIE_EXCEPT_BUCANG = 0.5 # 持仓比例, 新买入股票时使用, 补仓不使用 DATE_START = '2013-01-01' DATE_END = '2013-2-01'
leiyangyou/libvips
python/find_class_methods.py
Python
lgpl-2.1
1,412
0.002833
#!/usr/bin/python import sys import logging #logging.basicConfig(level = logging.DEBUG) from gi.repository import Vips, GObject # Search for all VipsOperation which don't have an input image object ... these # should be class methods and need to have their names pasted into Vips.py # This is slow :-( so we don't do this dynamically vips_type_image = GObject.GType.from_name("VipsImage") vips_type_operation = GObject.GType.from_name("VipsOperation") def find_class_methods(cls): if not cls.is_abstract(): op = Vips.Operation.new(cls.name) found = False for prop in op.props: flags = op.get_argument_flags(prop.name) if not flags & Vips.ArgumentFlags.INPUT: continue if not flags & Vips.ArgumentFlags.REQUIRED: continue if GObject.type_is_a(vips_type_image, prop.value_type): found = True break if not found:
gtype = Vips.type_find("VipsOperation", cls.name) nickname = Vips.nickname_find(gtype)
print ' "%s",' % nickname if len(cls.children) > 0: for child in cls.children: # not easy to get at the deprecated flag in an abtract type? if cls.name != 'VipsWrap7': find_class_methods(child) print 'found class methods:' find_class_methods(vips_type_operation)
FinnStutzenstein/OpenSlides
server/openslides/motions/config_variables.py
Python
mit
13,984
0.001001
from django.conf import settings from django.core.validators import MinValueValidator from openslides.core.config import ConfigVariable from openslides.motions.models import MotionPoll from .models import Workflow def get_workflow_choices(): """ Returns a list of all workflows to be used as choices for the config variable 'motions_workflow'. Each list item contains the pk and the display name. """ return [ {"value": str(workflow.pk), "display_name": workflow.name} for workflow in Workflow.objects.all() ] def get_config_variables(): """ Generator which yields all config variables of this app. They are grouped in 'General', 'Amendments', 'Supporters', 'Voting and ballot papers' and 'PDF'. The generator has to be evaluated during app loading (see apps.py). """ # General yield ConfigVariable( name="motions_workflow", default_value="1", input_type="choice", label="Workflow of new motions", choices=get_workflow_choices, weight=310, group="Motions", ) yield ConfigVariable( name="motions_statute_amendments_workflow", default_value="1", input_type="choice", label="Workflow of new statute amendments", choices=get_workflow_choices, weight=312, group="Motions", ) yield ConfigVariable( name="motions_amendments_workflow", default_value="1", input_type="choice", label="Workflow of new amendments", choices=get_workflow_choices, weight=314, group="Motions", ) yield ConfigVariable( name="motions_preamble", default_value="The assembly may decide:", label="Motion preamble", weight=320, group="Motions", ) yield ConfigVariable( name="motions_default_line_numbering", default_value="outside", input_type="choice", label="Default line numbering", choices=( {"value": "outside", "display_name": "outside"}, {"value": "inline", "display_name": "inline"}, {"value": "none", "display_name": "Disabled"}, ), weight=322, group="Motions", ) yield ConfigVariable( name="motions_line_length", default_value=85, input_type="integer", label="Line length", help_text="The maximum number of characters per line. Relevant when line numbering is enabled. Min: 40", weight=323, group="Motions", validators=(MinValueValidator(40),), ) yield ConfigVariable( name="motions_reason_required", default_value=False, input_type="boolean", label="Reason required for creating new motion", weight=324, group="Motions", ) yield ConfigVariable( name="motions_disable_text_on_projector", default_value=False, input_type="boolean", label="Hide motion text on projector", weight=325, group="Motions", ) yield ConfigVariable( name="motions_disable_reason_on_projector", default_value=False, input_type="boolean", label="Hide reason on projector", weight=326, group="Motions", ) yield ConfigVariable( name="motions_disable_recommendation_on_projector", default_value=False, input_type="boolean", label="Hide recommendation on projector", weight=327, group="Motions", ) yield ConfigVariable( name="motions_hide_referring_motions", default_value=False, input_type="boolean", label="Hide referring motions", weight=328, group="Motions", ) yield ConfigVariable( name="motions_disable_sidebox_on_projector", default_value=True, input_type="boolean", label="Show meta information box below the title on projector", weight=329, group="Motions", ) yield ConfigVariable( name="motions_show_sequential_numbers", default_value=True, input_type="boolean", label="Show the sequential number for a motion", help_text="In motion list, motion detail and PDF.", weight=330, group="Motions", ) yield ConfigVariable( name="motions_recommendations_by", default_value="", label="Name of recommender", help_text="Will be displayed as label before selected recommendation. Use an empty value to disable the recommendation system.", weight=332, group="Motions", ) yield ConfigVariable( name="motions_statute_recommendations_by", default_va
lue="", label="Name of recommender for statute amendments", help_text="Will b
e displayed as label before selected recommendation in statute amendments.", weight=333, group="Motions", ) yield ConfigVariable( name="motions_recommendation_text_mode", default_value="diff", input_type="choice", label="Default text version for change recommendations", choices=( {"value": "original", "display_name": "Original version"}, {"value": "changed", "display_name": "Changed version"}, {"value": "diff", "display_name": "Diff version"}, {"value": "agreed", "display_name": "Final version"}, ), weight=334, group="Motions", ) yield ConfigVariable( name="motions_motions_sorting", default_value="identifier", input_type="choice", label="Sort motions by", choices=( {"value": "weight", "display_name": "Call list"}, {"value": "identifier", "display_name": "Identifier"}, ), weight=335, group="Motions", ) # Numbering yield ConfigVariable( name="motions_identifier", default_value="per_category", input_type="choice", label="Identifier", choices=( {"value": "per_category", "display_name": "Numbered per category"}, {"value": "serially_numbered", "display_name": "Serially numbered"}, {"value": "manually", "display_name": "Set it manually"}, ), weight=340, group="Motions", subgroup="Numbering", ) yield ConfigVariable( name="motions_identifier_min_digits", default_value=1, input_type="integer", label="Number of minimal digits for identifier", help_text="Uses leading zeros to sort motions correctly by identifier.", weight=342, group="Motions", subgroup="Numbering", validators=(MinValueValidator(1),), ) yield ConfigVariable( name="motions_identifier_with_blank", default_value=False, input_type="boolean", label="Allow blank in identifier", help_text="Blank between prefix and number, e.g. 'A 001'.", weight=344, group="Motions", subgroup="Numbering", ) # Amendments yield ConfigVariable( name="motions_statutes_enabled", default_value=False, input_type="boolean", label="Activate statute amendments", weight=350, group="Motions", subgroup="Amendments", ) yield ConfigVariable( name="motions_amendments_enabled", default_value=False, input_type="boolean", label="Activate amendments", weight=351, group="Motions", subgroup="Amendments", ) yield ConfigVariable( name="motions_amendments_main_table", default_value=True, input_type="boolean", label="Show amendments together with motions", weight=352, group="Motions", subgroup="Amendments", ) yield ConfigVariable( name="motions_amendments_prefix", default_value="-", label="Prefix for the identifier for amendments", weight=353, group="Motions", subgroup="Amendments", ) yield Co
UQ-UQx/edx-platform_lti
common/djangoapps/external_auth/views.py
Python
agpl-3.0
38,028
0.001499
import functools import json import logging import random import re import string # pylint: disable=deprecated-module import fnmatch import unicodedata import urllib from textwrap import dedent from external_auth.models import ExternalAuthMap from external_auth.djangostore import DjangoOpenIDStore from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME, authenticate, login from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.core.validators import validate_email from django.core.exceptions import ValidationError if settings.FEATURES.get('AUTH_USE_CAS'): from django_cas.views import login as django_cas_login from student.models import UserProfile from django.http import HttpResponse, HttpResponseRedirect, HttpRequest, HttpResponseForbidden from django.utils.http import urlquote, is_safe_url from django.shortcuts import redirect from django.utils.translation import ugettext as _ from edxmako.shortcuts import render_to_response, render_to_string try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from django_future.csrf import ensure_csrf_cookie import django_openid_auth.views as openid_views from django_openid_auth import auth as openid_auth from openid.consumer.consumer import SUCCESS from openid.server.server import Server, ProtocolError, UntrustedReturnURL from openid.server.trustroot import TrustRoot from openid.extensions import ax, sreg from ratelimitbackend.exceptions import RateLimitException import student.views from xmodule.modulestore.django import modulestore from xmodule.course_module import CourseDescriptor from xmodule.modulestore.exceptions import ItemNotFoundError from opaque_keys.edx.locations import SlashSeparatedCourseKey log = logging.getLogger("edx.external_auth") AUDIT_LOG = logging.getLogger("audit") SHIBBOLETH_DOMAIN_PREFIX = settings.SHIBBOLETH_DOMAIN_PREFIX OPENID_DOMAIN_PREFIX = settings.OPENID_DOMAIN_PREFIX # ----------------------------------------------------------------------------- # OpenID Common # ----------------------------------------------------------------------------- @csrf_exempt def default_render_failure(request, message, status=403, template_name='extauth_failure.html', exception=None): """Render an Openid error page to the user""" log.debug("In openid_failure " + message) data = render_to_string(template_name, dict(message=message, exception=exception)) return HttpResponse(data, status=status) # ----------------------------------------------------------------------------- # OpenID Authentication # ----------------------------------------------------------------------------- def generate_password(length=12, chars=string.letters + string.digits): """Generate internal password for externally authenticated user""" choice = random.SystemRandom().choice return ''.join([choice(chars) for _i in range(length)]) @csrf_exempt def openid_login_complete(request, redirect_field_name=REDIRECT_FIELD_NAME, render_failure=None): """Complete the openid login process""" render_failure = (render_failure or default_render_failure) openid_response = openid_views.parse_openid_response(request) if not openid_response: return render_failure(request, 'This is an OpenID relying party endpoint.') if openid_response.status == SUCCESS: external_id = openid_response.identity_url oid_backend = openid_auth.OpenIDBackend() details = oid_backend._extract_user_details(openid_response) log.debug('openid success, details=%s', details) url = getattr(settings, 'OPENID_SSO_SERVER_URL', None) external_domain = "{0}{1}".format(OPENID_DOMAIN_PREFIX, url) fullname = '%s %s' % (details.get('first_name', ''), details.get('last_name', '')) return _external_login_or_signup( request, external_id, external_domain, details, details.get('email', ''), fullname ) return render_failure(request, 'Openid failure') def _external_login_or_signup(request, external_id, external_domain, credentials, email, fullname, retfun=None): """Generic external auth login or signup""" # see if we have a map from this external_id to an edX username try: eamap = ExternalAuthMap.objects.get(external_id=external_id, external_domain=external_domain) log.debug(u'Found eamap=%s', eamap) except ExternalAuthMap.DoesNotExist: # go render form for creating edX user eamap = ExternalAuthMap(external_id=external_id, external_domain=external_domain, external_credentials=json.dumps(credentials)) eamap.external_email = email eamap.external_name = fullname eamap.internal_password = generate_password() log.debug(u'Created eamap=%s', eamap) eamap.save() log.info(u"External_Auth login_or_signup for %s : %s : %s : %s", external_domain, external_id, email, fullname) uses_shibboleth = settings.FEATURES.get('AUTH_USE_SHIB') and external_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX) uses_certs = settings.FEATURES.get('AUTH_USE_CERTIFICATES') internal_user = eamap.user if internal_user is None: if uses_shibboleth: # If we are using shib, try to link ac
counts # For Stanford shib, the email the idp returns is actually under the control of the user. # Since the id the idps return is not user-editable, and is of the from "username@stanford.edu", # use the id to link accounts instead. try: link_user = User.objects.get
(email=eamap.external_id) if not ExternalAuthMap.objects.filter(user=link_user).exists(): # if there's no pre-existing linked eamap, we link the user eamap.user = link_user eamap.save() internal_user = link_user log.info(u'SHIB: Linking existing account for %s', eamap.external_id) # now pass through to log in else: # otherwise, there must have been an error, b/c we've already linked a user with these external # creds failure_msg = _(dedent(""" You have already created an account using an external login like WebAuth or Shibboleth. Please contact %s for support """ % getattr(settings, 'TECH_SUPPORT_EMAIL', 'techsupport@class.stanford.edu'))) return default_render_failure(request, failure_msg) except User.DoesNotExist: log.info(u'SHIB: No user for %s yet, doing signup', eamap.external_email) return _signup(request, eamap, retfun) else: log.info(u'No user for %s yet. doing signup', eamap.external_email) return _signup(request, eamap, retfun) # We trust shib's authentication, so no need to authenticate using the password again uname = internal_user.username if uses_shibboleth: user = internal_user # Assuming this 'AUTHENTICATION_BACKENDS' is set in settings, which I think is safe if settings.AUTHENTICATION_BACKENDS: auth_backend = settings.AUTHENTICATION_BACKENDS[0] else: auth_backend = 'django.contrib.auth.backends.ModelBackend' user.backend = auth_backend if settings.FEATURES['SQUELCH_P
richardliaw/ray
python/ray/tune/examples/pbt_convnet_example.py
Python
apache-2.0
4,748
0
#!/usr/bin/env python # flake8: noqa # yapf: disable # __tutorial_imports_begin__ import argparse import os import numpy as np import torch import torch.optim as optim from torchvision import datasets from ray.tune.examples.mnist_pytorch import train, test, ConvNet,\ get_data_loaders import ray from ray import tune from ray.tune.schedulers import PopulationBasedTraining from ray.tune.utils import validate_save_restore from ray.tune.trial import ExportFormat # __tutorial_imports_end__ # __trainable_begin__ class PytorchTrainable(tune.Trainable): """Train a Pytorch ConvNet with Trainable and PopulationBasedTraining scheduler. The example reuse some of the functions in mnist_pytorch, and is a good demo for how to add the tuning function without changing the original training code. """ def setup(self, config): self.train_loader, self.test_loader = get_data_loaders() self.model = ConvNet() self.optimizer = optim.SGD( self.model.parameters(), lr=config.get("lr", 0.01), momentum=config.get("momentum", 0.9)) def step(self): train(self.model, self.optimizer, self.train_loader) acc = test(self.model, self.test_loader) return {"mean_accuracy": acc} def save_checkpoint(self, checkpoint_dir): checkpoint_path = os.path.join(checkpoint_dir, "model.pth") torch.save(self.model.state_dict(), checkpoint_path) return checkpoint_path def load_checkpoint(self, checkpoint_path): self.model.load_state_dict(torch.load(checkpoint_path)) def _export_model(self, export_formats, export_dir): if export_formats == [ExportFormat.MODEL]: path = os.path.join(export_dir, "exported_convnet.pt") torch.save(self.model.state_dict(), path) return {export_formats[0]: path} else: raise ValueError("unexpected formats: " + str(export_formats)) def reset_config(self, new_config): for param_group in self.optimizer.param_groups: if "lr" in new_config: param_group["lr"] = new_config["lr"] if "momentum" in new_config: param_group["momentum"] = new_config["momentum"] self.config = new_config return True # __trainable_end__ if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--smoke-test", action="store_true", help="Finish quickly for testing") args, _ = parser.parse_known_args() ray.init(num_cpus=2) datasets.MNIST("~/data", train=True, download=True) # check if PytorchTrainble will save/restore correctly before execution validate_save_restore(PytorchTrainable) validate_save_restore(PytorchTrainable, use_object_store=True) # __pbt_begin__ scheduler = PopulationBasedTraining( time_attr="training_iteration", perturbation_interval=5, hyperparam_mutations={ # distribution for resampling "lr": lambda: np.random.uniform(0.0001, 1), # allow perturbations within this set of categorical values "momentum": [0.8, 0.9, 0.99], }) # __pbt_end__ # __tune_begin__ class CustomStopper(tune.Stopper): def __init__(self): self.should_stop = False def __call__(self, trial_id, result): max_iter = 5 if args.smoke_test else 100 if not self.should_stop and result["mean_accuracy"] > 0.96: self.should_stop = True return self.should_stop or result["training_iteration"] >= max_iter def stop_all(self): return self.should_stop stopper = CustomStopper() analysis = tune.run( PytorchTrainable, name="pbt_test", scheduler=scheduler, reuse_actors=True, metric="mean_accuracy", mode="max", verbose=1, stop=stopper,
export_formats=[ExportFormat.MODEL], checkpoint_score_attr="mean_accuracy", checkpoint_freq=5, keep_checkpoints_num=4, num_samples=4, config={ "lr": tune.uniform(0.001, 1), "momentum": tune.uniform(0.001, 1), }) # __tune_end__ best_trial = a
nalysis.best_trial best_checkpoint = analysis.best_checkpoint restored_trainable = PytorchTrainable() restored_trainable.restore(best_checkpoint) best_model = restored_trainable.model # Note that test only runs on a small random set of the test data, thus the # accuracy may be different from metrics shown in tuning process. test_acc = test(best_model, get_data_loaders()[1]) print("best model accuracy: ", test_acc)
DTUWindEnergy/FUSED-Wake
setup.py
Python
mit
2,875
0.005217
#!/usr/bin/env python # -*- coding: utf-8 -*- # # try: # from setuptools import setup # except ImportError: # from distutils.core import setup #from setuptools import setup #from setuptools import Extension from numpy.distutils.core import setup from numpy.distutils.extension import Extension import os import glob with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'sphinx', 'sphinx-fortran', 'numpy', 'sc
ipy', 'pandas',
'matplotlib', 'PyYAML', 'utm' ] test_requirements = [ 'tox', 'pytest', 'coverall', ] setup( name='fusedwake', version='0.1.0', description="A collection of wind farm flow models for FUSED-Wind", long_description=readme + '\n\n' + history, author="Pierre-Elouan Rethore", author_email='pire@dtu.dk', url='https://github.com/DTUWindEnergy/FUSED-Wake', packages=[ 'fusedwake', 'fusedwake.gcl', 'fusedwake.gcl.python', 'fusedwake.noj', # 'fusedwake.noj.python', 'fusedwake.gau', # 'fusedwake.gau.python', #'fusedwake.ainslie', # 'fusedwake.ainslie.python', #'fusedwake.sdwm', ], package_dir={'fusedwake': 'fusedwake'}, include_package_data=True, install_requires=requirements, license="GNU Affero v3", zip_safe=False, keywords='fusedwake', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero v3', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements, ext_package='fusedwake', ext_modules=[Extension('gcl.fortran', glob.glob(os.path.join('fusedwake', 'gcl', 'fortran', 'GCL.f'))), Extension('noj.fortran', glob.glob(os.path.join('fusedwake', 'noj', 'fortran', 'NOJ.f'))), Extension('noj.fortran_mod', glob.glob(os.path.join('fusedwake', 'noj', 'fortran', 'Mod_NOJ.f'))), Extension('gau.fortran', glob.glob(os.path.join('fusedwake', 'gau', 'fortran', 'GAU.f')))], )
sacgup/django-rest-swagger
rest_framework_swagger/__init__.py
Python
bsd-2-clause
1,311
0.000763
VERSION = '0.3.4' DEFAULT_SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_version': '', 'api_path': '/', 'api_key': '', 'token_type': 'Token', 'enabled_methods': ['get', 'post', 'put', 'patch', 'delete'], 'is_authenticated': False, 'is_superuser': False, 'unauthenticated_user': 'django.contrib.auth.models.AnonymousUser', 'permission_denied_handler': None, 'resource_access_handler': None, 'template_path': 'rest_framework_swagger/index.html', 'doc_expansion': 'none', } try: from django.conf import settings from django.test.signals import setting_changed def load_settings(provided_settings): global SWAGGER_SETTINGS SWAGGER_SETTINGS = provided_settings for key, value in DEFAULT_SWAGGER_SETTINGS.items(): if key not in SWAGGER_SETTINGS:
SWAGGER_SETTINGS[key] = value def reload_settings(*args, **kwargs): setting, value = kwargs['setting'], kwargs['value'] if setting == 'SWAGGER_SETTINGS': load_settings(value) load_settings(getattr(settin
gs, 'SWAGGER_SETTINGS', DEFAULT_SWAGGER_SETTINGS)) setting_changed.connect(reload_settings) except: SWAGGER_SETTINGS = DEFAULT_SWAGGER_SETTINGS
AsgerPetersen/QGIS
python/plugins/GdalTools/tools/doExtractProj.py
Python
gpl-2.0
7,413
0.001079
# -*- coding: utf-8 -*- """ *************************************************************************** doExtractProj.py --------------------- Date : August 2011 Copyright : (C) 2011 by Alexander Bruy Email : alexander dot bruy 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__ = 'Alexander Bruy' __date__ = 'August 2011' __copyright__ = '(C) 2011, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import Qt, QCoreApplication, QThread, QMutex from qgis.PyQt.QtWidgets import QDialog, QDialogButtonBox, QApplication, QMessageBox from qgis.PyQt.QtGui import QCursor from .ui_dialogExtractProjection import Ui_GdalToolsDialog as Ui_Dialog from . import GdalTools_utils as Utils import os.path req_mods = {"osgeo": "osgeo [python-gdal]"} try: from osgeo import gdal from osgeo import osr except ImportError as e: error_str = e.args[0] error_mod = error_str.replace("No module named ", "") if error_mod in req_mods: error_str = error_str.replace(error_mod, req_mods[error_mod]) raise ImportError(error_str) class GdalToolsDialog(QDialog, Ui_Dialog): def __init__(self, iface): QDialog.__init__(self, iface.mainWindow()) self.setupUi(self) self.iface = iface self.inSelector.setType(self.inSelector.FILE) self.recurseCheck.hide() self.okButton = self.buttonBox.button(QDialogButtonBox.Ok) self.cancelButton = self.buttonBox.button(QDialogButtonBox.Cancel) self.inSelector.selectClicked.connect(self.fillInputFileEdit) self.batchCheck.stateChanged.connect(self.switchToolMode) def switchToolMode(self): self.recurseCheck.setVisible(self.batchCheck.isChecked()) self.inSelector.clear() if self.batchCheck.isChecked(): self.inFileLabel = self.label.text() self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory")) self.inSelector.selectClicked.disconnect(self.fillInputFileEdit) self.inSelector.selectClicked.connect(self.fillInputDir) else: self.label.setText(self.inFileLabel) self.inSelector.selectClicked.connect(self.fillInputFileEdit) self.inSelector.selectClicked.disconnect(self.fillInputDir) def fillInputFileEdit(self): lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter() inputFile = Utils.FileDialog.getOpenFileName(self, self.tr("Select the file to analyse"), Utils.FileFilter.allRastersFilter(), lastUsedFilter) if not inputFile: return Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter) self.inSelector.setFilename(inputFile) def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory(self, self.tr("Select the input directory with files to Assign projection")) if not inputDir: return self.inSelector.setFilename(inputDir) def reject(self): QDialog.reject(self) def accept(self): self.inFiles = None if self.batchCheck.isChecked(): self.inFiles = Utils.getRasterFiles(self.inSelector.filename(), self.recurseCheck.isChecked()) else: self.inFiles = [self.inSelector.filename()] self.progressBar.setRange(0, len(self.inFiles)) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.okButton.setEnabled(False) self.extractor = ExtractThread(self.inFiles, self.prjCheck.isChecked()) self.extractor.fileProcessed.connect(self.updateProgress) self.extractor.processFinished.connect(self.processingFinished) self.extractor.processInterrupted.connect(self.processingInterrupted) self.buttonBox.rejected.disconnect(self.reject) self.buttonBox.rejected.connect(self.stopProcessing) self.extractor.start() def updateProgress(self): self.progressBar.setValue(self.progressBar.value() + 1) def processingFinished(self): self.stopProcessing() QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed.")) def processingInterrupted(self): self.restoreGui() def stopProcessing(self): if self.extractor is not None: self.extractor.stop() self.extractor = None self.restoreGui() def restoreGui(self): self.progressBar.setRange(0, 100) self.progressBar.setValue(0) QApplication.restoreOverrideCursor() self.buttonBox.rejected.disconnect(self.stopProcessing) self.buttonBox.rejected.connect(self.reject) self.okButton.setEnabled(True) # ---------------------------------------------------------------------- def extractProjection(filename, createPrj): raster = gdal.Open(unicode(filename)) crs = raster.GetProjection() geotransform = raster.GetGeoTransform() raster = None outFileName = os.path.splitext(unicode(filename))[0] # create prj file requested and if projection available if crs != "" and createPrj: # convert CRS into ESRI format tmp = osr.SpatialReference() tmp.ImportFromWkt(crs) tmp.MorphToESRI() crs = tmp.ExportToWkt() tmp = None prj = open(outFileName + '.prj', 'wt') prj.write(crs) prj.close() # create wld file wld = open(outFileName + '.wld', 'wt') wld.write("%0.8f\n" % geotransform[1]) wld.write("%0.8f\n" % geotransform[4]) wld.write("%0.8f\n" % geotransform[2]) wld.write("%0.8f\n" % geotransform[5]) wld.write("%0.8f\n" % (geotransform[0] + 0.5 * geotransform[1] + 0.5 * geotransform[2])) wld.write("%0.8f\n" % (geotransform[3] + 0.5 * geotransform[4] + 0.5 * geotransform[5])) wld.close() class ExtractThread(QThread): def __init__(self, files, needPrj): QThread.__init__(self, QThread.currentThread()) self.inFiles = files self.needPrj = needPrj self.mutex = QMutex() self.stopMe = 0 de
f run(self): self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False for f in self.inFiles: extractProjection(f, self.needPrj) self.fileProcessed.emit() self.mutex.lock() s = self.stopMe self.mutex.unlock
() if s == 1: interrupted = True break if not interrupted: self.processFinished.emit() else: self.processIterrupted.emit() def stop(self): self.mutex.lock() self.stopMe = 1 self.mutex.unlock() QThread.wait(self)
pudo/aleph
aleph/views/alerts_api.py
Python
mit
3,323
0
from flask import Blueprint, request from aleph.core import db from aleph.model import Alert from aleph.search import DatabaseQueryResult from aleph.views.serializers import AlertSerializer from aleph.views.util import require, obj_or_404 from aleph.views.util import parse_request from aleph.views.context import tag_request blueprint = Blueprint("alerts_api", __name__) @blueprint.route("/api/2/alerts", methods=["GET"]) def index(): """Returns a list of alerts for the user. --- get: summary: List alerts responses: '200': content: application/json: schema: type: object allOf: - $ref: '#/components/schemas/QueryResponse' properties: results: type: array items: $ref: '#/components/schemas/Alert' description: OK tags: - Alert """ require(request.authz.logged_in) query = Alert.by_role_id(request.authz.id) result = DatabaseQueryResult(request, query) return AlertSerializer.jsonify_result(result) @blueprint.route("/api/2/alerts", methods=["POST", "PUT"]) def create(): """Creates an alert for a given query string. --- post: summary: Create an alert requestBody: content: application/json: schema: $ref: '#/components/schemas/AlertCreate' responses: '200': content: application/json: schema: $ref: '#/components/schemas/Alert' description: OK tags: - Alert """ require(request.authz.session_write) data = parse_request("AlertCreate") alert = Alert.create(data, request.authz.id) db.session.commit() tag_request(alert_id=alert.id) return AlertSerializer.jsonify(alert) @blueprint.route("/api/2/alerts/<int:alert_id>", methods=["GET"]) def view(alert_id): """Return the alert with id `alert_id`. --- get: summary: Fetch an alert parameters: - description: The alert ID. in: path name:
alert_id required: true schema: minimum: 1 type: integer example: 2 responses: '200': content: application/json: schema: $ref: '#/components/schemas/Alert' description: OK tags: - Alert """ require(request.aut
hz.logged_in) alert = obj_or_404(Alert.by_id(alert_id, role_id=request.authz.id)) return AlertSerializer.jsonify(alert) @blueprint.route("/api/2/alerts/<int:alert_id>", methods=["DELETE"]) def delete(alert_id): """Delete the alert with id `alert_id`. --- delete: summary: Delete an alert parameters: - description: The alert ID. in: path name: alert_id required: true schema: minimum: 1 type: integer example: 2 responses: '204': description: No Content tags: - Alert """ require(request.authz.session_write) alert = obj_or_404(Alert.by_id(alert_id, role_id=request.authz.id)) alert.delete() db.session.commit() return ("", 204)
googleads/google-ads-python
google/ads/googleads/v10/services/types/keyword_plan_campaign_service.py
Python
apache-2.0
5,624
0.000533
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore from google.ads.googleads.v10.resources.types import keyword_plan_campaign
from google.protobuf import field_mask_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v10.services", marshal="google.ads.googleads.v10", manifest={ "M
utateKeywordPlanCampaignsRequest", "KeywordPlanCampaignOperation", "MutateKeywordPlanCampaignsResponse", "MutateKeywordPlanCampaignResult", }, ) class MutateKeywordPlanCampaignsRequest(proto.Message): r"""Request message for [KeywordPlanCampaignService.MutateKeywordPlanCampaigns][google.ads.googleads.v10.services.KeywordPlanCampaignService.MutateKeywordPlanCampaigns]. Attributes: customer_id (str): Required. The ID of the customer whose Keyword Plan campaigns are being modified. operations (Sequence[google.ads.googleads.v10.services.types.KeywordPlanCampaignOperation]): Required. The list of operations to perform on individual Keyword Plan campaigns. partial_failure (bool): If true, successful operations will be carried out and invalid operations will return errors. If false, all operations will be carried out in one transaction if and only if they are all valid. Default is false. validate_only (bool): If true, the request is validated but not executed. Only errors are returned, not results. """ customer_id = proto.Field(proto.STRING, number=1,) operations = proto.RepeatedField( proto.MESSAGE, number=2, message="KeywordPlanCampaignOperation", ) partial_failure = proto.Field(proto.BOOL, number=3,) validate_only = proto.Field(proto.BOOL, number=4,) class KeywordPlanCampaignOperation(proto.Message): r"""A single operation (create, update, remove) on a Keyword Plan campaign. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. Setting any member of the oneof automatically clears all other members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask that determines which resource fields are modified in an update. create (google.ads.googleads.v10.resources.types.KeywordPlanCampaign): Create operation: No resource name is expected for the new Keyword Plan campaign. This field is a member of `oneof`_ ``operation``. update (google.ads.googleads.v10.resources.types.KeywordPlanCampaign): Update operation: The Keyword Plan campaign is expected to have a valid resource name. This field is a member of `oneof`_ ``operation``. remove (str): Remove operation: A resource name for the removed Keyword Plan campaign is expected, in this format: ``customers/{customer_id}/keywordPlanCampaigns/{keywordPlan_campaign_id}`` This field is a member of `oneof`_ ``operation``. """ update_mask = proto.Field( proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask, ) create = proto.Field( proto.MESSAGE, number=1, oneof="operation", message=keyword_plan_campaign.KeywordPlanCampaign, ) update = proto.Field( proto.MESSAGE, number=2, oneof="operation", message=keyword_plan_campaign.KeywordPlanCampaign, ) remove = proto.Field(proto.STRING, number=3, oneof="operation",) class MutateKeywordPlanCampaignsResponse(proto.Message): r"""Response message for a Keyword Plan campaign mutate. Attributes: partial_failure_error (google.rpc.status_pb2.Status): Errors that pertain to operation failures in the partial failure mode. Returned only when partial_failure = true and all errors occur inside the operations. If any errors occur outside the operations (e.g. auth errors), we return an RPC level error. results (Sequence[google.ads.googleads.v10.services.types.MutateKeywordPlanCampaignResult]): All results for the mutate. """ partial_failure_error = proto.Field( proto.MESSAGE, number=3, message=status_pb2.Status, ) results = proto.RepeatedField( proto.MESSAGE, number=2, message="MutateKeywordPlanCampaignResult", ) class MutateKeywordPlanCampaignResult(proto.Message): r"""The result for the Keyword Plan campaign mutate. Attributes: resource_name (str): Returned for successful operations. """ resource_name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest))
vertexproject/synapse
synapse/cmds/hive.py
Python
apache-2.0
8,362
0.002153
import os import json import shlex import pprint import asyncio import tempfile import functools import subprocess import synapse.exc as s_exc import synapse.common as s_common import synapse.lib.cmd as s_cmd import synapse.lib.cli as s_cli ListHelp = ''' Lists all the keys underneath a particular key in the hive. Syntax: hive ls|list [path] Notes: If path is not specified, the root is listed. ''' GetHelp = ''' Display or save to file the contents of a key in the hive. Syntax: hive get [--file] [--json] {path} ''' DelHelp = ''' Deletes a key in the cell's hive. Syntax: hive rm|del {path} Notes: Delete will recursively delete all subkeys underneath path if they exist. ''' EditHelp = ''' Edits or creates a key in the cell's hive. Syntax: hive edit|mod {path} [--string] ({value} | --editor | -f {filename}) Notes: One may specify the value directly on the command line, from a file, or use an editor. For the --editor option, the environment variable VISUAL or EDITOR must be set. ''' class HiveCmd(s_cli.Cmd): ''' Manipulates values in a cell's Hive. A Hive is a hierarchy persistent storage mechanism typically used for configuration data. ''' _cmd_name = 'hive' _cmd_syntax = ( ('line', {'type': 'glob'}), # type: ignore ) def _make_argparser(self): parser = s_cmd.Parser(prog='hive', outp=self, description=self.__doc__) subparsers = parser.add_subparsers(title='subcommands', required=True, dest='cmd', parser_class
=functools.partial(s_cmd.Parser, outp=self)) parser_ls = subparsers.add_parser('list', aliases=['ls'], help="List entries in the hive", usage=ListHelp) parser_ls.add_argument('path', nargs='?', help='Hive path') parser_get = subparsers.add_parser('get', help="Get any entry in the hi
ve", usage=GetHelp) parser_get.add_argument('path', help='Hive path') parser_get.add_argument('-f', '--file', default=False, action='store', help='Save the data to a file.') parser_get.add_argument('--json', default=False, action='store_true', help='Emit output as json') parser_rm = subparsers.add_parser('del', aliases=['rm'], help='Delete a key in the hive', usage=DelHelp) parser_rm.add_argument('path', help='Hive path') parser_edit = subparsers.add_parser('edit', aliases=['mod'], help='Sets/creates a key', usage=EditHelp) parser_edit.add_argument('--string', action='store_true', help="Edit value as a single string") parser_edit.add_argument('path', help='Hive path') group = parser_edit.add_mutually_exclusive_group(required=True) group.add_argument('value', nargs='?', help='Value to set') group.add_argument('--editor', default=False, action='store_true', help='Opens an editor to set the value') group.add_argument('--file', '-f', help='Copies the contents of the file to the path') return parser async def runCmdOpts(self, opts): line = opts.get('line') if line is None: self.printf(self.__doc__) return core = self.getCmdItem() try: opts = self._make_argparser().parse_args(shlex.split(line)) except s_exc.ParserExit: return handlers = { 'list': self._handle_ls, 'ls': self._handle_ls, 'del': self._handle_rm, 'rm': self._handle_rm, 'get': self._handle_get, 'edit': self._handle_edit, 'mod': self._handle_edit, } await handlers[opts.cmd](core, opts) @staticmethod def parsepath(path): ''' Turn a slash-delimited path into a list that hive takes ''' return path.split('/') async def _handle_ls(self, core, opts): path = self.parsepath(opts.path) if opts.path is not None else None keys = await core.listHiveKey(path=path) if keys is None: self.printf('Path not found') return for key in keys: self.printf(key) async def _handle_get(self, core, opts): path = self.parsepath(opts.path) valu = await core.getHiveKey(path) if valu is None: self.printf(f'{opts.path} not present') return if opts.json: prend = json.dumps(valu, indent=4, sort_keys=True) rend = prend.encode() elif isinstance(valu, str): rend = valu.encode() prend = valu elif isinstance(valu, bytes): rend = valu prend = pprint.pformat(valu) else: rend = json.dumps(valu, indent=4, sort_keys=True).encode() prend = pprint.pformat(valu) if opts.file: with s_common.genfile(opts.file) as fd: fd.truncate(0) fd.write(rend) self.printf(f'Saved the hive entry [{opts.path}] to {opts.file}') return self.printf(f'{opts.path}:\n{prend}') async def _handle_rm(self, core, opts): path = self.parsepath(opts.path) await core.popHiveKey(path) async def _handle_edit(self, core, opts): path = self.parsepath(opts.path) if opts.value is not None: if opts.value[0] not in '([{"': data = opts.value else: data = json.loads(opts.value) await core.setHiveKey(path, data) return elif opts.file is not None: with open(opts.file) as fh: s = fh.read() if len(s) == 0: self.printf('Empty file. Not writing key.') return data = s if opts.string else json.loads(s) await core.setHiveKey(path, data) return editor = os.getenv('VISUAL', (os.getenv('EDITOR', None))) if editor is None or editor == '': self.printf('Environment variable VISUAL or EDITOR must be set for --editor') return tnam = None try: with tempfile.NamedTemporaryFile(mode='w', delete=False) as fh: old_valu = await core.getHiveKey(path) if old_valu is not None: if opts.string: if not isinstance(old_valu, str): self.printf('Existing value is not a string, therefore not editable as a string') return data = old_valu else: try: data = json.dumps(old_valu, indent=4, sort_keys=True) except (ValueError, TypeError): self.printf('Value is not JSON-encodable, therefore not editable.') return fh.write(data) tnam = fh.name while True: retn = subprocess.call(f'{editor} {tnam}', shell=True) if retn != 0: # pragma: no cover self.printf('Editor failed with non-zero code. Aborting.') return with open(tnam) as fh: rawval = fh.read() if len(rawval) == 0: # pragma: no cover self.printf('Empty file. Not writing key.') return try: valu = rawval if opts.string else json.loads(rawval) except json.JSONDecodeError as e: # pragma: no cover self.printf(f'JSON decode failure: [{e}]. Reopening.') await asyncio.sleep(1) continue # We lose the tuple/list distinction in the telepath round trip, so tuplify everything to compare if (opts.string and valu == old_valu) or (not opts.string and s_common.tuplify(valu) == old_valu): self.printf('Valu not changed. Not writing key.')
rayrrr/luigi
test/range_test.py
Python
apache-2.0
65,208
0.001871
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import datetime import fnmatch from helpers import unittest, LuigiTestCase import luigi import mock from luigi.mock import MockTarget, MockFileSystem from luigi.tools.range import (RangeDaily, RangeDailyBase, RangeEvent, RangeHourly, RangeHourlyBase, RangeByMinutes, RangeByMinutesBase, _constrain_glob, _get_filesystems_and_globs, RangeMonthly) class CommonDateMinuteTask(luigi.Task): dh = luigi.DateMinuteParameter() def output(self): return MockTarget(self.dh.strftime('/n2000y01a05n/%Y_%m-_-%daww/21mm%H%Mdara21/ooo')) class CommonDateHourTask(luigi.Task): dh = luigi.DateHourParameter() def output(self): return MockTarget(self.dh.strftime('/n2000y01a05n/%Y_%m-_-%daww/21mm%Hdara21/ooo')) class CommonDateTask(luigi.Task): d = luigi.DateParameter() def output(self): return MockTarget(self.d.strftime('/n2000y01a05n/%Y_%m-_-%daww/21mm01dara21/ooo')) class CommonMonthTask(luigi.Task): m = luigi.MonthParameter() def output(self): return MockTarget(self.m.strftime('/n2000y01a05n/%Y_%maww/21mm01dara21/ooo')) task_a_paths = [ 'TaskA/2014-03-20/18', 'TaskA/2014-03-20/21', 'TaskA/2014-03-20/23', 'TaskA/2014-03-21/00', 'TaskA/2014-03-21/00.attempt.1', 'TaskA/2014-03-21/00.attempt.2', 'TaskA/2014-03-21/01', 'TaskA/2014-03-21/02', 'TaskA/2014-03-21/03.attempt-temp-2014-03-21T13-22-58.165969', 'TaskA/2014-03-21/03.attempt.1', 'TaskA/2014-03-21/03.attempt.2', 'TaskA/2014-03-21/03.attempt.3', 'TaskA/2014-03-21/03.attempt.latest', 'TaskA/2014-03-21/04.attempt-temp-2014-03-21T13-23-09.078249', 'TaskA/2014-03-21/12', 'TaskA/2014-03-23/12', ] task_b_paths = [ 'TaskB/no/worries2014-03-20/23', 'TaskB/no/worries2014-03-21/01', 'TaskB/no/worries2014-03-21/03', 'TaskB/no/worries2014-03-21/04.attempt-yadayada', 'TaskB/no/worries2014-03-21/05', ] mock_contents = task_a_paths + task_b_paths expected_a = [ 'TaskA(dh=2014-03-20T17)', 'TaskA(dh=2014-03-20T19)', 'TaskA(dh=2014-03-20T20)', ] # expected_reverse = [ # ] expected_wrapper = [ 'CommonWrapperTask(dh=2014-03-21T00)', 'CommonWrapperTask(dh=2014-03-21T02)', 'CommonWrapperTask(dh=2014-03-21T03)', 'CommonWrapperTask(dh=2014-03-21T04)', 'CommonWrapperTask(dh=2014-03-21T05)', ] class TaskA(luigi.Task): dh = luigi.DateHourParameter() def output(self): return MockTarget(self.dh.strftime('TaskA/%Y-%m-%d/%H')) class TaskB(luigi.Task): dh = luigi.DateHourParameter() complicator = luigi.Parameter() def output(self): return MockTarget(self.dh.strftime('TaskB/%%s%Y-%m-%d/%H') % self.complicator) class TaskC(luigi.Task): dh = luigi.DateHourParameter() def output(self): return MockTarget(self.dh.strftime('not/a/real/path/%Y-%m-%d/%H')) class CommonWrapperTask(luigi.WrapperTask): dh = luigi.DateHourParameter() def requires(self): yield TaskA(dh=self.dh) yield TaskB(dh=self.dh, complicator='no/worries') # str(self.dh) would complicate beyond working class TaskMinutesA(luigi.Task): dm = luigi.DateMinuteParameter() def output(self): return MockTarget(self.dm.strftime('TaskA/%Y-%m-%d/%H%M')) class TaskMinutesB(luigi.Task): dm = luigi.DateMinuteParameter() complicator = luigi.Parameter() def output(self): return MockTarget(self.dm.strftime('TaskB/%%s%Y-%m-%d/%H%M') % self.complicator) class TaskMinute
sC(luigi.Task): dm = luigi.DateMinuteParameter() def output(self): return MockTarget(self.dm.strftime('not/a/real/path/%Y-%m-%d/%H%M')) class CommonWrapperTaskMinutes(luigi.WrapperTask):
dm = luigi.DateMinuteParameter() def requires(self): yield TaskMinutesA(dm=self.dm) yield TaskMinutesB(dm=self.dm, complicator='no/worries') # str(self.dh) would complicate beyond working def mock_listdir(contents): def contents_listdir(_, glob): for path in fnmatch.filter(contents, glob + '*'): yield path return contents_listdir def mock_exists_always_true(_, _2): yield True def mock_exists_always_false(_, _2): yield False class ConstrainGlobTest(unittest.TestCase): def test_limit(self): glob = '/[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]/[0-9][0-9]' paths = [(datetime.datetime(2013, 12, 31, 5) + datetime.timedelta(hours=h)).strftime('/%Y/%m/%d/%H') for h in range(40)] self.assertEqual(sorted(_constrain_glob(glob, paths)), [ '/2013/12/31/[0-2][0-9]', '/2014/01/01/[0-2][0-9]', ]) paths.pop(26) self.assertEqual(sorted(_constrain_glob(glob, paths, 6)), [ '/2013/12/31/0[5-9]', '/2013/12/31/1[0-9]', '/2013/12/31/2[0-3]', '/2014/01/01/0[012345689]', '/2014/01/01/1[0-9]', '/2014/01/01/2[0]', ]) self.assertEqual(sorted(_constrain_glob(glob, paths[:7], 10)), [ '/2013/12/31/05', '/2013/12/31/06', '/2013/12/31/07', '/2013/12/31/08', '/2013/12/31/09', '/2013/12/31/10', '/2013/12/31/11', ]) def test_no_wildcards(self): glob = '/2014/01' paths = '/2014/01' self.assertEqual(_constrain_glob(glob, paths), [ '/2014/01', ]) def datetime_to_epoch(dt): td = dt - datetime.datetime(1970, 1, 1) return td.days * 86400 + td.seconds + td.microseconds / 1E6 class RangeDailyBaseTest(unittest.TestCase): maxDiff = None def setUp(self): # yucky to create separate callbacks; would be nicer if the callback # received an instance of a subclass of Event, so one callback could # accumulate all types @RangeDailyBase.event_handler(RangeEvent.DELAY) def callback_delay(*args): self.events.setdefault(RangeEvent.DELAY, []).append(args) @RangeDailyBase.event_handler(RangeEvent.COMPLETE_COUNT) def callback_complete_count(*args): self.events.setdefault(RangeEvent.COMPLETE_COUNT, []).append(args) @RangeDailyBase.event_handler(RangeEvent.COMPLETE_FRACTION) def callback_complete_fraction(*args): self.events.setdefault(RangeEvent.COMPLETE_FRACTION, []).append(args) self.events = {} def test_consistent_formatting(self): task = RangeDailyBase(of=CommonDateTask, start=datetime.date(2016, 1, 1)) self.assertEqual(task._format_range([datetime.datetime(2016, 1, 2, 13), datetime.datetime(2016, 2, 29, 23)]), '[2016-01-02, 2016-02-29]') def _empty_subcase(self, kwargs, expected_events): calls = [] class RangeDailyDerived(RangeDailyBase): def missing_datetimes(self, task_cls, finite_datetimes): args = [self, task_cls, finite_datetimes] calls.append(args) return args[-1][:5] task = RangeDailyDerived(of=CommonDateTask, **kwargs) self.assertEqual(task.requires(), []) self.assertEqual(calls, []) self.assertEqual(task.requires(), []) self.assertEqual(calls, []) # subsequent requires() should return the cached result, never call missing_datetimes self.assertEqual(self.events, expected_events) self.assertTrue(task.complete()) def test_stop_before_d
ecreall/nova-ideo
novaideo/views/comment_management/remove.py
Python
agpl-3.0
2,434
0.000411
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from pyramid import renderers from dace.objectofcollaboration.principal.util import get_current from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.form import FormView from pontus.view import BasicView from pontus.view_operation import MultipleView from pontus.default_behavior import Cancel from novaideo.content.processes.comment_management.behaviors import Remove from novaideo.content.comment import Comment from novaideo import _ class RemoveViewStudyReport(BasicView): title = _('Alert for deletion') name = 'alertfordeletion' template = 'novaideo:views/comment_management/templates/alert_remove.pt' def update(self): result = {} user = get_current() values = {'object': self.context, 'current_user': user} comment_body = renderers.render( self.context.templates.get('default'), va
lues, self.request) values = {'comment_body': comment_body} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]}
return result class RemoveForm(FormView): title = _('Remove comment') name = 'removecommentform' behaviors = [Remove, Cancel] viewid = 'removecommentform' validate_behaviors = False def before_update(self): self.action = self.request.resource_url( self.context, 'novaideoapi', query={'op': 'remove_comment'}) formwidget = deform.widget.FormWidget(css_class='comment-remove-form deform') formwidget.template = 'novaideo:views/templates/ajax_form.pt' self.schema.widget = formwidget @view_config( name='removecomment', context=Comment, renderer='pontus:templates/views_templates/grid.pt', ) class RemoveView(MultipleView): title = _('Comment deletion') name = 'removecomment' behaviors = [Remove] viewid = 'removecomment' template = 'pontus:templates/views_templates/simple_multipleview.pt' views = (RemoveViewStudyReport, RemoveForm) validators = [Remove.get_validator()] DEFAULTMAPPING_ACTIONS_VIEWS.update( {Remove: RemoveView})
3cky/horus
src/horus/gui/wizard/scanningPage.py
Python
gpl-2.0
5,007
0.001398
# -*- coding: utf-8 -*- # This file is part of the Horus Project __author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>' __copyright__ = 'Copyright (C) 2014-2015 Mundo Reader S.L.' __license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html' import wx._core from horus.gui.wizard.wizardPage import WizardPage from horus.util import profile from horus.engine.driver.driver import Driver from horus.engine.scan.ciclop_scan import CiclopScan from horus.engine.algorithms.image_capture import ImageCapture class ScanningPage(WizardPage): def __in
it__(self, pare
nt, buttonPrevCallback=None, buttonNextCallback=None): WizardPage.__init__(self, parent, title=_("Scanning"), buttonPrevCallback=buttonPrevCallback, buttonNextCallback=buttonNextCallback) self.driver = Driver() self.ciclop_scan = CiclopScan() self.image_capture = ImageCapture() value = abs(float(profile.settings['motor_step_scanning'])) if value > 1.35: value = _("Low") elif value > 0.625: value = _("Medium") else: value = _("High") self.resolutionLabel = wx.StaticText(self.panel, label=_("Resolution")) self.resolutionComboBox = wx.ComboBox(self.panel, wx.ID_ANY, value=value, choices=[_("High"), _("Medium"), _("Low")], style=wx.CB_READONLY) _choices = [] choices = profile.settings.getPossibleValues('use_laser') for i in choices: _choices.append(_(i)) self.laserDict = dict(zip(_choices, choices)) self.laserLabel = wx.StaticText(self.panel, label=_("Use laser")) self.laserComboBox = wx.ComboBox(self.panel, wx.ID_ANY, value=_(profile.settings['use_laser']), choices=_choices, style=wx.CB_READONLY) self.skipButton.Hide() # Layout vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add(self.resolutionLabel, 0, wx.ALL ^ wx.BOTTOM | wx.EXPAND, 18) hbox.Add(self.resolutionComboBox, 1, wx.ALL ^ wx.BOTTOM | wx.EXPAND, 12) vbox.Add(hbox, 0, wx.ALL | wx.EXPAND, 5) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add(self.laserLabel, 0, wx.ALL ^ wx.BOTTOM | wx.EXPAND, 18) hbox.Add(self.laserComboBox, 1, wx.ALL ^ wx.BOTTOM | wx.EXPAND, 12) vbox.Add(hbox, 0, wx.ALL | wx.EXPAND, 5) self.panel.SetSizer(vbox) self.Layout() self.resolutionComboBox.Bind(wx.EVT_COMBOBOX, self.onResolutionComboBoxChanged) self.laserComboBox.Bind(wx.EVT_COMBOBOX, self.onLaserComboBoxChanged) self.Bind(wx.EVT_SHOW, self.onShow) self.videoView.setMilliseconds(10) self.videoView.setCallback(self.get_image) def onShow(self, event): if event.GetShow(): self.updateStatus(self.driver.is_connected) else: try: self.videoView.stop() except: pass def onResolutionComboBoxChanged(self, event): value = event.GetEventObject().GetValue() if value == _("High"): value = -0.45 elif value == _("Medium"): value = -0.9 elif value == _("Low"): value = -1.8 profile.settings['motor_step_scanning'] = value self.ciclop_scan.motor_step = value def onLaserComboBoxChanged(self, event): value = self.laserDict[event.GetEventObject().GetValue()] profile.settings['use_laser'] = value useLeft = value == 'Left' or value == 'Both' useRight = value == 'Right' or value == 'Both' if useLeft: self.driver.board.laser_on(0) else: self.driver.board.laser_off(0) if useRight: self.driver.board.laser_on(1) else: self.driver.board.laser_off(1) self.ciclop_scan.set_use_left_laser(useLeft) self.ciclop_scan.set_use_right_laser(useRight) def get_image(self): return self.image_capture.capture_texture() def updateStatus(self, status): if status: profile.settings['workbench'] = u'Scanning workbench' self.GetParent().parent.workbenchUpdate(False) self.videoView.play() value = profile.settings['use_laser'] if value == 'Left': self.driver.board.laser_on(0) self.driver.board.laser_off(1) elif value == 'Right': self.driver.board.laser_off(0) self.driver.board.laser_on(1) elif value == 'Both': self.driver.board.lasers_on() else: self.videoView.stop()
Flexlay/flexlay
netpanzer/netpanzer.py
Python
gpl-3.0
12,517
0.009907
## $Id$ ## ## Flexlay - A Generic 2D Game Editor ## Copyright (C) 2002 Ingo Ruhnke <grumbel@gmx.de> ## ## 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. from flexlay import * from netpanzerbrushes import * import os import sys import ConfigParser class Config: config = None datadir = None recent_files = [] def __init__(self): self.config = ConfigParser.ConfigParser() # Setting defaults self.config.add_section("netPanzer") self.config.set("netPanzer", "datadir", "/home/ingo/projects/netpanzer/cvs/netpanzer/") self.config.set("netPanzer", "recent_files", "[]") self.config.read(['netpanzer.cfg', os.path.expanduser('~/.flexlay/netpanzer.cfg')]) self.datadir = self.config.get("netPanzer", "datadir") str = self.config.get("netPanzer", "recent_files") self.recent_files = eval(str) def __del__(self): self.config.set("netPanzer", "datadir", self.datadir) self.config.set("netPanzer", "recent_files", self.recent_files) print "Writing config", self.config.write(open(os.path.expanduser('~/.flexlay/netpanzer.cfg'), 'w')) print "Writing Done" class Level: filename = None data = None editormap = None objects = None def __init__(self, *params): if len(params) == 2: (width, height) = params self.data = NetPanzerFileStruct(tileset, width, height) elif len(params) == 1: (self.filename,) = params self.data = NetPanzerFileStruct(tileset, self.filename) self.objects = ObjectLayer() self.editormap = EditorMap() self.editormap.add_layer(self.data.get_tilemap().to_layer()) self.editormap.add_layer(self.objects.to_layer()) # FIXME: Data might not get freed since its 'recursively' refcounted self.editormap.set_metadata(make_metadata(self)) def save_optfile(self, filename): outpots = [] # FIXME f = open(filename, "w") f.write("ObjectiveCount: %d\n\n" % le
n(outposts)) for (name, x , y) in outpots: f.write("Name: %s\n" % "Foobar") f.write("Location: %d %d\n\n" % (int(x)/32, int(y)/32)) def save_spnfile(self, filename): spawnpoints = [] f = open(filename, "w") f.write("SpawnCount: %d\n\n" % len(spawnpoints)) for (x, y) in spawnpoints: f.write("Location: %d %d\n" % (int(x)/32, int(y)/32)) def save(self, filename): if filename[-4
:] == ".npm": data.save(filename) save_optfile(filename[:-4] + ".opt") save_optfile(filename[:-4] + ".spn") else: raise "Fileextension not valid, must be .npm!" def activate(self, workspace): workspace.set_map(self.editormap) TilemapLayer.set_current(self.data.get_tilemap()) ObjectLayer.set_current(self.objects) flexlay = Flexlay() flexlay.init() config = Config() tileset = Tileset(32) load_netpanzer_tiles(tileset) screen_w = 800 screen_h = 600 editor = Editor() gui = editor.get_gui_manager() myrect = CL_Rect(CL_Point(0, 56), CL_Size(665, 488+56)) editor_map = EditorMapComponent(myrect, gui.get_component()) workspace = Workspace(myrect.get_width(), myrect.get_height()) editor_map.set_workspace(workspace) option_panel = Panel(CL_Rect(CL_Point(666, 56), CL_Size(134, 488+56)), gui.get_component()) brushbox = CL_ListBox(CL_Rect(CL_Point(3, 3), CL_Size(128, 488+56-128-9)), option_panel) for i in brushes: (index, width, height, name) = i brushbox.insert_item("%s - %sx%s" % (name, width, height)) def brushbox_change(index): (start, width, height, name) = brushes[index] brush = TileBrush(width, height) brush.set_data(range(start, start + width*height)) tilemap_paint_tool.set_brush(brush) connect_v1(brushbox.sig_highlighted(), brushbox_change) # Tools tilemap_paint_tool = TileMapPaintTool() tilemap_select_tool = TileMapSelectTool() zoom_tool = ZoomTool() objmap_select_tool = ObjMapSelectTool() workspace.set_tool(tilemap_paint_tool.to_tool()); def on_map_change(): if (workspace.get_map().undo_stack_size() > 0): undo_icon.enable() else: undo_icon.disable() if (workspace.get_map().redo_stack_size() > 0): redo_icon.enable() else: redo_icon.disable() startlevel = Level(256, 256) startlevel.activate(workspace) connect(startlevel.editormap.sig_change(), on_map_change) button_panel = Panel(CL_Rect(CL_Point(0, 23), CL_Size(800, 33)), gui.get_component()) def netpanzer_load_level(filename): level = Level(filename) level.activate(workspace) def netpanzer_save_level(filename): workspace.get_map().get_metadata().save(filename) def gui_level_save_as(): save_dialog.set_filename(os.path.dirname(save_dialog.get_filename()) + "/") save_dialog.run(netpanzer_save_level) def gui_level_save(): if workspace.get_map().get_metadata().filename: save_dialog.set_filename(workspace.get_map().get_metadata().filename) else: save_dialog.set_filename(os.path.dirname(save_dialog.get_filename()) + "/") save_dialog.run(netpanzer_save_level) def gui_level_load(): load_dialog.run(netpanzer_load_level) class Counter: counter = 0; def __init__(self, i): self.counter = i def inc(self, i): self.counter += i return self.counter p = Counter(2) new_icon = Icon(CL_Rect(CL_Point(p.inc(0), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_new.png"), "Some tooltip", button_panel); load_icon = Icon(CL_Rect(CL_Point(p.inc(32), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_open.png"), "Some tooltip", button_panel); load_recent_icon = Icon(CL_Rect(CL_Point(p.inc(32), 2), CL_Size(16, 32)), make_sprite("../data/images/icons24/downarrow.png"), "Some tooltip", button_panel); save_icon = Icon(CL_Rect(CL_Point(p.inc(16), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_save.png"), "Some tooltip", button_panel); save_as_icon = Icon(CL_Rect(CL_Point(p.inc(32), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_save_as.png"), "Some tooltip", button_panel); load_icon.set_callback(gui_level_load) load_recent_icon.set_callback(lambda: recent_files_menu.run()) save_icon.set_callback(gui_level_save) save_as_icon.set_callback(gui_level_save_as) copy_icon = Icon(CL_Rect(CL_Point(p.inc(48), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_copy.png"), "Some tooltip", button_panel); paste_icon = Icon(CL_Rect(CL_Point(p.inc(32), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_paste.png"), "Some tooltip", button_panel); undo_icon = Icon(CL_Rect(CL_Point(p.inc(48), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_undo.png"), "Some tooltip", button_panel); redo_icon = Icon(CL_Rect(CL_Point(p.inc(32), 2), CL_Size(32, 32)), make_sprite("../data/images/icons24/stock_redo.png"), "Some tooltip", button_panel); undo_icon.set_callback(lambda: workspace.get_map().undo()) redo_icon.set_callback(lambda: workspace.get_map().redo()) undo_icon.disable() redo_icon.disable() def gui_togg
nmercier/linux-cross-gcc
win32/bin/Lib/distutils/file_util.py
Python
bsd-3-clause
8,370
0.000597
"""distutils.file_util Utility functions for operating on single files. """ __revision__ = "$Id$" import os from distutils.errors import DistutilsFileError from distutils import log # for generating verbose output in 'copy_file()' _copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'} def _copy_file_contents(src, dst, buffer_size=16*1024): """Copy the file 'src' to 'dst'. Both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files. """ # Stolen from shutil module in the standard library, but with # custom error-handling added. fsrc = None fdst = None try: try: fsrc = open(src, 'rb') except os.error, (errno, errstr): raise DistutilsFileError("could not open '%s': %s" % (src, errstr)) if os.path.exists(dst): try: os.unlink(dst) except os.error, (errno, errstr): raise DistutilsFileError( "could not delete '%s': %s" % (dst, errstr)) try: fdst = open(dst, 'wb') except os.error, (errno, errstr): raise DistutilsFileError( "could not create '%s': %s" % (dst, errstr)) while 1: try: buf = fsrc.read(buffer_size) except os.error, (errno, errstr): raise DistutilsFileError( "could not read from '%s': %s" % (src, errstr)) if not buf: break try: fdst.write(buf) except os.error, (errno, errstr): raise DistutilsFileError( "could not write to '%s': %s" % (dst, errstr)) finally: if fdst: fdst.close() if fsrc: fsrc.close() def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=1, dry_run=0): """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' is true (the default), the file's mode (type and permission bits, or whatever is analogous on the current platform) is copied. If 'preserve_times' is true (the default), the last-modified and last-access times are copied as well. If 'update' is true, 'src' will only be copied if 'dst' does not exist, or if 'dst' does exist but is older than 'src'. 'link' allows you to make hard links (os.link) or symbolic links (os.symlink) instead of copying: set it to "hard" or "sym"; if it is None (the default), files are copied. Don't set 'link' on systems that don't support it: 'copy_file()' doesn't check if hard or symbolic linking is available. If hardlink fails, falls back to _copy_file_contents(). Under Mac OS, uses the native file copy function in macostools; on other systems, uses '_copy_file_contents()' to copy file contents. Return a tuple (dest_name, copied): 'dest_name' is the actual name of the output file, and 'copied' is true if the file was copied (or would have been copied, if 'dry_run' true). """ # XXX if the destination file already exists, we clobber it if # copying, but blow up if linking. Hmmm. And I don't know what # macostools.copyfile() does. Should definitely be consistent, and # should probably blow up if destination exists and we would be # changing it (ie. it's not already a hard/soft link to src OR # (not update) and (src newer than dst). from distutils.dep_util import newer from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE if not os.path.isfile(src): raise DistutilsFileError( "can't copy '%s': doesn't exist or not a regular file" % src) if os.path.isdir(dst): dir = dst dst = os.path.join(dst, os.path.basename(src)) else: dir = os.path.dirname(dst) if update and not newer(src, dst): if verbose >= 1: log.debug("not copying %s (output up-to-date)", src) return dst, 0 try: action = _copy_action[link] except KeyError: raise ValueError("invalid value '%s' for 'link' argument" % link) if verbose >= 1: if os.path.basename(dst) == os.path.basename(src): log.info("%s %s -> %s", action, src, dir) else: log.info("%s %s -> %s", action, src, dst) if dry_run: return (dst, 1) # If linking (hard or symbolic), use the appropriate system call # (Unix only, of course, but that's the caller's responsibility) if link == 'hard': if not (os.path.exists(dst) and os.path.samefile(src, dst)): try: os.link(src, dst) return (dst, 1) except OSError: # If hard linking fails, fall back on copying file # (some special filesystems don't support hard linking # even under Unix, see issue #8876). pass elif link == 'sym': if not (os.path.exists(dst) and os.path.samefile(src, dst)): os.symlink(src, dst) return (dst, 1) # Otherwise (non-Mac, not linking), copy the file contents and # (optionally) copy the times and mode. _copy_file_contents(src, dst) if preserve_mode or preserve_times: st = os.stat(src) # According to David Ascher <da@ski.org>, utime() should be done # before chmod() (at least under NT). if preserve_times: os.utime(dst, (st[ST_ATIME], st[ST_MTIME])) if preserve_mode: os.chmod(dst, S_IMODE(st[ST_MODE])) return (dst, 1) # XXX I suspect this is Unix-specific -- need porting help! def
move_file (src, dst, verbose=1, dry_run=0): """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will be moved into it with the same name; otherwise, 'src' is just renamed to 'dst'. Return the new full name of the file. Handles c
ross-device moves on Unix using 'copy_file()'. What about other systems??? """ from os.path import exists, isfile, isdir, basename, dirname import errno if verbose >= 1: log.info("moving %s -> %s", src, dst) if dry_run: return dst if not isfile(src): raise DistutilsFileError("can't move '%s': not a regular file" % src) if isdir(dst): dst = os.path.join(dst, basename(src)) elif exists(dst): raise DistutilsFileError( "can't move '%s': destination '%s' already exists" % (src, dst)) if not isdir(dirname(dst)): raise DistutilsFileError( "can't move '%s': destination '%s' not a valid path" % \ (src, dst)) copy_it = 0 try: os.rename(src, dst) except os.error, (num, msg): if num == errno.EXDEV: copy_it = 1 else: raise DistutilsFileError( "couldn't move '%s' to '%s': %s" % (src, dst, msg)) if copy_it: copy_file(src, dst, verbose=verbose) try: os.unlink(src) except os.error, (num, msg): try: os.unlink(dst) except os.error: pass raise DistutilsFileError( ("couldn't move '%s' to '%s' by copy/delete: " + "delete '%s' failed: %s") % (src, dst, src, msg)) return dst def write_file (filename, contents): """Create a file with the specified name and write 'contents' (a sequence o
Ziqi-Li/bknqgis
bokeh/examples/howto/server_embed/standalone_embed.py
Python
gpl-2.0
1,771
0.002259
from tornado.ioloop import IOLoop import yaml from bokeh.application.handlers import FunctionHandler from bokeh.application import App
lication from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.plotting import figure from bokeh.server.server import Server from bokeh.themes import Theme from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature io_loop = IOLoop.current() def modify_doc(doc): df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_r
ange=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(json=yaml.load(""" attrs: Figure: background_fill_color: "#DDDDDD" outline_line_color: white toolbar_location: above height: 500 width: 800 Grid: grid_line_dash: [6, 4] grid_line_color: white """)) bokeh_app = Application(FunctionHandler(modify_doc)) server = Server({'/': bokeh_app}, io_loop=io_loop) server.start() if __name__ == '__main__': print('Opening Bokeh application on http://localhost:5006/') io_loop.add_callback(server.show, "/") io_loop.start()
bittner/django-media-tree
media_tree/contrib/cms_plugins/media_tree_image/views.py
Python
bsd-3-clause
1,854
0.002157
from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage from media_tree.contrib.cms_plugins.helpers import PluginLink from media_tree.models import FileNode from media_tree.contrib.views.detail.image import ImageNodeDetailView from django.utils.translation import ugettext_lazy as _ from cms.utils.page_resolver import get_page_from_path from django.http import Http404 class ImagePluginDetailView(ImageNodeDetailView): return_url = None def get_object(self, *args, **kwargs): obj = super(ImagePluginDetailView, self).get_object(*args, **kwargs) if obj: allowed = False # validate that the object is actually published using the plugin... for plugin in MediaTreeImage.objects.filter(node=obj): # ...and on a publicly accessible page. # TODO: Iterating all plugins and getting each page
# is a bit inefficient. page = get_page_from_path(plugin.page.get_path()) if page: allowed = True break if not allowed: raise Http404 return obj def get_context_data(self, *args, **kwargs): context_data = super(ImagePluginDetailView, self).get_context_data( *args, **kwargs)
if self.return_url: page = get_page_from_path(self.return_url.strip('/')) if page: context_data.update({ 'link': PluginLink(url=page.get_absolute_url(), text=_('Back to %s') % page.get_title()) }) return context_data def get(self, request, *args, **kwargs): self.return_url = request.GET.get('return_url', None) return super(ImagePluginDetailView, self).get(request, *args, **kwargs)
PaddlePaddle/Paddle
python/paddle/incubate/__init__.py
Python
apache-2.0
1,529
0.000654
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .optimizer import LookAhead # noqa: F401 from .optimizer import ModelAverage # noqa: F401 from .optimize
r import DistributedFusedLamb # noqa: F401 from .checkpoint import auto
_checkpoint # noqa: F401 from ..fluid.layer_helper import LayerHelper # noqa: F401 from .operators import softmax_mask_fuse_upper_triangle # noqa: F401 from .operators import softmax_mask_fuse # noqa: F401 from .operators import graph_send_recv from .operators import graph_khop_sampler from .tensor import segment_sum from .tensor import segment_mean from .tensor import segment_max from .tensor import segment_min from .passes import fuse_resnet_unit_pass from . import nn #noqa: F401 __all__ = [ 'LookAhead', 'ModelAverage', 'softmax_mask_fuse_upper_triangle', 'softmax_mask_fuse', 'graph_send_recv', 'graph_khop_sampler', 'segment_sum', 'segment_mean', 'segment_max', 'segment_min', ]
vahana/prf
prf/s3.py
Python
mit
954
0.004193
import logging import boto3 import io from slovar import slovar from prf import fs log = logging.getLogger(__name__) def includeme(config): Settings = slovar(config.registry.settings) S3.setup(Settings) class S3(fs.FS): def __init__(self, ds, create=False): path = ds.ns.split('/') bucket_name = path[0] self.path = '/'.join(path[1:]+[ds.name]) s3 = boto3.resource('s3') self.bucket = s3.Bucket(bucket_name) self.file_or_buff = None self._total = None self.reader = fs.FileReader( self.get_file_or_buff(), format = fs.FileReader.get_format_from_fil
e(self.path) ) def drop_collection(self): for it in self.bucket.objects.filter(Prefix=self.path): it.delete() def get_file_or_bu
ff(self): obj = boto3.resource('s3').Object(self.bucket.name, self.path) return io.BytesIO(obj.get()['Body'].read())
eliquious/go-v8
v8-3.28/tools/testrunner/local/progress.py
Python
mit
10,716
0.008585
# Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY 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 NO
T # 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 json import os import sys import time from . import junit_output ABS_PATH_PREFIX = os.getcwd() + os.sep def EscapeCommand(command): parts = [] for part in command: if ' ' in part: # Escape spaces. We may need to escape more characters for this # to work properly. parts.append('"%s"' % part) else: parts.append(part) return " ".join(parts) class ProgressIndicator(object): def __init__(self): self.runner = None def Starting(self): pass def Done(self): pass def AboutToRun(self, test): pass def HasRun(self, test, has_unexpected_output): pass def PrintFailureHeader(self, test): if test.suite.IsNegativeTest(test): negative_marker = '[negative] ' else: negative_marker = '' print "=== %(label)s %(negative)s===" % { 'label': test.GetLabel(), 'negative': negative_marker } class SimpleProgressIndicator(ProgressIndicator): """Abstract base class for {Verbose,Dots}ProgressIndicator""" def Starting(self): print 'Running %i tests' % self.runner.total def Done(self): print for failed in self.runner.failed: self.PrintFailureHeader(failed) if failed.output.stderr: print "--- stderr ---" print failed.output.stderr.strip() if failed.output.stdout: print "--- stdout ---" print failed.output.stdout.strip() print "Command: %s" % EscapeCommand(self.runner.GetCommand(failed)) if failed.output.HasCrashed(): print "exit code: %d" % failed.output.exit_code print "--- CRASHED ---" if failed.output.HasTimedOut(): print "--- TIMEOUT ---" if len(self.runner.failed) == 0: print "===" print "=== All tests succeeded" print "===" else: print print "===" print "=== %i tests failed" % len(self.runner.failed) if self.runner.crashed > 0: print "=== %i tests CRASHED" % self.runner.crashed print "===" class VerboseProgressIndicator(SimpleProgressIndicator): def AboutToRun(self, test): print 'Starting %s...' % test.GetLabel() sys.stdout.flush() def HasRun(self, test, has_unexpected_output): if has_unexpected_output: if test.output.HasCrashed(): outcome = 'CRASH' else: outcome = 'FAIL' else: outcome = 'pass' print 'Done running %s: %s' % (test.GetLabel(), outcome) class DotsProgressIndicator(SimpleProgressIndicator): def HasRun(self, test, has_unexpected_output): total = self.runner.succeeded + len(self.runner.failed) if (total > 1) and (total % 50 == 1): sys.stdout.write('\n') if has_unexpected_output: if test.output.HasCrashed(): sys.stdout.write('C') sys.stdout.flush() elif test.output.HasTimedOut(): sys.stdout.write('T') sys.stdout.flush() else: sys.stdout.write('F') sys.stdout.flush() else: sys.stdout.write('.') sys.stdout.flush() class CompactProgressIndicator(ProgressIndicator): """Abstract base class for {Color,Monochrome}ProgressIndicator""" def __init__(self, templates): super(CompactProgressIndicator, self).__init__() self.templates = templates self.last_status_length = 0 self.start_time = time.time() def Done(self): self.PrintProgress('Done') print "" # Line break. def AboutToRun(self, test): self.PrintProgress(test.GetLabel()) def HasRun(self, test, has_unexpected_output): if has_unexpected_output: self.ClearLine(self.last_status_length) self.PrintFailureHeader(test) stdout = test.output.stdout.strip() if len(stdout): print self.templates['stdout'] % stdout stderr = test.output.stderr.strip() if len(stderr): print self.templates['stderr'] % stderr print "Command: %s" % EscapeCommand(self.runner.GetCommand(test)) if test.output.HasCrashed(): print "exit code: %d" % test.output.exit_code print "--- CRASHED ---" if test.output.HasTimedOut(): print "--- TIMEOUT ---" def Truncate(self, string, length): if length and (len(string) > (length - 3)): return string[:(length - 3)] + "..." else: return string def PrintProgress(self, name): self.ClearLine(self.last_status_length) elapsed = time.time() - self.start_time status = self.templates['status_line'] % { 'passed': self.runner.succeeded, 'remaining': (((self.runner.total - self.runner.remaining) * 100) // self.runner.total), 'failed': len(self.runner.failed), 'test': name, 'mins': int(elapsed) / 60, 'secs': int(elapsed) % 60 } status = self.Truncate(status, 78) self.last_status_length = len(status) print status, sys.stdout.flush() class ColorProgressIndicator(CompactProgressIndicator): def __init__(self): templates = { 'status_line': ("[%(mins)02i:%(secs)02i|" "\033[34m%%%(remaining) 4d\033[0m|" "\033[32m+%(passed) 4d\033[0m|" "\033[31m-%(failed) 4d\033[0m]: %(test)s"), 'stdout': "\033[1m%s\033[0m", 'stderr': "\033[31m%s\033[0m", } super(ColorProgressIndicator, self).__init__(templates) def ClearLine(self, last_line_length): print "\033[1K\r", class MonochromeProgressIndicator(CompactProgressIndicator): def __init__(self): templates = { 'status_line': ("[%(mins)02i:%(secs)02i|%%%(remaining) 4d|" "+%(passed) 4d|-%(failed) 4d]: %(test)s"), 'stdout': '%s', 'stderr': '%s', } super(MonochromeProgressIndicator, self).__init__(templates) def ClearLine(self, last_line_length): print ("\r" + (" " * last_line_length) + "\r"), class JUnitTestProgressIndicator(ProgressIndicator): def __init__(self, progress_indicator, junitout, junittestsuite): self.progress_indicator = progress_indicator self.outputter = junit_output.JUnitTestOutput(junittestsuite) if junitout: self.outfile = open(junitout, "w") else: self.outfile = sys.stdout def Starting(self): self.progress_indicator.runner = self.runner self.progress_indicator.Starting() def Done(self): self.progress_indicator.Done() self.outputter.FinishAndWrite(self.outfile) if self.outfile != sys.stdout: self.outfile.close() def AboutToRun(self, test): self.progress_indicator.AboutToRun(test) def HasRun(self, test, has_unexpected_output): self.progress_indicator.HasRun(test, ha
mkuiack/tkp
tests/test_utility/test_sorting.py
Python
bsd-2-clause
1,609
0.001865
import unittest from collections import namedtuple from datetime import datetime, timedelta import random from tkp.steps.misc import group_per_timestep MockOrmImage = namedtuple('MockOrmImage', ['taustart_ts', 'freq_eff', 'stokes']) now = datetime.now() def create_input(): """ returns a list of mock orm images with taustart_ts, freq_eff and stokes set. """ mockimages
= [] for hours in 1, 2, 3: taustart_ts = now - timedelta(hours=hours) for freq_ef
f in 100, 150, 200: for stokes in 1, 2, 3, 4: mockimages.append(MockOrmImage(taustart_ts=taustart_ts, freq_eff=freq_eff ** 6, stokes=stokes)) # when we seed the RNG with a constant the shuffle will be deterministic random.seed(1) random.shuffle(mockimages) return mockimages def create_output(): mockimages = [] for hours in 3, 2, 1: taustart_ts = now - timedelta(hours=hours) group = [] for freq_eff in 100, 150, 200: for stokes in 1, 2, 3, 4: group.append(MockOrmImage(taustart_ts=taustart_ts, freq_eff=freq_eff ** 6, stokes=stokes)) mockimages.append((taustart_ts, group)) return mockimages class TestSorting(unittest.TestCase): def test_sorting(self): input = create_input() should_be = create_output() evaluated = group_per_timestep(input) self.assertEqual(should_be, evaluated)
MidAtlanticPortal/marco-portal2
marco/portal/base/migrations/0003_auto_20150122_2130.py
Python
isc
440
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('base', '0002_auto_20150122_2113'), ] operations = [ migrations.AlterField( model_n
ame='portalimage', name='creator_URL', field=models.URLField(blank=True),
preserve_default=True, ), ]
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_file_system/shutil_get_unpack_formats.py
Python
apache-2.0
163
0
import shutil for format, exts, description in
shutil.get_unpack_formats(): print('{:<5}: {}, names ending in {}'.format( format,
description, exts))
cmouse/buildbot
master/buildbot/test/integration/test_customservices.py
Python
gpl-2.0
3,838
0
# This file is part of Buildbot. Buildbot 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, version 2. # # 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. # # Copyright Buildbot Team Members from twisted.internet import defer from buildbot.test.util.decorators import flaky from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with one builder and a custom step # The custom step is using a CustomService, in order to calculate its result # we make sure that we can reconfigure the master while build is running class CustomServiceMaster(RunMasterBase): @flaky(bugNumber=3340) @defer.inlineCallbacks def test_customService(self): yield self.setupConfig(masterConfig()) build = yield self.doForceBuild(wantSteps=True) self.assertEqual(
build['steps'][0]['state_string'], 'num reconfig: 1') myService = self.master.service_manager.namedServices['myService'] self.assertEqual(myService.num_reconfig, 1) self.assertTrue(myService.running)
# We do several reconfig, and make sure the service # are reconfigured as expected yield self.master.reconfig() build = yield self.doForceBuild(wantSteps=True) self.assertEqual(myService.num_reconfig, 2) self.assertEqual(build['steps'][0]['state_string'], 'num reconfig: 2') yield self.master.reconfig() myService2 = self.master.service_manager.namedServices['myService2'] self.assertTrue(myService2.running) self.assertEqual(myService2.num_reconfig, 3) self.assertEqual(myService.num_reconfig, 3) yield self.master.reconfig() # second service removed self.assertNotIn( 'myService2', self.master.service_manager.namedServices) self.assertFalse(myService2.running) self.assertEqual(myService2.num_reconfig, 3) self.assertEqual(myService.num_reconfig, 4) # master configuration num_reconfig = 0 def masterConfig(): global num_reconfig num_reconfig += 1 c = {} from buildbot.config import BuilderConfig from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.steps.shell import ShellCommand from buildbot.util.service import BuildbotService class MyShellCommand(ShellCommand): def getResultSummary(self): service = self.master.service_manager.namedServices['myService'] return dict(step="num reconfig: %d" % (service.num_reconfig,)) class MyService(BuildbotService): name = "myService" def reconfigService(self, num_reconfig): self.num_reconfig = num_reconfig return defer.succeed(None) c['schedulers'] = [ ForceScheduler( name="force", builderNames=["testy"])] f = BuildFactory() f.addStep(MyShellCommand(command='echo hei')) c['builders'] = [ BuilderConfig(name="testy", workernames=["local1"], factory=f)] c['services'] = [MyService(num_reconfig=num_reconfig)] if num_reconfig == 3: c['services'].append( MyService(name="myService2", num_reconfig=num_reconfig)) return c
sv1jsb/pCMS
pCMS/urls.py
Python
bsd-3-clause
702
0.012821
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.
autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root': settings.STATIC_ROOT}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root': settin
gs.MEDIA_ROOT}), url(r'fpg/',include('pCMS.fpg.urls')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), url(r'^comments/', include('django.contrib.comments.urls')), )
azumimuo/family-xbmc-addon
plugin.video.bubbles/resources/lib/sources/russian/hoster/open/__init__.py
Python
gpl-2.0
910
0.002198
# -*- coding: utf-8 -*- """ Bubbles Addon Copyright (C) 2
016 Exodus 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 l
ater version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os.path files = os.listdir(os.path.dirname(__file__)) __all__ = [filename[:-3] for filename in files if not filename.startswith('__') and filename.endswith('.py')]
AversivePlusPlus/AversivePlusPlus
tools/conan/conans/client/packager.py
Python
bsd-3-clause
2,736
0.001462
from conans.util.files import mkdir, save, rmdir import os from conans.util.log import logger from conans.paths import CONANINFO, CONAN_MANIFEST from conans.errors import ConanException, format_conanfile_exception from conans.model.build_info import DEFAULT_RES, DEFAULT_BIN, DEFAULT_LIB, DEFAULT_INCLUDE import shutil from conans.model.manifest import FileTreeManifest from conans.client.output import ScopedOutput from conans.client.file_copier import FileCopier def create_package(conanfile, build_folder, package_folder, output, local=False): """ copies built artifacts, libs, headers, data, etc from build_folder to package folder """ mkdir(package_folder) # Make the copy of all the patterns output.info("Generating the package") output.info("Package folder %s" % (package_folder)) conanfile.copy = FileCopier(build_folder, package_folder) def wrap(dst_folder): def new_method(pattern, src=""): conanfile.copy(pattern, dst_folder, src) return new_method conanfile.copy_headers = wrap(DEFAULT_INCLUDE) conanfile.copy_libs = wrap(DEFAULT_LIB) conanfile.copy_bins = wrap(DEFAULT_BIN) conanfile.copy_res = wrap(DEFAULT_RES) try: conanfile.package() package_output = ScopedOutput("%s package()" % output.scope, output) conanfile.copy.report(package_output, warn=True) except Exception as e: if not local: os.chdir(build_folder) try: rmdir(package_folder) except Exception as e_rm: output.error("Unable to remove package folder %s\n%s" % (package_folder, str(e_rm))) output.warn("**** Please delete it manually ****") msg = format_conanfile_exception(output.scope, "package", e)
raise ConanException(msg) _create_aux_files(build_folder, package_folder) output.success("Package '%s' created" %
os.path.basename(package_folder)) def generate_manifest(package_folder): # Create the digest for the package digest = FileTreeManifest.create(package_folder) save(os.path.join(package_folder, CONAN_MANIFEST), str(digest)) def _create_aux_files(build_folder, package_folder): """ auxiliary method that creates CONANINFO in the package_folder """ try: logger.debug("Creating config files to %s" % package_folder) shutil.copy(os.path.join(build_folder, CONANINFO), package_folder) # Create the digest for the package generate_manifest(package_folder) except IOError: raise ConanException("%s does not exist inside of your %s folder. Try to re-build it again" " to solve it." % (CONANINFO, build_folder))
F5Networks/f5-common-python
f5/bigip/tm/util/dig.py
Python
apache-2.0
1,322
0
# coding=utf-8 # # Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "Licen
se"); # 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. # """BIG-
IP® utility module REST URI ``http://localhost/mgmt/tm/util/dig`` GUI Path N/A REST Kind ``tm:util:dig:*`` """ from f5.bigip.mixins import CommandExecutionMixin from f5.bigip.resource import UnnamedResource class Dig(UnnamedResource, CommandExecutionMixin): """BIG-IP® utility command .. note:: This is an unnamed resource so it has no ~Partition~Name pattern at the end of its URI. """ def __init__(self, util): super(Dig, self).__init__(util) self._meta_data['required_command_parameters'].update(('utilCmdArgs',)) self._meta_data['required_json_kind'] = 'tm:util:dig:runstate' self._meta_data['allowed_commands'].append('run')
596acres/django-livinglots-lots
livinglots_lots/urls.py
Python
agpl-3.0
3,373
0.000296
from django.conf.urls import url from livinglots import get_organizer_model, get_watcher_model from .views import (AddToGroupView, CheckLotWithParcelExistsView, CountParticipantsView, CreateLotByGeomView, EmailParticipantsView, HideLotView, HideLotSuccessView, LotAutocomplete, LotContentJSON, LotDetailView, LotGeoJSONDetailView, LotGroupAutocomplete, LotsGeoJSON, LotsGeoJSONPolygon, LotsGeoJSONCentroid, LotsCountView, LotsCountBoundaryView, LotsCSV, LotsKML, RemoveFromGroupView) urlpatterns = [ url(r'^csv/', LotsCSV.as_view(), name='csv'), url(r'^geojson/', LotsGeoJSON.as_view(), name='geojson'), url(r'^kml/', LotsKML.as_view(), name='kml'), url(r'^geojson-polygon/', LotsGeoJSONPolygon.as_view(), name='lot_geojson_polygon'), url(r'^geojson-centroid/', LotsGeoJSONCentroid.as_view(), name='lot_geojson_centroid'), url(r'^count/', LotsCountView.as_view(), name='lot_count'), url(r'^count-by-boundary/', LotsCountBoundaryView.as_view(), name='lot_count_by_boundary'), url(r'^(?P<pk>\d+)/$', LotDetailView.as_view(), name='lot_detail'), url(r'^(?P<pk>\d+)/geojson/$', LotGeoJSONDetailView.as_view(), name='lot_detail_geojson'), url(r'^(?P<pk>\d+)/hide/$', HideLotView.as_view(), name='hide_lot'), url(r'^(?P<pk>\d+)/hide/success/$', HideLotSuccessView.as_view(), name='hide_lot_success'), url(r'^create/by-parcels/check-parcel/(?P<pk>\d+)/$', CheckLotWithParcelExistsView.as_view(), name='create_by_parcels_check_parcel'), url(r'^create/by-geom/$', CreateLotByGeomView.as_view(), name='create_by_geom'), url(r'^(?P<pk>\d+)/group/add/$', AddToGroupView.as_view(), name='add_to_group'), url(r'^(?P<pk>\d+)/group/remove/$', RemoveFromGroupView.as_view(), name='remove_from_group'), url(r'^organize/organizers/email/', EmailParticipantsView.as_view( model=get_organizer_model(), participant_type='organizer', permission_required='organize.email_organizer', ), name='lot_email_organizers'), url(r'^organize/organizers/count/', CountParticipantsView.as_view( model=get_organizer_model(), participant_type='organizer', permission_required='organize.email_organizer', ), name='lot_count_organizers'), url(r'^organize/watchers
/email/', EmailParticipantsView.as_view( model=get_watcher_model(), participant_type='watcher', permission_required='organize.email_watcher', ), name='lot_em
ail_watchers'), url(r'^organize/watchers/count/', CountParticipantsView.as_view( model=get_watcher_model(), participant_type='watcher', permission_required='organize.email_watcher', ), name='lot_count_watchers'), url(r'^(?P<pk>\d+)/content/json/$', LotContentJSON.as_view(), name='lot_content_json'), url( r'^lot-autocomplete/$', LotAutocomplete.as_view(), name='lot-autocomplete' ), url( r'^lotgroup-autocomplete/$', LotGroupAutocomplete.as_view(create_field='name'), name='lotgroup-autocomplete' ), ]
iut-ibk/DynaMind-UrbanSim
3rdparty/opus/src/sanfrancisco/business_relocation_probabilities.py
Python
gpl-2.0
218
0.009174
# Opus/UrbanSim urban simulat
ion software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from urbansim_parcel.business_relocation_probabilities import business_relocation_probabilitie
s
ztp-at/RKSV
librksv/depparser.py
Python
agpl-3.0
26,170
0.002981
########################################################################### # Copyright 2017 ZT Prentner IT GmbH (www.ztp.at) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ########################################################################### """ This module provides functions to parse a DEP. """ from builtins import int from builtins import range from .gettext_helper import _ import copy import ijson from math import ceil from six import string_types from . import utils from . import receipt class DEPException(utils.RKSVVerifyException): """ An exception that is thrown if something is wrong with a DEP. """ pass class DEPParseException(DEPException): """ Indicates that an error occurred while parsing the DEP. """ def __init__(self, msg): super(DEPParseException, self).__init__(msg) self._initargs = (msg,) class MalformedDEPException(DEPParseException): """ Indicates that the DEP is not properly formed. """ def __init__(self, msg=None, groupidx=None): if msg is None: super(MalformedDEPException, self).__init__(_("Malformed DEP")) else: if groupidx is None: super(MalformedDEPException, self).__init__( _('{}.').format(msg)) else: super(MalformedDEPException, self).__init__( _("In group {}: {}.").format(groupidx, msg)) self._initargs = (msg, groupidx) class MissingDEPElementException(MalformedDEPException): """ Indicates that an element in the DEP is missing. """ def __init__(self, elem, groupidx=None): super(MissingDEPElementException, self).__init__( _("Element \"{}\" missing").format(elem), groupidx) self._initargs = (elem, groupidx) class MalformedDEPElementException(MalformedDEPException): """ Indicates that an element in the DEP is malformed. """ def __init__(self, elem, detail=None, groupidx=None): if detail is None: super(MalformedDEPElementException, self).__init__( _("Element \"{}\" malformed").format(elem), groupidx) else: super(MalformedDEPElementException, self).__init__( _("Element \"{}\" malformed: {}").format(elem, detail), groupidx) self._initargs = (elem, detail, groupidx) class DuplicateDEPElementException(MalformedDEPException): """ Indicates that an elemen
t in the DEP is redundant. """ def __init__(self, elem, groupidx=None): super(DuplicateDEPElementException, self).__init__( _("Duplicate element \
"{}\"").format(elem), groupidx) self._initargs = (elem, groupidx) class MalformedCertificateException(DEPParseException): """ Indicates that a certificate in the DEP is not properly formed. """ def __init__(self, cert): super(MalformedCertificateException, self).__init__( _("Certificate \"{}\" malformed.").format(cert)) self._initargs = (cert,) class DEPState(object): def __init__(self, upper = None): self.upper = upper def parse(self, prefix, event, value): raise NotImplementedError("Please implement this yourself.") def ready(self): return False def getChunk(self): raise NotImplementedError("Please implement this yourself.") def needCrt(self): return None def setCrt(self, cert, cert_chain): raise NotImplementedError("Please implement this yourself.") class DEPStateWithData(DEPState): def __init__(self, chunksize, upper = None): super(DEPStateWithData, self).__init__(upper) self.chunksize = chunksize if upper: self.chunk = self.upper.chunk else: self.chunk = list() def currentChunksize(self): return sum(len(recs) for recs, cert, cert_chain in self.chunk) def ready(self): if self.chunksize == 0: return False return self.currentChunksize() >= self.chunksize def getChunk(self): if self.currentChunksize() <= 0: return [] # Note that we only copy the groups (of which there are hopefully few) # FIXME: but still... ret = copy.copy(self.chunk) del self.chunk[:] return ret class DEPStateWithIncompleteData(DEPStateWithData): class WIPData(object): def __init__(self): self.cert = None self.cert_chain = None self.recs = list() def __init__(self, chunksize, upper, idx): super(DEPStateWithIncompleteData, self).__init__(chunksize, upper) if hasattr(upper, 'wip'): self.wip = upper.wip else: self.wip = DEPStateWithIncompleteData.WIPData() self.idx = idx def needCrt(self): if self.wip.cert is None or self.wip.cert_chain is None: return self.idx return None def setCrt(self, cert, cert_chain): self.wip.cert = cert self.wip.cert_chain = cert_chain def mergeIntoChunk(self): if len(self.wip.recs) > 0: clist = self.wip.cert_chain if clist is None: clist = list() self.chunk.append((self.wip.recs, self.wip.cert, clist)) self.wip.recs = list() def ready(self): if self.chunksize == 0: return False return self.currentChunksize() + len(self.wip.recs) >= self.chunksize def getChunk(self): self.mergeIntoChunk() return super(DEPStateWithIncompleteData, self).getChunk() class DEPStateRoot(DEPStateWithData): def __init__(self, chunksize): super(DEPStateRoot, self).__init__(chunksize) self.root_seen = False def parse(self, prefix, event, value): if prefix == '' and event == 'start_map' and value == None: if self.root_seen: raise MalformedDEPException(_('Duplicate DEP root')) self.root_seen = True return DEPStateRootMap(self.chunksize, self) raise MalformedDEPException(_('Malformed DEP root')) class DEPStateRootMap(DEPStateWithData): def __init__(self, chunksize, upper): super(DEPStateRootMap, self).__init__(chunksize, upper) self.groups_seen = False def parse(self, prefix, event, value): if prefix == '' and event == 'end_map': if not self.groups_seen: raise MissingDEPElementException('Belege-Gruppe') return self.upper if prefix == 'Belege-Gruppe': if event != 'start_array': raise MalformedDEPException(_('Malformed DEP root')) if self.groups_seen: raise MalformedDEPException(_('Duplicate DEP root')) self.groups_seen = True return DEPStateBGList(self.chunksize, self) # TODO: handle other elements return self class DEPStateBGList(DEPStateWithData): def __init__(self, chunksize, upper): super(DEPStateBGList, self).__init__(chunksize, upper) self.curIdx = 0 def parse(self, prefix, event, value): if prefix == 'Belege-Gruppe' and event == 'end_array': return self.upper if prefix == 'Belege-Gruppe.item' and event == 'start_map': nextState = DEPStateGroup(self.chunksize, self, self.curIdx) self.curIdx += 1 return nextS
heejongahn/flask-sqlalchemy
flask_sqlalchemy/__init__.py
Python
bsd-3-clause
35,980
0.000334
# -*- coding: utf-8 -*- """ flaskext.sqlalchemy ~~~~~~~~~~~~~~~~~~~ Adds basic SQLAlchemy support to your application. :copyright: (c) 2014 by Armin Ronacher, Daniel Neuhäuser. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement, absolute_import import os import re import sys import time import funct
ools import warnings import sqlalchemy from math import ceil from functools import partial from flask import _request_ctx_stack, abort, has_request_context, request from flask.signals import Namespace from operator import itemgetter from threading import Lock from sqlalchemy import orm, event, inspect from sqlalchemy.orm.exc import UnmappedClassError from sqlalchemy.orm.session import Session as SessionBase from sqlalchemy.engine.url import make_url from sqlalchemy.ext.declarativ
e import declarative_base, DeclarativeMeta from flask_sqlalchemy._compat import iteritems, itervalues, xrange, \ string_types # the best timer function for the platform if sys.platform == 'win32': _timer = time.clock else: _timer = time.time try: from flask import _app_ctx_stack except ImportError: _app_ctx_stack = None __version__ = '2.0' # Which stack should we use? _app_ctx_stack is new in 0.9 connection_stack = _app_ctx_stack or _request_ctx_stack _camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])') _signals = Namespace() models_committed = _signals.signal('models-committed') before_models_committed = _signals.signal('before-models-committed') def _make_table(db): def _make_table(*args, **kwargs): if len(args) > 1 and isinstance(args[1], db.Column): args = (args[0], db.metadata) + args[1:] info = kwargs.pop('info', None) or {} info.setdefault('bind_key', None) kwargs['info'] = info return sqlalchemy.Table(*args, **kwargs) return _make_table def _set_default_query_class(d): if 'query_class' not in d: d['query_class'] = BaseQuery def _wrap_with_default_query_class(fn): @functools.wraps(fn) def newfn(*args, **kwargs): _set_default_query_class(kwargs) if "backref" in kwargs: backref = kwargs['backref'] if isinstance(backref, string_types): backref = (backref, {}) _set_default_query_class(backref[1]) return fn(*args, **kwargs) return newfn def _include_sqlalchemy(obj): for module in sqlalchemy, sqlalchemy.orm: for key in module.__all__: if not hasattr(obj, key): setattr(obj, key, getattr(module, key)) # Note: obj.Table does not attempt to be a SQLAlchemy Table class. obj.Table = _make_table(obj) obj.relationship = _wrap_with_default_query_class(obj.relationship) obj.relation = _wrap_with_default_query_class(obj.relation) obj.dynamic_loader = _wrap_with_default_query_class(obj.dynamic_loader) obj.event = event class _DebugQueryTuple(tuple): statement = property(itemgetter(0)) parameters = property(itemgetter(1)) start_time = property(itemgetter(2)) end_time = property(itemgetter(3)) context = property(itemgetter(4)) @property def duration(self): return self.end_time - self.start_time def __repr__(self): return '<query statement="%s" parameters=%r duration=%.03f>' % ( self.statement, self.parameters, self.duration ) def _calling_context(app_path): frm = sys._getframe(1) while frm.f_back is not None: name = frm.f_globals.get('__name__') if name and (name == app_path or name.startswith(app_path + '.')): funcname = frm.f_code.co_name return '%s:%s (%s)' % ( frm.f_code.co_filename, frm.f_lineno, funcname ) frm = frm.f_back return '<unknown>' class SignallingSession(SessionBase): """The signalling session is the default session that Flask-SQLAlchemy uses. It extends the default session system with bind selection and modification tracking. If you want to use a different session you can override the :meth:`SQLAlchemy.create_session` function. .. versionadded:: 2.0 """ def __init__(self, db, autocommit=False, autoflush=True, **options): #: The application that this session belongs to. self.app = app = db.get_app() track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] bind = options.pop('bind', None) or db.engine if track_modifications is None or track_modifications: _SessionSignalEvents.register(self) SessionBase.__init__( self, autocommit=autocommit, autoflush=autoflush, bind=bind, binds=db.get_binds(self.app), **options ) def get_bind(self, mapper=None, clause=None): # mapper is None if someone tries to just get a connection if mapper is not None: info = getattr(mapper.mapped_table, 'info', {}) bind_key = info.get('bind_key') if bind_key is not None: state = get_state(self.app) return state.db.get_engine(self.app, bind=bind_key) return SessionBase.get_bind(self, mapper, clause) class _SessionSignalEvents(object): @classmethod def register(cls, session): if not hasattr(session, '_model_changes'): session._model_changes = {} event.listen(session, 'before_flush', cls.record_ops) event.listen(session, 'before_commit', cls.record_ops) event.listen(session, 'before_commit', cls.before_commit) event.listen(session, 'after_commit', cls.after_commit) event.listen(session, 'after_rollback', cls.after_rollback) @classmethod def unregister(cls, session): if hasattr(session, '_model_changes'): del session._model_changes event.remove(session, 'before_flush', cls.record_ops) event.remove(session, 'before_commit', cls.record_ops) event.remove(session, 'before_commit', cls.before_commit) event.remove(session, 'after_commit', cls.after_commit) event.remove(session, 'after_rollback', cls.after_rollback) @staticmethod def record_ops(session, flush_context=None, instances=None): try: d = session._model_changes except AttributeError: return for targets, operation in ((session.new, 'insert'), (session.dirty, 'update'), (session.deleted, 'delete')): for target in targets: state = inspect(target) key = state.identity_key if state.has_identity else id(target) d[key] = (target, operation) @staticmethod def before_commit(session): try: d = session._model_changes except AttributeError: return if d: before_models_committed.send(session.app, changes=list(d.values())) @staticmethod def after_commit(session): try: d = session._model_changes except AttributeError: return if d: models_committed.send(session.app, changes=list(d.values())) d.clear() @staticmethod def after_rollback(session): try: d = session._model_changes except AttributeError: return d.clear() class _EngineDebuggingSignalEvents(object): """Sets up handlers for two events that let us track the execution time of queries.""" def __init__(self, engine, import_name): self.engine = engine self.app_package = import_name def register(self): event.listen(self.engine, 'before_cursor_execute', self.before_cursor_execute) event.listen(self.engine, 'after_cursor_execute', self.after_cursor_execute) def before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): if connection_stack.top is not None: context._query_start_time = _timer() def after_cursor_execute(self, conn, cursor, statemen
prusnak/bitcoin
test/functional/rpc_generateblock.py
Python
mit
5,595
0.006256
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. '''Test generateblock rpc. ''' from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) class GenerateBlockTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): node = self.nodes[0] self.log.info('Generate an empty block to address') address = node.getnewaddress() hash = self.generateblock(node, output=address, transactions=[])['hash'] block = node.getblock(blockhash=hash, verbose=2) assert_equal(len(block['tx']), 1) assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], address) self.log.info('Generate an empty block to a descriptor') hash = self.generateblock(node, 'addr(' + address + ')', [])['hash'] block = node.getblock(blockhash=hash, verbosity=2) assert_equal(len(block['tx']), 1) assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], address) self.log.info('Generate an empty block to a combo descriptor with compressed pubkey') combo_key = '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798' combo_address = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' hash = self.generateblock(node, 'combo(' + combo_key + ')', [])['hash'] block = node.getblock(hash, 2) assert_equal(len(block['tx']), 1) assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], combo_address) self.log.info('Generate an empty block to a combo descriptor with uncompressed pubkey') combo_key = '0408ef68c46d20596cc3f6ddf7c8794f71913add807f1dc55949fa805d764d191c0b7ce6894c126fce0babc6663042f3dde9b0cf76467ea315514e5a6731149c67' combo_address = 'mkc9STceoCcjoXEXe6cm66iJbmjM6zR9B2' hash = self.generateblock(node, 'combo(' + combo_key + ')', [])['hash'] block = node.getblock(hash, 2) assert_equal(len(block['tx']), 1) assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], combo_address) # Generate 110 blocks to spend self.generatetoaddress(node, 110, address) # Generate some extra mempool transactions to verify they don't get mined for _ in range(10): node.sendtoaddress(address, 0.001) self.log.info('Generate block with txid') txid = node.sendtoaddress(address, 1) hash = self.generateblock(node, address, [txid])['hash'] block = node.getblock(hash, 1) assert_equal(len(block['tx']), 2) assert_equal(block['tx'][1], txid) self.log.info('Generate block with raw tx') utxos = node.listunspent(addresses=[address]) raw = node.createrawtransaction([{'txid':utxos[0]['txid'], 'vout':utxos[0]['vout']}],[{address:1}]) signed_raw = node.signrawtransactionwithwallet(raw)['hex'] hash = self.generateblock(node, address, [signed_raw])['hash'] block = node.getblock(hash, 1) assert_equal(len(block['tx']), 2) txid = block['tx'][1] assert_equal(node.gettransaction(txid)['hex'], signed_raw)
self.log.info('Fail to generate block with out of order txs') raw1 = node.createrawtransaction([{'txid':txid, 'vout':0}],[{address:0.9999}]) signed_raw1 = node.signrawtransactionwithwallet(raw1)['hex'] txid1 = node.sendrawtransaction(signed_raw1)
raw2 = node.createrawtransaction([{'txid':txid1, 'vout':0}],[{address:0.999}]) signed_raw2 = node.signrawtransactionwithwallet(raw2)['hex'] assert_raises_rpc_error(-25, 'TestBlockValidity failed: bad-txns-inputs-missingorspent', self.generateblock, node, address, [signed_raw2, txid1]) self.log.info('Fail to generate block with txid not in mempool') missing_txid = '0000000000000000000000000000000000000000000000000000000000000000' assert_raises_rpc_error(-5, 'Transaction ' + missing_txid + ' not in mempool.', self.generateblock, node, address, [missing_txid]) self.log.info('Fail to generate block with invalid raw tx') invalid_raw_tx = '0000' assert_raises_rpc_error(-22, 'Transaction decode failed for ' + invalid_raw_tx, self.generateblock, node, address, [invalid_raw_tx]) self.log.info('Fail to generate block with invalid address/descriptor') assert_raises_rpc_error(-5, 'Invalid address or descriptor', self.generateblock, node, '1234', []) self.log.info('Fail to generate block with a ranged descriptor') ranged_descriptor = 'pkh(tpubD6NzVbkrYhZ4XgiXtGrdW5XDAPFCL9h7we1vwNCpn8tGbBcgfVYjXyhWo4E1xkh56hjod1RhGjxbaTLV3X4FyWuejifB9jusQ46QzG87VKp/0/*)' assert_raises_rpc_error(-8, 'Ranged descriptor not accepted. Maybe pass through deriveaddresses first?', self.generateblock, node, ranged_descriptor, []) self.log.info('Fail to generate block with a descriptor missing a private key') child_descriptor = 'pkh(tpubD6NzVbkrYhZ4XgiXtGrdW5XDAPFCL9h7we1vwNCpn8tGbBcgfVYjXyhWo4E1xkh56hjod1RhGjxbaTLV3X4FyWuejifB9jusQ46QzG87VKp/0\'/0)' assert_raises_rpc_error(-5, 'Cannot derive script without private keys', self.generateblock, node, child_descriptor, []) if __name__ == '__main__': GenerateBlockTest().main()
prodromou87/gem5
tests/configs/realview-switcheroo-atomic.py
Python
bsd-3-clause
2,428
0
# Copyright (c) 2012 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # un
modified and in its entirety i
n all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY 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. # # Authors: Andreas Sandberg from m5.objects import * from arm_generic import * import switcheroo root = LinuxArmFSSwitcheroo( mem_class=DDR3_1600_x64, cpu_classes=(AtomicSimpleCPU, AtomicSimpleCPU) ).create_root() # Setup a custom test method that uses the switcheroo tester that # switches between CPU models. run_test = switcheroo.run_test
sadad111/leetcodebox
Binary Tree Inorder Traversal.py
Python
gpl-3.0
1,336
0
# /** # * Definition for
a binary tree node. # * public class TreeNode { # * int val; # * TreeNode left; # * TreeNode right; # * TreeNode(int x) { val = x; } # * } # */ # public class Solution { # public List<Integer> inorderTraversal(TreeNode root) { # List<Integer> list = new ArrayList<Integer>(); # # Stack<TreeNode> stack = new Stack<TreeNode>(); # TreeNode cur = root; # # while(cur!=null || !stack.empty()){ # while(cur!=null){ #
stack.add(cur); # cur = cur.left; # } # cur = stack.pop(); # list.add(cur.val); # cur = cur.right; # } # # return list; # } # } # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res, stack = [], [] while True: while root: stack.append(root) root = root.left if not stack: return res node = stack.pop() res.append(node.val) root = node.right
rivasd/djPsych
djsend/migrations/0056_auto_20170614_1552.py
Python
gpl-3.0
588
0.001701
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-06-14 19:52 from __future__ import unicode_literals from django.db import migrations, models cla
ss Migration(migrations.Migration): dependencies = [ ('djsend', '0055_relationcategorizationblock_response_wait'), ] operations = [ migrations.AlterField( model_name='relationcategorizationblock', name='response_wait', field=models.BooleanField(default=False, help_text='If the subject have to wait that the stimuli
are gone before answering'), ), ]
glogiotatidis/bedrock
tests/functional/firefox/test_ios.py
Python
mpl-2.0
1,107
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from selenium.common.exceptions import TimeoutException from pages.firefox.ios import IOSPage @pytest.mark
.nondestructive def
test_send_to_device_sucessful_submission(base_url, selenium): page = IOSPage(selenium, base_url).open() send_to_device = page.send_to_device send_to_device.type_email('success@example.com') send_to_device.click_send() assert send_to_device.send_successful @pytest.mark.nondestructive def test_send_to_device_fails_when_missing_required_fields(base_url, selenium): page = IOSPage(selenium, base_url).open() with pytest.raises(TimeoutException): page.send_to_device.click_send() @pytest.mark.nondestructive def test_send_to_device_not_supported_locale(base_url, selenium): page = IOSPage(selenium, base_url, locale='it').open() assert page.is_app_store_button_displayed assert not page.send_to_device.is_displayed
collingreen/djeroku
project/settings/prod.py
Python
mit
4,008
0
""" Production settings Debug OFF Djeroku Defaults: Mandrill Email -- Requires Mandrill addon dj_database_url and django-postgrespool for heroku postgres configuration memcachify for heroku memcache configuration Commented out by default - redisify for heroku redis cache configuration What you need to set in your heroku environment (heroku config:set key=value): ALLOWED_HOSTS - You MUST add your site urls here if they don't match the included defaults. If you have trouble, try prepending your url with a . - eg: '.yourproject.herokuapp.com'. Optional - Update your production environment SECRET_KEY (created and set automatically by during project creation by the djeroku setup) Email: Default
s to mandril, which is already set up when added to your app There is also a commented version that uses your gmail address. For more control, you can set any of the following keys in your environment: EMAIL_HOST, EMAIL_HOST_PASSWORD, EMAIL_HOST_USER, EMAIL_PORT """ from os
import environ import dj_database_url # automagically sets up whatever memcache heroku addon you have as the cache # https://github.com/rdegges/django-heroku-memcacheify from memcacheify import memcacheify # use redisify instead of memcacheify if you prefer # https://github.com/dirn/django-heroku-redisify # from redisify import redisify from project.settings.common import * # NOQA # ALLOWED HOSTS # https://docs.djangoproject.com/en/1.8/ref/settings/#allowed-hosts ALLOWED_HOSTS = [ '.{{ project_name }}.herokuapp.com', '.{{ project_name}}-staging.herokuapp.com' ] # you MUST add your domain names here, check the link for details # END ALLOWED HOSTS # EMAIL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-password # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-user # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-port # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-use-tls EMAIL_HOST = environ.get('EMAIL_HOST', 'smtp.mandrillapp.com') EMAIL_HOST_PASSWORD = environ.get('MANDRILL_APIKEY', '') EMAIL_HOST_USER = environ.get('MANDRILL_USERNAME', '') EMAIL_PORT = environ.get('EMAIL_PORT', 587) EMAIL_USE_TLS = True # use this to channel your emails through a gmail powered account instead # EMAIL_HOST = environ.get('EMAIL_HOST', 'smtp.gmail.com') # EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER', 'your_email@gmail.com') # EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD', '') # EMAIL_PORT = environ.get('EMAIL_PORT', 587) # EMAIL_USE_TLS = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME # See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email SERVER_EMAIL = EMAIL_HOST_USER # END EMAIL CONFIGURATION # DATABASE CONFIGURATION DATABASES['default'] = dj_database_url.config() DATABASES['default']['ENGINE'] = 'django_postgrespool' # END DATABASE CONFIGURATION # CACHE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = memcacheify() # CACHES = redisify() # END CACHE CONFIGURATION # Simplest redis-based config possible # *very* easy to overload free redis/MQ connection limits # You MUST update REDIS_SERVER_URL or use djeroku_redis to set it automatically BROKER_POOL_LIMIT = 0 BROKER_URL = environ.get('REDIS_SERVER_URL') CELERY_IGNORE_RESULT = True CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True # END CELERY CONFIGURATION # SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = environ.get('SECRET_KEY', SECRET_KEY) # END SECRET CONFIGURATION # ADDITIONAL MIDDLEWARE MIDDLEWARE_CLASSES += () # END ADDITIONAL MIDDLEWARE
amonmoce/corba_examples
omniORBpy-4.2.1/build/python/COS/CosRelationships_idl.py
Python
mit
42,484
0.008191
# Python stubs generated by omniidl from /usr/local/share/idl/omniORB/COS/CosRelationships.idl # DO NOT EDIT THIS FILE! import omniORB, _omnipy from omniORB import CORBA, PortableServer _0_CORBA = CORBA _omnipy.checkVersion(4,2, __file__, 1) tr
y: property except NameError: def property(*args): return None # #include "corbaidl.idl" import corbaidl_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniOR
B.openModule("CORBA__POA") # #include "boxes.idl" import boxes_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniORB.openModule("CORBA__POA") # #include "ir.idl" import ir_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniORB.openModule("CORBA__POA") # #include "CosObjectIdentity.idl" import CosObjectIdentity_idl _0_CosObjectIdentity = omniORB.openModule("CosObjectIdentity") _0_CosObjectIdentity__POA = omniORB.openModule("CosObjectIdentity__POA") # # Start of module "CosRelationships" # __name__ = "CosRelationships" _0_CosRelationships = omniORB.openModule("CosRelationships", r"/usr/local/share/idl/omniORB/COS/CosRelationships.idl") _0_CosRelationships__POA = omniORB.openModule("CosRelationships__POA", r"/usr/local/share/idl/omniORB/COS/CosRelationships.idl") # forward interface RoleFactory; _0_CosRelationships._d_RoleFactory = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosRelationships/RoleFactory:1.0", "RoleFactory") omniORB.typeMapping["IDL:omg.org/CosRelationships/RoleFactory:1.0"] = _0_CosRelationships._d_RoleFactory # forward interface RelationshipFactory; _0_CosRelationships._d_RelationshipFactory = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosRelationships/RelationshipFactory:1.0", "RelationshipFactory") omniORB.typeMapping["IDL:omg.org/CosRelationships/RelationshipFactory:1.0"] = _0_CosRelationships._d_RelationshipFactory # forward interface Relationship; _0_CosRelationships._d_Relationship = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosRelationships/Relationship:1.0", "Relationship") omniORB.typeMapping["IDL:omg.org/CosRelationships/Relationship:1.0"] = _0_CosRelationships._d_Relationship # forward interface Role; _0_CosRelationships._d_Role = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosRelationships/Role:1.0", "Role") omniORB.typeMapping["IDL:omg.org/CosRelationships/Role:1.0"] = _0_CosRelationships._d_Role # forward interface RelationshipIterator; _0_CosRelationships._d_RelationshipIterator = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosRelationships/RelationshipIterator:1.0", "RelationshipIterator") omniORB.typeMapping["IDL:omg.org/CosRelationships/RelationshipIterator:1.0"] = _0_CosRelationships._d_RelationshipIterator # typedef ... RelatedObject class RelatedObject: _NP_RepositoryId = "IDL:omg.org/CosRelationships/RelatedObject:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosRelationships.RelatedObject = RelatedObject _0_CosRelationships._d_RelatedObject = omniORB.typeMapping["IDL:omg.org/CORBA/Object:1.0"] _0_CosRelationships._ad_RelatedObject = (omniORB.tcInternal.tv_alias, RelatedObject._NP_RepositoryId, "RelatedObject", omniORB.typeMapping["IDL:omg.org/CORBA/Object:1.0"]) _0_CosRelationships._tc_RelatedObject = omniORB.tcInternal.createTypeCode(_0_CosRelationships._ad_RelatedObject) omniORB.registerType(RelatedObject._NP_RepositoryId, _0_CosRelationships._ad_RelatedObject, _0_CosRelationships._tc_RelatedObject) del RelatedObject # typedef ... Roles class Roles: _NP_RepositoryId = "IDL:omg.org/CosRelationships/Roles:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosRelationships.Roles = Roles _0_CosRelationships._d_Roles = (omniORB.tcInternal.tv_sequence, omniORB.typeMapping["IDL:omg.org/CosRelationships/Role:1.0"], 0) _0_CosRelationships._ad_Roles = (omniORB.tcInternal.tv_alias, Roles._NP_RepositoryId, "Roles", (omniORB.tcInternal.tv_sequence, omniORB.typeMapping["IDL:omg.org/CosRelationships/Role:1.0"], 0)) _0_CosRelationships._tc_Roles = omniORB.tcInternal.createTypeCode(_0_CosRelationships._ad_Roles) omniORB.registerType(Roles._NP_RepositoryId, _0_CosRelationships._ad_Roles, _0_CosRelationships._tc_Roles) del Roles # typedef ... RoleName class RoleName: _NP_RepositoryId = "IDL:omg.org/CosRelationships/RoleName:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosRelationships.RoleName = RoleName _0_CosRelationships._d_RoleName = (omniORB.tcInternal.tv_string,0) _0_CosRelationships._ad_RoleName = (omniORB.tcInternal.tv_alias, RoleName._NP_RepositoryId, "RoleName", (omniORB.tcInternal.tv_string,0)) _0_CosRelationships._tc_RoleName = omniORB.tcInternal.createTypeCode(_0_CosRelationships._ad_RoleName) omniORB.registerType(RoleName._NP_RepositoryId, _0_CosRelationships._ad_RoleName, _0_CosRelationships._tc_RoleName) del RoleName # typedef ... RoleNames class RoleNames: _NP_RepositoryId = "IDL:omg.org/CosRelationships/RoleNames:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosRelationships.RoleNames = RoleNames _0_CosRelationships._d_RoleNames = (omniORB.tcInternal.tv_sequence, omniORB.typeMapping["IDL:omg.org/CosRelationships/RoleName:1.0"], 0) _0_CosRelationships._ad_RoleNames = (omniORB.tcInternal.tv_alias, RoleNames._NP_RepositoryId, "RoleNames", (omniORB.tcInternal.tv_sequence, omniORB.typeMapping["IDL:omg.org/CosRelationships/RoleName:1.0"], 0)) _0_CosRelationships._tc_RoleNames = omniORB.tcInternal.createTypeCode(_0_CosRelationships._ad_RoleNames) omniORB.registerType(RoleNames._NP_RepositoryId, _0_CosRelationships._ad_RoleNames, _0_CosRelationships._tc_RoleNames) del RoleNames # struct NamedRole _0_CosRelationships.NamedRole = omniORB.newEmptyClass() class NamedRole (omniORB.StructBase): _NP_RepositoryId = "IDL:omg.org/CosRelationships/NamedRole:1.0" def __init__(self, name, aRole): self.name = name self.aRole = aRole _0_CosRelationships.NamedRole = NamedRole _0_CosRelationships._d_NamedRole = (omniORB.tcInternal.tv_struct, NamedRole, NamedRole._NP_RepositoryId, "NamedRole", "name", omniORB.typeMapping["IDL:omg.org/CosRelationships/RoleName:1.0"], "aRole", omniORB.typeMapping["IDL:omg.org/CosRelationships/Role:1.0"]) _0_CosRelationships._tc_NamedRole = omniORB.tcInternal.createTypeCode(_0_CosRelationships._d_NamedRole) omniORB.registerType(NamedRole._NP_RepositoryId, _0_CosRelationships._d_NamedRole, _0_CosRelationships._tc_NamedRole) del NamedRole # typedef ... NamedRoles class NamedRoles: _NP_RepositoryId = "IDL:omg.org/CosRelationships/NamedRoles:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosRelationships.NamedRoles = NamedRoles _0_CosRelationships._d_NamedRoles = (omniORB.tcInternal.tv_sequence, omniORB.typeMapping["IDL:omg.org/CosRelationships/NamedRole:1.0"], 0) _0_CosRelationships._ad_NamedRoles = (omniORB.tcInternal.tv_alias, NamedRoles._NP_RepositoryId, "NamedRoles", (omniORB.tcInternal.tv_sequence, omniORB.typeMapping["IDL:omg.org/CosRelationships/NamedRole:1.0"], 0)) _0_CosRelationships._tc_NamedRoles = omniORB.tcInternal.createTypeCode(_0_CosRelationships._ad_NamedRoles) omniORB.registerType(NamedRoles._NP_RepositoryId, _0_CosRelationships._ad_NamedRoles, _0_CosRelationships._tc_NamedRoles) del NamedRoles # struct RelationshipHandle _0_CosRelationships.RelationshipHandle = omniORB.newEmptyClass() class RelationshipHandle (omniORB.StructBase): _NP_RepositoryId = "IDL:omg.org/CosRelationships/RelationshipHandle:1.0" def __init__(self, the_relationship, constant_random_id): self.the_relationship = the_relationship self.constant_random_id = constant_random_id _0_CosRelationships.RelationshipHandle = RelationshipHandle _0_CosRelationships._d_RelationshipHandle = (omniORB.tcInternal.tv_struct, RelationshipHandle, RelationshipHandle._NP_RepositoryId, "RelationshipHandle", "the_relationship", omniORB.typeMapping["IDL:omg.org/CosRelationships/Relationship:1.0"], "constant_random_id", omniORB.typeMapping["IDL:
smartyrad/Python-scripts-for-web-scraping
shopclues_string.py
Python
gpl-3.0
2,978
0.004701
from lxml import html import csv, os, json import requests from exceptions import ValueError from time import sleep import urllib import lxml.html genList_shopclues = [] extracted_data_shopclues = [] data = [] papa = None site = None def ShopcluesParser(url): headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} page = requests.get(url, headers=headers) doc = html.fromstring(page.content) XPATH_NAME = '//h1[@itemprop="name"]//text()' XPATH_PRODUCTID = '//span[@class="pID"]//text()' XPATH_DISCOUNTED_PRICE = '//span[@class="f_price"]//text()' XPATH_SALE_PRICE = '//span[@id="sec_discounted_price_"]//text()' XPATH_ORIGINAL_PRICE = '//span[@id="sec_list_price_"]//text()' XPATH_DISCOUNT = '//span[@class="discount"]//text()' RAW_NAME = doc.xpath(XPATH_NAME) RAW_PRODUCTID = doc.xpath(XPATH_PRODUCTID) RAW_DISCOUNTED_PRICE = doc.xpath(XPATH_DISCOUNTED_PRICE) RAW_SALE_PRICE = doc.xpath(XPATH_SALE_PRICE) RAW_ORIGINAL_PRICE = doc.xpath(XPATH_ORIGINAL_PRICE) RAW_DISCOUNT = doc.xpath(XPATH_DISCOUNT) NAME = ' '.
join(''.join(RAW_NAME).split()) if RAW_NAME else None PRODUCTID = ' '.join(''.join(RAW_PRODUCTID).split()).strip() if RAW_PRODUCTID else None DISCOUNTED_PRICE = ' '.join(''.join(RAW_DISCOUNTED_PRICE).split()).strip() if RAW_DISCOUNTED_PRICE else None SALE_PRICE = ' '.join(''.join(RAW
_SALE_PRICE).split()).strip() if RAW_SALE_PRICE else None ORIGINAL_PRICE = ''.join(RAW_ORIGINAL_PRICE).strip() if RAW_ORIGINAL_PRICE else None DISCOUNT = ''.join(RAW_DISCOUNT).strip() if RAW_DISCOUNT else None if page.status_code != 200: raise ValueError('captcha') data = { 'NAME': NAME, 'PRODUCTID': PRODUCTID, 'DISCOUNTED_PRICE': DISCOUNTED_PRICE, 'SALE_PRICE': SALE_PRICE, 'ORIGINAL_PRICE': ORIGINAL_PRICE, 'ORIGINAL_PRICE': ORIGINAL_PRICE, 'DISCOUNT': DISCOUNT, 'URL': url, 'SITE': site } return data def ReadAsin_shopclues(): # AsinList = csv.DictReader(open(os.path.join(os.path.dirname(__file__),"Asinfeed.csv"))) for i in genList_shopclues: url = i print "Processing: " + url extracted_data_shopclues.append(ShopcluesParser(url)) papa = ShopcluesParser(url) sleep(5) print papa['ORIGINAL_PRICE'] def Initial_shopclues(pepe): urlprod = "http://www.shopclues.com/search?q=" + pepe + "&sc_z=2222&z=0" connection = urllib.urlopen(urlprod) dom = lxml.html.fromstring(connection.read()) for link in dom.xpath("//div[@class='column col3']/descendant::*[@href][1]/@href"): genList_shopclues.append(link) ReadAsin_shopclues() a = raw_input() data= a.split(",") i = 0 while i < len(data): print "Inside link no" + str(i) Initial_shopclues(data[i]) i = i + 1 f = open('mama.json', 'w') json.dump(extracted_data_shopclues, f, indent=1)
mitodl/micromasters
discussions/api.py
Python
bsd-3-clause
16,514
0.002241
"""API for open discussions integration""" import logging from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import transaction from open_discussions_api.client import OpenDiscussionsApi from open_discussions_api.constants import ROLE_STAFF from requests.exceptions import HTTPError from rest_framework import status as statuses from discussions.models import ( Channel, ChannelProgram, DiscussionUser, ) from discussions.exceptions import ( DiscussionSyncException, ChannelCreationException, ChannelAlreadyExistsException, ContributorSyncException, DiscussionUserSyncException, ModeratorSyncException, SubscriberSyncException, ) from discussions.utils import get_moderators_for_channel from roles.models import Role from roles.roles import Permissions from search.api import adjust_search_for_percolator from search.models import ( PercolateQuery, PercolateQueryMembership, ) log = logging.getLogger(__name__) def get_staff_client(): """ Gets a client configured for user management """ if not settings.OPEN_DISCUSSIONS_JWT_SECRET: raise ImproperlyConfigured('OPEN_DISCUSSIONS_JWT_SECRET must be set') if not settings.OPEN_DISCUSSIONS_BASE_URL: raise ImproperlyConfigured('OPEN_DISCUSSIONS_BASE_URL must be set') if not settings.OPEN_DISCUSSIONS_API_USERNAME: raise ImproperlyConfigured('OPEN_DISCUSSIONS_API_USERNAME must be set') return OpenDiscussionsApi( settings.OPEN_DISCUSSIONS_JWT_SECRET, settings.OPEN_DISCUSSIONS_BASE_URL, settings.OPEN_DISCUSSIONS_API_USERNAME, roles=[ROLE_STAFF] ) def create_or_update_discussion_user(user_id, allow_email_optin=False): """ Create or update a DiscussionUser record and sync it Args: user_id (int): user id of the user to sync allow_email_optin (bool): if True send email_optin in profile dict on users.update call Returns: DiscussionUser: The DiscussionUser connected to the user """ discussion_user, _ = DiscussionUser.objects.get_or_create(user_id=user_id) with transaction.atomic(): discussion_user = ( DiscussionUser.objects.select_for_update() .select_related('user') .get(id=discussion_user.id) ) # defer decision to create or update the profile until we have a lock if discussion_user.username is None: create_discussion_user(discussion_user) else: if settings.FEATURES.get('OPEN_DISCUSSIONS_USER_UPDATE', True): update_discussion_user(discussion_user, allow_email_optin=allow_email_optin) return discussion_user def create_discussion_user(discussion_user): """ Creates the user's discussion user and profile Args: discussion_user (profiles.models.DiscussionUser): discus
sion user to create Raises: DiscussionUserSyncException: if t
here was an error syncing the profile """ profile = discussion_user.user.profile api = get_staff_client() result = api.users.create( profile.user.username, email=profile.user.email, profile=dict( name=profile.full_name, image=profile.image.url if profile.image else None, image_small=profile.image_small.url if profile.image_small else None, image_medium=profile.image_medium.url if profile.image_medium else None, email_optin=profile.email_optin ) ) try: result.raise_for_status() except HTTPError as ex: raise DiscussionUserSyncException( "Error creating discussion user for {}".format(profile.user.username) ) from ex discussion_user.username = result.json()['username'] discussion_user.last_sync = profile.updated_on discussion_user.save() def update_discussion_user(discussion_user, allow_email_optin=False): """ Updates the user's discussion user profile Args: discussion_user (discussions.models.DiscussionUser): discussion user to update allow_email_optin (bool): if True send email_optin in profile dict on users.update call Raises: DiscussionUserSyncException: if there was an error syncing the profile """ profile = discussion_user.user.profile if ( not allow_email_optin and discussion_user.last_sync is not None and profile.updated_on <= discussion_user.last_sync ): return api = get_staff_client() profile_dict = dict( name=profile.full_name, image=profile.image.url if profile.image else None, image_small=profile.image_small.url if profile.image_small else None, image_medium=profile.image_medium.url if profile.image_medium else None, ) if allow_email_optin: profile_dict["email_optin"] = profile.email_optin result = api.users.update( discussion_user.username, uid=profile.user.username, email=profile.user.email, profile=profile_dict ) try: result.raise_for_status() except HTTPError as ex: raise DiscussionUserSyncException( "Error updating discussion user for {}".format(profile.user.username) ) from ex discussion_user.last_sync = profile.updated_on discussion_user.save() def add_contributor_to_channel(channel_name, discussion_username): """ Add user to channel as a contributor Args: channel_name (str): An open-discussions channel discussion_username (str): The username used by open-discussions """ admin_client = get_staff_client() try: admin_client.channels.add_contributor(channel_name, discussion_username).raise_for_status() except HTTPError as ex: raise ContributorSyncException("Error adding contributor {user} to channel {channel}".format( user=discussion_username, channel=channel_name, )) from ex def add_moderator_to_channel(channel_name, discussion_username): """ Add user to channel as a moderator Args: channel_name (str): An open-discussions channel discussion_username (str): The username used by open-discussions """ admin_client = get_staff_client() try: admin_client.channels.add_moderator(channel_name, discussion_username).raise_for_status() except HTTPError as ex: raise ModeratorSyncException("Error adding moderator {user} to channel {channel}".format( user=discussion_username, channel=channel_name, )) from ex def remove_moderator_from_channel(channel_name, discussion_username): """ Remove user to channel as a moderator Args: channel_name (str): An open-discussions channel discussion_username (str): The username used by open-discussions """ admin_client = get_staff_client() try: admin_client.channels.remove_moderator(channel_name, discussion_username).raise_for_status() except HTTPError as ex: raise ModeratorSyncException("Error removing moderator {user} to channel {channel}".format( user=discussion_username, channel=channel_name, )) from ex def add_subscriber_to_channel(channel_name, discussion_username): """ Add a subscriber to channel Args: channel_name (str): An open-discussions channel discussion_username (str): The username used by open-discussions """ admin_client = get_staff_client() try: admin_client.channels.add_subscriber(channel_name, discussion_username).raise_for_status() except HTTPError as ex: raise SubscriberSyncException("Error adding subscriber {user} to channel {channel}".format( user=discussion_username, channel=channel_name, )) from ex def remove_contributor_from_channel(channel_name, discussion_username): """ Remove contributor from a channel Args: channel_name (str): An open-discussions channel discussion_username (str): The username used
JamesLinus/OMMPS
ProcessMonitor.py
Python
lgpl-3.0
1,496
0.009358
#!/usr/bin/env python # -*- coding: utf-8 -*- #*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 & import sys import subprocess import os.path as op import socket def this_abs_path(script_name): return op.abspath(op.join(op.dirname(__file__), script_name)) def monitor_process(key_word, cmd): p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE) p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE) lines = p3.stdout.readlines() if len(lines) > 0:
return sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd)) subprocess.call(cmd, shell=True)
def monitor_port(protocol, port, cmd): address = ('127.0.0.1', port) socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM client = socket.socket(socket.AF_INET, socket_type) try: client.bind(address) except Exception, e: pass else: sys.stderr.write('port[%s-%s] is lost, run [%s]\n' % (protocol, port, cmd)) subprocess.call(cmd, shell=True) finally: client.close() #============================================================================= def yuanzhaopin(): cmd = '%s start' % this_abs_path('gun.sh') #monitor_process('\[yuanzhaopin\]', cmd) monitor_port('tcp', 8635, cmd) def main(): yuanzhaopin() if __name__ == '__main__': main()
phiros/nepi
src/nepi/resources/ns3/ns3server.py
Python
gpl-3.0
7,038
0.011367
# # NEPI, a framework to manage network experiments # Copyright (C) 2014 INRIA # # 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: Alina Quereilhac <alina.quereilhac@inria.fr> import base64 import cPickle import errno import logging import os import socket import sys from optparse import OptionParser, SUPPRESS_HELP from ns3wrapper import NS3Wrapper class NS3WrapperMessage: CREATE = "CREATE" FACTORY = "FACTORY" INVOKE = "INVOKE" SET = "SET" GET = "GET" FLUSH = "FLUSH" START = "START" STOP = "STOP" SHUTDOWN = "SHUTDOWN" def handle_message(ns3_wrapper, msg_type, args, kwargs): if msg_type == NS3WrapperMessage.SHUTDOWN: ns3_wrapper.shutdown() return "BYEBYE" if msg_type == NS3WrapperMessage.STOP: time = kwargs.get("time") ns3_wrapper.stop(time=time) return "STOPPED" if msg_type == NS3WrapperMessage.START: ns3_wrapper.start() return "STARTED" if msg_type == NS3WrapperMessage.CREATE: clazzname = args.pop(0) return ns3_wrapper.create(clazzname, *args) if msg_type == NS3WrapperMessage.FACTORY: type_name = args.pop(0) return ns3_wrapper.factory(type_name, **kwargs) if msg_type == NS3WrapperMessage.INVOKE: uuid = args.pop(0) operation = args.pop(0) return ns3_wrapper.invoke(uuid, operation, *args, **kwargs) if msg_type == NS3WrapperMessage.GET: uuid = args.pop(0) name = args.pop(0) return ns3_wrapper.get(uuid, name) if msg_type == NS3WrapperMessage.SET: uuid = args.pop(0) name = args.pop(0) value = args.pop(0) return ns3_wrapper.set(uuid, name, value) if msg_type == NS3WrapperMessage.FLUSH: # Forces flushing output and error streams. # NS-3 output will stay unflushed until the program exits or # explicit invocation flush is done sys.stdout.flush() sys.stderr.flush() ns3_wrapper.logger.debug("FLUSHED") return "FLUSHED" def open_socket(socket_name): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(socket_name) return sock def close_socket(sock): try: sock.close() except: pass def recv_msg(conn): msg = [] chunk = '' while '\n' not in chunk: try: chunk = conn.recv(1024) except (OSError, socket.error), e: if e[0] != errno.EINTR: raise # Ignore eintr errors continue if chunk: msg.append(chunk) else: # empty chunk = EOF break msg = ''.join(msg).strip() # The message is formatted as follows: # MESSAGE_TYPE|args|kwargs # # where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64 def decode(item): item = base64.b64decode(item).rstrip() return cPickle.loads(item) decoded = map(decode, msg.split("|")) # decoded message dmsg_type = decoded.pop(0) dargs = list(decoded.pop(0)) # transforming touple into list dkwargs = decoded.pop(0) return (dmsg_type, dargs, dkwargs) def send_reply(conn, reply): encoded = base64.b64encode(cPickle.dumps(reply)) conn.send("%s\n" % encoded) def get_options(): usage = ("usage: %prog -S <socket-name> -L <ns-log> -D <enable-dump> -v ") parser = OptionParser(usage = usage) parser.add_option("-S", "--socket-name", dest="socket_name", help = "Name for the unix socket used to interact with this process", default = "tap.sock", type="str") parser.add_option("-L", "--ns-log", dest="ns_log", help = "NS_LOG environmental variable to be set", default = "", type="str") parser.add_option("-D", "--enable-dump", dest="enable_dump", help = "Enable dumping the remote executed ns-3 commands to a script " "in order to later reproduce and debug the experiment", action = "store_true", default = False) parser.add_option("-v", "--verbose", help="Print debug output", action="store_true", dest="verbose", default=False) (options, args) = parser.parse_args() return (options.socket_name, options.verbose, options.ns_log, options.enable_dump) def run_server(socket_name, level = logging.INFO, ns_log = None, enable_dump = False): # Sets NS_LOG environmental variable for NS debugging if ns_log: os.environ["NS_LOG"] = ns_log ###### ns-3 wrapper instantiation ns3_wrapper = NS3Wrapper(loglevel=level, enable_dump = enable_dump) ns3_wrapper.logger.info("STARTING...") # create unix socket to receive instructions sock = open_socket(socket_name) sock.listen(0) # wait for messages to arrive and process them stop = False while not stop: conn, addr = sock.accept() conn.settimeout(5) try: (msg_type, args, kwargs) = recv_msg(conn) except socket.timeout, e: # Ingore time-out close_socket(conn) continue i
f not msg_type: # Ignore - connection lost close_socket(conn) continue if msg_type == NS3WrapperMessage.SHUTDOWN: stop = True try: reply = handle_message(ns3_wrapper, msg_type, args, kwargs) except: import traceback err = traceback.format_exc() ns3_wrapper.lo
gger.error(err) close_socket(conn) raise try: send_reply(conn, reply) except socket.error: import traceback err = traceback.format_exc() ns3_wrapper.logger.error(err) close_socket(conn) raise close_socket(conn) close_socket(sock) ns3_wrapper.logger.info("EXITING...") if __name__ == '__main__': (socket_name, verbose, ns_log, enable_dump) = get_options() ## configure logging FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s" level = logging.DEBUG if verbose else logging.INFO logging.basicConfig(format = FORMAT, level = level) ## Run the server run_server(socket_name, level, ns_log, enable_dump)
tvalacarta/tvalacarta
python/main-classic/channels/xiptv.py
Python
gpl-3.0
11,785
0.018058
# -*- coding: utf-8 -*- #------------------------------------------------------------ # tvalacarta - XBMC Plugin # Canal para xip/tv # http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/ #------------------------------------------------------------ import urlparse,urllib,re from core import logger from core import scrapertools from core.item import Item DEBUG = False CHANNELNAME = "xiptv" PROGRAMAS_URL = "http://www.xiptv.cat/programes" def isGeneric(): return True def mainlist(item): logger.info("tvalacarta.channels.xiptv mainlist") itemlist=[] itemlist.append( Item( channel=CHANNELNAME , title="Últimos vídeos añadidos" , action="episodios" , url="http://www.xiptv.cat/capitols" , folder=True) ) itemlist.append( Item( channel=CHANNELNAME , title="Televisiones locales" , action="cadenas" , url="http://www.xiptv.cat" )) itemlist.append( Item( channel=CHANNELNAME , title="Todos los programas" , action="programas" , url=PROGRAMAS_URL )) itemlist.append( Item( channel=CHANNELNAME , title="Programas por categorías" , action="categorias" , url="http://www.xiptv.cat/programes" )) return itemlist def cadenas(item): logger.info("tvalacarta.channels.xiptv cadenas") itemlist=[] # Descarga la página data = scrapertools.cache_page(item.url) data = scrapertools.find_single_match(data,'<a href="#">Televisions locals</a>(.*?)</div>') # Extrae las categorias (carpetas) patron = '<a href="([^"]+)">([^<]+)</a>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) for scrapedurl,scrapedtitle in matches: title = scrapertools.htmlclean(scrapedtitle) url = scrapedurl if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]") itemlist.append( Item(channel=CHANNELNAME, title=title , action="cadena" , url=url, folder=True) ) return itemlist def cadena(item): logger.info("tvalacarta.channels.xiptv cadena") itemlist=[] itemlist.append( Item( channel=CHANNELNAME , title="Últimos vídeos añadidos a "+item.title , action="episodios" , url=urlparse.urljoin(item.url,"/capitols") , folder=True) ) itemlist.append( Item( channel=CHANNELNAME , title="Todos los programas de "+item.title , action="programas" , url=urlparse.urljoin(item.url,"/programes") )) return itemlist def categorias(item): logger.info("tvalacarta.channels.xiptv categorias") itemlist=[] # Descarga la página data = scrapertools.cachePage(item.url) data = scrapertools.get_match(data,'<select id="program_program_categories" name="program.program_categories.">(.*?)</select>') # Extrae las categorias (carpetas) patron = '<option value="([^"]+)">([^>]+)</option>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) for scrapedurl,scrapedtitle in matches: title = scrapedtitle #http://www.xiptv.cat/programes?program%5Bfull_text%5D=&program%5Bprogram_categories%5D=Infantils&program%5Bhistoric%5D=1&commit=Cercar url = "http://www.xiptv.cat/programes?program%5Bfull_text%5D=&program%5Bprogram_categories%5D="+scrapedurl+"&program%5Bhistoric%5D=1&commit=Cercar" if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]") itemlist.append( Item(channel=CHANNELNAME, title=title , action="programas" , url=url, folder=True) ) return itemlist def programas(item, load_all_pages=False): logger.info("tvalacarta.channels.xiptv programas") itemlist=[] if item.url=="": item.url=PROGRAMAS_URL # Extrae los programas data = scrapertools.cache_page(item.url) data = scrapertools.find_single_match(data,'(<li[^<]+<div class="item">.*?<div class="pager">.*?</div>)') ''' <li> <div class="item"> <div class="image drop-shadow curved curved-hz-1"> <a href="/sex-toy-ficcions"><img
alt="Frame_sex_toy_ficcions" src="/media/asset_publics/resources /000/106/321/program/FRAME_SEX_TOY_FICCIONS.JPG?1350386776" /></a> </div> <div class="archived"><em>Històric</em></div> <div class="content"> <h4><a href="/sex-toy-ficcions">Sex Toy Ficcions</a></h4> <h5> <a href="/programes/page/10?model_type=Program&amp;pro
gram%5Bprogram_categories%5D=Nous+formats" >Nous formats</a> </h5> <p>Sèrie en clau de comèdia, que gira al voltant de reunions cada cop més habituals conegudes com a "tupper sex", trobades a domicili per millorar la vida sexual de les persones que hi participen . La intenció de Sex Toy Ficcions és aconseguir que l'espectador s'identifiqui amb les conductes i frustracions sexuals dels protagonistes d'aquesta ficció...</p> <span class="chapters"> 13 capítols </span> <dl> <dt>TV responsable</dt> <dd>La Xarxa</dd> <dt>Categoria</dt> <dd> <a href="/programes/page/10?model_type=Program&amp;program%5Bprogram_categories%5D=Nous+formats" >Nous formats</a> ''' patron = '<li>[^<]+<div class="item">(.*?)</li>' matches = re.compile(patron,re.DOTALL).findall(data) for match in matches: scrapedurl = scrapertools.find_single_match(match,'<a href="([^"]+)"') scrapedthumbnail = scrapertools.find_single_match(match,'<img alt="[^"]+" src="([^"]+)"') scrapedtitle = scrapertools.find_single_match(match,'<h4[^<]+<a href="[^"]+">([^<]+)</a>') scrapedcategory = scrapertools.find_single_match(match,'<h5[^<]+<a href="[^"]+">([^<]+)</a>') scrapedplot = scrapertools.find_single_match(match,'<p>(.*?)</p>') title = scrapertools.htmlclean(scrapedtitle) url = urlparse.urljoin(item.url,scrapedurl) thumbnail = urlparse.urljoin(item.url,scrapedthumbnail) plot = scrapertools.htmlclean(scrapedcategory+"\n"+scrapedplot).strip() if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]") itemlist.append( Item(channel=CHANNELNAME, title=title , action="episodios" , url=url, page=url , thumbnail=thumbnail, fanart=thumbnail, plot=plot , show=title , category = "programas" , viewmode="movie_with_plot", folder=True) ) # Página siguiente next_page_url = scrapertools.find_single_match(data,'<a href="([^"]+)">next</a>') if next_page_url!="": next_page_url = urlparse.urljoin(item.url,next_page_url) logger.info("next_page_url="+next_page_url) next_page_item = Item(channel=CHANNELNAME, title=">> Página siguiente" , action="programas" , extra="pager", url=next_page_url, folder=True) if load_all_pages: itemlist.extend(programas(next_page_item,load_all_pages)) else: itemlist.append(next_page_item) return itemlist def episodios(item): import urllib logger.info("tvalacarta.channels.xiptv episodios") itemlist = [] # Descarga la página data = scrapertools.cache_page(item.url) if item.url=="http://www.xiptv.cat/ben-trobats": data = scrapertools.find_single_match(data,'(<li[^<]+<div class="item">.*?<div class="pager">.*?</div>)',1) else: data = scrapertools.find_single_match(data,'(<li[^<]+<div class="item">.*?<div class="pager">.*?</div>)') ''' <li> <div class="item"> <div class="image drop-shadow curved curved-hz-1 "> <a href="/la-setmana-catalunya-central/capitol/capitol-30"><img alt="Imatge_pgm30" src="/media/asset_publics/resources/000/180/341/video/imatge_pgm30.jpg?1396620287" /></a> </div> <div class="content"> <span class="date"> 04/04/2014 </span> <h4> <a href="/la-setmana-catalunya-central/capitol/capitol-30">Capítol 30</a> </h4> <p><h5><a href="/la-setmana-catalunya-central" target="_blank">La setmana Catalunya central</a> </h5> </p> <span class="duration">25:02</span> <span class="views">0 reproduccions</span> <p>Al llarg dels segle XIX el Seminari de Vic va anar forjant una col·lecció de Ciències Naturals que representa, a dia d’avui, un valuós testimoni històri
ExploreEmbedded/Tit-Windows
tools/share/gdb/python/gdb/__init__.py
Python
bsd-3-clause
3,494
0.004007
# Copyright (C) 2010-2014 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import traceback import os import sys import _gdb if sys.version_info[0] > 2: # Python 3 moved "reload" from imp import reload from _gdb import * class _GdbFile (object): # These two are needed in Python 3 encoding = "UTF-8" errors = "strict" def close(self): # Do nothing. return None def isatty(self): return False def writelines(self, iterable): for line in iterable: self.write(line) def flush(self): flush() class GdbOutputFile (_GdbFile): def write(self, s): write(s, stream=STDOUT) sys.stdout = GdbOutputFile() class GdbOutputErrorFile (_GdbFile): def write(self, s): write(s, stream=STDERR) sys.stderr = GdbOutputErrorFile() # Default prompt hook does nothing. prompt_hook = No
ne # Ensure that sys.argv is set to something. # We do not use PySys_SetArgvEx because it di
d not appear until 2.6.6. sys.argv = [''] # Initial pretty printers. pretty_printers = [] # Initial type printers. type_printers = [] # Initial xmethod matchers. xmethods = [] # Initial frame filters. frame_filters = {} # Convenience variable to GDB's python directory PYTHONDIR = os.path.dirname(os.path.dirname(__file__)) # Auto-load all functions/commands. # Packages to auto-load. packages = [ 'function', 'command' ] # pkgutil.iter_modules is not available prior to Python 2.6. Instead, # manually iterate the list, collating the Python files in each module # path. Construct the module name, and import. def auto_load_packages(): for package in packages: location = os.path.join(os.path.dirname(__file__), package) if os.path.exists(location): py_files = filter(lambda x: x.endswith('.py') and x != '__init__.py', os.listdir(location)) for py_file in py_files: # Construct from foo.py, gdb.module.foo modname = "%s.%s.%s" % ( __name__, package, py_file[:-3] ) try: if modname in sys.modules: # reload modules with duplicate names reload(__import__(modname)) else: __import__(modname) except: sys.stderr.write (traceback.format_exc() + "\n") auto_load_packages() def GdbSetPythonDirectory(dir): """Update sys.path, reload gdb and auto-load packages.""" global PYTHONDIR try: sys.path.remove(PYTHONDIR) except ValueError: pass sys.path.insert(0, dir) PYTHONDIR = dir # note that reload overwrites the gdb module without deleting existing # attributes reload(__import__(__name__)) auto_load_packages()
viur-framework/server
db.py
Python
lgpl-3.0
43,494
0.040488
# -*- coding: utf-8 -*- from google.appengine.api import datastore, datastore_types, datastore_errors from google.appengine.datastore import datastore_query, datastore_rpc from google.appengine.api import memcache from google.appengine.api import search from server.config import conf import logging """ Tiny wrapper around *google.appengine.api.datastore*. This just ensures that operations issued directly through the database-api doesn't interfere with ViURs internal caching. If you need skeletons anyway, query the database using skel.all(); its faster and is able to serve more requests from cache. """ __cacheLockTime__ = 42 #Prevent an entity from creeping into the cache for 42 Secs if it just has been altered. __cacheTime__ = 15*60 #15 Mins __CacheKeyPrefix__ ="viur-db-cache:" #Our Memcache-Namespace. Dont use that for other purposes __MemCacheBatchSize__ = 30 __undefinedC__ = object() def PutAsync( entities, **kwargs ): """ Asynchronously store one or more entities in the data store. This function is identical to :func:`server.db.Put`, except that it returns an asynchronous object. Call ``get_result()`` on the return value to block on the call and get the results. """ if isinstance( entities, Entity ): entities._fixUnindexedProperties() elif isinstance( entities, list ): for entity in entities: assert isinstance( entity, Entity ) entity._fixUnindexedProperties() if conf["viur.db.caching" ]>0: if isinstance( entities, Entity ): #Just one: if entities.is_saved(): #Its an update memcache.delete( str( entities.key() ), namespace=__CacheKeyPrefix__, seconds=__cacheLockTime__ ) elif isinstance( entities, list ): for entity in entities: assert isinstance( entity, Entity ) if entity.is_saved(): #Its an update memcache.delete( str( entity.key() ), namespace=__CacheKeyPrefix__, seconds=__cacheLockTime__ ) return( datastore.PutAsync( entities, **kwargs ) ) def Put( entities, **kwargs ): """ Store one or more entities in the data store. The entities may be new or previously existing. For new entities, ``Put()`` will fill in the app id and key assi
gned by the data store. :param entities: Entity or list of entities to be stored. :type entities: :class:`server.db.Entity` | list of :class:`
server.db.Entity` :param config: Optional configuration to use for this request. This must be specified\ as a keyword argument. :type config: dict :returns: If the argument ``entities`` is a single :class:`server.db.Entity`, \ a single Key is returned. If the argument is a list of :class:`server.db.Entity`, \ a list of Keys will be returned. :rtype: Key | list of keys :raises: :exc:`TransactionFailedError`, if the action could not be committed. """ if isinstance( entities, Entity ): entities._fixUnindexedProperties() elif isinstance( entities, list ): for entity in entities: assert isinstance( entity, Entity ) entity._fixUnindexedProperties() if conf["viur.db.caching" ]>0: if isinstance( entities, Entity ): #Just one: if entities.is_saved(): #Its an update memcache.delete( str( entities.key() ), namespace=__CacheKeyPrefix__, seconds=__cacheLockTime__ ) elif isinstance( entities, list ): for entity in entities: assert isinstance( entity, Entity ) if entity.is_saved(): #Its an update memcache.delete( str( entity.key() ), namespace=__CacheKeyPrefix__, seconds=__cacheLockTime__ ) return( datastore.Put( entities, **kwargs ) ) def GetAsync( keys, **kwargs ): """ Asynchronously retrieves one or more entities from the data store. This function is identical to :func:`server.db.Get`, except that it returns an asynchronous object. Call ``get_result()`` on the return value to block on the call and get the results. """ class AsyncResultWrapper: """ Wraps an result thats allready there into something looking like an RPC-Object. """ def __init__( self, res ): self.res = res def get_result( self ): return( self.res ) if conf["viur.db.caching" ]>0 and not datastore.IsInTransaction(): if isinstance( keys, datastore_types.Key ) or isinstance( keys, basestring ): #Just one: res = memcache.get( str(keys), namespace=__CacheKeyPrefix__ ) if res: return( AsyncResultWrapper( res ) ) #Either the result wasnt found, or we got a list of keys to fetch; # --> no caching possible return( datastore.GetAsync( keys, **kwargs ) ) def Get( keys, **kwargs ): """ Retrieve one or more entities from the data store. Retrieves the entity or entities with the given key(s) from the data store and returns them as fully populated :class:`server.db.Entity` objects. If there is an error, the function raises a subclass of :exc:`datastore_errors.Error`. If keys is a single key or str, an Entity will be returned, or :exc:`EntityNotFoundError` will be raised if no existing entity matches the key. However, if keys is a list or tuple, a list of entities will be returned that corresponds to the sequence of keys. It will include entities for keys that were found and None placeholders for keys that were not found. :param keys: Key, str or list of keys or strings to be retrieved. :type keys: Key | str | list of Key | list of str :param config: Optional configuration to use for this request. This must be specified\ as a keyword argument. :type config: dict :returns: Entity or list of Entity objects corresponding to the specified key(s). :rtype: :class:`server.db.Entity` | list of :class:`server.db.Entity` """ if conf["viur.db.caching" ]>0 and not datastore.IsInTransaction(): if isinstance( keys, datastore_types.Key ) or isinstance( keys, basestring ): #Just one: res = memcache.get( str(keys), namespace=__CacheKeyPrefix__ ) if not res: #Not cached - fetch and cache it :) res = Entity.FromDatastoreEntity( datastore.Get( keys, **kwargs ) ) res[ "key" ] = str( res.key() ) memcache.set( str(res.key() ), res, time=__cacheTime__, namespace=__CacheKeyPrefix__ ) return( res ) #Either the result wasnt found, or we got a list of keys to fetch; elif isinstance( keys,list ): #Check Memcache first cacheRes = {} tmpRes = [] keyList = [ str(x) for x in keys ] while keyList: #Fetch in Batches of 30 entries, as the max size for bulk_get is limited to 32MB currentBatch = keyList[:__MemCacheBatchSize__] keyList = keyList[__MemCacheBatchSize__:] cacheRes.update( memcache.get_multi( currentBatch, namespace=__CacheKeyPrefix__) ) #Fetch the rest from DB missigKeys = [ x for x in keys if not str(x) in cacheRes ] dbRes = [ Entity.FromDatastoreEntity(x) for x in datastore.Get( missigKeys ) if x is not None ] # Cache what we had fetched saveIdx = 0 while len(dbRes)>saveIdx*__MemCacheBatchSize__: cacheMap = {str(obj.key()): obj for obj in dbRes[saveIdx*__MemCacheBatchSize__:(saveIdx+1)*__MemCacheBatchSize__]} try: memcache.set_multi( cacheMap, time=__cacheTime__ , namespace=__CacheKeyPrefix__ ) except: pass saveIdx += 1 for key in [ str(x) for x in keys ]: if key in cacheRes: tmpRes.append( cacheRes[ key ] ) else: for e in dbRes: if str( e.key() ) == key: tmpRes.append ( e ) break if conf["viur.debug.traceQueries"]: logging.debug( "Fetched a result-set from Datastore: %s total, %s from cache, %s from datastore" % (len(tmpRes),len( cacheRes.keys()), len( dbRes ) ) ) return( tmpRes ) if isinstance( keys, list ): return( [ Entity.FromDatastoreEntity(x) for x in datastore.Get( keys, **kwargs ) ] ) else: return( Entity.FromDatastoreEntity( datastore.Get( keys, **kwargs ) ) ) def GetOrInsert( key, kindName=None, parent=None, **kwargs ): """ Either creates a new entity with the given key, or returns the existing one. Its guaranteed that there is no race-condition here; it will never overwrite an previously created entity. Extra keyword arguments passed to this function will be used to populate the entity if it has to be created; otherwise they are ignored. :param key: The key which will be fetched or created. \ If key is a string, it will be used
joke2k/faker
faker/providers/person/en_NZ/__init__.py
Python
mit
40,961
0.000024
from collections import OrderedDict from typing import Dict from .. import Provider as PersonProvider class Provider(PersonProvider): formats = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}-{{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}-{{last_name}}", ) # Names compiled from the following sources: # # https://www.dia.govt.nz/diawebsite.nsf/wpg_URL/Services-Births-Deaths-and-Marriages-Most-Popular-Male-and-Female-First-Names first_names_male: Dict[str, float] = OrderedDict( ( ("Aaron", 9912.0), ("Adam", 7639), ("Adrian", 2420), ("Aidan", 1521), ("Aiden", 782), ("Alan", 5689), ("Alex", 2819), ("Alexander", 7783), ("Alistair", 429), ("Allan", 3148), ("Allen", 51), ("Andre", 127), ("Andrew", 25593), ("Angus", 1680), ("Anthony", 12549), ("Antony", 1594), ("Archer", 381), ("Archie", 774), ("Arlo", 584), ("Arthur", 630), ("Asher", 319), ("Ashley", 861), ("Ashton", 1236), ("Austin", 688), ("Bailey", 1304), ("Barry", 3624), ("Beau", 491), ("Beauden", 125), ("Ben", 2427), ("Benjamin", 15497), ("Bernard", 657), ("Bevan", 634), ("Blair", 2863), ("Blake", 3500), ("Bodhi", 70), ("Brad", 450), ("Bradley", 3910), ("Brandon", 1000), ("Braxton", 741), ("Brayden", 317), ("Brendan", 2010), ("Brendon", 3163), ("Brent", 5564), ("Brett", 4598), ("Brian", 6247), ("Brodie", 216), ("Brooklyn", 406), ("Bruce", 6079), ("Bryan", 1435), ("Caleb", 5374), ("Callum", 2364), ("Cameron", 7756), ("Campbell", 422), ("Carl", 3304), ("Carlos", 122), ("Carter", 1308), ("Charles", 3933), ("Charlie", 2367), ("Chase", 174), ("Christian", 1138), ("Christopher", 23459), ("Clayton", 59), ("Clinton", 1004), ("Cody", 2482), ("Cohen", 99), ("Cole", 648), ("Colin", 3980), ("Connor", 4632), ("Conor", 54), ("Cooper", 2113), ("Corey", 1656), ("Cory", 129), ("Craig", 12702), ("Cruz", 52), ("Damian", 1084), ("Damon", 211), ("Daniel", 23515), ("Darren", 3143), ("Darrin", 217), ("Darryl", 1517), ("Darryn", 260), ("Daryl", 421), ("David", 36792), ("Dean", 6096), ("Declan", 108), ("Denis", 66), ("Dennis", 1129), ("Derek", 1307), ("Desmond", 224), ("Dillon", 63), ("Dion", 1283), ("Dominic", 801), ("Donald", 2405), ("Douglas", 2587), ("Duncan", 471), ("Dwayne", 57), ("Dylan", 6564), ("Edward", 4864), ("Eli", 961), ("Elijah", 2137), ("Elliot", 54), ("Eric", 808), ("Ethan", 6578), ("Ezra", 309), ("Felix", 769), ("Finn", 2084), ("Fletcher", 447), ("Flynn", 1577), ("Francis", 420), ("Frank", 46), ("Fraser", 51), ("Frederick", 49), ("Gabriel", 739), ("Gareth", 2087), ("Garry", 1840), ("Gary", 5520), ("Gavin", 3197), ("Geoffrey", 4439), ("George", 7320), ("Gerald", 104), ("Gerard", 614), ("Glen", 2709), ("Glenn", 3983), ("Gordon", 1444), ("Graeme", 4705), ("Graham", 3746), ("Grant", 8355), ("Grayson", 259), ("Gregory", 7916), ("Hamish", 5758), ("Harley", 403), ("Harrison", 2800), ("Harry", 2454), ("Harvey", 192), ("Hayden", 5209), ("Henry", 3111), ("Hudson", 281), ("Hugh", 101), (
"Hugo", 543), ("Hunter", 3044), ("Ian", 7592),
("Isaac", 4208), ("Isaiah", 349), ("Israel", 52), ("Ivan", 236), ("Jack", 9468), ("Jackson", 3088), ("Jacob", 8612), ("Jake", 2421), ("Jakob", 46), ("James", 27224), ("Jamie", 5064), ("Jared", 2840), ("Jarrod", 773), ("Jason", 14737), ("Jasper", 246), ("Jaxon", 623), ("Jayden", 4541), ("Jeffrey", 2826), ("Jeremy", 4775), ("Jesse", 3965), ("Joel", 2932), ("John", 26867), ("Jonathan", 7957), ("Jonathon", 349), ("Jordan", 6499), ("Joseph", 10061), ("Josh", 56), ("Joshua", 17109), ("Josiah", 52), ("Julian", 232), ("Justin", 3882), ("Kaleb", 492), ("Kane", 1236), ("Karl", 3822), ("Kayden", 123), ("Keanu", 54), ("Keegan", 351), ("Keith", 2175), ("Kelly", 58), ("Kelvin", 1262), ("Kenneth", 3240), ("Kerry", 2404), ("Kevin", 9358), ("Kieran", 1525), ("Kim", 125), ("Kingston", 692), ("Kurt", 515), ("Kyle", 2568), ("Lachlan", 2965), ("Lance", 2958), ("Lawrence", 226), ("Lee", 872), ("Leo", 1872), ("Leon", 967), ("Leonard", 102), ("Leslie", 1126), ("Levi", 2986), ("Lewis", 324), ("Liam", 8629), ("Lincoln", 857), ("Lindsay", 883), ("Lloyd", 46), ("Logan", 5063), ("Louis", 863), ("Luca", 1318), ("Lucas", 3329), ("Luka", 119), ("Lukas", 70), ("Luke", 8296), ("Malcolm", 2398), ("Marcus", 1129), ("Mark", 23154), ("Martin", 4260), ("Mason", 2613), ("Mathew", 3107), ("Matthew", 23181), ("Maurice", 385), ("Max", 3988), ("Maxwell", 172), ("Mervyn", 162), ("Micah", 52), ("Michael", 40099), ("Micheal", 49), ("Mitchell", 2730), ("Morgan", 58), ("Murray", 4843), ("Nate", 48), ("Nathan", 8920), ("Nathaniel", 329), ("Neil", 3392), ("Neville", 1268), ("Nicholas", 13132), ("Nigel", 4435), ("Nikau", 53), ("Nixon", 219), ("Noah", 3511), ("Noel", 778), ("Norman", 221), ("Oliver", 6515), ("Oscar", 1987), ("Owen", 484), ("Patrick", 6219), ("Paul", 22959), ("Peter", 23996), ("Philip", 7036), ("Phillip", 5977), ("Phoenix", 882), ("Quentin", 67), ("Quin
ziirish/burp-ui
burpui/misc/backend/burp2.py
Python
bsd-3-clause
30,550
0.000556
# -*- coding: utf8 -*- """ .. module:: burpui.misc.backend.burp2 :platform: Unix :synopsis: Burp-UI burp2 backend module. .. moduleauthor:: Ziirish <hi+burpui@ziirish.me> """ import re import os import time import json from collections import OrderedDict from .burp1 import Burp as Burp1 from .interface import BUIbackend from .utils.burp2 import Monitor from .utils.constant import BURP_REVERSE_COUNTERS, BURP_STATUS_FORMAT_V2 from ..parser.burp2 import Parser from ...utils import human_readable as _hr, utc_to_local from ...exceptions import BUIserverException from ..._compat import to_unicode # Some functions are the same as in Burp1 backend class Burp(Burp1): """The :class:`burpui.misc.backend.burp2.Burp` class provides a consistent backend for ``burp-2`` servers. It extends the :class:`burpui.misc.backend.burp1.Burp` class because a few functions can be reused. The rest is just overrided. :param server: ``Burp-UI`` server instance in order to access logger and/or some global settings :type server: :class:`burpui.engines.server.BUIServer` :param conf: Configuration to use :type conf: :class:`burpui.config.BUIConfig` """ # backend version _vers = 2 # cache to store the guessed OS _os_cache = {} def __init__(self, server=None, conf=None): """ :param server: ``Burp-UI`` server instance in order to access logger and/or some global settings :type server: :class:`burpui.engines.server.BUIServer` :param conf: Configuration to use :type conf: :class:`burpui.config.BUIConfig` """ BUIbackend.__init__(self, server, conf) self.monitor = Monitor(self.burpbin, self.burpconfcli, self.app, self.timeout) self.batch_list_supported = self.monitor.batch_list_supported self.parser = Parser(self) self.logger.info(f"burp binary: {self.burpbin}") self.logger.info(f"strip binary: {self.stripbin}") self.logger.info(f"burp conf cli: {self.burpconfcli}") self.logger.info(f"burp conf srv: {self.burpconfsrv}") self.logger.info(f"command timeout: {self.timeout}") self.logger.info(f"tmpdir: {self.tmpdir}") self.logger.info(f"zip64: {self.zip64}") self.logger.info(f"includes: {self.includes}") self.logger.info(f"enforce: {self.enforce}") self.logger.info(f"revoke: {self.revoke}") self.logger.info(f"client version: {self.client_version}") self.logger.info(f"server version: {self.server_version}") @property def client_version(self): return self.monitor.client_version @property def server_version(self): return self.monitor.server_version @staticmethod def _human_st_mode(mode): """Convert the st_mode returned by stat in human readable (ls-like) format """ hur = "" if os.path.stat.S_ISREG(mode): hur = "-" elif os.path.stat.S_ISLNK(mode): hur = "l" elif os.path.stat.S_ISSOCK(mode): hur = "s" elif os.path.stat.S_ISDIR(mode): hur = "d" elif os.path.stat.S_ISBLK(mode): hur = "b" elif os.path.stat.S_ISFIFO(mode): hur = "p" elif os.path.stat.S_ISCHR(mode): hur = "c" else: hur = "-" for who in "USR", "GRP", "OTH": for perm in "R", "W", "X": if mode & getattr(os.path.stat, "S_I" + perm + who): hur += perm.lower() else: hur += "-" return hur def statistics(self, agent=None): """See :func:`burpui.misc.backend.interface.BUIbackend.statistics`""" return { "alive": self.monitor.alive, "server_version": self.server_version, "client_version": self.client_version, } def status(self, query="c:\n", timeout=None, cache=True, agent=None): """See :func:`burpui.misc.backend.interface.BUIbackend.status`""" return self.monitor.status(query, timeout, cache) def _get_backup_logs(self, number, client, forward=False, deep=False): """See :func:`burpui.misc.backend.interface.BUIbackend.get_backup_logs` """ ret = {} ret2 = {} if not client or not number: return ret query = self.status("c:{0}:b:{1}\n".format(client, number)) if not query: return ret try: logs = query["clients"][0]["backups"][0]["logs"]["list"] except KeyError: self.logger.warning("No logs found") return ret if "backup_stats" in logs: ret = self._parse_backup_stats(number, client, forward) if "backup" in logs and deep: ret2 = self._parse_backup_l
og(number, client) ret.update(ret2) ret["encrypted"] = False if "files_enc" in ret and ret["files_enc"]["total"] > 0: ret["encrypted"] = True return ret @staticmethod def _do_parse_backup_log(data, client):
# tests ordered as the logs order ret = OrderedDict() ret["client_version"] = None ret["protocol"] = 1 ret["is_windows"] = False ret["server_version"] = None if not data: return ret try: log = data["clients"][0]["backups"][0]["logs"]["backup"] except KeyError: # Assume protocol 1 in all cases unless explicitly found Protocol 2 return ret # pre-compile regex since they'll be called on every log line regex = { "client_version": re.compile(r"Client version: (\d+\.\d+\.\d+)$"), "server_version": re.compile( r"WARNING: Client '{}' version '\d+\.\d+\.\d+' does not match server version '(\d+\.\d+\.\d+)'. An upgrade is recommended.$".format( client ) ), "protocol": re.compile(r"Protocol: (\d)$"), "is_windows": re.compile(r"Client is Windows$"), } expressions_list = list(ret.keys()) catching_expressions = ["client_version", "server_version", "protocol"] casting_expressions = { "protocol": int, } def __dummy(val): return val for line in log: expressions = expressions_list for expression in expressions: if expression in catching_expressions: catch = regex[expression].search(line) if catch: cast = casting_expressions.get(expression, __dummy) ret[expression] = cast(catch.group(1)) # don't search this expression twice expressions_list.remove(expression) break else: if expression in regex and regex[expression].search(line): ret[expression] = True # don't search this expression twice expressions_list.remove(expression) break return ret def _parse_backup_log(self, number, client): """The :func:`burpui.misc.backend.burp2.Burp._parse_backup_log` function helps you determine if the backup is protocol 2 or 1 and various useful details. :param number: Backup number to work on :type number: int :param client: Client name to work on :type client: str :returns: a dict with some useful details """ data = self.status("c:{0}:b:{1}:l:backup\n".format(client, number)) return self._do_parse_backup_log(data, client) def _do_parse_backup_stats( self, data, result, number, client, forward=False, agent=None ): ret = {} translate = { "time_start": "start", "time_end": "end", "time_taken": "duration", "bytes": "totsize", "bytes_receiv
Azure/azure-sdk-for-python
sdk/apimanagement/azure-mgmt-apimanagement/setup.py
Python
mit
2,672
0.001497
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import re import os.path from io import open from setuptools import find_packages, setup # Change the PACKAGE_NAME only to change folder and different name PACKAGE_NAME = "azure-mgmt-apimanagement" PACKAGE_PPRINT_NAME = "API Management" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace('-', '/') # a-b-c => a.b.c namespace_name = PACKAGE_NAME.replace('-', '.') # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, 'version.py') if os.path.exists(os.path.join(package_folder_path, 'version.py')) else os.path.join(package_folder_path, '_version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.md', encoding='utf-8') as f: readme = f.read() with open('CHANGELOG.md', encoding='utf-8') as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), long_description=readme + '\n\n' + changelog, long_description_content_type='text/markdown', license='MIT License', author='Microsoft Corporation', author_email='azpysdkhelp@microsoft.com', url='https://github.com/Azure/azure-sdk-for-python', keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3', 'Programmi
ng Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'License :: OSI Approved :: MIT License', ], zip_safe=False, packages=find_packages(exclude=[ 'tests', # Exclude packages th
at will be covered by PEP420 or nspkg 'azure', 'azure.mgmt', ]), install_requires=[ 'msrest>=0.6.21', 'azure-common~=1.1', 'azure-mgmt-core>=1.3.0,<2.0.0', ], python_requires=">=3.6" )
xbmc/atv2
xbmc/lib/libPython/Python/Lib/plat-atheos/TYPES.py
Python
gpl-2.0
2,682
0.00783
# Generated by h2py from /include/sys/types.h _SYS_TYPES_H = 1 # Included from features.h _FEATURES_H = 1 __USE_ANSI = 1 __FAVOR_BSD = 1 _ISOC9X_SOURCE = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 199506L _XOPEN_SOURCE = 500 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 _BSD_SOURCE = 1 _SVID_SOURCE = 1 _BSD_SOURCE = 1 _SVID_SOURCE = 1 __USE_ISOC9X = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 2 _POSIX_C_SOURCE = 199506L __USE_POSIX = 1 __USE_POSIX2 = 1 __USE_POSIX199309 = 1 __USE_POSIX199506 = 1 __USE_XOPEN = 1 __USE_XOPEN_EXTENDED = 1 __USE_UNIX98 = 1 _LARGEFILE_SOURCE = 1 __USE_XOPEN_EXTENDED = 1 __USE_LARGEFILE = 1 __USE_LARGEFILE64 = 1 __USE_FILE_OFFSET64 = 1 __USE_MISC = 1 __USE_BSD = 1 __USE_SVID = 1 __USE_GNU = 1 __USE_REENTRANT = 1 __STDC_IEC_559__ = 1 __STDC_IEC_559_COMPLEX__ = 1 __GNU_LIBRARY__ = 6 __GLIBC__ = 2 __GLIBC_MINOR__ = 1 # Included from sys/cdefs.h _SYS_CDEFS_H = 1 def __PMT(args): return args def __P(args): return args def __PMT(args): return args def __P(args): return () def __PMT(args): return () def __STRING(x): return #x def __STRING(x): return "x" def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) def __attribute__(xyz): return __USE_EXTERN_INLINES = 1 # Included from gnu/stubs.h # Included from bits/types.h _BITS_TYPES_H = 1 __FD_SETSIZE = 1024 def __FDELT(d): return ((d) / __NFDBITS) # Included from bits/pthreadtypes.h # Included from time.h _TIME_H = 1 # Included from bits/time.h # Included from posix/time.h # Included from posix/types.h MAXHOSTNAMELEN = 64 FD_SETSIZE = 1024 CLOCKS_PER_SEC = 1000000 _BITS_TIME_H = 1 CLOCKS_PER_SEC = 1000000 CLK_TCK = 100 _STRUCT_TIMEVAL = 1 CLK_TCK = CLOCKS_PER_SEC __clock_t_defined = 1 __time_t_defined = 1 __timespec_defined = 1 def __isleap(year): return \ __BIT_TYPES_DEFINED__ = 1 # Included from endian.h _ENDIAN_H = 1 __LITTLE_ENDIAN = 1234 __BIG_ENDIAN = 4321 __PDP_ENDIAN = 3412 # Included from bits/endian.h __BYTE_ORDER = __LITTLE_ENDIAN __FLOAT_WORD_ORDER = __BYTE_ORDER LITTLE_ENDIAN = __LITTLE_ENDIAN BIG_ENDIAN = __BIG_ENDIAN PDP_ENDIAN = __PDP_ENDIAN BYTE_ORDER = __BYTE_ORDER # Included from sys/select.h _SYS_SELECT_H = 1 # Included from bits/select.h def __FD_ZERO(fdsp): return \ def __FD_ZERO(set): return \ # Included from bits/sigset.h _SIGSET_H_types = 1 _SIGSET_H_fns = 1 def __sigmask(sig): return \ def __sigemptyset(set): return \ def __sigfillset(set): return \ def __sigisemptyset(set): return \ FD_SETSIZE = __
FD_SETSIZE def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) # Included from sys/sysmacros.h _SYS_SYSMACROS_H = 1 def major(dev): return ( (( (dev) >> 8) & 0xff)) def minor(dev): retur
n ( ((dev) & 0xff))
pypa/warehouse
warehouse/packaging/search.py
Python
apache-2.0
2,723
0.000367
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lic
ense. # 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 packaging.version from elasticsearch_dsl import Date, Document, Float, Keyword, Text, analyzer from warehouse.search.utils import doc_type EmailAnalyzer = analyzer( "email", tokenizer="uax_url_email", filter=["lowercase", "stop", "snowball"], ) NameAnalyzer = analyzer( "normalized_name", tokenizer="lowercase", filter=["lowercase", "word_delimiter"], ) @doc_type class Project(Document): name = Text() normalized_name = Text(analyzer=NameAnalyzer) version = Keyword(multi=True) latest_version = Keyword() summary = Text(analyzer="snowball") description = Text(analyzer="snowball") author = Text() author_email = Text(analyzer=EmailAnalyzer) maintainer = Text() maintainer_email = Text(analyzer=EmailAnalyzer) license = Text() home_page = Keyword() download_url = Keyword() keywords = Text(analyzer="snowball") platform = Keyword() created = Date() classifiers = Keyword(multi=True) zscore = Float() @classmethod def from_db(cls, release): obj = cls(meta={"id": release.normalized_name}) obj["name"] = release.name obj["normalized_name"] = release.normalized_name obj["version"] = sorted( release.all_versions, key=lambda r: packaging.version.parse(r), reverse=True ) obj["latest_version"] = release.latest_version obj["summary"] = release.summary obj["description"] = release.description obj["author"] = release.author obj["author_email"] = release.author_email obj["maintainer"] = release.maintainer obj["maintainer_email"] = release.maintainer_email obj["home_page"] = release.home_page obj["download_url"] = release.download_url obj["keywords"] = release.keywords obj["platform"] = release.platform obj["created"] = release.created obj["classifiers"] = release.classifiers obj["zscore"] = release.zscore return obj class Index: # make sure this class can match any index so it will always be used to # deserialize data coming from elasticsearch. name = "*"
ramineni/my_congress
congress/datasources/datasource_utils.py
Python
apache-2.0
6,907
0.000145
# Copyright (c) 2013,2014 VMware, 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. from __future__ import print_function from __future__ import division from __future__ import absolute_import import functools import inspect import re from six.moves.urllib import parse as urlparse import keystoneauth1.identity.v2 as v2 import keystoneauth1.identity.v3 as v3 import keystoneauth1.session as kssession from congress.datasources import constants def get_openstack_required_config(): return {'auth_url': constants.REQUIRED, 'endpoint': constants.OPTIONAL, 'region': constants.OPTIONAL, 'username': constants.REQUIRED, 'password': constants.REQUIRED, 'tenant_name': constants.REQUIRED, 'project_name': constants.OPTIONAL, 'poll_time': constants.OPTIONAL} def update_state_on_changed(root_table_name): """Decorator to check raw data before retranslating. If raw data is same with cached self.raw_state, don't translate data, return empty list directly. If raw data is changed, translate it and update state. """ def outer(f): @functools.wraps(f) def inner(self, raw_data, *args, **kw): if (root_table_name not in self.raw_state or # TODO(RuiChen): workaround for oslo-incubator bug/1499369, # enable self.raw_state cache, once the bug is resolved. raw_data is not self.raw_state[root_table_name]): result = f(self, raw_data, *args, **kw) self._update_state(root_table_name, result) self.raw_state[root_table_name] = raw_data else: result = [] return result return inner return outer def add_column(colname, desc=None): """Adds column in the form of dict.""" return {'name': colname, 'desc': desc} def inspect_methods(client, api
_prefix): """Inspect all callable methods from client for congress.""" # some methods are referred multiple times, we should # save them here to avoid infinite loop obj_checked = [] method_checked = [] # For depth-first search o
bj_stack = [] # save all inspected methods that will be returned allmethods = [] obj_checked.append(client) obj_stack.append(client) while len(obj_stack) > 0: cur_obj = obj_stack.pop() # everything starts with '_' are considered as internal only for f in [f for f in dir(cur_obj) if not f.startswith('_')]: p = getattr(cur_obj, f, None) if inspect.ismethod(p): m_p = {} # to get a name that can be called by Congress, no need # to return the full path m_p['name'] = cur_obj.__module__.replace(api_prefix, '') if m_p['name'] == '': m_p['name'] = p.__name__ else: m_p['name'] = m_p['name'] + '.' + p.__name__ # skip checked methods if m_p['name'] in method_checked: continue m_doc = inspect.getdoc(p) # not return deprecated methods if m_doc and "DEPRECATED:" in m_doc: continue if m_doc: m_doc = re.sub('\n|\s+', ' ', m_doc) x = re.split(' :param ', m_doc) m_p['desc'] = x.pop(0) y = inspect.getargspec(p) m_p['args'] = [] while len(y.args) > 0: m_p_name = y.args.pop(0) if m_p_name == 'self': continue if len(x) > 0: m_p_desc = x.pop(0) else: m_p_desc = "None" m_p['args'].append({'name': m_p_name, 'desc': m_p_desc}) else: m_p['args'] = [] m_p['desc'] = '' allmethods.append(m_p) method_checked.append(m_p['name']) elif inspect.isfunction(p): m_p = {} m_p['name'] = cur_obj.__module__.replace(api_prefix, '') if m_p['name'] == '': m_p['name'] = f else: m_p['name'] = m_p['name'] + '.' + f # TODO(zhenzanz): Never see doc for function yet. # m_doc = inspect.getdoc(p) m_p['args'] = [] m_p['desc'] = '' allmethods.append(m_p) method_checked.append(m_p['name']) elif isinstance(p, object) and hasattr(p, '__module__'): # avoid infinite loop by checking that p not in obj_checked. # don't use 'in' since that uses ==, and some clients err if ((not any(p is x for x in obj_checked)) and (not inspect.isbuiltin(p))): if re.match(api_prefix, p.__module__): if (not inspect.isclass(p)): obj_stack.append(p) return allmethods # Note (thread-safety): blocking function def get_keystone_session(creds): url_parts = urlparse.urlparse(creds['auth_url']) path = url_parts.path.lower() if path.startswith('/v3'): # Use v3 plugin to authenticate # Note (thread-safety): blocking call auth = v3.Password( auth_url=creds['auth_url'], username=creds['username'], password=creds['password'], project_name=creds.get('project_name') or creds.get('tenant_name'), user_domain_name=creds.get('user_domain_name', 'Default'), project_domain_name=creds.get('project_domain_name', 'Default')) else: # Use v2 plugin # Note (thread-safety): blocking call auth = v2.Password(auth_url=creds['auth_url'], username=creds['username'], password=creds['password'], tenant_name=creds['tenant_name']) # Note (thread-safety): blocking call? session = kssession.Session(auth=auth) return session
wprice/qpid-proton
tests/python/proton_tests/interop.py
Python
apache-2.0
5,318
0.004513
# # 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. # from proton import * import os from . import common from proton._compat import str2bin def find_test_interop_dir(): """Walk up the directory tree to find the tests directory.""" f = os.path.dirname(__file__) while f and os.path.basename(f) != "tests": f = os.path.dirname(f) f = os.path.join(f, "interop") if not os.path.isdir(f): raise Exception("Cannot find test/interop directory from "+__file__) return f test_interop_dir=find_test_interop_dir() class InteropTest(common.Test): def setup(self): self.data = Data() self.message = Message() def teardown(self): self.data = None def get_data(self, name): filename = os.path.join(test_interop_dir, name+".amqp") f = open(filename,"rb") try: return f.read() finally: f.close() def decode_data(self, encoded): buffer = encoded while buffer: n = self.data.decode(buffer) buffer = buffer[n:] self.data.rewind() def decode_data_file(self, name): encoded = self.get_data(name) self.decode_data(encoded) encoded_size = self.data.encoded_size() # Re-encode and verify pre-computed and actual encoded size match. reencoded = self.data.encode() assert encoded_size == len(reencoded), "%d != %d" % (encoded_size, len(reencoded)) def decode_message_file(self, name): self.message.decode(self.get_data(name)) body = self.message.body if str(type(body)) == "<type 'org.apache.qpid.proton.amqp.Binary'>": body = body.array.tostring() self.decode_data(body) def assert_next(self, type, value): next_type = self.data.next() assert next_type == type, "Type mismatch: %s != %s"%( Data.type_names[next_type], Data.type_names[type]) next_value = self.data.get_object() assert next_value == value, "Value mismatch: %s != %s"%(next_value, value) def test_message(self): self.decode_message_file("message") self.assert_next(Data.STRING, "hello") assert self.data.next() is None def test_primitives(self): self.decode_data_file("primitives") self.assert_next(Data.BOOL, True) self.assert_next(Data.BOOL, False) self.assert_next(Data.UBYTE, 42) self.assert_next(Data.USHORT, 42) self.assert_next(Data.SHORT, -42) self.assert_next(Data.UINT, 12345) self.assert_next(Data.INT, -12345) self.assert_next(Data.ULONG, 12345) self.assert_next(Data.LONG, -12345) self.assert_next(Data.FLOAT, 0.125) self.assert_next(Data.DOUBLE, 0.125) assert self.data.next() is None def test_strings(self): self.decode_data_file("strings") self.assert_next(Data.BINARY, str2bin("abc\0defg")) self.assert_next(Data.STRING, "abcdefg") self.assert_next(Data.SYMBOL, "abcdefg") self.ass
ert_next(Data.BINARY, str2bin("")) self.assert_next(Data.STRING, "") self.assert_next(Data.SYMBOL, "") assert self.data.next() is None def test_described(self): self.decode_data_file("described") self.assert_next(Data.DESCRIBED, Described("foo-descriptor", "foo-value")) self.data.exit() assert self.data.next() == Data.DESCRIBED sel
f.data.enter() self.assert_next(Data.INT, 12) self.assert_next(Data.INT, 13) self.data.exit() assert self.data.next() is None def test_described_array(self): self.decode_data_file("described_array") self.assert_next(Data.ARRAY, Array("int-array", Data.INT, *range(0,10))) def test_arrays(self): self.decode_data_file("arrays") self.assert_next(Data.ARRAY, Array(UNDESCRIBED, Data.INT, *range(0,100))) self.assert_next(Data.ARRAY, Array(UNDESCRIBED, Data.STRING, *["a", "b", "c"])) self.assert_next(Data.ARRAY, Array(UNDESCRIBED, Data.INT)) assert self.data.next() is None def test_lists(self): self.decode_data_file("lists") self.assert_next(Data.LIST, [32, "foo", True]) self.assert_next(Data.LIST, []) assert self.data.next() is None def test_maps(self): self.decode_data_file("maps") self.assert_next(Data.MAP, {"one":1, "two":2, "three":3 }) self.assert_next(Data.MAP, {1:"one", 2:"two", 3:"three"}) self.assert_next(Data.MAP, {}) assert self.data.next() is None
posix4e/electron
script/lib/config.py
Python
mit
2,118
0.01322
#!/usr/bin/env python import errno import os import platform import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/brave-laptop-binaries/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = os.getenv('LIBCHROMIUMCONTENT_COMMIT') or \ 'd715734c03b0c892ea66695ae63fc0db9c3fc027' PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def get_platform_key(): if os.environ.has_key('MAS_BUILD'): return 'mas' else: return PLATFORM def get_target_arch(): try: target_arch_path = os.path.join(__file__, '..', '..', '..', 'vendor', 'brightray', 'vendor', 'download', 'libchromiumcontent', '.target_arch') with open(os.path.normpath(target_arch_path)) as f: return f.read().strip() except IOError as e: if e.errno != errno.ENOENT: raise return 'x64' def get_chromedriver_version(): return 'v2.21' def get_env_var(name): value = os.environ.get('ELECTRON_' + name, '') if not value: # TODO Remove ATOM_SHELL_* fallback values value = os.environ.get('ATOM_SHELL_' + name, '') if value: print 'Warning: Use $ELECTRON_' + name + ' instead of
$ATOM_SHELL_' + name return value def s3_config(): config = (get_env_var('S3_BUCKET'), get_env_var('S3_ACCESS_KEY'), get_env_var('S3_SECRET_KEY')) message = ('Error: Please set the $ELECTRON_S3_BUCKET, ' '$ELECTRON_S3_
ACCESS_KEY, and ' '$ELECTRON_S3_SECRET_KEY environment variables') assert all(len(c) for c in config), message return config def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode def get_zip_name(name, version, suffix=''): arch = get_target_arch() if arch == 'arm': arch += 'v7l' zip_name = '{0}-{1}-{2}-{3}'.format(name, version, get_platform_key(), arch) if suffix: zip_name += '-' + suffix return zip_name + '.zip'
jsjohnst/tornado
tornado/locks.py
Python
apache-2.0
15,234
0.000197
# Copyright 2015 The Tornado 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import, division, print_function, with_statement __all__ = ['Condition', 'Event', 'Semaphore', 'BoundedSemaphore', 'Lock'] import collections from tornado import gen, ioloop from tornado.concurrent import Future class _TimeoutGarbageCollector(object): """Base class for objects that periodically clean up timed-out waiters. Avoids memory leak in a common pattern like: while True: yield condition.wait(short_timeout) print('looping....') """ def __init__(self): self._waiters = collections.deque() # Futures. self._timeouts = 0 def _garbage_collect(self): # Occasionally clear timed-out waiters. self._timeouts += 1 if self._timeouts > 100: self._timeouts = 0 self._waiters = collections.deque( w for w in self._waiters if not w.done()) class Condition(_TimeoutGarbageCollector): """A condition allows one or more coroutines to wait until notified. Like a standard `threading.Condition`, but does not need an underlying lock that is acquired and released. With a `Condition`, coroutines can wait to be notified by other coroutines: .. testcode:: from tornado import gen from tornado.ioloop import IOLoop from tornado.locks import Condition condition = Condition() @gen.coroutine def waiter(): print("I'll wait right here") yield condition.wait() # Yield a Future. print("I'm done waiting") @gen.coroutine def notifier(): print("About to notify") condition.notify() print("Done notifying") @gen.coroutine def runner(): # Yield two Futures; wait for waiter() and notifier() to finish. yield [waiter(), notifier()] IOLoop.current().run_sync(runner) .. testoutput:: I'll wait right here About to notify Done notifying I'm done waiting `wait` takes an optional ``timeout`` argument, which is either an absolute timestamp:: io_loop = IOLoop.current() # Wait up to 1 second for a notification. yield condition.wait(timeout=io_loop.time() + 1) ...or a `datetime.timedelta` for a timeout relative to the current time:: # Wait up to 1 second. yield condition.wait(timeout=datetime.timedelta(seconds=1)) The method raises `tornado.gen.TimeoutError` if there's no notification before the deadline. """ def __init__(self): super(Condition, self).__init__() self.io_loop = ioloop.IOLoop.current() def __repr__(self): result = '<%s' % (self.__class__.__name__, ) if self._waiters: result += ' waiters[%s]' % len(self._waiters) return result + '>' def wait(self, timeout=None): """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. """ waiter = Future() self._waiters.append(waiter) if timeout: def on_timeout(): waiter.set_result(False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle)) return waiter def notify(self, n=1): """Wake ``n`` waiters.""" waiters = [] # Waiters we plan to run right now. while n and self._waiters: waiter = self._waiters.popleft() if not waiter.done(): # Might have timed out. n -= 1 waiters.append(waiter) for waiter in waiters: waiter.set_result(True)
def notify_all(self): """Wake all waiters.""" self.notify(len(self._waiters)) class Event(object): """An event blocks coroutines until its internal flag is set to True. Similar to `threading.Event`. A coroutine can wait for an event to be set. On
ce it is set, calls to ``yield event.wait()`` will not block unless the event has been cleared: .. testcode:: from tornado import gen from tornado.ioloop import IOLoop from tornado.locks import Event event = Event() @gen.coroutine def waiter(): print("Waiting for event") yield event.wait() print("Not waiting this time") yield event.wait() print("Done") @gen.coroutine def setter(): print("About to set the event") event.set() @gen.coroutine def runner(): yield [waiter(), setter()] IOLoop.current().run_sync(runner) .. testoutput:: Waiting for event About to set the event Not waiting this time Done """ def __init__(self): self._future = Future() def __repr__(self): return '<%s %s>' % ( self.__class__.__name__, 'set' if self.is_set() else 'clear') def is_set(self): """Return ``True`` if the internal flag is true.""" return self._future.done() def set(self): """Set the internal flag to ``True``. All waiters are awakened. Calling `.wait` once the flag is set will not block. """ if not self._future.done(): self._future.set_result(None) def clear(self): """Reset the internal flag to ``False``. Calls to `.wait` will block until `.set` is called. """ if self._future.done(): self._future = Future() def wait(self, timeout=None): """Block until the internal flag is true. Returns a Future, which raises `tornado.gen.TimeoutError` after a timeout. """ if timeout is None: return self._future else: return gen.with_timeout(timeout, self._future) class _ReleasingContextManager(object): """Releases a Lock or Semaphore at the end of a "with" statement. with (yield semaphore.acquire()): pass # Now semaphore.release() has been called. """ def __init__(self, obj): self._obj = obj def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): self._obj.release() class Semaphore(_TimeoutGarbageCollector): """A lock that can be acquired a fixed number of times before blocking. A Semaphore manages a counter representing the number of `.release` calls minus the number of `.acquire` calls, plus an initial value. The `.acquire` method blocks if necessary until it can return without making the counter negative. Semaphores limit access to a shared resource. To allow access for two workers at a time: .. testsetup:: semaphore from collections import deque from tornado import gen from tornado.ioloop import IOLoop from tornado.concurrent import Future # Ensure reliable doctest output: resolve Futures one at a time. futures_q = deque([Future() for _ in range(3)]) @gen.coroutine def simulator(futures): for f in futures: yield gen.moment f.set_result(None) IOLoop.current().add_callback(simulator, list(futures_q)) def use_some_resource(): return futures_q.popleft(
sensbio/sensbiotk
examples/scripts/fox_raw.py
Python
gpl-3.0
7,557
0.000265
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is a part of sensbiotk # Contact : sensbiotk@inria.fr # Copyright (C) 2015 INRIA # # 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/>. # pylint:disable= I0011, E1101, R0912, R0913, R0914, R0915 # E1101 no-member false positif """ fox_raw.py convert/plot raw Fox filename [-cdbvtfpamgh] -i <raw_foxfilename or path> or --input=<raw_foxfilename or path> for the output directory --dir<dirname> or -d<dirname> for a new basename output --basename<basename> or -b<basename> for time verification --verif or -v for sample time --time=<sample_time(sec)> or -t <sample_time(sec)> for sample frequency --frequency=<frequency(Hz)> or -s <frequency(Hz)> for plot IMU raw data --plot or -p for plot accelero raw data --acc or -a for plot magneto raw data --mag or -m for plot gyro raw data --gyr or -g for help use --help or -h """ import sys import os import getopt import numpy as np import matplotlib.pyplot as plt from sensbiotk.io import iofox from sensbiotk.io import viz def getnamefiles(filename, newbasename, diroutput): """ getnamefiles """ if len(filename) == 0: usage() sys.exit(2) # Compute output namefile basefile = os.path.basename(filename) basefile = os.path.splitext(basefile)[0] if newbasename != "": basename = basefile.split("_")[0] # print "BASE", basefile, basename if basename != basefile: basefile = basefile.replace(basename, newbasename) else: basefile = newbasename if os.path.isdir(diroutput): facc = diroutput + "/" + basefile + "_acc.csv" fmag = diroutput + "/" + basefile + "_mag.csv" fgyr = diroutput + "/" + basefile + "_gyr.csv" fimu = diroutput + "/" + basefile + "_imu.csv" else: print "error: bad output directory" usage() sys.exit(2) return basefile, facc, fmag, fgyr, fimu def plotsig(time, data, title, labely): """ Plot one signal """ plt.figure() plt.title(title) plt.plot(time, data[:, 0:3]) plt.ylabel(labely) plt.xlabel('time (s)') plt.legend(('x', 'y', 'z')) def veriftime(label, ptime): """ Clock verification Parameters: ------------ ptime: numpy array """ plt.figure() plt.title(label) plt.grid() clock = np.diff(ptime) plt.plot(clock) print 'NB Points =', len(ptime) print 'Duration (s)=', ptime[-1] - ptime[0] print 'Steptime (ms)=', (ptime[-1] - ptime[0]) / len(ptime) print 'Time to', ptime[0], 'From', ptime[-1] print 'Clock mean (ms)=', np.mean(clock) print 'Clock std (ms)=', np.std(clock) print 'Clock max (ms)=', np.max(clock) print 'Clock min (ms)=', np.min(clock) return def usage(): """Usage command print """ print "Usage" print __doc__ def main(argv): """ Main command """ options = [] filename = "" try: opts, _ = getopt.getopt(argv, "i:d:b:vt:f:pamgh", ["input=", "dir=", "basename", "verif", "time=", "frequency=", "plot", "acc", "mag", "gyr", "help"]) except getopt.GetoptError: usage() sys.exit(2) period = 0.005 diroutput = "." newbasename = "" filenames = "" for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-i", "--input"): fnames = arg if not os.path.isfile(fnames): if not os.path.isdir(fnames): print "error: input file/dir does not exist" usage() sys.exit(2) else: # directory input specified filenames = os.listdir(fnames) idx = 0 for onefile in filenames: filenames[idx] = fnames + "/" + onefile #filenames[idx] = fnames + "/" + filenames[idx] idx = idx + 1 else: # filename input spec
ified filenames = [fnames] elif opt in ("-d", "--dir"): diroutput = arg elif opt in ("-b", "--basename"): newbasename = arg elif opt in ("-v", "--verif"): options.append("-v") elif opt in ("-t", "--time"): try: period = float(arg) except ValueError: usage() sys.exit(2) if peri
od <= 0: usage() sys.exit(2) elif opt in ("-f", "--frequency"): try: period = float(arg) except ValueError: usage() sys.exit(2) if period <= 0: usage() sys.exit(2) else: period = 1 / period elif opt in ("-p", "--plot"): options.append("-p") elif opt in ("-a", "--acc"): options.append("-a") elif opt in ("-m", "--mag"): options.append("-m") elif opt in ("-g", "--gyr"): options.append("-g") if len(filenames) == 0: usage() sys.exit(2) for filename in filenames: print "Conversion:", filename # Get names file basefile, fileacc, filemag, filegyr, fileimu =\ getnamefiles(filename, newbasename, diroutput) # Read and convert file answer = iofox.convert_sensors_rawfile(filename, fileacc, filemag, filegyr) if answer != "OK": usage() sys.exit(2) # Load ascii files converted [myt, acc, mag, gyr] = \ iofox.load_foximu_csvfile(fileacc, filemag, filegyr, period, 1) iofox.save_foxsignals_csvfile(myt, acc, mag, gyr,* fileimu) # Plot if necessary if "-p" in options: label = basefile + " IMU" viz.plot_imu(-1, label, myt, acc, mag, gyr) if "-a" in options: label = basefile + " Acc" plotsig(myt, acc, label, "ACC (m/s^2") if "-m" in options: label = basefile + " Mag" plotsig(myt, mag, label, "MAG (gauss)") if "-g" in options: label = basefile + " Gyr" plotsig(myt, gyr, label, "GYR (rad/s)") if "-v" in options: [myt, acc] = iofox.load_foxacc_csvfile(fileacc) label = basefile + " time verif." veriftime(label, myt[:, 0]) # Clean temp files os.remove(fileacc) os.remove(filemag) os.remove(filegyr) plt.show() if __name__ == "__main__": main(sys.argv[1:])
bcicen/fig
fig/__init__.py
Python
apache-2.0
107
0
from __future__ import unicode_literals from .service
import Service # noqa
:flake8 __version__ = '1.0.1'
kedz/cuttsum
trec2014/python/cuttsum/summarizer/filters.py
Python
apache-2.0
26,439
0.005371
from cuttsum.sentsim import SentenceLatentVectorsResource from cuttsum.summarizer.ap import APSummarizer, APSalienceSummarizer from cuttsum.summarizer.baseline import HACSummarizer import os import pandas as pd import numpy as np from datetime import datetime, timedelta from sklearn.metrics.pairwise import cosine_similarity from cuttsum.salience import SaliencePredictionAggregator from cuttsum.data import get_resource_manager from cuttsum.misc import passes_simple_filter class RankedSalienceFilteredSummary(object): def __init__(self): self.dir_ = os.path.join( os.getenv(u'TREC_DATA', u'.'), u'ranked-salience-filtered-summaries') if not os.path.exists(self.dir_): os.makedirs(self.dir_) def get_tsv_path(self, event, sal_cutoff, sim_cutoff): return os.path.join(self.dir_, "sal-ranked-{}-sal_{}-sim_{}.tsv".format( event.fs_name(), sal_cutoff, sim_cutoff)) def get_dataframe(self, event, sal_cutoff, sim_cutoff): tsv = self.get_tsv_path(event, sal_cutoff, sim_cutoff) if not os.path.exists(tsv): return None else: with open(tsv, u'r') as f: df = pd.io.parsers.read_csv( f, sep='\t', quoting=3) df.columns = ['query id', 'system id', 'run id', 'stream id', 'sentence id', 'timestamp', 'conf', 'text'] return df def make(self, event, prefix, feature_set, sal_cutoff, sim_cutoff): tsv_path = self.get_tsv_path(event, sal_cutoff, sim_cutoff) lvecs = SentenceLatentVectorsResource() string_res = get_resource_manager(u'SentenceStringsResource') spa = SaliencePredictionAggregator() #cluster_df = hac.get_dataframe(event, dist_cutoff) #for _, row in cluster_df.iterrows(): # print row['hour'], datetime.utcfromtimestamp(row['timestamp']) epoch = datetime.utcfromtimestamp(0) updates = [] Xcache = None #timestamps = sorted(list(cluster_df['timestamp'].unique())) hours = event.list_event_hours() for hour in hours: #hour = datetime.utcfromtimestamp(timestamp) - timedelta(hours=1) hp1 = hour + timedelta(hours=1) timestamp = str(int((hp1 - epoch).total_seconds())) lvec_df = lvecs.get_dataframe(event, hour) sal_df = spa.get_dataframe(event, hour, prefix, feature_set) str_df = string_res.get_dataframe(event, hour) if lvec_df is None or sal_df is None or str_df is None: continue str_df.drop_duplicates(['stream id', 'sentence id'], inplace=True) lvec_df.drop_duplicates(['stream id', 'sentence id'], inplace=True) sal_df.drop_duplicates(['stream id', 'sentence id'], inplace=True) str_df.sort(['stream id', 'sentence id'], inplace=True) str_df.reset_index(drop=True, inplace=True) lvec_df.sort(['stream id', 'sentence id'], inplace=True) lvec_df.reset_index(drop=True, inplace=True) sal_df.sort(['stream id', 'sentence id'], inplace=True) sal_df.reset_index(drop=True, inplace=True) str_df = str_df.join( str_df.groupby('stream id')['sentence id'].agg('count'), on='stream id', rsuffix='_r').rename( columns={"sentence id_r": "document count"}) good_sents = str_df.apply( lambda x: passes_simple_filter( x['streamcorpus'], x['document count']), axis=1) #good_sents = good_sents.reset_index() str_df = str_df[good_sents] lvec_df = lvec_df[good_sents] sal_df = sal_df[good_sents] n_rows = len(sal_df) for i in xrange(n_rows): assert sal_df['stream id'].iloc[i] == \ lvec_df['stream id'].iloc[i] assert sal_df['sentence id'].iloc[i] == \ lvec_df['sentence id'].iloc[i] assert str_df['stream id'].iloc[i] == \ lvec_df['stream id'].iloc[i] assert str_df['sentence id'].iloc[i] == \ lvec_df['sentence id'].iloc[i] if n_rows == 0: continue Xsal = sal_df.as_matrix()[:,2:].astype(np.float64).mean(axis=1) mu_sal = np.mean(Xsal) sig_sal = np.std(Xsal) Xsal_norm = (Xsal - mu_sal) / sig_sal lvec_df
= lvec_df[Xsal_norm > sal_cutoff] str_df = str_df[Xsal_norm > sal_cutof
f] str_df = str_df.set_index(['stream id', 'sentence id']) lvec_df['salience'] = Xsal_norm[Xsal_norm > sal_cutoff] lvec_df.sort(['salience'], inplace=True, ascending=False) if Xcache is None: Xlvecs = lvec_df.as_matrix()[:, 2:-2].astype(np.float64) K = cosine_similarity(Xlvecs) K_ma = np.ma.array(K, mask=True) good_indexes = [] for i, (_, row) in enumerate(lvec_df.iterrows()): sim = K_ma[i,:].max(fill_value=0.0) if not isinstance(sim, np.float64): sim = 0 if sim < sim_cutoff: up_str = str_df.loc[ row['stream id'], row['sentence id']]['streamcorpus'] updates.append({ 'query id': event.query_num, 'system id': 'cunlp', 'run id': 'sal-ranked-sal_{}-sim_{}'.format( sal_cutoff, sim_cutoff), 'stream id': row['stream id'], 'sentence id': row['sentence id'], 'timestamp': timestamp, 'conf': row['salience'], 'string': up_str}) K_ma.mask[:,i] = False good_indexes.append(i) Xcache = Xlvecs[good_indexes].copy() else: xtmp = lvec_df.as_matrix()[:, 2:-2].astype(np.float64) Xlvecs = np.vstack([Xcache, xtmp]) start_index = Xcache.shape[0] K = cosine_similarity(Xlvecs) K_ma = np.ma.array(K, mask=True) K_ma.mask.T[np.arange(0, start_index)] = False good_indexes = [] for i, (_, row) in enumerate(lvec_df.iterrows(), start_index): #print i sim = K_ma[i,:].max(fill_value=0.0) #print sim if sim < sim_cutoff: up_str = str_df.loc[ row['stream id'], row['sentence id']]['streamcorpus'] updates.append({ 'query id': event.query_num, 'system id': 'cunlp', 'run id': 'sal-ranked-sal_{}-sim_{}'.format( sal_cutoff, sim_cutoff), 'stream id': row['stream id'], 'sentence id': row['sentence id'], 'timestamp': timestamp, 'conf': row['salience'], 'string': up_str}) K_ma.mask[:,i] = False good_indexes.append(i) if len(good_indexes) > 0: Xcache = np.vstack([Xcache, Xlvecs[good_indexes].copy()]) #Xcache = Xlvecs[good_indexes].copy() if len(updates) == 0: updates.append({ 'query id': event.query_num, 'system id': 'cunlp', 'run id': 'sal-ranked-sal_{}-sim_{}'.format( sal_cu
dmahugh/gitdata
reposbymonth.py
Python
mit
629
0.00318
# reposbymonth.py # Convert temp.csv to temp2.csv (monthly totals) # temp.csv was created with this gitdata command: # gitdata repos -o* -amsftgi
ts -sa -ntemp.csv -fowner.login/name/private -v import csv with open('temp.csv', newline='') as csvfile1, open('temp2.csv', 'w', newline='') as csvfile2: reporeader = csv.reader(csvfile1, delimiter=' ', quotechar='|') repowriter = csv.writer(csvfile2, delimiter=' '
, quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in reporeader: values = row[0].split(',') values[3] = values[3][:7] print(values) repowriter.writerow([','.join(values)])
odoocn/pos-addons
pos_multi_session/__openerp__.py
Python
lgpl-3.0
424
0
{ 'na
me': "Sync POS orders across multiple sessions", 'version': '1.0.0', 'author':
'Ivan Yelizariev', 'category': 'Point Of Sale', 'website': 'https://yelizariev.github.io', 'depends': ['pos_disable_payment', 'bus'], 'data': [ 'security/ir.model.access.csv', 'views.xml', ], 'qweb': [ 'static/src/xml/pos_multi_session.xml', ], 'installable': True, }
colour-science/colour
colour/io/tests/test_uprtek_sekonic.py
Python
bsd-3-clause
33,878
0
"""Defines unit tests for :mod:`colour.io.uprtek_sekonic` module.""" from __future__ import annotations import json import numpy as np import os import unittest from colour.colorimetry import SpectralDistribution from colour.hints import Any, Dict, Optional from colour.io import ( SpectralDistribution_UPRTek, SpectralDistribution_Sekonic, ) __author__ = "Colour Developers" __copyright__ = "Copyright 2013 Colour Developers" __license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause" __maintainer__ = "Colour Developers" __email__ = "colour-developers@colour-science.org" __status__ = "Production" __all__ = [ "RESOURCES_DIRECTORY", "AbstractSpectralDistributionTest", "TestSpectralDistributionUprTek", "TestSpectralDistributionSekonic", ] RESOURCES_DIRECTORY: str = os.path.join(os.path.dirname(__file__), "resources") class AbstractSpectralDistributionTest(unittest.TestCase): """ Define :class:`colour.SpectralDistribution_UPRTek`, :class:`colour.SpectralDistribution_Sekonic` classes common unit tests methods. """ def __init__(self, *args: Any): """ Create an instance of the class. Other Parameters ---------------- args Arguments. """ super().__init__(*args) self._sd_factory: Any = None self._path: Optional[str] = None self._spectral_data: Optional[Dict] = None def test_required_attributes(self): """Test the presence of required attributes.""" required_attributes = ( "mapping", "path", "header", "spectral_quantity", "reflection_geometry", "transmission_geometry", "bandwidth_FWHM", "bandwidth_corrected", "metadata", ) for attribute in required_attributes: self.assertIn(attribute, dir(SpectralDistribution_UPRTek)) def test_required_methods(self): """Test the presence of required methods.""" required_methods = ("__init__", "read", "write") for method in required_methods: self.assertIn(method, dir(SpectralDistribution_UPRTek)) def test_read(self): """ Test :meth:`colour.SpectralDistribution_UPRTek.read` and :meth:`colour.SpectralDistribution_Sekonic.read` methods. """ if self._sd_factory is None: return sd = self._sd_factory( os.path.join(RESOURCES_DIRECTORY, self._path) ).read() sd_r = SpectralDistribution(self._spectral_data) np.testing.assert_array_equal(sd_r.domain, sd.domain) np.testing.assert_almost_equal(sd_r.values, sd.values, decimal=6) for key, value in self._header.items(): for specification in sd.header.mapping.elements: if key == specification.element: if key == "Comments": self.assertDictEqual(
json.loads(sd.header.comments), value
) else: self.assertEqual( getattr(sd.header, specification.attribute), value ) class TestSpectralDistributionUprTek(AbstractSpectralDistributionTest): """ Define :class:`colour.SpectralDistribution_UPRTek` class unit tests methods. """ def __init__(self, *args: Any): """ Create an instance of the class. Other Parameters ---------------- args Arguments. """ super().__init__(*args) self._sd_factory = SpectralDistribution_UPRTek self._path = "ESPD2021_0104_231446.xls" self._spectral_data = { 380: 0.030267, 381: 0.030267, 382: 0.030267, 383: 0.029822, 384: 0.028978, 385: 0.028623, 386: 0.030845, 387: 0.035596, 388: 0.039231, 389: 0.039064, 390: 0.035223, 391: 0.031580, 392: 0.029181, 393: 0.027808, 394: 0.026256, 395: 0.024526, 396: 0.022557, 397: 0.020419, 398: 0.018521, 399: 0.018149, 400: 0.019325, 401: 0.021666, 402: 0.024045, 403: 0.026473, 404: 0.029076, 405: 0.031840, 406: 0.033884, 407: 0.034038, 408: 0.032302, 409: 0.030383, 410: 0.029426, 411: 0.029979, 412: 0.032614, 413: 0.037204, 414: 0.042279, 415: 0.046029, 416: 0.048698, 417: 0.053064, 418: 0.059530, 419: 0.070840, 420: 0.087678, 421: 0.110043, 422: 0.136705, 423: 0.165180, 424: 0.199071, 425: 0.241976, 426: 0.293837, 427: 0.359177, 428: 0.434192, 429: 0.523828, 430: 0.632578, 431: 0.758893, 432: 0.915528, 433: 1.096489, 434: 1.307487, 435: 1.557125, 436: 1.838779, 437: 2.183382, 438: 2.586251, 439: 3.054022, 440: 3.625659, 441: 4.279538, 442: 5.055838, 443: 5.919301, 444: 6.869926, 445: 7.940298, 446: 9.090219, 447: 10.336670, 448: 11.619895, 449: 12.939739, 450: 14.206918, 451: 15.396660, 452: 16.430536, 453: 17.267374, 454: 17.912292, 455: 18.261185, 456: 18.404581, 457: 18.288025, 458: 18.002302, 459: 17.570372, 460: 17.011297, 461: 16.411137, 462: 15.779440, 463: 15.168951, 464: 14.585364, 465: 14.057872, 466: 13.575768, 467: 13.144953, 468: 12.737307, 469: 12.346188, 470: 11.967313, 471: 11.590308, 472: 11.209807, 473: 10.815372, 474: 10.406748, 475: 10.007284, 476: 9.627886, 477: 9.279286, 478: 8.958391, 479: 8.663115, 480: 8.427362, 481: 8.238759, 482: 8.110200, 483: 8.011048, 484: 7.939125, 485: 7.900343, 486: 7.880703, 487: 7.887271, 488: 7.907047, 489: 7.939895, 490: 7.977298, 491: 8.013443, 492: 8.056756, 493: 8.112617, 494: 8.181398, 495: 8.256148, 496: 8.332609, 497: 8.418014, 498: 8.513148, 499: 8.616785, 500: 8.719036, 501: 8.817776, 502: 8.914417, 503: 9.011255, 504: 9.105255, 505: 9.193217, 506: 9.274889, 507: 9.350751, 508: 9.423820, 509: 9.490992, 510: 9.553215, 511: 9.608335, 512: 9.653841, 513: 9.691347, 514: 9.727146, 515: 9.767722, 516: 9.809064, 517: 9.842565, 518: 9.867527, 519: 9.887219, 520: 9.906105, 521: 9.920433, 522: 9.929304, 523: 9.932856, 524: 9.935204, 525: 9.937991, 526: 9.938448, 527: 9.936127, 528: 9.930192, 529: 9.922665, 530: 9.913944, 531: 9.905774, 532: 9.898767, 533: 9.894219, 534: 9.891479, 535: 9.883711, 536: 9.862693, 537: 9.829168, 538: 9.795257, 539: 9.767633, 540: 9.747380,
jtara1/tol-bot
tests_etc/PIL-test.py
Python
mit
340
0.017647
# -*- coding: utf-8 -*- """ Created on Wed Jul 22 14:49:04 2015 @author: James """ #import PIL from PIL import ImageOps, ImageFilter, ImageGrab, Image import os fp = os.getcwd() + '\\trees_ss 8.jpg\\' img = Image.open('
trees_ss 8.jpg', 'r') #labels = img.sp
lit #print labels pixel = img.getpixel((1,1)) r, g, b = img.split() print r
1065865483/0python_script
four/Webdriver/FindElement/By_xpath_p1.py
Python
mit
674
0.001684
from selenium import webdrive
r from time import sleep driver = webdriver.Firefox() driver.get("https://www.baidu.com/") #绝对路径定位 # driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div[1]/div/form/span[1]/input").send_keys("51zxw") # a.根据input标签中的id属性定位元素 driver.find_element_by_xpath("//input[@id='kw']").send_keys("51zxw") # b.根据input标签中name属性定位元素 driver.find_element_by_xpath("//input[@name='wd']").send_keys("51zxw") # c.根据input标签中class属性定位元素 driver.find_element_by_xpath("//*[@class='s_ipt
']").send_keys("51zxw") driver.find_element_by_id("su").click() sleep(3) driver.quit()
thumbor-community/prometheus
tc_prometheus/metrics/prometheus_metrics.py
Python
mit
3,108
0.001287
#!/usr/bin/python # -*- coding: utf-8 -*- # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2017 Simon Effenberg <savar@schuldeigen.de> # Copyright (c) 2017 Thumbor Community Extensions from prometheus_client import Counter, start_http_server, Summary from thumbor.metrics import BaseMetrics class Metrics(BaseMetrics): def __init__(self, config): super(Metrics, self).__init__(config) if not hasattr(Metrics, 'http_server_started'): start_http_server(config.PROMETHEUS_SCRAPE_PORT) Metrics.http_server_started = True Metrics.counters = {} Metrics.summaries = {} # hard coded mapping right now self.mapping = { 'response.status': ['statuscode'], 'response.format': ['extension'], 'response.bytes': ['extension'],
'original_image.status': ['statuscode'], 'original_image.fetch': ['statuscode', 'networklocation'], 'response.time': ['statuscode_extension'], } def incr(self, metricname, value=1): name, labels = self.__data(metricname) if name not in Metrics.counters: Metrics.counters[name] = Counter(name, name, labels.keys()) counter = Metrics.counters[name]
if len(labels) != 0: counter = counter.labels(**labels) counter.inc(value) def timing(self, metricname, value): name, labels = self.__data(metricname) if name not in Metrics.summaries: Metrics.summaries[name] = Summary(name, name, labels.keys()) summary = Metrics.summaries[name] if len(labels) != 0: summary = summary.labels(**labels) summary.observe(value) def __data(self, metricname): basename = self.__basename(metricname) return (self.__format(basename), self.__labels(basename, metricname)) def __format(self, basename): # stolen from https://github.com/prometheus/statsd_exporter # _ -> __ # - -> __ # . -> _ # following prometheus advice to prefix names with the app name return "thumbor_{0}".format( basename.replace('_','__').replace('-','__').replace('.','_') ) def __labels(self, name, metricname): if name not in self.mapping: return {} # the split('.', MAXSPLIT) is mainly necessary to get the correct # stuff for original_image.fetch where the networklocation is # something like 'domain' so like 'test.com' and would be splitted at # least 1 time too often values = metricname.replace(name + '.', '').split('.', len(self.mapping[name])-1) labels = {} for index, label in enumerate(self.mapping[name]): labels[label] = values[index] return labels def __basename(self, metricname): for mapped in self.mapping.keys(): if metricname.startswith(mapped + "."): metricname = mapped return metricname
ctgk/BayesianNetwork
test/image/test_util.py
Python
mit
1,753
0.00057
import unittest import numpy as np from bayesnet.image.util import img2patch, patch2img class TestImg2Patch(unittest.TestCase): def test_img2patch(self): img = np.arange(16).reshape(1, 4, 4, 1) patch = img2patch(img, size=3, step=1) expected = np.asarray([ [img[0, 0:3, 0:3, 0], img[0, 0:3, 1:4, 0]], [img[0, 1:4, 0:3, 0], img[0, 1:4, 1:4, 0]] ]) expected = expected[None, ..., None] self.assertTrue((patch == expected).all()) imgs = [ np.random.randn(2, 5, 6, 3), np.random.randn(3, 10, 10, 2), np.random.randn(1, 23, 17, 5) ] sizes = [ (1, 1), 2, (3, 4) ] steps = [ (1, 2), (3, 1), 3 ] shapes = [ (2, 5, 3, 1, 1, 3), (3, 3, 9, 2, 2, 2), (1, 7, 5, 3, 4, 5) ] for img, size, step, shape in zip(imgs, sizes, steps, shapes): self.assertEqual(shape, img2patch(img, size, step).shape) class TestPatch2Img(unittest.TestCase): def test_patch2img(self): img = np.arange(16).reshape(1, 4, 4, 1) patch = img2patch(img, size=2, step=2) self.assertTrue((img == patch2img(patch, (2, 2), (1, 4, 4, 1))).all()) patch = img2patch(img, size=3, step=1) expected = np.arange(0, 32, 2).reshape(1, 4, 4, 1) expected[0, 0, 0, 0] /= 2 expected[0, 0, -1, 0] /= 2 expected[0, -1, 0, 0] /= 2 expected[0, -1, -1, 0] /= 2 expected[0, 1:3, 1:3, 0] *= 2 self.assertTrue((expected == patch2img(patch, (1, 1),
(1, 4, 4, 1))).all()) if __name__
== '__main__': unittest.main()
CubicERP/geraldo
site/newsite/django_1_0/django/core/cache/__init__.py
Python
lgpl-3.0
2,288
0.003059
""" Caching framework. This package defines set of cache backends that all conform to a simple API. In a nutshell, a cache is a set of values -- which can be any object that may be pickled -- identified by string keys. For the complete API, see the abstract BaseCache class in django.core.cache.backends.base. Client code should not access a cache backend directly; instead it should either use the "cache" variable made available here, or it should use the get_cache() function made available here. get_cache() takes a backend URI (e.g. "memcached://127.0.0.1:11211/") and returns an instance of a backend cache class. See docs/cache.txt for information on the public API. """ from cgi import parse_qsl from django.conf import settings from django.core.cache.backends.base import InvalidCacheBackendError # Name for use in settings file --> name of module in "backends" directory. # Any backend scheme that is not in this dictionary is treated as a Python # import path to a custom backend. BACKENDS = { 'memcached': 'memcached', 'locmem': 'locmem', 'file': 'filebased', 'db': 'db', 'dummy': 'dummy', } DEPRECATED_BACKENDS = { # deprecated backend --> replacement module 'simple': 'locmem', } def get_cache(backend_uri): if backend_uri.find(':') == -1: raise InvalidCacheBackendError, "Bac
kend URI must start with scheme://" scheme, rest = backend_uri.split(':', 1) if not rest.startswith('//'): raise InvalidCacheBackendError, "Backend URI must start with scheme://" if scheme in DEPRECATED_BACKENDS: import warnings warnings.warn("'%s' backend is deprecated. Use '%s' instead." % (scheme, DEPRECATED_BACKENDS[scheme]), DeprecationWa
rning) scheme = DEPRECATED_BACKENDS[scheme] host = rest[2:] qpos = rest.find('?') if qpos != -1: params = dict(parse_qsl(rest[qpos+1:])) host = rest[2:qpos] else: params = {} if host.endswith('/'): host = host[:-1] if scheme in BACKENDS: module = __import__('django.core.cache.backends.%s' % BACKENDS[scheme], {}, {}, ['']) else: module = __import__(scheme, {}, {}, ['']) return getattr(module, 'CacheClass')(host, params) cache = get_cache(settings.CACHE_BACKEND)
python-attrs/cattrs
src/cattr/preconf/tomlkit.py
Python
mit
1,561
0
"""Preconfigured converters for tomlkit.""" from base64 import b85decode, b85encode from datetime import datetime from typing import Any from .._compat import Set, is_mapping from ..converters import GenConverter from . import validate_datetime def configure_converter(converter: GenConverter): """ Configure the converter for use with the tomlkit library. * bytes are serialized as base85 strings * sets are serialized as lists * tuples are serializas as lists * mapping keys are coerced into strings when unstructuring """ converter.register_structure_hook(bytes, lambda v, _: b85decode(v)) converter.register_unstructure_hook( bytes, lambda v: (b85encode(v) if v else b"").decode("utf8") ) def gen_unstructure_mapping(cl: Any, unstructure_to=None): key_handler = str args = getattr(cl, "__args__", None) if args and issubclass(args[0], str): key_handler = None return con
ver
ter.gen_unstructure_mapping( cl, unstructure_to=unstructure_to, key_handler=key_handler ) converter._unstructure_func.register_func_list( [(is_mapping, gen_unstructure_mapping, True)] ) converter.register_structure_hook(datetime, validate_datetime) def make_converter(*args, **kwargs) -> GenConverter: kwargs["unstruct_collection_overrides"] = { **kwargs.get("unstruct_collection_overrides", {}), Set: list, tuple: list, } res = GenConverter(*args, **kwargs) configure_converter(res) return res
tseaver/gcloud-python
speech/nox.py
Python
apache-2.0
3,927
0
# Copyright 2016 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from
__future__ import absolute_import import os import nox LOCAL_DEPS = ( os.path.join('..', 'api_core'), ) @nox.session def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of
Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, then install this package in-place. session.install('mock', 'pytest', 'pytest-cov', *LOCAL_DEPS) session.install('-e', '.') # Run py.test against the unit tests. session.run( 'py.test', '--quiet', '--cov=google.cloud.speech_v1', '--cov=tests.unit', '--cov-append', '--cov-config=.coveragerc', '--cov-report=', '--cov-fail-under=0', os.path.join('tests', 'unit'), ) @nox.session @nox.parametrize('py', ['2.7', '3.5', '3.6', '3.7']) def unit(session, py): """Run the unit test suite.""" # Run unit tests against all supported versions of Python. session.interpreter = 'python{}'.format(py) # Set the virtualenv dirname. session.virtualenv_dirname = 'unit-' + py default(session) @nox.session @nox.parametrize('py', ['2.7', '3.6']) def system(session, py): """Run the system test suite.""" # Sanity check: Only run system tests if the environment variable is set. if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environment variable.') # Run the system tests against latest Python 2 and Python 3 only. session.interpreter = 'python{}'.format(py) # Set the virtualenv dirname. session.virtualenv_dirname = 'sys-' + py # Use pre-release gRPC for system tests. session.install('--pre', 'grpcio') # Install all test dependencies, then install this package into the # virtualenv's dist-packages. session.install('mock', 'pytest', *LOCAL_DEPS) session.install('../test_utils/', '../storage/') session.install('.') # Run py.test against the system tests. session.run('py.test', '--quiet', os.path.join('tests', 'system')) @nox.session def lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """ session.interpreter = 'python3.6' session.install('flake8', *LOCAL_DEPS) session.install('.') session.run('flake8', 'google', 'tests') @nox.session def lint_setup_py(session): """Verify that setup.py is valid (including RST check).""" session.interpreter = 'python3.6' # Set the virtualenv dirname. session.virtualenv_dirname = 'setup' session.install('docutils', 'Pygments') session.run( 'python', 'setup.py', 'check', '--restructuredtext', '--strict') @nox.session def cover(session): """Run the final coverage report. This outputs the coverage report aggregating coverage from the unit test runs (not system test runs), and then erases coverage data. """ session.interpreter = 'python3.6' session.chdir(os.path.dirname(__file__)) session.install('coverage', 'pytest-cov') session.run('coverage', 'report', '--show-missing', '--fail-under=100') session.run('coverage', 'erase')
IvanaXu/Test_Class_GOF
tPatterns/Behavioral_Patterns/test_Observer_Pattern.py
Python
gpl-3.0
1,644
0.001217
# -*-coding:utf-8-*- # @auth ivan # @time 2016-10-25 21:00:02 # @goal test for Observer Pattern class Subject(): def __init__(self): self.observers = [] self.state = 0 def getState(self): return self.state def setState(self, state): self.state = state def attach(self, observer): self.observers.append(observer) self.notifyAllObservers() def notifyAllObservers(
self): for observer in self.observers: observer.update() class Observer: def update(self):
return class BinaryObserver(Observer): def __init__(self, subject): self.subject = subject self.subject.attach(self) def update(self): print("Binary String: " + bin(self.subject.getState())) # BinaryObserver class OctalObserver(Observer): def __init__(self, subject): self.subject = subject self.subject.attach(self) def update(self): print("Octal String: " + oct(self.subject.getState())) # OctalObserver class HexaObserver(Observer): def __init__(self, subject): self.subject = subject self.subject.attach(self) def update(self): print("Hex String: " + hex(self.subject.getState())) # HexaObserver class ObserverPatternDemo: def run(self): self.subject = Subject() BinaryObserver(self.subject) OctalObserver(self.subject) HexaObserver(self.subject) print("First state change: 15") self.subject.setState(15) print("Second state change: 10") self.subject.setState(10) O = ObserverPatternDemo() O.run()
interlegis/sapl
sapl/sessao/urls.py
Python
gpl-3.0
11,025
0.001452
from django.conf.urls import include, url from sapl.sessao.views import (AdicionarVariasMateriasExpediente, AdicionarVariasMateriasOrdemDia, BancadaCrud, CargoBancadaCrud, ExpedienteMateriaCrud, ExpedienteView, JustificativaAusenciaCrud, OcorrenciaSessaoView, ConsideracoesFinaisView, MateriaOrdemDiaCrud, OradorOrdemDiaCrud, MesaView, OradorCrud, OradorExpedienteCrud, PainelView, PautaSessaoDetailView, PautaSessaoView, PesquisarPautaSessaoView, PesquisarSessaoPlenariaView, PresencaOrdemDiaView, PresencaView, ResumoOrdenacaoView, ResumoView, ResumoAtaView, RetiradaPautaCrud, SessaoCrud, TipoJustificativaCrud, TipoExpedienteCrud, TipoResultadoVotacaoCrud, TipoExpedienteCrud, TipoResultadoVotacaoCrud, TipoRetiradaPautaCrud, TipoSessaoCrud, VotacaoEditView, VotacaoExpedienteEditView, VotacaoExpedienteView, VotacaoNominalEditView, VotacaoNominalExpedienteDetailView, VotacaoNominalExpedienteEditView, VotacaoNominalExpedienteView, VotacaoNominalTransparenciaDetailView, VotacaoSimbolicaTransparenciaDetailView, VotacaoNominalView, VotacaoView, abrir_votacao, atualizar_mesa, insere_parlamentar_composicao, mudar_ordem_materia_sessao, recuperar_materia, recuperar_numero_sessao_view, remove_parlamentar_composicao, reordena_materias, sessao_legislativa_legislatura_ajax, VotacaoEmBlocoOrdemDia, VotacaoEmBlocoExpediente, VotacaoEmBlocoSimbolicaView, VotacaoEmBlocoNominalView, recuperar_nome_tipo_sessao, ExpedienteLeituraView, OrdemDiaLeituraView, retirar_leitura, TransferenciaMateriasExpediente, TransferenciaMateriasOrdemDia, filtra_materias_copia_sessao_ajax, verifica_materia_sessao_plenaria_ajax) from .apps import AppConfig app_name = AppConfig.name urlpatterns = [ url(r'^sessao/', include(SessaoCrud.get_urls() + OradorCrud.get_urls() + OradorExpedienteCrud.get_urls() + ExpedienteMateriaCrud.get_urls() + JustificativaAusenciaCrud.get_urls() + MateriaOrdemDiaCrud.get_urls() + OradorOrdemDiaCrud.get_urls() + RetiradaPautaCrud.get_urls())), url(r'^sessao/(?P<pk>\d+)/mesa$', MesaView.as_view(), name='mesa'), url(r'^sessao/mesa/atualizar-mesa/$', atualizar_mesa, name='atualizar_mesa'), url(r'^sessao/mesa/insere-parlamentar/composicao/$', insere_parlamentar_composicao, name='insere_parlamentar_composicao'), url(r'^sessao/mesa/remove-parlamentar-composicao/$', remove_parlamentar_composicao, name='remove_parlamentar_composicao'), url(r'^sessao/recuperar-materia/', recuperar_materia), url(r'^sessao/recuperar-numero-sessao/', recuperar_numero_sessao_view, name='recuperar_numero_sessao_view' ), url(r'^sessao/recuperar-nome-tipo-sessao/', recuperar_nome_tipo_sessao, name='recuperar_nome_tipo_sessao'), url(r'^sessao/sessao-legislativa-legislatura-ajax/', sessao_legislativa_legislatura_ajax, name='sessao_legislativa_legislatura_ajax_view'), url(r'^sessao/filtra-materias-copia-sessao-ajax/', filtra_materias_copia_sessao_ajax, name='filtra_materias_copia_sessao_ajax_view'), url(r'^sessao/verifica-materia-sessao-plenaria-ajax/', verifica_materia_sessao_plenaria_ajax, name='verifica_materia_sessao_plen
aria_ajax_view'), url(r'^sessao/(?P<pk>\d+)/(?P<spk>\d+)/abrir-votacao$', abrir_votacao, name="abrir_votacao"), url(
r'^sessao/(?P<pk>\d+)/reordena/(?P<tipo>[\w\-]+)/(?P<ordenacao>\d+)/$', reordena_materias, name="reordena_materias"), url(r'^sistema/sessao-plenaria/tipo/', include(TipoSessaoCrud.get_urls())), url(r'^sistema/sessao-plenaria/tipo-resultado-votacao/', include(TipoResultadoVotacaoCrud.get_urls())), url(r'^sistema/sessao-plenaria/tipo-expediente/', include(TipoExpedienteCrud.get_urls())), url(r'^sistema/sessao-plenaria/tipo-justificativa/', include(TipoJustificativaCrud.get_urls())), url(r'^sistema/sessao-plenaria/tipo-retirada-pauta/', include(TipoRetiradaPautaCrud.get_urls())), url(r'^sistema/bancada/', include(BancadaCrud.get_urls())), url(r'^sistema/cargo-bancada/', include(CargoBancadaCrud.get_urls())), url(r'^sistema/resumo-ordenacao/', ResumoOrdenacaoView.as_view(), name='resumo_ordenacao'), url(r'^sessao/(?P<pk>\d+)/adicionar-varias-materias-expediente/', AdicionarVariasMateriasExpediente.as_view(), name='adicionar_varias_materias_expediente'), url(r'^sessao/(?P<pk>\d+)/adicionar-varias-materias-ordem-dia/', AdicionarVariasMateriasOrdemDia.as_view(), name='adicionar_varias_materias_ordem_dia'), # PAUTA SESSÃO url(r'^sessao/pauta-sessao$', PautaSessaoView.as_view(), name='pauta_sessao'), url(r'^sessao/pauta-sessao/pesquisar-pauta$', PesquisarPautaSessaoView.as_view(), name='pesquisar_pauta'), url(r'^sessao/pauta-sessao/(?P<pk>\d+)/(?:pdf)?$', PautaSessaoDetailView.as_view(), name='pauta_sessao_detail'), # Subnav sessão url(r'^sessao/(?P<pk>\d+)/expediente$', ExpedienteView.as_view(), name='expediente'), url(r'^sessao/(?P<pk>\d+)/ocorrencia_sessao$', OcorrenciaSessaoView.as_view(), name='ocorrencia_sessao'), url(r'^sessao/(?P<pk>\d+)/consideracoes_finais$', ConsideracoesFinaisView.as_view(), name='consideracoes_finais'), url(r'^sessao/(?P<pk>\d+)/presenca$', PresencaView.as_view(), name='presenca'), url(r'^sessao/(?P<pk>\d+)/painel$', PainelView.as_view(), name='painel'), url(r'^sessao/(?P<pk>\d+)/presencaordemdia$', PresencaOrdemDiaView.as_view(), name='presencaordemdia'), url(r'^sessao/(?P<pk>\d+)/votacao_bloco_ordemdia$', VotacaoEmBlocoOrdemDia.as_view(), name='votacao_bloco_ordemdia'), url(r'^sessao/(?P<pk>\d+)/votacao_bloco/votnom$', VotacaoEmBlocoNominalView.as_view(), name='votacaobloconom'), url(r'^sessao/(?P<pk>\d+)/votacao_bloco/votsimb$', VotacaoEmBlocoSimbolicaView.as_view(), name='votacaoblocosimb'), url(r'^sessao/(?P<pk>\d+)/votacao_bloco_expediente$', VotacaoEmBlocoExpediente.as_view(), name='votacao_bloco_expediente'), url(r'^sessao/(?P<pk>\d+)/resumo$', ResumoView.as_view(), name='resumo'), url(r'^sessao/(?P<pk>\d+)/resumo_ata$', ResumoAtaView.as_view(), name='resumo_ata'), url(r'^sessao/pesquisar-sessao$', PesquisarSessaoPlenariaView.as_view(), name='pesquisar_sessao'), url(r'^sessao/(?P<pk>\d+)/matordemdia/votnom/(?P<oid>\d+)/(?P<mid>\d+)$', VotacaoNominalView.as_view(), name='votacaonominal'), url(r'^sessao/(?P<pk>\d+)/matordemdia/votnom/edit/(?P<oid>\d+)/(?P<mid>\d+)$', VotacaoNominalEditView.as_view(), name='votacaonominaledit'), url(r'^sessao/(?P<pk>\d+)/matordemdia/votsec/(?P<oid>\d+)/(?P<mid>\d+)$', VotacaoView.as_view(), name='votacaose
GoogleCloudPlatformTraining/cp100-appengine-memcache-python
guestbook.py
Python
apache-2.0
1,998
0.001001
#!/usr/bin/env python # # Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import jinja2 import os import webapp2 import logging from google.appengine.api import memcache jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class MainPage(webapp2.RequestHandler): def get(self): greetings = memcache.get('entries') if greetings is None: greetings = [] template = jinja_environment.get_template('index.html') self.response.out.write(template.render(entries=greetings)) def post(self): greeting = self.request.get('entry') greetings = memcache.get('entries') if greetings is not None: greetings.append(greeting) if not memcache.replace('entries', greetings): logging.error('Memcache replace failed.') else: greetings = [greeting] if not memcache.set('entries', greetings): logging.error('Memcache set failed.') self.redirect('/') class Clear(webapp2.RequestHandler): def post(self): if not memcache.delete('entries'): logging.error("Memcache failed to delete entries") self.redirect('/') appli
cation = webapp2.WSGI
Application([ ('/', MainPage), ('/clear', Clear) ], debug=True)
ofreshy/vast
vast/errors.py
Python
gpl-3.0
298
0.006711
""" All err
or from this project can be found here """ class IllegalModelStateError(Exception): """ Raise when trying to create a Model which invalidates VAST specifications """ pass class ParseError(Exception): """ Raise when encountering a parsi
ng error """ pass
alexpearce/example-monitoring-app
monitoring_app/tasks.py
Python
mit
3,193
0
import os import ROOT def add_file_extension(filename): """Add `.root` extension to `filename`, if it's not already present.""" return (filename + '.root') if filename[-5:] != '.root' else filename def tfile_path(filename): """Return the path to the TFile with `filename`.""" here = os.path.dirname(__file__) return '{0}/static/files/{1}'.format(here, filename) def data_for_object(obj): """Return a dictionary representing the data inside the object.""" obj_class = obj.ClassName() d = {} if obj_class[0:3] == 'TH1': # For histograms, we provide # binning: List of 2-tuples defining the (low, high) binning edges, # values: List of bin contents, ith entry falling in the ith bin # uncertainties: List of 2-tuples of (low, high) errors on the values # axis_titles: 2-tuple of (x, y) axis titles xaxis = obj.GetXaxis() yaxis = obj.GetYaxis() nbins = xaxis.GetNbins() d['binning'] = [ (xaxis.GetBinLowEdge(i), xaxis.GetBinUpEdge(i)) for i in range(nbins) ] d['values'] = [obj.GetBinContent(i) for i in range(nbins)] d['uncertainties'] = [ (obj.GetBinErrorLow(i), obj.GetBinErrorUp(i)) for i in range(nbins) ] d['axis_titles'] = (xaxis.GetTitle(), yaxis.GetTitle()) return d def list_file(filename): """Return a list of keys, as strings, in `filename`. Keyword arguments: filename -- Name of file with full path, e.g. `/a/b/my_file.root` """ f = ROOT.TFile(filename) if f.IsZombie(): d = dict( success=False, message='Could not open file `{0}`'.format(filename) ) else: d = dict( success=not f.IsZombie(), data=dict( filename=filename, keys=[key.GetName() for key in f.GetListOfKeys()] ) ) f.Close() return d def get_key_from_file(filename, key_name): """Return the object, stored under `key_name`, in `filename`. Keyword arguments:
filename -- Name of file with full path, e.g. `/a/b/my_file.root` key_name -- Name of key object is stored as """ fil
ename = tfile_path(add_file_extension(filename)) f = ROOT.TFile(filename) if f.IsZombie(): return dict( success=False, message='Could not open file `{0}`'.format(filename) ) obj = None # This method, opposed to TFile.Get, is more robust against odd key names for key in f.GetListOfKeys(): if key.GetName() == key_name: obj = key.ReadObj() if not obj: d = dict( success=False, message='Could not find key `{0}` in file `{1}`'.format( filename, key_name ) ) else: d = dict( success=True, data=dict( filename=filename, key_name=obj.GetName(), key_title=obj.GetTitle(), key_class=obj.ClassName(), key_data=data_for_object(obj) ) ) f.Close() return d