code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
from datetime import datetime as DateTime from genetics.genepool import GenePool from vessels import Vessels from schedule import Schedule import util import settings class FitnessTest: # Weighting #TODO fine tune weighting bonusPerHourTillDeadline = 5 penaltyPerHourOverDeadline = -10 penaltyPerHourOverlapping = -5 penaltyPerHourIdle = -2 totalTimeWeight = -1 penaltyForOutOfHours = -10 percentageTimeUsedWeight = 5 startTime = DateTime.now() @staticmethod def testPool(genepool): """! tests every schedule in the genePool that is passed to it :param genepool: genepool containing the schedules to be tested :type genepool: GenePool """ assert isinstance(genepool, GenePool) # print("Testing ", len(genepool.schedules), " schedules") for schedule in genepool.schedules: FitnessTest.testSchedule(schedule) @staticmethod def testSchedule(schedule): # TODO more requirements """ Tests a single schedule for it's fitness :param schedule: schedule to be tested :type schedule: Schedule """ # print("Testing schedule ", schedule.id) fitness = 100 schedule.flags = set() fitness += FitnessTest.timeToDeadline(schedule) fitness += FitnessTest.isOverDeadline(schedule) fitness += FitnessTest.isOverlapping(schedule) fitness += FitnessTest.checkIdleVessels(schedule) fitness += FitnessTest.testTotalTime(schedule) fitness += FitnessTest.testOutOfHours(schedule) fitness += FitnessTest.testPercentageUsed(schedule) # print("score of ", fitness) schedule.fitness = fitness @staticmethod def timeToDeadline(schedule): score = 0 for task in schedule.tasks: if task.product.dueDate is None: continue dTime = util.addDateTimeAndTime(task.getEndTime(), task.coolDown) - task.product.dueDate score += util.getTotalHours(dTime) * FitnessTest.bonusPerHourTillDeadline return score @staticmethod def isOverDeadline(schedule): score = 0 for task in schedule.tasks: if task.product.dueDate is None: continue dTime = util.addDateTimeAndTime(task.getEndTime(), task.coolDown) - task.product.dueDate partialScore = util.getTotalHours(dTime) * FitnessTest.penaltyPerHourOverDeadline if partialScore > 0: score += partialScore return score @staticmethod def isOverlapping(schedule): """! Tests if tasks on a schedule are overlapping :param schedule: schedule to test :type schedule: Schedule :return: score """ score = 0 for index, task in enumerate(schedule.tasks[:-1]): for otherTask in schedule.tasks[index:]: if task.getEndTime() <= otherTask.startTime: # if no overlap continue schedule.flags.add("Olap") hoursOverlapping = otherTask.getEndTime() - task.startTime score += util.getTotalHours(hoursOverlapping) * FitnessTest.penaltyPerHourOverlapping return score @staticmethod def checkIdleVessels(schedule): score = 0 for vessel in Vessels.vessels: timeCurrent = None for task in schedule.tasks: if task.vessel == vessel: if timeCurrent is None: timeCurrent = task.getEndTime() + task.cleanTime else: score += util.getTotalHours(task.startTime - timeCurrent) * FitnessTest.penaltyPerHourIdle return score @staticmethod def testTotalTime(schedule): """! return total time that the schedule uses including brewtime and cleaning :param schedule: schedule to test :type schedule: Schedule :return: score from test """ assert isinstance(schedule, Schedule) return util.getTotalHours(schedule.getTotalTime()) * FitnessTest.totalTimeWeight @staticmethod def testPercentageUsed(schedule): """! checks what percentage of each vessel's time is spent idle :param schedule: schedule to test :type schedule: Schedule :return: score from test """ lastTask = schedule.tasks[0] for task in schedule.tasks[1:]: if task.getEndTime() > lastTask.getEndTime(): lastTask = task totalTime = util.getTotalHours(schedule.getTotalTime())/len(Vessels.vessels) timeToEnd = util.getTotalHours(lastTask.getEndTime() - FitnessTest.startTime) return (timeToEnd/totalTime) * FitnessTest.percentageTimeUsedWeight @staticmethod def testOutOfHours(schedule): """! Check if the schedule has anything finishing out of hours :param schedule: schedule to test :type schedule: Schedule :return: score from test """ assert isinstance(schedule, Schedule) score = 0 for task in schedule.tasks: if not settings.openingTime < task.startTime.time() < settings.closingTime: score += FitnessTest.penaltyForOutOfHours schedule.flags.add("outHs") # out of hours start if not settings.openingTime < task.getEndTime().time() < settings.closingTime: score += FitnessTest.penaltyForOutOfHours schedule.flags.add("outHe") # out of hours end return score
TeamAbstract/GeneticScheduling
genetics/fitnessTest.py
Python
apache-2.0
4,794
# -*- coding: utf-8 -*- # Copyright 2022 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 warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.artifactregistry_v1.types import artifact from google.cloud.artifactregistry_v1.types import repository from .base import ArtifactRegistryTransport, DEFAULT_CLIENT_INFO class ArtifactRegistryGrpcTransport(ArtifactRegistryTransport): """gRPC backend transport for ArtifactRegistry. The Artifact Registry API service. Artifact Registry is an artifact management system for storing artifacts from different package management systems. The resources managed by this API are: - Repositories, which group packages and their data. - Packages, which group versions and their tags. - Versions, which are specific forms of a package. - Tags, which represent alternative names for versions. - Files, which contain content and are optionally associated with a Package or Version. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ _stubs: Dict[str, Callable] def __init__( self, *, host: str = "artifactregistry.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None else: if api_mtls_endpoint: host = api_mtls_endpoint # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: self._ssl_channel_credentials = SslCredentials().ssl_credentials else: if client_cert_source_for_mtls and not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, # use the credentials which are saved credentials=self._credentials, # Set ``credentials_file`` to ``None`` here as # the credentials that we saved earlier should be used. credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) # Wrap messages. This must be done after self._grpc_channel exists self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = "artifactregistry.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. quota_project_id (Optional[str]): An optional project to use for billing and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. Raises: google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def list_docker_images( self, ) -> Callable[ [artifact.ListDockerImagesRequest], artifact.ListDockerImagesResponse ]: r"""Return a callable for the list docker images method over gRPC. Lists docker images. Returns: Callable[[~.ListDockerImagesRequest], ~.ListDockerImagesResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_docker_images" not in self._stubs: self._stubs["list_docker_images"] = self.grpc_channel.unary_unary( "/google.devtools.artifactregistry.v1.ArtifactRegistry/ListDockerImages", request_serializer=artifact.ListDockerImagesRequest.serialize, response_deserializer=artifact.ListDockerImagesResponse.deserialize, ) return self._stubs["list_docker_images"] @property def list_repositories( self, ) -> Callable[ [repository.ListRepositoriesRequest], repository.ListRepositoriesResponse ]: r"""Return a callable for the list repositories method over gRPC. Lists repositories. Returns: Callable[[~.ListRepositoriesRequest], ~.ListRepositoriesResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_repositories" not in self._stubs: self._stubs["list_repositories"] = self.grpc_channel.unary_unary( "/google.devtools.artifactregistry.v1.ArtifactRegistry/ListRepositories", request_serializer=repository.ListRepositoriesRequest.serialize, response_deserializer=repository.ListRepositoriesResponse.deserialize, ) return self._stubs["list_repositories"] @property def get_repository( self, ) -> Callable[[repository.GetRepositoryRequest], repository.Repository]: r"""Return a callable for the get repository method over gRPC. Gets a repository. Returns: Callable[[~.GetRepositoryRequest], ~.Repository]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_repository" not in self._stubs: self._stubs["get_repository"] = self.grpc_channel.unary_unary( "/google.devtools.artifactregistry.v1.ArtifactRegistry/GetRepository", request_serializer=repository.GetRepositoryRequest.serialize, response_deserializer=repository.Repository.deserialize, ) return self._stubs["get_repository"] def close(self): self.grpc_channel.close() __all__ = ("ArtifactRegistryGrpcTransport",)
googleapis/python-artifact-registry
google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc.py
Python
apache-2.0
14,387
# -*- coding:utf-8 -*- # !/usr/bin/env python # # Author: Leann Mak # Email: leannmak@139.com # # This is the init file defining api with urls for the cmdb package. # from .hostgroupapi import HostGroupListAPI, HostGroupAPI from .hostapi import HostListAPI, HostAPI # from .host import HostAPI from .. import api api.add_resource( HostGroupListAPI, '/api/v0.0/hostgroup', endpoint='hostgroup_list_ep') api.add_resource( HostGroupAPI, '/api/v0.0/hostgroup', endpoint='hostgroup_ep') api.add_resource( HostGroupAPI, '/api/v0.0/hostgroup/<groupid>', endpoint='hostgroup_id_ep') api.add_resource( HostListAPI, '/api/v0.0/host', endpoint='host_list_ep') api.add_resource( HostAPI, '/api/v0.0/host/<hostid>', endpoint='host_id_ep')
tecstack/opback
promise/zabber/__init__.py
Python
apache-2.0
747
import _plotly_utils.basevalidators class XanchorValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="xanchor", parent_name="choroplethmapbox.colorbar", **kwargs ): super(XanchorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), values=kwargs.pop("values", ["left", "center", "right"]), **kwargs )
plotly/plotly.py
packages/python/plotly/plotly/validators/choroplethmapbox/colorbar/_xanchor.py
Python
mit
507
""" This plugin returns common files that can be opened in a browser i.e. images and PDF documents """ from yapsy.IPlugin import IPlugin from flask import send_from_directory import os class Preview(IPlugin): def __init__(self): self.display_name = 'Preview' self.popularity = 8 category = 'misc' self.cache = True self.fast = False self.action = False self.icon = 'fa-eye' IPlugin.__init__(self) def activate(self): IPlugin.activate(self) return def deactivate(self): IPlugin.deactivate(self) return def check(self, evidence, path_on_disk): """Checks if the file is compatible with this plugin""" #TODO: Whitelist mimetypes only allowed_mimetype = ['application/pdf', 'message/rfc822'] allowed_prefix = ['image', 'video', 'audio'] exclude = [ 'image/tiff', 'video/x-ms-asf', 'image/x-ms-bmp' ] return (str(evidence['mimetype'].split('/')[0]).lower() in allowed_prefix or evidence['mimetype'] in allowed_mimetype ) and evidence['meta_type'] != 'Directory' and evidence['mimetype'] not in exclude def mimetype(self, mimetype): """Returns the mimetype of this plugins get command""" return mimetype def get(self, evidence, helper, path_on_disk, request): """Returns the result of this plugin to be displayed in a browser""" smart_redirect = helper.get_request_value(request, 'redirect', 'False').lower() in ['true', 't', 'y', 'yes'] if smart_redirect and not self.check(evidence, path_on_disk): return helper.plugin_manager.get_plugin_by_name('analyze').get(evidence, helper, path_on_disk, request) return send_from_directory(os.path.dirname(path_on_disk), os.path.basename(path_on_disk))
maurermj08/efetch
efetch_server/plugins/core/preview/preview.py
Python
apache-2.0
1,840
## # Copyright (c) 2006-2014 Apple 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. ## """ Implements drop-box functionality. A drop box is an external attachment store. """ __all__ = [ "DropBoxHomeResource", "DropBoxCollectionResource", ] from twext.python.log import Logger from txweb2 import responsecode from txdav.xml import element as davxml from txweb2.dav.http import ErrorResponse from txweb2.dav.resource import DAVResource, TwistedACLInheritable from txweb2.dav.util import joinURL from twisted.internet.defer import inlineCallbacks, returnValue from twistedcaldav.config import config from twistedcaldav.customxml import calendarserver_namespace log = Logger() class DropBoxHomeResource (DAVResource): """ Drop box collection resource. """ def resourceType(self): return davxml.ResourceType.dropboxhome #@UndefinedVariable def isCollection(self): return True def http_PUT(self, request): return responsecode.FORBIDDEN @inlineCallbacks def accessControlList(self, request, *args, **kwargs): """ Override this to give write proxies DAV:write-acl privilege so they can add attachments too. """ acl = (yield super(DropBoxHomeResource, self).accessControlList(request, *args, **kwargs)) if config.EnableProxyPrincipals: owner = (yield self.ownerPrincipal(request)) newaces = tuple(acl.children) newaces += ( # DAV:write-acl access for this principal's calendar-proxy-write users. davxml.ACE( davxml.Principal(davxml.HRef(joinURL(owner.principalURL(), "calendar-proxy-write/"))), davxml.Grant( davxml.Privilege(davxml.WriteACL()), ), davxml.Protected(), TwistedACLInheritable(), ), ) returnValue(davxml.ACL(*newaces)) else: returnValue(acl) class DropBoxCollectionResource (DAVResource): """ Drop box resource. """ def resourceType(self): return davxml.ResourceType.dropbox #@UndefinedVariable def isCollection(self): return True def writeNewACEs(self, newaces): """ Write a new ACL to the resource's property store. We override this for calendar collections and force all the ACEs to be inheritable so that all calendar object resources within the calendar collection have the same privileges unless explicitly overridden. The same applies to drop box collections as we want all resources (attachments) to have the same privileges as the drop box collection. @param newaces: C{list} of L{ACE} for ACL being set. """ # Add inheritable option to each ACE in the list edited_aces = [] for ace in newaces: if TwistedACLInheritable() not in ace.children: children = list(ace.children) children.append(TwistedACLInheritable()) edited_aces.append(davxml.ACE(*children)) else: edited_aces.append(ace) # Do inherited with possibly modified set of aces return super(DropBoxCollectionResource, self).writeNewACEs(edited_aces) def http_PUT(self, request): return ErrorResponse( responsecode.FORBIDDEN, (calendarserver_namespace, "valid-drop-box"), "Cannot store resources in dropbox", )
trevor/calendarserver
twistedcaldav/dropbox.py
Python
apache-2.0
4,075
import notify2 import os from time import * start_time = time() notify2.init('') r = notify2.Notification('', '') while True: for i in [ ('TO DO', 'Write JavaScript'), ('TO DO', 'Write Python'), ('Thought of the Day', 'Support Open Source'), ('Learn. . .', 'Use Linux'), ('Thought of the Day', 'Stay Cool'), ('Thought of the Day', 'Stop running for cheese'), ('Thought of the Day', 'You are cool')]: r.update(i[0], i[1]) sleep(120) x = int(time() - start_time)%120 if x == 119: os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % ( 0.5, 500)) r.show()
OpenC-IIIT/scriptonia
notif.py
Python
mit
695
####################################################################### # # Author: Gabi Roeger # Modified by: Silvia Richter (silvia.richter@nicta.com.au) # (C) Copyright 2008: Gabi Roeger and NICTA # # This file is part of LAMA. # # LAMA 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. # # LAMA 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 string import conditions def parse_expression(exp): if isinstance(exp, list): functionsymbol = exp[0] return PrimitiveNumericExpression(functionsymbol, [conditions.parse_term(arg) for arg in exp[1:]]) elif exp.replace(".","").isdigit(): return NumericConstant(string.atof(exp)) else: return PrimitiveNumericExpression(exp,[]) def parse_assignment(alist): assert len(alist) == 3 op = alist[0] head = parse_expression(alist[1]) exp = parse_expression(alist[2]) if op == "=": return Assign(head, exp) elif op == "increase": return Increase(head, exp) else: assert False, "Assignment operator not supported." class FunctionalExpression(object): def __init__(self, parts): self.parts = tuple(parts) def dump(self, indent=" "): print "%s%s" % (indent, self._dump()) for part in self.parts: part.dump(indent + " ") def _dump(self): return self.__class__.__name__ def instantiate(self, var_mapping, init_facts): raise ValueError("Cannot instantiate condition: not normalized") class NumericConstant(FunctionalExpression): parts = () def __init__(self, value): self.value = value def __eq__(self, other): return (self.__class__ == other.__class__ and self.value == other.value) def __str__(self): return "%s %s" % (self.__class__.__name__, self.value) def _dump(self): return str(self) def instantiate(self, var_mapping, init_facts): return self class PrimitiveNumericExpression(FunctionalExpression): parts = () def __init__(self, symbol, args): self.symbol = symbol self.args = tuple(args) def __eq__(self, other): if not (self.__class__ == other.__class__ and self.symbol == other.symbol and len(self.args) == len(other.args)): return False else: for s,o in zip(self.args, other.args): if not s == o: return False return True def __str__(self): return "%s %s(%s)" % ("PNE", self.symbol, ", ".join(map(str, self.args))) def dump(self, indent=" "): print "%s%s" % (indent, self._dump()) for arg in self.args: arg.dump(indent + " ") def _dump(self): return str(self) def instantiate(self, var_mapping, init_facts): args = [conditions.ObjectTerm(var_mapping.get(arg.name, arg.name)) for arg in self.args] pne = PrimitiveNumericExpression(self.symbol, args) assert not self.symbol == "total-cost" # We know this expression is constant. Substitute it by corresponding # initialization from task. for fact in init_facts: if isinstance(fact, FunctionAssignment): if fact.fluent == pne: return fact.expression assert False, "Could not find instantiation for PNE!" class FunctionAssignment(object): def __init__(self, fluent, expression): self.fluent = fluent self.expression = expression def __str__(self): return "%s %s %s" % (self.__class__.__name__, self.fluent, self.expression) def dump(self, indent=" "): print "%s%s" % (indent, self._dump()) self.fluent.dump(indent + " ") self.expression.dump(indent + " ") def _dump(self): return self.__class__.__name__ def instantiate(self, var_mapping, init_facts): if not (isinstance(self.expression, PrimitiveNumericExpression) or isinstance(self.expression, NumericConstant)): raise ValueError("Cannot instantiate assignment: not normalized") # We know that this assignment is a cost effect of an action (for initial state # assignments, "instantiate" is not called). Hence, we know that the fluent is # the 0-ary "total-cost" which does not need to be instantiated assert self.fluent.symbol == "total-cost" fluent = self.fluent expression = self.expression.instantiate(var_mapping, init_facts) return self.__class__(fluent, expression) class Assign(FunctionAssignment): def __str__(self): return "%s := %s" % (self.fluent, self.expression) class Increase(FunctionAssignment): pass
PlanTool/plantool
wrappingPlanners/Deterministic/LAMA/seq-sat-lama/lama/translate/pddl/f_expression.py
Python
gpl-2.0
5,321
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of REDHAWK core. # # REDHAWK core is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # REDHAWK core 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # from redhawk.codegen.utils import strenum, parseBoolean from ossie.utils.prop_helpers import parseComplexString from ossie import properties from idl import CorbaTypes NULL = 'null' TRUE = 'true' FALSE = 'false' Types = strenum('boolean', 'char', 'byte', 'short', 'int', 'long', 'float', 'double') BoxTypes = strenum('Boolean', 'Character', 'Byte', 'Short', 'Integer', 'Long', 'Float', 'Double') _reservedKeywords = set(("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "if", "goto", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while", "true", "false", "null")) _boxMap = { Types.BOOLEAN: BoxTypes.BOOLEAN, Types.CHAR: BoxTypes.CHARACTER, Types.BYTE: BoxTypes.BYTE, Types.SHORT: BoxTypes.SHORT, Types.INT: BoxTypes.INTEGER, Types.LONG: BoxTypes.LONG, Types.FLOAT: BoxTypes.FLOAT, Types.DOUBLE: BoxTypes.DOUBLE } _typeSize = { Types.CHAR: 1, Types.BYTE: 1, Types.SHORT: 2, Types.INT: 4, Types.FLOAT: 4, Types.LONG: 8, Types.DOUBLE: 8 } def stringLiteral(string): return '"' + string + '"' def charLiteral(char): return "'" + char + "'" def typeSize(typename): return _typeSize[typename] def boxedType(typename): return _boxMap.get(typename, typename) def identifier(name): """ Returns a valid Java identifer based on the given name. """ # Replace invalid characters with '_' _name = '' for ch in name: if ch.isalnum(): _name += ch else: _name += '_' name = _name # Cannot start with a digit if name[0].isdigit(): name = '_' + name # Cannot clash with a Java keyword if name in _reservedKeywords: name += '_' return name def translateBoolean(value): if parseBoolean(value): return TRUE else: return FALSE def _complexLiteral(value, typename): memberType = properties.getMemberType(typename) real, imag = parseComplexString(value, memberType) if typename == "complexBoolean": real = translateBoolean(real) imag = translateBoolean(imag) elif typename == "complexFloat": real = str(real) + "F" imag = str(imag) + "F" elif typename in ["complexShort", "complexUShort"]: real = '(short)%d' % int(real) imag = '(short)%d' % int(imag) elif typename == "complexChar": real = charLiteral(str(real)) imag = charLiteral(str(imag)) elif typename == "complexOctet": real = '(byte)%d' % int(real) imag = '(byte)%d' % int(imag) return "new CF." + typename + "(" + str(real) + "," + str(imag) + ")" def literal(value, typename, complex=False): if complex: return _complexLiteral(value, typename) elif typename == 'String': return stringLiteral(value) elif typename == 'Object': return NULL elif typename in (Types.FLOAT, BoxTypes.FLOAT, Types.DOUBLE, BoxTypes.DOUBLE): value = repr(float(value)) if typename in (Types.FLOAT, BoxTypes.FLOAT): return value + 'F' else: return value elif typename in (Types.LONG, BoxTypes.LONG): return value+'L' elif typename in (Types.BOOLEAN, BoxTypes.BOOLEAN): return translateBoolean(value) elif typename in (Types.BYTE, BoxTypes.BYTE): return '(byte)%d' % int(value) elif typename in (Types.SHORT, BoxTypes.SHORT): return '(short)%d' % int(value) elif typename in (Types.CHAR, BoxTypes.CHARACTER): return charLiteral(value) elif typename in (Types.INT, BoxTypes.INTEGER): return str(int(value)) else: return NULL def defaultValue(typename): if typename == 'String': return stringLiteral('') elif typename == 'Object': return NULL elif typename == Types.BOOLEAN: return FALSE else: return literal('0', typename) def qualifiedName(name, package): if package: return package + '.' + name else: return name
RedhawkSDR/framework-codegen
redhawk/codegen/lang/java.py
Python
lgpl-3.0
5,420
# -*- coding: utf-8 -*- # (Copyright) 2017 Esther Martín - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
esthermm/odoo-addons
mrp_utilities/__init__.py
Python
agpl-3.0
134
# Copyright 2011 the Melange 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. """Module for constructing GSoC related URL patterns """ from django.conf.urls import url as django_url from soc.views.helper.url_patterns import namedIdBasedPattern from soc.views.helper.url_patterns import namedLinkIdPattern from soc.views.helper import url_patterns def url(regex, view, kwargs=None, name=None): """Constructs an url pattern prefixed with ^gsoc/. Args: see django.conf.urls.url """ return django_url('^gsoc/%s' % regex, view, kwargs=kwargs, name=name) class SOCUrlPatternConstructor(url_patterns.UrlPatternConstructor): """Implementation of UrlPatternConstructor which constructs Summer Of Code-specific URL patterns prefixed with ^gsoc/. """ def construct(self, regex, view, kwargs=None, name=None): """See url_patterns.UrlPatternConstructor.construct for specification.""" return django_url('^gsoc/%s' % regex, view, kwargs=kwargs, name=name) SOC_URL_PATTERN_CONSTRUCTOR = SOCUrlPatternConstructor() SHIPMENT_INFO = namedIdBasedPattern(['sponsor', 'program']) SURVEY = namedLinkIdPattern(['sponsor', 'program', 'survey']) COMMENT = namedIdBasedPattern(['sponsor', 'program', 'user']) SURVEY_RECORD = namedIdBasedPattern(['sponsor', 'program', 'survey', 'user']) GRADING_RECORD = '/'.join([ url_patterns.USER_ID, r'(?P<group>(\d+))', r'(?P<record>(\d+))']) PREFIXES = "(gsoc_program|gsoc_org)" DOCUMENT = url_patterns.DOCUMENT_FMT % PREFIXES ORG_DOCUMENT = url_patterns.ORG_DOCUMENT_FMT % PREFIXES
rhyolight/nupic.son
app/soc/modules/gsoc/views/helper/url_patterns.py
Python
apache-2.0
2,041
""" Cement print extension module. """ from ..core import output from ..utils.misc import minimal_logger LOG = minimal_logger(__name__) def extend_print(app): def _print(text): app.render({'out': text}, handler='print') app.extend('print', _print) class PrintOutputHandler(output.OutputHandler): """ This class implements the :ref:`Output <cement.core.output>` Handler interface. It takes a dict and only prints out the ``out`` key. It is primarily used by the ``app.print()`` extended function in order to replace ``print()`` so that framework features like ``pre_render`` and ``post_render`` hooks are honored. Please see the developer documentation on :cement:`Output Handling <dev/output>`. """ class Meta: """Handler meta-data""" label = 'print' """The string identifier of this handler.""" #: Whether or not to include ``json`` as an available choice #: to override the ``output_handler`` via command line options. overridable = False def render(self, data_dict, template=None, **kw): """ Take a data dictionary and render only the ``out`` key as text output. Note that the template option is received here per the interface, however this handler just ignores it. Args: data_dict (dict): The data dictionary to render. Keyword Args: template: This option is completely ignored. Returns: str: A text string. """ if 'out' in data_dict.keys(): LOG.debug("rendering content as text via %s" % self.__module__) return data_dict['out'] + '\n' else: LOG.debug("no 'out' key found in data dict. " "not rendering content via %s" % self.__module__) return None class PrintDictOutputHandler(output.OutputHandler): """ This class implements the :ref:`Output <cement.core.output>` Handler interface. It is intended primarily for development where printing out a string reprisentation of the data dictionary would be useful. Please see the developer documentation on :cement:`Output Handling <dev/output>`. """ class Meta: """Handler meta-data""" label = 'print_dict' """The string identifier of this handler.""" #: Whether or not to include ``json`` as an available choice #: to override the ``output_handler`` via command line options. overridable = False def render(self, data_dict, template=None, **kw): """ Take a data dictionary and render it as text output. Note that the template option is received here per the interface, however this handler just ignores it. Args: data_dict (dict): The data dictionary to render. Keyword Args: template: This option is completely ignored. Returns: str: A text string. """ LOG.debug("rendering content as text via %s" % self.__module__) out = '' for key, val in data_dict.items(): out = out + '%s: %s\n' % (key, val) return out def load(app): app.handler.register(PrintDictOutputHandler) app.handler.register(PrintOutputHandler) app.hook.register('pre_argument_parsing', extend_print)
datafolklabs/cement
cement/ext/ext_print.py
Python
bsd-3-clause
3,380
# Library for JSTest tests. # # This contains classes that represent an individual test, including # metadata, and know how to run the tests and determine failures. import datetime, os, sys, time from contextlib import contextmanager from subprocess import Popen, PIPE from threading import Thread from results import TestOutput # When run on tbpl, we run each test multiple times with the following # arguments. JITFLAGS = { 'all': [ [], # no flags, normal baseline and ion ['--ion-eager', '--ion-offthread-compile=off'], # implies --baseline-eager ['--ion-eager', '--ion-offthread-compile=off', '--non-writable-jitcode', '--ion-check-range-analysis', '--ion-extra-checks', '--no-sse3', '--no-threads'], ['--baseline-eager'], ['--no-baseline', '--no-ion'], ], # used by jit_test.py 'ion': [ ['--baseline-eager'], ['--ion-eager', '--ion-offthread-compile=off'] ], # Run reduced variants on debug builds, since they take longer time. 'debug': [ [], # no flags, normal baseline and ion ['--ion-eager', '--ion-offthread-compile=off'], # implies --baseline-eager ['--baseline-eager'], ], 'none': [ [] # no flags, normal baseline and ion ] } def get_jitflags(variant, **kwargs): if variant not in JITFLAGS: print('Invalid jitflag: "{}"'.format(variant)) sys.exit(1) if variant == 'none' and 'none' in kwargs: return kwargs['none'] return JITFLAGS[variant] def get_environment_overlay(js_shell): """ Build a dict of additional environment variables that must be set to run tests successfully. """ env = { # Force Pacific time zone to avoid failures in Date tests. 'TZ': 'PST8PDT', # Force date strings to English. 'LC_TIME': 'en_US.UTF-8', # Tell the shell to disable crash dialogs on windows. 'XRE_NO_WINDOWS_CRASH_DIALOG': '1', } # Add the binary's directory to the library search path so that we find the # nspr and icu we built, instead of the platform supplied ones (or none at # all on windows). if sys.platform.startswith('linux'): env['LD_LIBRARY_PATH'] = os.path.dirname(js_shell) elif sys.platform.startswith('darwin'): env['DYLD_LIBRARY_PATH'] = os.path.dirname(js_shell) elif sys.platform.startswith('win'): env['PATH'] = os.path.dirname(js_shell) return env @contextmanager def change_env(env_overlay): # Apply the overlaid environment and record the current state. prior_env = {} for key, val in env_overlay.items(): prior_env[key] = os.environ.get(key, None) if 'PATH' in key and key in os.environ: os.environ[key] = '{}{}{}'.format(val, os.pathsep, os.environ[key]) else: os.environ[key] = val try: # Execute with the new environment. yield finally: # Restore the prior environment. for key, val in prior_env.items(): if val is not None: os.environ[key] = val else: del os.environ[key] def get_cpu_count(): """ Guess at a reasonable parallelism count to set as the default for the current machine and run. """ # Python 2.6+ try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass # POSIX try: res = int(os.sysconf('SC_NPROCESSORS_ONLN')) if res > 0: return res except (AttributeError, ValueError): pass # Windows try: res = int(os.environ['NUMBER_OF_PROCESSORS']) if res > 0: return res except (KeyError, ValueError): pass return 1 class RefTest(object): """A runnable test.""" def __init__(self, path): self.path = path # str: path of JS file relative to tests root dir self.options = [] # [str]: Extra options to pass to the shell self.jitflags = [] # [str]: JIT flags to pass to the shell self.test_reflect_stringify = None # str or None: path to # reflect-stringify.js file to test # instead of actually running tests @staticmethod def prefix_command(path): """Return the '-f shell.js' options needed to run a test with the given path.""" if path == '': return ['-f', 'shell.js'] head, base = os.path.split(path) return RefTest.prefix_command(head) \ + ['-f', os.path.join(path, 'shell.js')] def get_command(self, prefix): dirname, filename = os.path.split(self.path) cmd = prefix + self.jitflags + self.options \ + RefTest.prefix_command(dirname) if self.test_reflect_stringify is not None: cmd += [self.test_reflect_stringify, "--check", self.path] else: cmd += ["-f", self.path] return cmd class RefTestCase(RefTest): """A test case consisting of a test and an expected result.""" def __init__(self, path): RefTest.__init__(self, path) self.enable = True # bool: True => run test, False => don't run self.expect = True # bool: expected result, True => pass self.random = False # bool: True => ignore output as 'random' self.slow = False # bool: True => test may run slowly # The terms parsed to produce the above properties. self.terms = None # The tag between |...| in the test header. self.tag = None # Anything occuring after -- in the test header. self.comment = None def __str__(self): ans = self.path if not self.enable: ans += ', skip' if not self.expect: ans += ', fails' if self.random: ans += ', random' if self.slow: ans += ', slow' if '-d' in self.options: ans += ', debugMode' return ans @staticmethod def build_js_cmd_prefix(js_path, js_args, debugger_prefix): parts = [] if debugger_prefix: parts += debugger_prefix parts.append(js_path) if js_args: parts += js_args return parts def __cmp__(self, other): if self.path == other.path: return 0 elif self.path < other.path: return -1 return 1 def __hash__(self): return self.path.__hash__()
cstipkovic/spidermonkey-research
js/src/tests/lib/tests.py
Python
mpl-2.0
6,612
from cv2.cv import CV_INTER_LINEAR __author__ = 'tmkasun' import numpy as np import cv2 cap = cv2.VideoCapture(0) while (True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = frame r = 500.0 / gray.shape[1] dim = (500, int(gray.shape[0] * r)) resized_frame = cv2.resize(gray, dim,interpolation=CV_INTER_LINEAR) # Display the resulting frame cv2.imshow('frame', resized_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
tmkasun/human_tracking_PIR_FYP
grid_eye_server/camera_capture.py
Python
gpl-2.0
657
import unittest import json from google.appengine.api import urlfetch from google.appengine.ext import testbed from google.appengine.api import modules from google.appengine.api.app_identity import get_default_version_hostname from models import Conference # Deployed app tests # Test that endpoints return appropriate no-login status codes on deployed app class DeployedAuthorizationTestCase(unittest.TestCase): #### SET UP and TEAR DOWN #### def setUp(self): self.urlbase = 'https://' + get_default_version_hostname() #### TESTS #### def testHomepageAndNopageReturns(self): res = urlfetch.fetch(self.urlbase) self.assertEqual(res.status_code, 200) res = urlfetch.fetch(self.urlbase + '/monkey') self.assertEqual(res.status_code, 404) def test_createConference(self): url = '/_ah/api/conference/v1/conference' res = urlfetch.fetch(self.urlbase + url, payload=json.dumps({}), method=urlfetch.POST, headers={'Content-Type': 'application/json'}) self.assertEqual(res.status_code, 401) def test_updateConference(self): url = '/_ah/api/conference/v1/conference/dummy' res = urlfetch.fetch(self.urlbase + url, payload=json.dumps({}), method=urlfetch.PUT, headers={'Content-Type': 'application/json'}) self.assertEqual(res.status_code, 401) def test_getProfile(self): url = '/_ah/api/conference/v1/profile' res = urlfetch.fetch(self.urlbase + url) self.assertEqual(res.status_code, 401) def test_getConferencesCreated(self): url = '/_ah/api/conference/v1/getConferencesCreated' res = urlfetch.fetch(self.urlbase + url) self.assertEqual(res.status_code, 401) def test_getSessionsInWishlist(self): url = '/_ah/api/conference/v1/wishlist/dummy' res = urlfetch.fetch(self.urlbase + url) self.assertEqual(res.status_code, 401) def test_getConferencesToAttend(self): url = '/_ah/api/conference/v1/conferences/attending' res = urlfetch.fetch(self.urlbase + url) self.assertEqual(res.status_code, 401) def test_deleteSession(self): url = '/_ah/api/conference/v1/session/dummy' res = urlfetch.fetch(self.urlbase + url, method=urlfetch.DELETE) self.assertEqual(res.status_code, 401)
Ripley6811/FSND-P4-Conference-Organization-App
ConferenceCentral/tests/test_unauthorized.py
Python
gpl-3.0
2,534
from sympy.strategies.traverse import (top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns) from sympy.strategies.util import expr_fns from sympy import Basic, symbols, Symbol, S zero_symbols = lambda x: S.Zero if isinstance(x, Symbol) else x x,y,z = symbols('x,y,z') def test_sall(): zero_onelevel = sall(zero_symbols) assert zero_onelevel(Basic(x, y, Basic(x, z))) == \ Basic(0, 0, Basic(x, z)) def test_bottom_up(): _test_global_traversal(bottom_up) _test_stop_on_non_basics(bottom_up) def test_top_down(): _test_global_traversal(top_down) _test_stop_on_non_basics(top_down) def _test_global_traversal(trav): x,y,z = symbols('x,y,z') zero_all_symbols = trav(zero_symbols) assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \ Basic(0, 0, Basic(0, 0)) def _test_stop_on_non_basics(trav): def add_one_if_can(expr): try: return expr + 1 except: return expr expr = Basic(1, 'a', Basic(2, 'b')) expected = Basic(2, 'a', Basic(3, 'b')) rl = trav(add_one_if_can) assert rl(expr) == expected class Basic2(Basic): pass rl = lambda x: Basic2(*x.args) if isinstance(x, Basic) else x def test_top_down_once(): top_rl = top_down_once(rl) assert top_rl(Basic(1, 2, Basic(3, 4))) == \ Basic2(1, 2, Basic(3, 4)) def test_bottom_up_once(): bottom_rl = bottom_up_once(rl) assert bottom_rl(Basic(1, 2, Basic(3, 4))) == \ Basic(1, 2, Basic2(3, 4)) def test_expr_fns(): from sympy.strategies.rl import rebuild from sympy import Add x, y = map(Symbol, 'xy') expr = x + y**3 e = bottom_up(lambda x: x + 1, expr_fns)(expr) b = bottom_up(lambda x: Basic.__new__(Add, x, 1), basic_fns)(expr) assert rebuild(b) == e
drufat/sympy
sympy/strategies/tests/test_traverse.py
Python
bsd-3-clause
1,853
""" SignXML utility functions bytes_to_long, long_to_bytes copied from https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py """ from __future__ import absolute_import, division, print_function, unicode_literals import sys, re, struct, textwrap from eight import str, bytes USING_PYTHON2 = True if sys.version_info < (3, 0) else False PEM_HEADER = "-----BEGIN CERTIFICATE-----" PEM_FOOTER = "-----END CERTIFICATE-----" def ensure_bytes(x, encoding="utf-8", none_ok=False): if none_ok is True and x is None: return x if not isinstance(x, bytes): x = x.encode(encoding) return x def ensure_str(x, encoding="utf-8", none_ok=False): if none_ok is True and x is None: return x if not isinstance(x, str): x = x.decode(encoding) return x def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes(). """ if isinstance(s, int): # On Python 2, indexing into a bytearray returns a byte string; on Python 3, an int. return s acc = 0 if USING_PYTHON2: acc = long(acc) # noqa unpack = struct.unpack length = len(s) if length % 4: extra = (4 - length % 4) s = b'\000' * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack(b'>I', s[i:i+4])[0] return acc def long_to_bytes(n, blocksize=0): """long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize. """ # after much testing, this algorithm was deemed to be the fastest s = b'' if USING_PYTHON2: n = long(n) # noqa pack = struct.pack while n > 0: s = pack(b'>I', n & 0xffffffff) + s n = n >> 32 # strip off leading zeros for i in range(len(s)): if s[i] != b'\000'[0]: break else: # only happens when n == 0 s = b'\000' i = 0 s = s[i:] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and len(s) % blocksize: s = (blocksize - len(s) % blocksize) * b'\000' + s return s def strip_pem_header(cert): pem_regexp = "{header}\n(.+?){footer}".format(header=PEM_HEADER, footer=PEM_FOOTER) try: return re.search(pem_regexp, ensure_str(cert), flags=re.S).group(1) except Exception: return ensure_str(cert) def add_pem_header(bare_base64_cert): bare_base64_cert = ensure_str(bare_base64_cert) if bare_base64_cert.startswith(PEM_HEADER): return bare_base64_cert return PEM_HEADER + "\n" + textwrap.fill(bare_base64_cert, 64) + "\n" + PEM_FOOTER
CoresecSystems/signxml
signxml/util/__init__.py
Python
apache-2.0
2,954
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from django.contrib.auth.views import login, logout from django.views.generic import RedirectView from area.views import RedirectToGame from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^blog/', include('blog.urls')), url(r'^game/', include('area.urls'), name='game'), url(r'^$', RedirectToGame.as_view(), name='main'), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': 'main'}), url(r'^accounts/login/$', 'django.contrib.auth.views.login'), # url(r'^accounts/', include('django.contrib.auth.urls')), )
rezolvent/game
game/urls.py
Python
mit
738
""" Test functions for limits module. """ from numpy.testing import * from numpy.core import finfo, iinfo from numpy import half, single, double, longdouble import numpy as np ################################################## class TestPythonFloat(TestCase): def test_singleton(self): ftype = finfo(float) ftype2 = finfo(float) assert_equal(id(ftype),id(ftype2)) class TestHalf(TestCase): def test_singleton(self): ftype = finfo(half) ftype2 = finfo(half) assert_equal(id(ftype),id(ftype2)) class TestSingle(TestCase): def test_singleton(self): ftype = finfo(single) ftype2 = finfo(single) assert_equal(id(ftype),id(ftype2)) class TestDouble(TestCase): def test_singleton(self): ftype = finfo(double) ftype2 = finfo(double) assert_equal(id(ftype),id(ftype2)) class TestLongdouble(TestCase): def test_singleton(self,level=2): ftype = finfo(longdouble) ftype2 = finfo(longdouble) assert_equal(id(ftype),id(ftype2)) class TestIinfo(TestCase): def test_basic(self): dts = zip(['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'], [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64]) for dt1, dt2 in dts: assert_equal(iinfo(dt1).min, iinfo(dt2).min) assert_equal(iinfo(dt1).max, iinfo(dt2).max) self.assertRaises(ValueError, iinfo, 'f4') def test_unsigned_max(self): types = np.sctypes['uint'] for T in types: assert_equal(iinfo(T).max, T(-1)) class TestRepr(TestCase): def test_iinfo_repr(self): expected = "iinfo(min=-32768, max=32767, dtype=int16)" assert_equal(repr(np.iinfo(np.int16)), expected) def test_finfo_repr(self): expected = "finfo(resolution=1e-06, min=-3.4028235e+38," + \ " max=3.4028235e+38, dtype=float32)" # Python 2.5 float formatting on Windows adds an extra 0 to the # exponent. So test for both. Once 2.5 compatibility is dropped, this # can simply use `assert_equal(repr(np.finfo(np.float32)), expected)`. expected_win25 = "finfo(resolution=1e-006, min=-3.4028235e+038," + \ " max=3.4028235e+038, dtype=float32)" actual = repr(np.finfo(np.float32)) if not actual == expected: if not actual == expected_win25: msg = build_err_msg([actual, desired], verbose=True) raise AssertionError(msg) def test_instances(): iinfo(10) finfo(3.0) if __name__ == "__main__": run_module_suite()
lthurlow/Network-Grapher
proj/external/numpy-1.7.0/numpy/core/tests/test_getlimits.py
Python
mit
2,703
# Foremast - Pipeline Tooling # # Copyright 2018 Gogo, 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 .api_gateway_event import *
gogoair/foremast
src/foremast/awslambda/api_gateway_event/__init__.py
Python
apache-2.0
661
############################# #get_L_L_H3N2_predictions.tex # # this script identifies the strain names we obtained from Luksza and Laessig # with sequences in our mutliple sequence alignment # ################################ import sys sys.path.append('../src') import predict_flu as PF from datetime import date from Bio import Phylo,AlignIO,SeqIO from matplotlib import pyplot as plt import numpy as np from scipy import stats import glob,pickle,gzip,os, argparse #parse the command line arguments aln_fname = '../data/H3N2_HA1_all_years_filtered.fasta.gz' with open('../data/annotations.pickle', 'r') as infile: annotation = pickle.load(infile) with gzip.open(aln_fname) as infile: total_alignment = AlignIO.read(infile,'fasta') seq_look_up = {c.name.split('|')[0].lower():c for c in total_alignment} L_L={} with open('../data/H3N2_L_L_predicted_vaccine_strains.dat') as L_L_file: for line in L_L_file: entries = line.strip().split() year=int(entries[0][:-1]) strain_name = '_'.join(entries[1].split('_')[:-3]).lower().replace('-', '_') if strain_name in seq_look_up: L_L[year-1] = seq_look_up[strain_name] else: print "strain for year", year-1, "not found" with open('../data/H3N2_L_L_predictions.pickle', 'w') as outfile: pickle.dump(L_L, outfile)
rneher/FitnessInference
flu/sequence_and_annotations/get_L_L_H3N2_predictions.py
Python
mit
1,340
# -*- coding: utf-8 -*- """ Preprocessor to finalize system description after PDB Scan, this is the first step in PDB Rx SASSIE: Copyright (C) 2011 Joseph E. Curtis, Ph.D. 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/>. """ from __future__ import print_function from . import segname_utils as segname_utils from . import terminal_utils as terminal_utils from . import sassie_web_utils as sassie_web_utils def user_input(other_self, mol, pdbscan_report): """ Get user input from terminal or other source. ONLY TERMINAL CURRENTLY @return: """ other_self.resid_descriptions = segname_utils.create_residue_descriptions(mol) if other_self.mvars.user_interface == 'terminal': terminal_utils.handle_terminal_user_input(other_self, mol) elif other_self.mvars.user_interface == 'sassie_web': sassie_web_utils.handle_sassie_web_user_input(other_self, mol, pdbscan_report) return
madscatt/zazzie
src_2.7/sassie/build/pdbrx/pdbrx/preprocessor.py
Python
gpl-3.0
1,558
import discord from discord.ext import commands import re class Iron(): def __init__(self, bot): self.bot = bot async def on_message(self, message): match = re.search(r"iron|айрон", message.content, re.IGNORECASE) if match and (message.author != self.bot.user): await self.bot.send_message(message.channel, "<@219003663455223810>") def setup(bot): bot.add_cog(Iron(bot))
mouzfun/discbot
iron.py
Python
mit
446
# coding: utf-8 from django import forms from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.utils.translation import ugettext_lazy as _ from canaa.core.models import Step, Banner SUBJECT_CHOICES = ( (_(u'--- Escolha um assunto ---'), _(u'--- Escolha um assunto ---')), (_(u'Dúvida'), _(u'Dúvida')), (_(u'Elogio'), _(u'Elogio')), (_(u'SAC'), _(u'SAC')), (_(u'Informação'), _(u'Informação')), (_(u'Reclamação'), _(u'Reclamação')), (_(u'Venda'), _(u'Venda')), ) class ContactForm(forms.Form): name = forms.CharField(label=_(u'Nome'), widget=forms.TextInput(attrs={'class': 'span12'})) email = forms.EmailField(label=_(u'E-mail'), widget=forms.EmailInput(attrs={'class': 'span12'})) subject = forms.ChoiceField(label=_(u'Assunto'), choices=SUBJECT_CHOICES, widget=forms.Select(attrs={'class': 'span12'})) message = forms.CharField(label=_(u'Mensagem'), widget=forms.Textarea(attrs={'class': 'span12', 'rows': 6})) def send_mail(self): subject = u'Contato do site (%s)' % self.cleaned_data['name'] context = { 'name': self.cleaned_data['name'], 'email': self.cleaned_data['email'], 'subject': self.cleaned_data['subject'], 'message': self.cleaned_data['message'], } message = render_to_string('contact_mail.txt', context) message_html = render_to_string('contact_mail.html', context) msg = EmailMultiAlternatives(subject, message, 'no-reply@polpacanaa.com.br', ['polpacanaa@polpacanaa.com.br']) # ['kleberr@msn.com']) msg.attach_alternative(message_html, 'text/html') msg.send() class StepForm(forms.ModelForm): description = forms.CharField(widget=forms.Textarea( attrs={'cols': 60, 'rows': 6, 'maxlength': 255})) class Meta: model = Step class BannerForm(forms.ModelForm): title = forms.CharField(widget=forms.Textarea( attrs={'cols': 60, 'rows': 6, 'maxlength': 50})) text = forms.CharField(widget=forms.Textarea( attrs={'cols': 60, 'rows': 6, 'maxlength': 100}), required=False) class Meta: model = Banner
klebercode/canaa
canaa/core/forms.py
Python
mit
2,834
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # Python import contextlib import logging import threading import json # Django from django.conf import settings from django.db.models.signals import post_save, pre_delete, post_delete, m2m_changed from django.dispatch import receiver # Django-CRUM from crum import get_current_request, get_current_user from crum.signals import current_user_getter # AWX from awx.main.models import * # noqa from awx.api.serializers import * # noqa from awx.main.utils import model_instance_diff, model_to_dict, camelcase_to_underscore from awx.main.utils import ignore_inventory_computed_fields, ignore_inventory_group_removal, _inventory_updates from awx.main.tasks import update_inventory_computed_fields from awx.main.fields import is_implicit_parent from awx.main.consumers import emit_channel_notification __all__ = [] logger = logging.getLogger('awx.main.signals') # Update has_active_failures for inventory/groups when a Host/Group is deleted, # when a Host-Group or Group-Group relationship is updated, or when a Job is deleted def get_current_user_or_none(): u = get_current_user() if not isinstance(u, User): return None return u def emit_job_event_detail(sender, **kwargs): instance = kwargs['instance'] created = kwargs['created'] if created: event_serialized = JobEventSerializer(instance).data event_serialized['id'] = instance.id event_serialized["created"] = event_serialized["created"].isoformat() event_serialized["modified"] = event_serialized["modified"].isoformat() event_serialized["event_name"] = instance.event event_serialized["group_name"] = "job_events" emit_channel_notification('job_events-' + str(instance.job.id), event_serialized) def emit_ad_hoc_command_event_detail(sender, **kwargs): instance = kwargs['instance'] created = kwargs['created'] if created: event_serialized = AdHocCommandEventSerializer(instance).data event_serialized['id'] = instance.id event_serialized["created"] = event_serialized["created"].isoformat() event_serialized["modified"] = event_serialized["modified"].isoformat() event_serialized["event_name"] = instance.event event_serialized["group_name"] = "ad_hoc_command_events" emit_channel_notification('ad_hoc_command_events-' + str(instance.ad_hoc_command_id), event_serialized) def emit_update_inventory_computed_fields(sender, **kwargs): logger.debug("In update inventory computed fields") if getattr(_inventory_updates, 'is_updating', False): return instance = kwargs['instance'] if sender == Group.hosts.through: sender_name = 'group.hosts' elif sender == Group.parents.through: sender_name = 'group.parents' elif sender == Host.inventory_sources.through: sender_name = 'host.inventory_sources' elif sender == Group.inventory_sources.through: sender_name = 'group.inventory_sources' else: sender_name = unicode(sender._meta.verbose_name) if kwargs['signal'] == post_save: if sender == Job: return sender_action = 'saved' elif kwargs['signal'] == post_delete: sender_action = 'deleted' elif kwargs['signal'] == m2m_changed and kwargs['action'] in ('post_add', 'post_remove', 'post_clear'): sender_action = 'changed' else: return logger.debug('%s %s, updating inventory computed fields: %r %r', sender_name, sender_action, sender, kwargs) try: inventory = instance.inventory except Inventory.DoesNotExist: pass else: update_inventory_computed_fields.delay(inventory.id, True) def emit_update_inventory_on_created_or_deleted(sender, **kwargs): if getattr(_inventory_updates, 'is_updating', False): return instance = kwargs['instance'] if ('created' in kwargs and kwargs['created']) or \ kwargs['signal'] == post_delete: pass else: return sender_name = unicode(sender._meta.verbose_name) logger.debug("%s created or deleted, updating inventory computed fields: %r %r", sender_name, sender, kwargs) try: inventory = instance.inventory except Inventory.DoesNotExist: pass else: if inventory is not None: update_inventory_computed_fields.delay(inventory.id, True) def rebuild_role_ancestor_list(reverse, model, instance, pk_set, action, **kwargs): 'When a role parent is added or removed, update our role hierarchy list' if action == 'post_add': if reverse: model.rebuild_role_ancestor_list(list(pk_set), []) else: model.rebuild_role_ancestor_list([instance.id], []) if action in ['post_remove', 'post_clear']: if reverse: model.rebuild_role_ancestor_list([], list(pk_set)) else: model.rebuild_role_ancestor_list([], [instance.id]) def sync_superuser_status_to_rbac(instance, **kwargs): 'When the is_superuser flag is changed on a user, reflect that in the membership of the System Admnistrator role' update_fields = kwargs.get('update_fields', None) if update_fields and 'is_superuser' not in update_fields: return if instance.is_superuser: Role.singleton(ROLE_SINGLETON_SYSTEM_ADMINISTRATOR).members.add(instance) else: Role.singleton(ROLE_SINGLETON_SYSTEM_ADMINISTRATOR).members.remove(instance) def create_user_role(instance, **kwargs): if not kwargs.get('created', True): return try: Role.objects.get( content_type=ContentType.objects.get_for_model(instance), object_id=instance.id, role_field='admin_role' ) except Role.DoesNotExist: role = Role.objects.create( role_field='admin_role', content_object = instance, ) role.members.add(instance) def org_admin_edit_members(instance, action, model, reverse, pk_set, **kwargs): content_type = ContentType.objects.get_for_model(Organization) if reverse: return else: if instance.content_type == content_type and \ instance.content_object.member_role.id == instance.id: items = model.objects.filter(pk__in=pk_set).all() for user in items: if action == 'post_add': instance.content_object.admin_role.children.add(user.admin_role) if action == 'pre_remove': instance.content_object.admin_role.children.remove(user.admin_role) def rbac_activity_stream(instance, sender, **kwargs): user_type = ContentType.objects.get_for_model(User) # Only if we are associating/disassociating if kwargs['action'] in ['pre_add', 'pre_remove']: # Only if this isn't for the User.admin_role if hasattr(instance, 'content_type'): if instance.content_type in [None, user_type]: return elif sender.__name__ == 'Role_parents': role = kwargs['model'].objects.filter(pk__in=kwargs['pk_set']).first() # don't record implicit creation / parents in activity stream if role is not None and is_implicit_parent(parent_role=role, child_role=instance): return else: role = instance instance = instance.content_object else: role = kwargs['model'].objects.filter(pk__in=kwargs['pk_set']).first() activity_stream_associate(sender, instance, role=role, **kwargs) def cleanup_detached_labels_on_deleted_parent(sender, instance, **kwargs): for l in instance.labels.all(): if l.is_candidate_for_detach(): l.delete() def connect_computed_field_signals(): post_save.connect(emit_update_inventory_on_created_or_deleted, sender=Host) post_delete.connect(emit_update_inventory_on_created_or_deleted, sender=Host) post_save.connect(emit_update_inventory_on_created_or_deleted, sender=Group) post_delete.connect(emit_update_inventory_on_created_or_deleted, sender=Group) m2m_changed.connect(emit_update_inventory_computed_fields, sender=Group.hosts.through) m2m_changed.connect(emit_update_inventory_computed_fields, sender=Group.parents.through) m2m_changed.connect(emit_update_inventory_computed_fields, sender=Host.inventory_sources.through) m2m_changed.connect(emit_update_inventory_computed_fields, sender=Group.inventory_sources.through) post_save.connect(emit_update_inventory_on_created_or_deleted, sender=InventorySource) post_delete.connect(emit_update_inventory_on_created_or_deleted, sender=InventorySource) post_save.connect(emit_update_inventory_on_created_or_deleted, sender=Job) post_delete.connect(emit_update_inventory_on_created_or_deleted, sender=Job) connect_computed_field_signals() post_save.connect(emit_job_event_detail, sender=JobEvent) post_save.connect(emit_ad_hoc_command_event_detail, sender=AdHocCommandEvent) m2m_changed.connect(rebuild_role_ancestor_list, Role.parents.through) m2m_changed.connect(org_admin_edit_members, Role.members.through) m2m_changed.connect(rbac_activity_stream, Role.members.through) m2m_changed.connect(rbac_activity_stream, Role.parents.through) post_save.connect(sync_superuser_status_to_rbac, sender=User) post_save.connect(create_user_role, sender=User) pre_delete.connect(cleanup_detached_labels_on_deleted_parent, sender=UnifiedJob) pre_delete.connect(cleanup_detached_labels_on_deleted_parent, sender=UnifiedJobTemplate) # Migrate hosts, groups to parent group(s) whenever a group is deleted @receiver(pre_delete, sender=Group) def save_related_pks_before_group_delete(sender, **kwargs): if getattr(_inventory_updates, 'is_removing', False): return instance = kwargs['instance'] instance._saved_inventory_pk = instance.inventory.pk instance._saved_parents_pks = set(instance.parents.values_list('pk', flat=True)) instance._saved_hosts_pks = set(instance.hosts.values_list('pk', flat=True)) instance._saved_children_pks = set(instance.children.values_list('pk', flat=True)) @receiver(post_delete, sender=Group) def migrate_children_from_deleted_group_to_parent_groups(sender, **kwargs): if getattr(_inventory_updates, 'is_removing', False): return instance = kwargs['instance'] parents_pks = getattr(instance, '_saved_parents_pks', []) hosts_pks = getattr(instance, '_saved_hosts_pks', []) children_pks = getattr(instance, '_saved_children_pks', []) is_updating = getattr(_inventory_updates, 'is_updating', False) with ignore_inventory_group_removal(): with ignore_inventory_computed_fields(): if parents_pks: for parent_group in Group.objects.filter(pk__in=parents_pks): for child_host in Host.objects.filter(pk__in=hosts_pks): logger.debug('adding host %s to parent %s after group deletion', child_host, parent_group) parent_group.hosts.add(child_host) for child_group in Group.objects.filter(pk__in=children_pks): logger.debug('adding group %s to parent %s after group deletion', child_group, parent_group) parent_group.children.add(child_group) inventory_pk = getattr(instance, '_saved_inventory_pk', None) if inventory_pk and not is_updating: try: inventory = Inventory.objects.get(pk=inventory_pk) inventory.update_computed_fields() except (Inventory.DoesNotExist, Project.DoesNotExist): pass # Update host pointers to last_job and last_job_host_summary when a job is deleted def _update_host_last_jhs(host): jhs_qs = JobHostSummary.objects.filter(host__pk=host.pk) try: jhs = jhs_qs.order_by('-job__pk')[0] except IndexError: jhs = None update_fields = [] last_job = jhs.job if jhs else None if host.last_job != last_job: host.last_job = last_job update_fields.append('last_job') if host.last_job_host_summary != jhs: host.last_job_host_summary = jhs update_fields.append('last_job_host_summary') if update_fields: host.save(update_fields=update_fields) @receiver(pre_delete, sender=Job) def save_host_pks_before_job_delete(sender, **kwargs): instance = kwargs['instance'] hosts_qs = Host.objects.filter( last_job__pk=instance.pk) instance._saved_hosts_pks = set(hosts_qs.values_list('pk', flat=True)) @receiver(post_delete, sender=Job) def update_host_last_job_after_job_deleted(sender, **kwargs): instance = kwargs['instance'] hosts_pks = getattr(instance, '_saved_hosts_pks', []) for host in Host.objects.filter(pk__in=hosts_pks): _update_host_last_jhs(host) # Set via ActivityStreamRegistrar to record activity stream events class ActivityStreamEnabled(threading.local): def __init__(self): self.enabled = True def __nonzero__(self): return bool(self.enabled and getattr(settings, 'ACTIVITY_STREAM_ENABLED', True)) activity_stream_enabled = ActivityStreamEnabled() @contextlib.contextmanager def disable_activity_stream(): ''' Context manager to disable capturing activity stream changes. ''' try: previous_value = activity_stream_enabled.enabled activity_stream_enabled.enabled = False yield finally: activity_stream_enabled.enabled = previous_value @contextlib.contextmanager def disable_computed_fields(): post_save.disconnect(emit_update_inventory_on_created_or_deleted, sender=Host) post_delete.disconnect(emit_update_inventory_on_created_or_deleted, sender=Host) post_save.disconnect(emit_update_inventory_on_created_or_deleted, sender=Group) post_delete.disconnect(emit_update_inventory_on_created_or_deleted, sender=Group) m2m_changed.disconnect(emit_update_inventory_computed_fields, sender=Group.hosts.through) m2m_changed.disconnect(emit_update_inventory_computed_fields, sender=Group.parents.through) m2m_changed.disconnect(emit_update_inventory_computed_fields, sender=Host.inventory_sources.through) m2m_changed.disconnect(emit_update_inventory_computed_fields, sender=Group.inventory_sources.through) post_save.disconnect(emit_update_inventory_on_created_or_deleted, sender=InventorySource) post_delete.disconnect(emit_update_inventory_on_created_or_deleted, sender=InventorySource) post_save.disconnect(emit_update_inventory_on_created_or_deleted, sender=Job) post_delete.disconnect(emit_update_inventory_on_created_or_deleted, sender=Job) yield connect_computed_field_signals() model_serializer_mapping = { Organization: OrganizationSerializer, Inventory: InventorySerializer, Host: HostSerializer, Group: GroupSerializer, InventorySource: InventorySourceSerializer, CustomInventoryScript: CustomInventoryScriptSerializer, Credential: CredentialSerializer, Team: TeamSerializer, Project: ProjectSerializer, JobTemplate: JobTemplateSerializer, Job: JobSerializer, AdHocCommand: AdHocCommandSerializer, NotificationTemplate: NotificationTemplateSerializer, Notification: NotificationSerializer, } def activity_stream_create(sender, instance, created, **kwargs): if created and activity_stream_enabled: # TODO: remove deprecated_group conditional in 3.3 # Skip recording any inventory source directly associated with a group. if isinstance(instance, InventorySource) and instance.deprecated_group: return object1 = camelcase_to_underscore(instance.__class__.__name__) changes = model_to_dict(instance, model_serializer_mapping) # Special case where Job survey password variables need to be hidden if type(instance) == Job: if 'extra_vars' in changes: changes['extra_vars'] = instance.display_extra_vars() activity_entry = ActivityStream( operation='create', object1=object1, changes=json.dumps(changes), actor=get_current_user_or_none()) activity_entry.save() #TODO: Weird situation where cascade SETNULL doesn't work # it might actually be a good idea to remove all of these FK references since # we don't really use them anyway. if instance._meta.model_name != 'setting': # Is not conf.Setting instance getattr(activity_entry, object1).add(instance) def activity_stream_update(sender, instance, **kwargs): if instance.id is None: return if not activity_stream_enabled: return try: old = sender.objects.get(id=instance.id) except sender.DoesNotExist: return new = instance changes = model_instance_diff(old, new, model_serializer_mapping) if changes is None: return object1 = camelcase_to_underscore(instance.__class__.__name__) activity_entry = ActivityStream( operation='update', object1=object1, changes=json.dumps(changes), actor=get_current_user_or_none()) activity_entry.save() if instance._meta.model_name != 'setting': # Is not conf.Setting instance getattr(activity_entry, object1).add(instance) def activity_stream_delete(sender, instance, **kwargs): if not activity_stream_enabled: return # TODO: remove deprecated_group conditional in 3.3 # Skip recording any inventory source directly associated with a group. if isinstance(instance, InventorySource) and instance.deprecated_group: return # Inventory delete happens in the task system rather than request-response-cycle. # If we trigger this handler there we may fall into db-integrity-related race conditions. # So we add flag verification to prevent normal signal handling. This funciton will be # explicitly called with flag on in Inventory.schedule_deletion. if isinstance(instance, Inventory) and not kwargs.get('inventory_delete_flag', False): return changes = model_to_dict(instance) object1 = camelcase_to_underscore(instance.__class__.__name__) activity_entry = ActivityStream( operation='delete', changes=json.dumps(changes), object1=object1, actor=get_current_user_or_none()) activity_entry.save() def activity_stream_associate(sender, instance, **kwargs): if not activity_stream_enabled: return if kwargs['action'] in ['pre_add', 'pre_remove']: if kwargs['action'] == 'pre_add': action = 'associate' elif kwargs['action'] == 'pre_remove': action = 'disassociate' else: return obj1 = instance object1=camelcase_to_underscore(obj1.__class__.__name__) obj_rel = sender.__module__ + "." + sender.__name__ for entity_acted in kwargs['pk_set']: obj2 = kwargs['model'] obj2_id = entity_acted obj2_actual = obj2.objects.filter(id=obj2_id) if not obj2_actual.exists(): continue obj2_actual = obj2_actual[0] if isinstance(obj2_actual, Role) and obj2_actual.content_object is not None: obj2_actual = obj2_actual.content_object object2 = camelcase_to_underscore(obj2_actual.__class__.__name__) else: object2 = camelcase_to_underscore(obj2.__name__) # Skip recording any inventory source, or system job template changes here. if isinstance(obj1, InventorySource) or isinstance(obj2_actual, InventorySource): continue if isinstance(obj1, SystemJobTemplate) or isinstance(obj2_actual, SystemJobTemplate): continue if isinstance(obj1, SystemJob) or isinstance(obj2_actual, SystemJob): continue activity_entry = ActivityStream( changes=json.dumps(dict(object1=object1, object1_pk=obj1.pk, object2=object2, object2_pk=obj2_id, action=action, relationship=obj_rel)), operation=action, object1=object1, object2=object2, object_relationship_type=obj_rel, actor=get_current_user_or_none()) activity_entry.save() getattr(activity_entry, object1).add(obj1) getattr(activity_entry, object2).add(obj2_actual) # Record the role for RBAC changes if 'role' in kwargs: role = kwargs['role'] if role.content_object is not None: obj_rel = '.'.join([role.content_object.__module__, role.content_object.__class__.__name__, role.role_field]) # If the m2m is from the User side we need to # set the content_object of the Role for our entry. if type(instance) == User and role.content_object is not None: getattr(activity_entry, role.content_type.name.replace(' ', '_')).add(role.content_object) activity_entry.role.add(role) activity_entry.object_relationship_type = obj_rel activity_entry.save() @receiver(current_user_getter) def get_current_user_from_drf_request(sender, **kwargs): ''' Provider a signal handler to return the current user from the current request when using Django REST Framework. Requires that the APIView set drf_request on the underlying Django Request object. ''' request = get_current_request() drf_request = getattr(request, 'drf_request', None) return (getattr(drf_request, 'user', False), 0) @receiver(pre_delete, sender=Organization) def delete_inventory_for_org(sender, instance, **kwargs): inventories = Inventory.objects.filter(organization__pk=instance.pk) user = get_current_user_or_none() for inventory in inventories: try: inventory.schedule_deletion(user_id=getattr(user, 'id', None)) except RuntimeError, e: logger.debug(e)
snahelou/awx
awx/main/signals.py
Python
apache-2.0
22,691
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, 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 six import datetime from ..environment import Environment from ..utils import instrument_type_str2enum class Instrument(object): DEFAULT_LISTED_DATE = datetime.datetime(1990, 1, 1) DEFAULT_DE_LISTED_DATE = datetime.datetime(2999, 12, 31) @staticmethod def _fix_date(ds, dflt): if ds == '0000-00-00': return dflt year, month, day = ds.split('-') return datetime.datetime(int(year), int(month), int(day)) def __init__(self, dic): self.__dict__ = dic if 'listed_date' in self.__dict__: self.listed_date = self._fix_date(self.listed_date, self.DEFAULT_LISTED_DATE) if 'de_listed_date' in self.__dict__: self.de_listed_date = self._fix_date(self.de_listed_date, self.DEFAULT_DE_LISTED_DATE) if 'maturity_date' in self.__dict__: self.maturity_date = self._fix_date(self.maturity_date, self.DEFAULT_DE_LISTED_DATE) def __repr__(self): return "{}({})".format(type(self).__name__, ", ".join(["{}={}".format(k, repr(v)) for k, v in six.iteritems(self.__dict__)])) @property def listing(self): now = Environment.get_instance().calendar_dt return self.listed_date <= now <= self.de_listed_date def days_from_listed(self): if self.listed_date == self.DEFAULT_LISTED_DATE: return -1 date = Environment.get_instance().trading_dt.date() if self.de_listed_date.date() < date: return -1 ipo_days = (date - self.listed_date.date()).days return ipo_days if ipo_days >= 0 else -1 @property def enum_type(self): return instrument_type_str2enum(self.type) def days_to_expire(self): if self.type != 'Future' or self.order_book_id[-2:] == '88' or self.order_book_id[-2:] == '99': return -1 date = Environment.get_instance().trading_dt.date() days = (self.maturity_date.date() - date).days return -1 if days < 0 else days class SectorCodeItem(object): def __init__(self, cn, en, name): self.__cn = cn self.__en = en self.__name = name @property def cn(self): return self.__cn @property def en(self): return self.__en @property def name(self): return self.__name def __repr__(self): return "{}: {}, {}".format(self.__name, self.__en, self.__cn) class SectorCode(object): Energy = SectorCodeItem("能源", "energy", 'Energy') Materials = SectorCodeItem("原材料", "materials", 'Materials') ConsumerDiscretionary = SectorCodeItem("非必需消费品", "consumer discretionary", 'ConsumerDiscretionary') ConsumerStaples = SectorCodeItem("必需消费品", "consumer staples", 'ConsumerStaples') HealthCare = SectorCodeItem("医疗保健", "health care", 'HealthCare') Financials = SectorCodeItem("金融", "financials", 'Financials') InformationTechnology = SectorCodeItem("信息技术", "information technology", 'InformationTechnology') TelecommunicationServices = SectorCodeItem("电信服务", "telecommunication services", 'TelecommunicationServices') Utilities = SectorCodeItem("公共服务", "utilities", 'Utilities') Industrials = SectorCodeItem("工业", "industrials", "Industrials") class IndustryCodeItem(object): def __init__(self, code, name): self.__code = code self.__name = name @property def code(self): return self.__code @property def name(self): return self.__name def __repr__(self): return "{0}:{1}".format(self.__code, self.__name) class IndustryCode(object): A01 = IndustryCodeItem("A01", "农业") A02 = IndustryCodeItem("A02", "林业") A03 = IndustryCodeItem("A03", "畜牧业") A04 = IndustryCodeItem("A04", "渔业") A05 = IndustryCodeItem("A05", "农、林、牧、渔服务业") B06 = IndustryCodeItem("B06", "煤炭开采和洗选业") B07 = IndustryCodeItem("B07", "石油和天然气开采业") B08 = IndustryCodeItem("B08", "黑色金属矿采选业") B09 = IndustryCodeItem("B09", "有色金属矿采选业") B10 = IndustryCodeItem("B10", "非金属矿采选业") B11 = IndustryCodeItem("B11", "开采辅助活动") B12 = IndustryCodeItem("B12", "其他采矿业") C13 = IndustryCodeItem("C13", "农副食品加工业") C14 = IndustryCodeItem("C14", "食品制造业") C15 = IndustryCodeItem("C15", "酒、饮料和精制茶制造业") C16 = IndustryCodeItem("C16", "烟草制品业") C17 = IndustryCodeItem("C17", "纺织业") C18 = IndustryCodeItem("C18", "纺织服装、服饰业") C19 = IndustryCodeItem("C19", "皮革、毛皮、羽毛及其制品和制鞋业") C20 = IndustryCodeItem("C20", "木材加工及木、竹、藤、棕、草制品业") C21 = IndustryCodeItem("C21", "家具制造业") C22 = IndustryCodeItem("C22", "造纸及纸制品业") C23 = IndustryCodeItem("C23", "印刷和记录媒介复制业") C24 = IndustryCodeItem("C24", "文教、工美、体育和娱乐用品制造业") C25 = IndustryCodeItem("C25", "石油加工、炼焦及核燃料加工业") C26 = IndustryCodeItem("C26", "化学原料及化学制品制造业") C27 = IndustryCodeItem("C27", "医药制造业") C28 = IndustryCodeItem("C28", "化学纤维制造业") C29 = IndustryCodeItem("C29", "橡胶和塑料制品业") C30 = IndustryCodeItem("C30", "非金属矿物制品业") C31 = IndustryCodeItem("C31", "黑色金属冶炼及压延加工业") C32 = IndustryCodeItem("C32", "有色金属冶炼和压延加工业") C33 = IndustryCodeItem("C33", "金属制品业") C34 = IndustryCodeItem("C34", "通用设备制造业") C35 = IndustryCodeItem("C35", "专用设备制造业") C36 = IndustryCodeItem("C36", "汽车制造业") C37 = IndustryCodeItem("C37", "铁路、船舶、航空航天和其它运输设备制造业") C38 = IndustryCodeItem("C38", "电气机械及器材制造业") C39 = IndustryCodeItem("C39", "计算机、通信和其他电子设备制造业") C40 = IndustryCodeItem("C40", "仪器仪表制造业") C41 = IndustryCodeItem("C41", "其他制造业") C42 = IndustryCodeItem("C42", "废弃资源综合利用业") C43 = IndustryCodeItem("C43", "金属制品、机械和设备修理业") D44 = IndustryCodeItem("D44", "电力、热力生产和供应业") D45 = IndustryCodeItem("D45", "燃气生产和供应业") D46 = IndustryCodeItem("D46", "水的生产和供应业") E47 = IndustryCodeItem("E47", "房屋建筑业") E48 = IndustryCodeItem("E48", "土木工程建筑业") E49 = IndustryCodeItem("E49", "建筑安装业") E50 = IndustryCodeItem("E50", "建筑装饰和其他建筑业") F51 = IndustryCodeItem("F51", "批发业") F52 = IndustryCodeItem("F52", "零售业") G53 = IndustryCodeItem("G53", "铁路运输业") G54 = IndustryCodeItem("G54", "道路运输业") G55 = IndustryCodeItem("G55", "水上运输业") G56 = IndustryCodeItem("G56", "航空运输业") G57 = IndustryCodeItem("G57", "管道运输业") G58 = IndustryCodeItem("G58", "装卸搬运和运输代理业") G59 = IndustryCodeItem("G59", "仓储业") G60 = IndustryCodeItem("G60", "邮政业") H61 = IndustryCodeItem("H61", "住宿业") H62 = IndustryCodeItem("H62", "餐饮业") I63 = IndustryCodeItem("I63", "电信、广播电视和卫星传输服务") I64 = IndustryCodeItem("I64", "互联网和相关服务") I65 = IndustryCodeItem("I65", "软件和信息技术服务业") J66 = IndustryCodeItem("J66", "货币金融服务") J67 = IndustryCodeItem("J67", "资本市场服务") J68 = IndustryCodeItem("J68", "保险业") J69 = IndustryCodeItem("J69", "其他金融业") K70 = IndustryCodeItem("K70", "房地产业") L71 = IndustryCodeItem("L71", "租赁业") L72 = IndustryCodeItem("L72", "商务服务业") M73 = IndustryCodeItem("M73", "研究和试验发展") M74 = IndustryCodeItem("M74", "专业技术服务业") M75 = IndustryCodeItem("M75", "科技推广和应用服务业") N76 = IndustryCodeItem("N76", "水利管理业") N77 = IndustryCodeItem("N77", "生态保护和环境治理业") N78 = IndustryCodeItem("N78", "公共设施管理业") O79 = IndustryCodeItem("O79", "居民服务业") O80 = IndustryCodeItem("O80", "机动车、电子产品和日用产品修理业") O81 = IndustryCodeItem("O81", "其他服务业") P82 = IndustryCodeItem("P82", "教育") Q83 = IndustryCodeItem("Q83", "卫生") Q84 = IndustryCodeItem("Q84", "社会工作") R85 = IndustryCodeItem("R85", "新闻和出版业") R86 = IndustryCodeItem("R86", "广播、电视、电影和影视录音制作业") R87 = IndustryCodeItem("R87", "文化艺术业") R88 = IndustryCodeItem("R88", "体育") R89 = IndustryCodeItem("R89", "娱乐业") S90 = IndustryCodeItem("S90", "综合")
zhengwsh/InplusTrader_Linux
rqalpha/model/instrument.py
Python
mit
9,716
import RRT import taskSpaceFuncs as TSFs initPos = [0.0, 0.0, 0.0] #[x, y, z] goalPos = [9.0, 0.0, 0.0] #[x, y, z] objects = {1:[1, 3.0, 0.0, 0.0], 2:[5, 0.0, 7.0, 0.0]} #{key:[radius, x, y, z]} #objects = {} limits = [[-10.0, -10.0, -10.0], [10.0, 10.0, 10.0]] path = RRT.RRT(initPos, goalPos, objects, limits, TSFs.dist, TSFs.validation, TSFs.extension) for p in path: print p
tapomayukh/projects_in_python
sandbox_tapo/src/AI/RIP-2012/Project3/Code/RRTTaskSpaceTest.py
Python
mit
386
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post # Create your views here. def post_list(request): """ Create a view that will return a list of Posts that were published prior to 'now' and render them to the 'blogposts.html' template :param request: :return: """ posts = Post.objects.filter(published_date__lte=timezone.now() ).order_by('-published_date') return render(request, "blogposts.html", {'posts': posts}) def post_detail(request, slug): """ Create a view that return a single Post object based on the post ID and and render it to the 'postdetail.html' template. Or return a 404 error if the post is not found """ post = get_object_or_404(Post, slug=slug) post.views += 1 # clock up the number of post views post.save() return render(request, "postdetail.html", {'post': post})
GunnerJnr/_CodeInstitute
Stream-3/Full-Stack-Development/8.Django-Blog-Part-Four/3.Integrate-Comments-Into-A-Blog/Blog_prj/Blog_app/views.py
Python
mit
1,034
# Written by Greg Ver Steeg (http://www.isi.edu/~gregv/npeet.html) import scipy.spatial as ss from scipy.special import digamma from math import log import numpy.random as nr import numpy as np import random # continuous estimators def entropy(x, k=3, base=2): """ The classic K-L k-nearest neighbor continuous entropy estimator x should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ assert k <= len(x)-1, "Set k smaller than num. samples - 1" d = len(x[0]) N = len(x) intens = 1e-10 # small noise to break degeneracy, see doc. x = [list(p + intens * nr.rand(len(x[0]))) for p in x] tree = ss.cKDTree(x) nn = [tree.query(point, k+1, p=float('inf'))[0][k] for point in x] const = digamma(N)-digamma(k) + d*log(2) return (const + d*np.mean(map(log, nn)))/log(base) def mi(x, y, k=3, base=2): """ Mutual information of x and y; x, y should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ assert len(x) == len(y), "Lists should have same length" assert k <= len(x) - 1, "Set k smaller than num. samples - 1" intens = 1e-10 # small noise to break degeneracy, see doc. x = [list(p + intens * nr.rand(len(x[0]))) for p in x] y = [list(p + intens * nr.rand(len(y[0]))) for p in y] points = zip2(x, y) # Find nearest neighbors in joint space, p=inf means max-norm tree = ss.cKDTree(points) dvec = [tree.query(point, k+1, p=float('inf'))[0][k] for point in points] a, b, c, d = avgdigamma(x, dvec), avgdigamma(y, dvec), digamma(k), digamma(len(x)) return (-a-b+c+d)/log(base) def cmi(x, y, z, k=3, base=2): """ Mutual information of x and y, conditioned on z; x, y, z should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ assert len(x) == len(y), "Lists should have same length" assert k <= len(x) - 1, "Set k smaller than num. samples - 1" intens = 1e-10 # small noise to break degeneracy, see doc. x = [list(p + intens * nr.rand(len(x[0]))) for p in x] y = [list(p + intens * nr.rand(len(y[0]))) for p in y] z = [list(p + intens * nr.rand(len(z[0]))) for p in z] points = zip2(x, y, z) # Find nearest neighbors in joint space, p=inf means max-norm tree = ss.cKDTree(points) dvec = [tree.query(point, k+1, p=float('inf'))[0][k] for point in points] a, b, c, d = avgdigamma(zip2(x, z), dvec), avgdigamma(zip2(y, z), dvec), avgdigamma(z, dvec), digamma(k) return (-a-b+c+d)/log(base) def kldiv(x, xp, k=3, base=2): """ KL Divergence between p and q for x~p(x), xp~q(x); x, xp should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ assert k <= len(x) - 1, "Set k smaller than num. samples - 1" assert k <= len(xp) - 1, "Set k smaller than num. samples - 1" assert len(x[0]) == len(xp[0]), "Two distributions must have same dim." d = len(x[0]) n = len(x) m = len(xp) const = log(m) - log(n-1) tree = ss.cKDTree(x) treep = ss.cKDTree(xp) nn = [tree.query(point, k+1, p=float('inf'))[0][k] for point in x] nnp = [treep.query(point, k, p=float('inf'))[0][k-1] for point in x] return (const + d*np.mean(map(log, nnp))-d*np.mean(map(log, nn)))/log(base) # Discrete estimators def entropyd(sx, base=2): """ Discrete entropy estimator given a list of samples which can be any hashable object """ return entropyfromprobs(hist(sx), base=base) def midd(x, y): """ Discrete mutual information estimator given a list of samples which can be any hashable object """ return -entropyd(list(zip(x, y)))+entropyd(x)+entropyd(y) def cmidd(x, y, z): """ Discrete mutual information estimator given a list of samples which can be any hashable object """ return entropyd(list(zip(y, z)))+entropyd(list(zip(x, z)))-entropyd(list(zip(x, y, z)))-entropyd(z) def hist(sx): # Histogram from list of samples d = dict() for s in sx: d[s] = d.get(s, 0) + 1 return map(lambda z: float(z)/len(sx), d.values()) def entropyfromprobs(probs, base=2): # Turn a normalized list of probabilities of discrete outcomes into entropy (base 2) return -sum(map(elog, probs))/log(base) def elog(x): # for entropy, 0 log 0 = 0. but we get an error for putting log 0 if x <= 0. or x >= 1.: return 0 else: return x*log(x) # Mixed estimators def micd(x, y, k=3, base=2, warning=True): """ If x is continuous and y is discrete, compute mutual information """ overallentropy = entropy(x, k, base) n = len(y) word_dict = dict() for sample in y: word_dict[sample] = word_dict.get(sample, 0) + 1./n yvals = list(set(word_dict.keys())) mi = overallentropy for yval in yvals: xgiveny = [x[i] for i in range(n) if y[i] == yval] if k <= len(xgiveny) - 1: mi -= word_dict[yval]*entropy(xgiveny, k, base) else: if warning: print("Warning, after conditioning, on y={0} insufficient data. Assuming maximal entropy in this case.".format(yval)) mi -= word_dict[yval]*overallentropy return mi # units already applied # Utility functions def vectorize(scalarlist): """ Turn a list of scalars into a list of one-d vectors """ return [(x,) for x in scalarlist] def shuffle_test(measure, x, y, z=False, ns=200, ci=0.95, **kwargs): """ Shuffle test Repeatedly shuffle the x-values and then estimate measure(x,y,[z]). Returns the mean and conf. interval ('ci=0.95' default) over 'ns' runs, 'measure' could me mi,cmi, e.g. Keyword arguments can be passed. Mutual information and CMI should have a mean near zero. """ xp = x[:] # A copy that we can shuffle outputs = [] for i in range(ns): random.shuffle(xp) if z: outputs.append(measure(xp, y, z, **kwargs)) else: outputs.append(measure(xp, y, **kwargs)) outputs.sort() return np.mean(outputs), (outputs[int((1.-ci)/2*ns)], outputs[int((1.+ci)/2*ns)]) # Internal functions def avgdigamma(points, dvec): # This part finds number of neighbors in some radius in the marginal space # returns expectation value of <psi(nx)> N = len(points) tree = ss.cKDTree(points) avg = 0. for i in range(N): dist = dvec[i] # subtlety, we don't include the boundary point, # but we are implicitly adding 1 to kraskov def bc center point is included num_points = len(tree.query_ball_point(points[i], dist-1e-15, p=float('inf'))) avg += digamma(num_points)/N return avg def zip2(*args): # zip2(x,y) takes the lists of vectors and makes it a list of vectors in a joint space # E.g. zip2([[1],[2],[3]],[[4],[5],[6]]) = [[1,4],[2,5],[3,6]] return [sum(sublist, []) for sublist in zip(*args)]
UltronAI/Deep-Learning
Pattern-Recognition/hw2-Feature-Selection/skfeature/utility/entropy_estimators.py
Python
mit
7,335
# -*- coding: utf-8 -*- import time from datetime import datetime from nose.tools import * # noqa (PEP8 asserts) import mock from dateutil import relativedelta from framework.auth import Auth from tests.base import OsfTestCase from tests.factories import UserFactory, ProjectFactory from website.addons.base import exceptions from website.addons.googledrive.client import GoogleAuthClient from website.addons.googledrive.model import ( GoogleDriveUserSettings, GoogleDriveNodeSettings, GoogleDriveOAuthSettings, GoogleDriveGuidFile, ) from website.addons.googledrive.tests.factories import ( GoogleDriveNodeSettingsFactory, GoogleDriveUserSettingsFactory, GoogleDriveOAuthSettingsFactory, ) class TestFileGuid(OsfTestCase): def setUp(self): super(OsfTestCase, self).setUp() self.user = UserFactory() self.project = ProjectFactory(creator=self.user) self.project.add_addon('googledrive', auth=Auth(self.user)) self.node_addon = self.project.get_addon('googledrive') self.node_addon.folder_id = 'Lulz' self.node_addon.folder_path = 'baz' self.node_addon.save() def test_path_doesnt_crash_without_addon(self): guid = GoogleDriveGuidFile(node=self.project, path='/baz/foo/bar') self.project.delete_addon('googledrive', Auth(self.user)) assert_is(self.project.get_addon('googledrive'), None) assert_true(guid.path) assert_true(guid.waterbutler_path) def test_path_doesnt_crash_nonconfig_addon(self): guid = GoogleDriveGuidFile(node=self.project, path='/baz/foo/bar') self.node_addon.folder_id = None self.node_addon.folder_path = None self.node_addon.save() self.node_addon.reload() assert_true(guid.path) assert_true(guid.waterbutler_path) def test_provider(self): assert_equal('googledrive', GoogleDriveGuidFile().provider) def test_correct_path(self): guid = GoogleDriveGuidFile(node=self.project, path='/baz/foo/bar') assert_equals(guid.path, '/baz/foo/bar') assert_equals(guid.waterbutler_path, '/foo/bar') @mock.patch('website.addons.base.requests.get') def test_unique_identifier(self, mock_get): mock_response = mock.Mock(ok=True, status_code=200) mock_get.return_value = mock_response mock_response.json.return_value = { 'data': { 'name': 'Morty', 'extra': { 'revisionId': 'Ricksy' } } } guid = GoogleDriveGuidFile(node=self.project, path='/foo/bar') guid.enrich() assert_equals('Ricksy', guid.unique_identifier) def test_node_addon_get_or_create(self): guid, created = self.node_addon.find_or_create_file_guid('/foo/bar') assert_true(created) assert_equal(guid.path, '/baz/foo/bar') assert_equal(guid.waterbutler_path, '/foo/bar') def test_node_addon_get_or_create_finds(self): guid1, created1 = self.node_addon.find_or_create_file_guid('/foo/bar') guid2, created2 = self.node_addon.find_or_create_file_guid('/foo/bar') assert_true(created1) assert_false(created2) assert_equals(guid1, guid2) def test_node_addon_get_or_create_finds_changed(self): self.node_addon.folder_path = 'baz' self.node_addon.save() self.node_addon.reload() guid1, created1 = self.node_addon.find_or_create_file_guid('/foo/bar') self.node_addon.folder_path = 'baz/foo' self.node_addon.save() self.node_addon.reload() guid2, created2 = self.node_addon.find_or_create_file_guid('/bar') assert_true(created1) assert_false(created2) assert_equals(guid1, guid2) def test_node_addon_get_or_create_finds_changed_root(self): self.node_addon.folder_path = 'baz' self.node_addon.save() self.node_addon.reload() guid1, created1 = self.node_addon.find_or_create_file_guid('/foo/bar') self.node_addon.folder_path = '/' self.node_addon.save() self.node_addon.reload() guid2, created2 = self.node_addon.find_or_create_file_guid('/baz/foo/bar') assert_true(created1) assert_false(created2) assert_equals(guid1, guid2) class TestGoogleDriveUserSettingsModel(OsfTestCase): def setUp(self): super(TestGoogleDriveUserSettingsModel, self).setUp() self.user = UserFactory() def test_fields(self): user_settings = GoogleDriveUserSettingsFactory() retrieved = GoogleDriveUserSettings.load(user_settings._primary_key) assert_true(retrieved.owner) assert_true(retrieved.username) assert_true(retrieved.expires_at) assert_true(retrieved.access_token) def test_has_auth(self): user_settings = GoogleDriveUserSettingsFactory(access_token=None) assert_false(user_settings.has_auth) user_settings.access_token = '12345' user_settings.save() assert_true(user_settings.has_auth) @mock.patch.object(GoogleDriveOAuthSettings, '_needs_refresh') def test_access_token_checks(self, mock_needs_refresh): mock_needs_refresh.return_value = False user_settings = GoogleDriveUserSettingsFactory() user_settings.access_token mock_needs_refresh.assert_called_once() @mock.patch.object(GoogleAuthClient, 'refresh') @mock.patch.object(GoogleDriveOAuthSettings, '_needs_refresh') def test_access_token_refreshes(self, mock_needs_refresh, mock_refresh): mock_refresh.return_value = { 'access_token': 'abc', 'refresh_token': '123', 'expires_at': time.time(), } user_settings = GoogleDriveUserSettingsFactory() user_settings.expires_at = datetime.now() user_settings.access_token mock_refresh.assert_called_once() @mock.patch.object(GoogleAuthClient, 'refresh') def test_access_token_refreshes_timeout(self, mock_refresh): mock_refresh.return_value = { 'access_token': 'abc', 'refresh_token': '123', 'expires_at': time.time(), } user_settings = GoogleDriveUserSettingsFactory() user_settings.expires_at = (datetime.utcnow() + relativedelta.relativedelta(seconds=5)) user_settings.access_token mock_refresh.assert_called_once() @mock.patch.object(GoogleAuthClient, 'refresh') def test_access_token_refreshes_timeout_longer(self, mock_refresh): mock_refresh.return_value = { 'access_token': 'abc', 'refresh_token': '123', 'expires_at': time.time(), } user_settings = GoogleDriveUserSettingsFactory() user_settings.expires_at = datetime.utcnow() + relativedelta.relativedelta(minutes=4) user_settings.access_token mock_refresh.assert_called_once() @mock.patch.object(GoogleAuthClient, 'refresh') def test_access_token_doesnt_refresh(self, mock_refresh): user_settings = GoogleDriveUserSettingsFactory() user_settings.save() user_settings.access_token assert_false(mock_refresh.called) def test_clear_clears_associated_node_settings(self): node_settings = GoogleDriveNodeSettingsFactory.build() user_settings = GoogleDriveUserSettingsFactory() node_settings.user_settings = user_settings node_settings.save() user_settings.clear() user_settings.save() # Node settings no longer associated with user settings assert_is(node_settings.folder_id, None) assert_is(node_settings.user_settings, None) def test_clear(self): node_settings = GoogleDriveNodeSettingsFactory.build() user_settings = GoogleDriveUserSettingsFactory(access_token='abcde') node_settings.user_settings = user_settings node_settings.save() assert_true(user_settings.access_token) user_settings.clear() user_settings.save() assert_false(user_settings.access_token) @mock.patch.object(GoogleDriveOAuthSettings, 'revoke_access_token') def test_clear_wo_oauth_settings(self, mock_revoke_access_token): user_settings = GoogleDriveUserSettingsFactory(access_token='abcde') user_settings.oauth_settings = None user_settings.save() node_settings = GoogleDriveNodeSettingsFactory.build() node_settings.user_settings = user_settings node_settings.save() assert_false(user_settings.oauth_settings) user_settings.clear() user_settings.save() assert_false(mock_revoke_access_token.called) def test_delete(self): user_settings = GoogleDriveUserSettingsFactory() assert_true(user_settings.has_auth) user_settings.delete() user_settings.save() assert_false(user_settings.access_token) assert_true(user_settings.deleted) def test_delete_clears_associated_node_settings(self): node_settings = GoogleDriveNodeSettingsFactory.build() user_settings = GoogleDriveUserSettingsFactory() node_settings.user_settings = user_settings node_settings.save() user_settings.delete() user_settings.save() # Node settings no longer associated with user settings assert_false(node_settings.deleted) assert_is(node_settings.folder_id, None) assert_is(node_settings.user_settings, None) class TestGoogleDriveNodeSettingsModel(OsfTestCase): def setUp(self): super(TestGoogleDriveNodeSettingsModel, self).setUp() self.user = UserFactory() self.user.add_addon('googledrive') self.user.save() self.user_settings = self.user.get_addon('googledrive') oauth_settings = GoogleDriveOAuthSettingsFactory() oauth_settings.save() self.user_settings.oauth_settings = oauth_settings self.user_settings.save() self.project = ProjectFactory() self.node_settings = GoogleDriveNodeSettingsFactory( user_settings=self.user_settings, owner=self.project, ) def test_fields(self): node_settings = GoogleDriveNodeSettings(user_settings=self.user_settings) node_settings.save() assert_true(node_settings.user_settings) assert_true(hasattr(node_settings, 'folder_id')) assert_true(hasattr(node_settings, 'folder_path')) assert_true(hasattr(node_settings, 'folder_name')) assert_equal(node_settings.user_settings.owner, self.user) def test_complete_true(self): assert_true(self.node_settings.has_auth) assert_true(self.node_settings.complete) def test_complete_false(self): self.node_settings.folder_id = None assert_true(self.node_settings.has_auth) assert_false(self.node_settings.complete) def test_complete_auth_false(self): self.node_settings.user_settings = None assert_false(self.node_settings.has_auth) assert_false(self.node_settings.complete) def test_folder_defaults_to_none(self): node_settings = GoogleDriveNodeSettings(user_settings=self.user_settings) node_settings.save() assert_is_none(node_settings.folder_id) assert_is_none(node_settings.folder_path) def test_has_auth(self): settings = GoogleDriveNodeSettings(user_settings=self.user_settings) settings.user_settings.access_token = None settings.save() assert_false(settings.has_auth) settings.user_settings.access_token = '123abc' settings.user_settings.save() assert_true(settings.has_auth) # TODO use this test if delete function is used in googledrive/model # def test_delete(self): # assert_true(self.node_settings.user_settings) # assert_true(self.node_settings.folder) # old_logs = self.project.logs # self.node_settings.delete() # self.node_settings.save() # assert_is(self.node_settings.user_settings, None) # assert_is(self.node_settings.folder, None) # assert_true(self.node_settings.deleted) # assert_equal(self.project.logs, old_logs) def test_deauthorize(self): assert_true(self.node_settings.folder_id) assert_true(self.node_settings.user_settings) self.node_settings.deauthorize(auth=Auth(self.user)) self.node_settings.save() assert_is(self.node_settings.folder_id, None) assert_is(self.node_settings.user_settings, None) last_log = self.project.logs[-1] params = last_log.params assert_in('node', params) assert_in('folder', params) assert_in('project', params) assert_equal(last_log.action, 'googledrive_node_deauthorized') def test_set_folder(self): folder_name = { 'id': '1234', 'name': 'freddie', 'path': 'queen/freddie', } self.node_settings.set_folder(folder_name, auth=Auth(self.user)) self.node_settings.save() # Folder was set assert_equal(self.node_settings.folder_name, folder_name['name']) # Log was saved last_log = self.project.logs[-1] assert_equal(last_log.action, 'googledrive_folder_selected') def test_set_user_auth(self): node_settings = GoogleDriveNodeSettingsFactory() user_settings = GoogleDriveUserSettingsFactory() node_settings.set_user_auth(user_settings) node_settings.save() assert_true(node_settings.has_auth) assert_equal(node_settings.user_settings, user_settings) # A log was saved last_log = node_settings.owner.logs[-1] log_params = last_log.params assert_equal(last_log.user, user_settings.owner) assert_equal(log_params['folder'], node_settings.folder_path) assert_equal(last_log.action, 'googledrive_node_authorized') assert_equal(log_params['node'], node_settings.owner._primary_key) def test_serialize_credentials(self): self.user_settings.access_token = 'secret' self.user_settings.save() credentials = self.node_settings.serialize_waterbutler_credentials() expected = {'token': self.node_settings.user_settings.access_token} assert_equal(credentials, expected) def test_serialize_credentials_not_authorized(self): self.node_settings.user_settings = None self.node_settings.save() with assert_raises(exceptions.AddonError): self.node_settings.serialize_waterbutler_credentials() def test_serialize_settings(self): self.node_settings.folder_path = 'camera uploads/pizza.nii' self.node_settings.save() settings = self.node_settings.serialize_waterbutler_settings() expected = { 'folder': { 'id': '12345', 'name': 'pizza.nii', 'path': 'camera uploads/pizza.nii', } } assert_equal(settings, expected) def test_serialize_settings_not_configured(self): self.node_settings.folder_id = None self.node_settings.save() with assert_raises(exceptions.AddonError): self.node_settings.serialize_waterbutler_settings() def test_create_log(self): action = 'file_added' path = '12345/camera uploads/pizza.nii' nlog = len(self.project.logs) self.node_settings.create_waterbutler_log( auth=Auth(user=self.user), action=action, metadata={'path': path}, ) self.project.reload() assert_equal(len(self.project.logs), nlog + 1) assert_equal( self.project.logs[-1].action, 'googledrive_{0}'.format(action), ) assert_equal(self.project.logs[-1].params['path'], path) class TestNodeSettingsCallbacks(OsfTestCase): def setUp(self): super(TestNodeSettingsCallbacks, self).setUp() # Create node settings with auth self.user_settings = GoogleDriveUserSettingsFactory(access_token='123abc', username='name/email') self.node_settings = GoogleDriveNodeSettingsFactory( user_settings=self.user_settings, folder='', ) self.project = self.node_settings.owner self.user = self.user_settings.owner def test_after_fork_by_authorized_googledrive_user(self): fork = ProjectFactory() clone, message = self.node_settings.after_fork( node=self.project, fork=fork, user=self.user_settings.owner ) assert_equal(clone.user_settings, self.user_settings) def test_after_fork_by_unauthorized_googledrive_user(self): fork = ProjectFactory() user = UserFactory() clone, message = self.node_settings.after_fork( node=self.project, fork=fork, user=user, save=True ) # need request context for url_for assert_is(clone.user_settings, None) def test_before_fork(self): node = ProjectFactory() message = self.node_settings.before_fork(node, self.user) assert_true(message) def test_before_remove_contributor_message(self): message = self.node_settings.before_remove_contributor( self.project, self.user) assert_true(message) assert_in(self.user.fullname, message) assert_in(self.project.project_or_component, message) def test_after_remove_authorized_googledrive_user_not_self(self): message = self.node_settings.after_remove_contributor( self.project, self.user_settings.owner) self.node_settings.save() assert_is_none(self.node_settings.user_settings) assert_true(message) assert_in("You can re-authenticate", message) def test_after_remove_authorized_googledrive_user_self(self): auth = Auth(user=self.user_settings.owner) message = self.node_settings.after_remove_contributor( self.project, self.user_settings.owner, auth) self.node_settings.save() assert_is_none(self.node_settings.user_settings) assert_true(message) assert_not_in("You can re-authenticate", message) def test_after_delete(self): self.project.remove_node(Auth(user=self.project.creator)) # Ensure that changes to node settings have been saved self.node_settings.reload() assert_true(self.node_settings.folder_id is None) assert_true(self.node_settings.folder_path is None) assert_true(self.node_settings.user_settings is None) def test_does_not_get_copied_to_registrations(self): registration = self.project.register_node( schema=None, auth=Auth(user=self.project.creator), template='Template1', data='hodor' ) assert_false(registration.has_addon('googledrive'))
himanshuo/osf.io
website/addons/googledrive/tests/test_models.py
Python
apache-2.0
19,128
""" Add an email alias entry command. """ from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.db import IntegrityError from django.core.exceptions import ValidationError from django.core.validators import validate_email from vmail.models import Domain, Alias HELP_TEXT = """ This will create an email aliases, forwarding address, or catch-all alias (@example.com) by adding an Alias entry with the given source and destination addresses. Neither the souce address, nor the destination address is required to be an existing MailUser. If --create-domain is used then the domain is also created if it does not exist. A virtual alias cannot receive mail, but may only forward mail to other email addresses. The source address may be repeated for each destination mailbox to forward to, and may also forward to a mailbox of the same address to keep a copy of an email. A source address may also be missing the name portion if the destination address is to be a catch-all mailbox. Source and destination addresses are not required to be local, and thus are not necessarily related to local virtual mailbox users. @example.org > john@example.org # catch-all alias john@example.org > john@example.org # keep a copy in local mailbox john@example.org > jeff@example.com # forward john to jeff """ class Command(BaseCommand): args = 'owner-domain source-address destination-address [--create-domain]' help = (HELP_TEXT) option_list = BaseCommand.option_list + ( make_option('--create-domain', action='store_true', dest='create_domain', default=False, help='Create the domain which will own the alias if it does not already exist.'), ) def handle(self, *args, **options): usage = 'Required arguments: source-address destination-address [--create-domain]' if len(args) != 3: raise CommandError(usage) fqdn = args[0].strip().lower() source = args[1].strip().lower() if fqdn.startswith('@'): fqdn = fqdn[1:] destination = args[2].strip().lower() try: validate_email(destination) except ValidationError: msg = 'Improperly formatted email address: {0}.'.format(destination) raise CommandError(msg) try: domain = Domain.objects.get(fqdn=fqdn) except Domain.DoesNotExist: if options['create_domain']: domain = Domain.objects.create(fqdn=fqdn) self.stdout.write('Created domain: {0}.\n'.format(str(domain))) else: raise CommandError("Domain '{0}', does not exist.".format(fqdn)) try: Alias.objects.create(domain=domain, source=source, destination=destination) except IntegrityError: raise CommandError('Alias exists already.') self.stdout.write('Success.\n')
lgunsch/django-vmail
vmail/management/commands/vmail-addalias.py
Python
mit
3,055
# Compute resource - Libvirt entities import pytest from nailgun import entities @pytest.fixture(scope="module") def module_cr_libvirt(module_org, module_location): return entities.LibvirtComputeResource( organization=[module_org], location=[module_location] ).create() @pytest.fixture(scope="module") def module_libvirt_image(module_cr_libvirt): return entities.Image(compute_resource=module_cr_libvirt).create()
JacobCallahan/robottelo
pytest_fixtures/component/provision_libvirt.py
Python
gpl-3.0
438
import logging from gettext import gettext as _ from typing import Tuple from aai_framework.dial import ColorTxt from .l_mount import ModulePartMountBase from .main import Options, vars_, POINT_EFI_ID logger = logging.getLogger(__name__) class Module(ModulePartMountBase): ID = POINT_EFI_ID @property def is_run(self) -> bool: return vars_.efi.is_mount def __init__(self): super().__init__() self.opti_ = Options(self.ID) self.conflicts.add(self) @property def name(self) -> str: return _('UEFI раздел') @property def menu_item(self) -> Tuple[str, str]: text = [self.opti_.partition, ColorTxt('(' + _('ВЫПОЛНЕНО') + ')').green.bold if self.is_run else ColorTxt('(' + _('ОБЯЗАТЕЛЬНО!!!') + ')').red.bold] return super().get_menu_item(text) @ModulePartMountBase.decor_can_not_perform def run(self) -> bool: ret = super().run() if ret: vars_.efi = self.opti_ vars_.efi.mount() return ret
AnTAVR/aai2
src/modules/part/m_mount_efi.py
Python
gpl-2.0
1,097
from bs4 import BeautifulSoup import datetime import parmed from pathlib import Path from urllib.request import Request, urlopen from urllib.error import URLError def dict_from_mmcif(mmcif, path=True): """Parse mmcif file into a dictionary. Notes ----- Full list of keys/value types, and further information on them can be viewed here: http://mmcif.wwpdb.org/docs/pdb_to_pdbx_correspondences.html All values in the returned dict are str or list(str). This means that some of the data values are string representations of integers - parse these outside of this function if desired. An alternative approach to this can be found in Biopython (via the function Bio.PDB.MMCIF2Dict.MMCIF2Dict). mmcif files are subject to the usual "here be dragons" problems of the PDB and difficult file formats. As such, this function is likely to be in a permanent state of flux as more dragons are found. Parameters ---------- mmcif : str mmcif string or a path to an mmcif file. path : bool True if mmcif is a path. Returns ------- cif_data : dict Keys are cif data names, e.g. '_struct_keywords.text'. Values are str or list(str). """ if path: with open(mmcif, 'r') as foo: lines = foo.readlines() else: lines = mmcif.splitlines() lines = [' '.join(x.strip().split()) for x in lines] # Some of the data in a .cif files are stored between 'loop_' to initiate a loop, and '#' to terminate it. # The variable 'loop' is a flag to keep track of this behaviour. loop = False # Set up the dictionary to populate as the lines of the .cif file are iterated over. cif_data = {} for i, line in enumerate(lines): if not line: continue # hash signifies end of a loop. Ensure loop flag is set to False. if line == '#': loop = False continue if not loop: # This line initiates a loop section, in which keys are listed first, # followed by lines of data in which the values are listed in the same order as the above keys. # The values in the loop section will be stored as lists - there are multiple values for one key. # An example of this type of data is the 'REVDAT' section, which stores details on the (potentially # numerous) various revisions made to the PDB file during its history. if line[:5] == 'loop_': loop = True key_list = [] continue # Lines beginning with '_' start with data names, i.e. keys in the cif_data dictionary. elif line[0] == '_': # If line consists only of a key, then subsequent lines may contain the associated value. if len(line.split()) == 1: current_key = line count = 1 while True: # Look forward until a key is found, keeping count of the number of lines in between. try: if lines[i + count][0] != '_': count += 1 # prevent infinite loop. elif i + count > len(lines): break else: if count > 1: try: cif_data[current_key] = ' '.join(lines[i + 1: i + count]) except IndexError: cif_data[current_key] = None else: cif_data[current_key] = None break except IndexError: break continue # Simplest case. Line is a key-value pair, with the key identified by its first character, '_'. elif len(line.split()) > 1: line = line.split() try: cif_data[line[0]] = ' '.join(line[1:]) except IndexError: cif_data[line[0]] = None continue # Line is one of multiple lines that are combined into a value in the while True: loop above. else: continue else: # Within a loop section, keys are identified by their first character '_'. # Add them to the list of keys in the loop. if line[0] == '_': if len(line.split()) == 1: key_list.append(line) if line not in cif_data.keys(): cif_data[line] = [] # Within a loop section, the values are listed within a single space-separated line in the same order # that the keys were listed at the start of the loop. else: # Cannot do a simple split if any of the values themselves are strings containing at least one space. if '\"' in line and line.count('\"') % 2 == 0: line_parts = [x.strip() for x in line.split('\"') if x] line = [] for part in line_parts: if line_parts.index(part) % 2 == 0: for x in part.split(): line.append(x) else: line.append(part) elif '\'' in line and line.count('\'') % 2 == 0: line = [x.strip() for x in line.split('\'') if x] elif len(key_list) == len(line.split()): line = line.split() if len(key_list) == len(line): for j, v in enumerate(line): cif_data[key_list[j]].append(line[j]) else: # CURRENTLY THERE IS A PROBLEM WITH REALLY LONG LOOPS eg _pdbx_refine_tls*, _pdbx_struct_oper_list* # The values span multiple lines, and therefore do not satisfy # the condition of the above 'if' statement. # A correction for this needs to keep track of the value count on subsequent lines, # until the 'if' condition is met. continue return cif_data def get_protein_dict(cif_data): """ Parse cif_data dict for a subset of its data. Notes ----- cif_data dict contains all the data from the .cif file, with values as strings. This function returns a more 'human readable' dictionary of key-value pairs. The keys have simpler (and still often more descriptive!) names, and the values are not restricted to being strings. To add more key-value pairs to the protein_dict, follow the patterns used in this function. Add the key and youre name for it to mmcif_data_names. Will it need further parsing, like with the dates in the function below? If the value is not a string, add it to a list of data-types at the end of the function. More information on what key-value pairs can be obtained can be gleaned by examining cif_data and/or by viewing the mmcif resource on the PDB website: http://mmcif.wwpdb.org/docs/pdb_to_pdbx_correspondences.html WARNING: Do not alter the keys of protein_dict without caution. The keys of protein_dict MUST match the column names of the Protein model in the protgraph database. Parameters ---------- cif_data : dict Key/value pairs taken directly from a .cif file. Output of the function dict_from_mmcif. Returns ------- protein_dict : dict A dictionary containing a parsed subset of the data in cif_data. The keys have the same name as fields in the Protein model. """ # Dictionary relating the keys of protein_dict (column names in Protein model) to the keys of cif_data. mmcif_data_names = { 'keywords': '_struct_keywords.text', 'header': '_struct_keywords.pdbx_keywords', 'space_group': '_symmetry.space_group_name_H-M', 'experimental_method': '_exptl.method', 'crystal_growth': '_exptl_crystal_grow.pdbx_details', 'resolution': '_refine.ls_d_res_high', 'r_value_obs': '_refine.ls_R_factor_obs', 'atoms_protein': '_refine_hist.pdbx_number_atoms_protein', 'atoms_solvent': '_refine_hist.number_atoms_solvent', 'atoms_ligand': '_refine_hist.pdbx_number_atoms_ligand', 'atoms_nucleic_acid': '_refine_hist.pdbx_number_atoms_nucleic_acid', 'atoms_total': '_refine_hist.number_atoms_total', 'title': '_struct.title', 'pdb_descriptor': '_struct.pdbx_descriptor', 'model_details': '_struct.pdbx_model_details', 'casp_flag': '_struct.pdbx_CASP_flag', 'model_type_details': '_struct.pdbx_model_type_details', 'ncbi_taxonomy': '_entity_src_nat.pdbx_ncbi_taxonomy_id', 'ncbi_taxonomy_gene': '_entity_src_gen.pdbx_gene_src_ncbi_taxonomy_id', 'ncbi_taxonomy_host_org': '_entity_src_gen.pdbx_host_org_ncbi_taxonomy_id', } # Set up initial protein_dict. protein_dict = {} for column_name, cif_name in mmcif_data_names.items(): try: data = cif_data[cif_name] except IndexError: data = None except KeyError: data = None protein_dict[column_name] = data # These entries are modified from the mmcif dictionary. # There may be many revision dates in cif_data. We save the original deposition, release and last_modified dates. # If there are many dates, they will be in a list in cif_data, otherwise it's one date in a string # Is there a tidier way to do this? if isinstance(cif_data['_database_PDB_rev.date_original'], str): protein_dict['deposition_date'] = cif_data['_database_PDB_rev.date_original'] else: protein_dict['deposition_date'] = cif_data['_database_PDB_rev.date_original'][0] if isinstance(cif_data['_database_PDB_rev.date'], str): protein_dict['release_date'] = cif_data['_database_PDB_rev.date'] protein_dict['last_modified_date'] = cif_data['_database_PDB_rev.date'] else: protein_dict['release_date'] = cif_data['_database_PDB_rev.date'][0] protein_dict['last_modified_date'] = cif_data['_database_PDB_rev.date'][-1] # crystal_growth should be a string or None crystal_growth = protein_dict['crystal_growth'] if type(crystal_growth) == list and len(crystal_growth) >= 1: protein_dict['crystal_growth'] = crystal_growth[0] else: protein_dict['crystal_growth'] = None # taxonomy data types should be ints, not lists taxonomy_keys = ['ncbi_taxonomy', 'ncbi_taxonomy_gene', 'ncbi_taxonomy_host_org'] for taxonomy_key in taxonomy_keys: if protein_dict[taxonomy_key]: if type(protein_dict[taxonomy_key]) == list: try: protein_dict[taxonomy_key] = int(protein_dict[taxonomy_key][0]) except ValueError or IndexError: protein_dict[taxonomy_key] = None # Convert data types from strings to their correct data type. ints = ['atoms_ligand', 'atoms_nucleic_acid', 'atoms_protein', 'atoms_solvent', 'atoms_total'] floats = ['r_value_obs', 'resolution'] dates = ['deposition_date', 'release_date', 'last_modified_date'] for k, v in protein_dict.items(): if v: if v == '?' or v == 'None' or v == '.': protein_dict[k] = None elif k in ints: protein_dict[k] = int(v) elif k in floats: protein_dict[k] = float(v) elif k in dates: protein_dict[k] = datetime.datetime.strptime(v, '%Y-%m-%d') # Parse awkward strings from cif_data. elif type(v) == str: v = v.replace('loop_', '') v = v.replace(' # ', '') if v[0] == v[-1] == '\'': protein_dict[k] = v[1:-1] return protein_dict def get_protein_dict_from_parmed(cif_file): s = parmed.formats.CIFFile.parse(cif_file, skip_bonds=True) protein_dict = { 'keywords': s.keywords, 'space group': s.space_group, 'experimental_method': s.experimental, 'resolution': s.resolution, 'atoms_total': len(s.atoms), 'title': s.title, 'journal': s.journal, 'authors': s.authors, 'journal_year': s.year, 'journal_volume': s.volume, 'journal_volume_page': s.volume_page, 'journal_page': s.page, 'doi': s.doi, } return protein_dict def parse_PISCES_output(pisces_output, path=False): """ Takes the output list of a PISCES cull and returns in a usable dictionary. Notes ----- Designed for outputs of protein sequence redundancy culls conducted using the PISCES server. http://dunbrack.fccc.edu/PISCES.php G. Wang and R. L. Dunbrack, Jr. PISCES: a protein sequence culling server. Bioinformatics, 19:1589-1591, 2003. Parameters ---------- pisces_output : str or path Output list of non-redundant protein chains from PISCES, or path to text file. path : bool True if path given rather than string. Returns ------- pisces_dict : dict Data output by PISCES in dictionary form. """ pisces_dict = {} if path: pisces_path = Path(pisces_output) pisces_content = pisces_path.read_text().splitlines()[1:] else: pisces_content = pisces_output.splitlines()[1:] for line in pisces_content: pdb = line.split()[0][:4].lower() chain = line.split()[0][-1] pdb_dict = {'length': line.split()[1], 'method': line.split()[2], 'resolution': line.split()[3], 'R-factor': line.split()[4], 'R-free': line.split()[5]} if pdb in pisces_dict: pisces_dict[pdb]['chains'].append(chain) else: pdb_dict['chains'] = [chain] pisces_dict[pdb] = pdb_dict return pisces_dict def download_decode(URL, encoding='utf-8', verbose=True): """ Downloads data from URL and returns decoded contents.""" if verbose: print("Downloading data from " + URL) req = Request(URL) try: with urlopen(req) as u: decoded_file = u.read().decode(encoding) except URLError as e: if hasattr(e, 'reason'): print('Server could not be reached.') print('Reason: ', e.reason) elif hasattr(e, 'code'): print('The server couldn\'t fulfill the request.') print('Error code: ', e.code) return None return decoded_file def olderado_best_model(pdb_id): """ Checks the Olderado web server and returns the most representative conformation for PDB NMR structures. Notes ----- Uses OLDERADO from the EBI. See http://www.ebi.ac.uk/pdbe/nmr/olderado/ and citations therein. Parameters ---------- pdb_id : str The 4-character PDB code for the NMR structure of interest. Returns ------- model_no : int The conformation number of the most-representative conformation. Raises ------ ValueError If the model number it finds is not an integer. This might indicate that the website format has changed. """ pdb_code = pdb_id[:4].lower() olderado_url = 'http://www.ebi.ac.uk/pdbe/nmr/olderado/searchEntry?pdbCode=' + pdb_code olderado_page = download_decode(olderado_url, verbose=False) if olderado_page: parsed_page = BeautifulSoup(olderado_page, 'html.parser') else: return None try: best_model = parsed_page.find_all('td')[1] except IndexError: print("No model info could be found for {0} - ensure that it's an NMR structure.".format(pdb_id)) return None try: model_no = int(best_model.string) except ValueError as v: print("Did not find a number for best model.") raise v return model_no __author__ = 'Jack W. Heal, Kieran L. Hudson'
woolfson-group/isambard
isambard/tools/file_parsing.py
Python
mit
16,437
import unittest from tests import count_prefix from functools import partial from collections import Counter from flaubert.preprocess import tokenizer_builder from flaubert.tokenize import RegexpFeatureTokenizer from pymaptools.utils import SetComparisonMixin FEATURES = [ 'CUSTOMTOKEN', 'CENSORED', 'EMPHASIS_B', 'EMPHASIS_U', 'TIMEOFDAY', 'DATE', 'EMOTIC_EAST_LO', 'EMOTIC_EAST_HI', 'EMOTIC_EAST_SAD', 'EMOTIC_WEST_L', 'EMOTIC_WEST_R', 'EMOTIC_WEST_CHEER', 'EMOTIC_WEST_L_MISC', 'EMOTIC_WEST_R_MISC', 'EMOTIC_RUSS_HAPPY', 'EMOTIC_RUSS_SAD', 'EMOTIC_HEART', 'CONTRACTION', 'STARRATING', 'STARRATING_FULL', 'STARRATING_X', 'MPAARATING', 'GRADE_POST', 'GRADE_PRE', 'THREED', 'DECADE', 'ASCIIARROW_R', 'ASCIIARROW_L', 'MNDASH', 'ABBREV1', 'ABBREV2', 'ABBREV3', 'ELLIPSIS', 'XOXO', 'PUNKT', 'ANYWORD'] class TestImdbTokens(unittest.TestCase, SetComparisonMixin): maxDiff = 2000 def setUp(self): TOKENIZER = tokenizer_builder(features=FEATURES) self.tokenizer = TOKENIZER self.tokenize = partial(TOKENIZER.tokenize, remove_stopwords=False) self.sentence_tokenize = TOKENIZER.sentence_tokenize self.base_tokenizer = RegexpFeatureTokenizer(features=FEATURES, debug=True) def test_preprocess(self): text = u"wow \u2014 such \u2013 doge" preprocessed = self.tokenizer.preprocess(text) self.assertEqual(u'wow --- such -- doge', preprocessed) def test_dashes(self): text = u"wow \u2014 such \u2013 doge -- and --- are dashes" counts = Counter(self.tokenize(text)) self.assertEqual(2, counts[u'--']) self.assertEqual(2, counts[u'---']) def test_censored(self): text = u"she's a b*tch in a f***d world" tokens = self.tokenize(text) self.assertSetContainsSubset([u'she', u"'s", u'b*tch', u'f***d'], tokens) def test_sentence_split_ellipsis(self): """ Make sure there is a sentence break after ellipsis Note: The sentence splitter we use does not treat ellipsis as a sentence terminator if the word after it is not capitalized. """ text = u"I had a feeling that after \"Submerged\", this one wouldn't " \ u"be any better... I was right." sentences = self.sentence_tokenize(text) self.assertEqual(2, len(sentences)) def test_sentence_split_br(self): """ Make sure there is a sentence break before "O.K." """ text = u'Memorable lines like: "You son-of-a-gun!", "You son-of-a-witch!",' \ u' "Shoot!", and "Well, Forget You!"<br /><br />O.K. Bye.' sentences = self.sentence_tokenize(text) joint = u' | '.join([u' '.join(sentence) for sentence in sentences]) self.assertIn(u' | o', joint) def test_western_emoticons_happy(self): """With custom features removed, this text should be idempotent on tokenization """ text = u":-) :) =) =)) :=) >:) :] :') :^) (: [: ((= (= (=: :-p :D :o" tokens = self.tokenize(text) reconstructed = u' '.join(token for token in tokens if not token.startswith(u"<EMOTIC")) self.assertEqual(text.lower(), reconstructed) group_names = [m.lastgroup for m in zip(*self.base_tokenizer.tokenize(text))[1]] self.assertEqual(len(tokens), count_prefix(u"EMOTIC", group_names)) def test_western_emoticons_sad(self): """With custom features removed, this text should be idempotent on tokenization """ text = u":-( :( =( =(( :=( >:( :[ :'( :^( ): ]: ))= )= )=: :-c :C :O :@ D:" tokens = self.tokenize(text) reconstructed = u' '.join(token for token in tokens if not token.startswith(u"<EMOTIC")) self.assertEqual(text.lower(), reconstructed) group_names = [m.lastgroup for m in zip(*self.base_tokenizer.tokenize(text))[1]] self.assertEqual(len(tokens), count_prefix(u"EMOTIC", group_names)) def test_western_emoticons_misc(self): """With custom features removed, this text should be idempotent on tokenization """ text = u":0 :l :s :x \o/ \m/" tokens = self.tokenize(text) self.assertSetContainsSubset([u':0', u':l', u':s', u':x', u'\o/', u'\m/'], tokens) def test_hearts(self): """With custom features removed, this text should be idempotent on tokenization """ text = u"<3 full heart </3 heartbreak" tokens = self.tokenize(text) reconstructed = u' '.join(token for token in tokens if not token.startswith(u"<EMOTIC")) self.assertEqual(text.lower(), reconstructed) group_names = [m.lastgroup for m in zip(*self.base_tokenizer.tokenize(text))[1]] self.assertSetContainsSubset([u'<3', u'<EMOTIC_HEART_HAPPY>', u'</3', u'<EMOTIC_HEART_SAD>'], tokens) self.assertEqual(len(tokens) - 3, count_prefix(u"EMOTIC", group_names)) def test_no_emoticon(self): """No emoticon should be detected in this text """ text = u"(8) such is the game): - (7 or 8) and also (8 inches)" \ u" and spaces next to parentheses ( space ) ." group_names = [m.lastgroup for m in zip(*self.base_tokenizer.tokenize(text))[1]] self.assertEqual(0, count_prefix(u"EMOTIC", group_names)) def test_eastern_emoticons(self): text = u"*.* (^_^) *_* *-* +_+ ~_~ -.- -__- -___- t_t q_q ;_; t.t q.q ;.;" tokens = self.tokenize(text) reconstructed = u' '.join(token for token in tokens if not (token.startswith(u"<") and token.endswith(u">"))) self.assertEqual(text, reconstructed) group_names = [m.lastgroup for m in zip(*self.base_tokenizer.tokenize(text))[1]] self.assertEqual(len(tokens), count_prefix(u"EMOTIC", group_names)) def test_russian_emoticons(self): text = u"haha! ))))) )) how sad ((" tokens = self.tokenize(text) reconstructed = u' '.join(tokens) self.assertEqual(u'haha ! ))) )) how sad ((', reconstructed) group_names = [m.lastgroup for m in zip(*self.base_tokenizer.tokenize(text))[1]] self.assertEqual(len(tokens) - 4, count_prefix(u"EMOTIC", group_names)) def test_ascii_arrow(self): text = u"Look here -->> such doge <<<" tokens = self.tokenize(text) self.assertSetContainsSubset( {'<ASCIIARROW_R>', '<ASCIIARROW_L>'}, tokens) def test_abbrev(self): text = u"S&P index of X-men in the U.S." tokens = self.tokenize(text) self.assertListEqual( [u's&p', u'index', u'of', u'x-men', u'in', u'the', u'u.s.'], tokens) def test_url_email(self): text = u"a dummy comment with http://www.google.com/ and sergey@google.com" tokens = self.tokenize(text) self.assertListEqual( [u'a', u'dummy', u'comment', u'with', u'<URI>', u'and', u'<EMAIL>'], tokens) def test_contraction(self): text = u"Daniel's life isn't great" tokens = self.tokenize(text) self.assertSetContainsSubset([u'daniel', u"'s", u'be', u"n't"], tokens) def test_contraction_lookalike(self): text = u"abr'acad'a'bra" tokens = self.tokenize(text) self.assertEqual(text, u"'".join(tokens)) def test_special_3d(self): text = u"3-d (3D) effect" tokens = self.tokenize(text) self.assertListEqual([u"<3D>", u"<3D>", u"effect"], tokens) def test_rating_false_0(self): text = u"I re-lived 1939/40 and my own evacuation from London" tokens = self.tokenize(text) self.assertSetContainsSubset([u'40'], tokens) def test_rating_false_1(self): text = u"Update: 9/4/07-I've now read Breaking Free" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<DATE>'], tokens) def test_rating_false_2(self): text = u"the humility of a 10 year old in cooking class" tokens = self.tokenize(text) self.assertSetContainsSubset([u'10'], tokens) def test_rating_0(self): text = u"My rating: 8.75/10----While most of this show is good" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<9/10>'], tokens) def test_rating_1(self): text = u"which deserves 11 out of 10," tokens = self.tokenize(text) self.assertSetContainsSubset([u'<11/10>'], tokens) def test_rating_2(self): text = u"I give this film 10 stars out of 10." tokens = self.tokenize(text) self.assertSetContainsSubset([u'<10/10>'], tokens) def test_rating_3(self): text = u"A must-see for fans of Japanese horror.10 out of 10." tokens = self.tokenize(text) self.assertSetContainsSubset([u'<10/10>'], tokens) def test_rating_4(self): text = u"a decent script.<br /><br />3/10" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<3/10>'], tokens) def test_rating_5(self): text = u"give it five stars out of ten" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<5/10>'], tokens) def test_rating_6(self): text = u"give it 3 1/2 stars out of five" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<7/10>'], tokens) def test_rating_7(self): text = u"give it ** 1/2 stars out of four" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<6/10>'], tokens) def test_rating_8(self): text = u"has been done so many times.. 7 of 10" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<7/10>'], tokens) def test_rating_9(self): text = u"has been done so many times.. 8 / 10" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<8/10>'], tokens) def test_rating_10(self): text = u"I give it a 7 star rating" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<7/10>'], tokens) def test_rating_11(self): text = u"Grade: * out of *****" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<2/10>'], tokens) def test_rating_12(self): text = u"Final Judgement: **/****" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<5/10>'], tokens) def test_rating_13(self): text = u'on March 18th, 2007.<br /><br />84/100 (***)' tokens = self.tokenize(text) self.assertSetContainsSubset([u'<8/10>'], tokens) def test_rating_14(self): text = u'I give it a full 10.' tokens = self.tokenize(text) self.assertSetContainsSubset([u'<10/10>'], tokens) def test_rating_15(self): text = u'I give it a -50 out of 10. MY GOD!!!!' tokens = self.tokenize(text) self.assertSetContainsSubset([u'<0/10>'], tokens) def test_rating_16(self): text = u"* * 1/2 / * * * *" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<6/10>'], tokens) def test_rating_17(self): text = u"i gave this movie a 2 for the actors" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<2/10>'], tokens) def test_grade_1(self): text = u"can save this boring, Grade B+ western." tokens = self.tokenize(text) self.assertSetContainsSubset([u'<GRADE_B+>'], tokens) def test_grade_2(self): text = u"can save this boring, Grade B western." tokens = self.tokenize(text) self.assertSetContainsSubset([u'<GRADE_B>'], tokens) def test_grade_3(self): text = u"My grade: F." tokens = self.tokenize(text) self.assertSetContainsSubset([u'<GRADE_F>'], tokens) def test_grade_4(self): text = u"mindless B-grade \"entertainment.\"" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<GRADE_B>'], tokens) def test_decade_1(self): text = u"Nice 1950s & 60s \"Americana\"" tokens = self.tokenize(text) self.assertSetContainsSubset( [u'nice', u'1950s', u'60s', u'americana'], tokens) def test_decade_2(self): text = u"Nice 1950s & 60's \"Americana\"" tokens = self.tokenize(text) self.assertSetContainsSubset( [u'nice', u'1950s', u'60s', u'americana'], tokens) def test_emphasis_star(self): text = u"@hypnotic I know *cries*" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<EMPHASIS_B>', u'cry'], tokens) def test_emphasis_underscore(self): text = u"I _hate_ sunblock" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<EMPHASIS_U>', u'hate'], tokens) def test_unescape(self): text = u"@artmeanslove I &lt;3 that book" tokens = self.tokenize(text) self.assertSetContainsSubset([u'<3', u'<EMOTIC_HEART_HAPPY>'], tokens)
escherba/flaubert
tests/test_imdb.py
Python
mit
12,987
#!/usr/bin/env python from socket import socket, AF_UNIX, SOCK_DGRAM from select import select from os import unlink, getcwd, stat from os.path import exists from os.path import relpath from sys import argv, exit def main(): if len(argv) < 2: print 'Usage: %s <socket name>' % argv[0] exit(1) sn = relpath(argv[1] + 'slocket', getcwd()) s = socket(AF_UNIX, SOCK_DGRAM) s.setblocking(False) try_unlink(sn) s.bind(sn) print 'listening on %r' % sn while not exists(relpath(argv[1] + '/slocket_listen_kill_flag', getcwd())): x,_,_ = select([s], [], [], 1.0) if len(x) > 0: x = x[0] y = x.recv(1024) print y print 'found slocket_listen_kill_flag... closing' s.close() try_unlink(sn) def try_unlink(sn): try: unlink(sn) except: pass if __name__ == '__main__': main()
yoshinorim/mysql-5.6
mysql-test/t/slocket_listen.py
Python
gpl-2.0
842
print(I play classical piano)
ledeprogram/algorithms
class1/homework/Kromrei_Georgia_1_1.py
Python
gpl-3.0
30
import boto3 import os import zipfile import glob import logging import shutil logger = logging.getLogger() logger.setLevel(logging.INFO) class S3CopyLogic: ### src - dict with Bucket and Key elements ### destination - dict with Bucket and Key elements ### def __init__(self, context, type, src, dst): self.context = context self.type = type self.src = src self.dst = dst self.local_filename = None self.local_download_path = f"/tmp/cache/{self.context.aws_request_id}" self.local_prefix_unzip = f"/tmp/cache/{self.context.aws_request_id}/unpacked" self.local_prefix = f"/tmp/cache/{self.context.aws_request_id}/upload" def copy(self): shutil.rmtree(self.local_download_path, ignore_errors=True) if self.type == 'object-zip': self.download_object_unpack_zip_upload() elif self.type == 'object': self.download_object_upload() elif self.type == 'sync': self.download_prefix_upload_prefix() else: raise f"{self.type} type not supported" def clean_destination(self): client = boto3.client('s3') bucket = boto3.resource('s3').Bucket(self.dst['Bucket']) resp = client.list_objects_v2(Bucket=self.dst['Bucket'], Prefix=self.dst['Prefix']) logger.info(resp) if resp['KeyCount'] > 0: # delete api allow deletion of multiple objects in single call bucket.delete_objects(Delete={'Objects': list(map(lambda x: {'Key': x['Key']}, resp['Contents']))}) while resp['IsTruncated']: resp = client.list_objects_v2(Bucket=self.dst['Bucket'], Prefix=self.dst['Prefix'], ContinuationToken=resp['NextContinuationToken']) bucket.delete_objects(Delete={'Objects': list(map(lambda x: {'Key': x['Key']}, resp['Contents']))}) def download_object_unpack_zip_upload(self): self.download_object() self.unpack_zip() self.upload(self.local_prefix_unzip) def download_object_upload(self): self.download_object() self.upload(self.local_download_path) def download_prefix_upload_prefix(self): self.download_prefix() self.upload(self.local_download_path) # Download whole bucket prefix def download_prefix(self): client = boto3.client('s3') bucket = boto3.resource('s3').Bucket(self.src['Bucket']) objects = [] resp = client.list_objects_v2(Bucket=self.src['Bucket'], Prefix=self.src['Prefix']) objects += map(lambda x: x['Key'], resp['Contents']) while resp['IsTruncated']: resp = client.list_objects_v2(Bucket=self.src['Bucket'], Prefix=self.src['Prefix'], ContinuationToken=resp['NextContinuationToken']) objects += map(lambda x: x['Key'], resp['Contents']) for object in objects: local_path = self.local_download_path + "/" local_path += object.replace(self.src['Prefix'], '') logger.info(f"s3://{self.src['Bucket']}/{object} -> {local_path}") os.makedirs(os.path.dirname(local_path), exist_ok=True) bucket.download_file(object, local_path) # Download S3 object to lambda /tmp under current request def download_object(self): local_filename = os.path.basename(self.src['Key']) self.local_filename = f"{self.local_download_path}/{local_filename}" os.makedirs(os.path.dirname(self.local_filename), exist_ok=True) s3 = boto3.resource('s3') logger.info(f"s3://{self.src['Bucket']}/{self.src['Key']} -> {self.local_filename}") s3.Bucket(self.src['Bucket']).download_file(self.src['Key'], self.local_filename) # Unpack downloaded zip archive def unpack_zip(self): os.makedirs(os.path.dirname(self.local_prefix_unzip), exist_ok=True) logger.info(f"Unpack {self.local_filename} to {self.local_prefix_unzip}") zip_ref = zipfile.ZipFile(self.local_filename, 'r') zip_ref.extractall(self.local_prefix_unzip) zip_ref.close() # Upload files to destination def upload(self, path): bucket = boto3.resource('s3').Bucket(self.dst['Bucket']) logger.info(f"Uploading from {path}") for local_path in glob.glob(f"{path}/**/*", recursive=True): if not os.path.isdir(local_path): destination_key = self.dst['Prefix'] if not destination_key[-1] == '/': destination_key += '/' destination_key += local_path.replace(f"{path}/", '') logger.info(f"{local_path} -> s3://{self.dst['Bucket']}/{destination_key}") bucket.upload_file(local_path, destination_key)
base2Services/cloudformation-custom-resouces
src/s3-copy/logic.py
Python
mit
5,000
import math import random def test(): tmp1 = [] tmp2 = [] print('build') for i in xrange(1024): tmp1.append(chr(int(math.floor(random.random() * 256)))) tmp1 = ''.join(tmp1) for i in xrange(1024): tmp2.append(tmp1) tmp2 = ''.join(tmp2) print(len(tmp2)) print('run') for i in xrange(5000): res = tmp2.encode('hex') test()
tassmjau/duktape
tests/perf/test-hex-encode.py
Python
mit
341
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): pass def backwards(self, orm): pass models = { } complete_apps = ['profiles']
halalaninitiative/polcat
profiles/migrations/0001_initial.py
Python
mit
317
from django import forms from django.utils.translation import ugettext_lazy as _ from oioioi.publicsolutions.utils import problem_instances_with_any_public_solutions class FilterPublicSolutionsForm(forms.Form): category = forms.ChoiceField(choices=[], label=_("Problem"), required=False) def __init__(self, request, *args, **kwargs): super(FilterPublicSolutionsForm, self).__init__(*args, **kwargs) pis = problem_instances_with_any_public_solutions(request).select_related( 'problem' ) choices = [(pi.id, pi) for pi in pis] choices.insert(0, ('', _("All"))) self.fields['category'].choices = choices
sio2project/oioioi
oioioi/publicsolutions/forms.py
Python
gpl-3.0
674
# coding: utf-8 """Test that longer and mixed texts are tokenized correctly.""" from __future__ import unicode_literals import pytest def test_tokenizer_handles_long_text(de_tokenizer): text = """Die Verwandlung Als Gregor Samsa eines Morgens aus unruhigen Träumen erwachte, fand er sich in seinem Bett zu einem ungeheueren Ungeziefer verwandelt. Er lag auf seinem panzerartig harten Rücken und sah, wenn er den Kopf ein wenig hob, seinen gewölbten, braunen, von bogenförmigen Versteifungen geteilten Bauch, auf dessen Höhe sich die Bettdecke, zum gänzlichen Niedergleiten bereit, kaum noch erhalten konnte. Seine vielen, im Vergleich zu seinem sonstigen Umfang kläglich dünnen Beine flimmerten ihm hilflos vor den Augen. »Was ist mit mir geschehen?«, dachte er.""" tokens = de_tokenizer(text) assert len(tokens) == 109 @pytest.mark.parametrize('text', [ "Donaudampfschifffahrtsgesellschaftskapitänsanwärterposten", "Rindfleischetikettierungsüberwachungsaufgabenübertragungsgesetz", "Kraftfahrzeug-Haftpflichtversicherung", "Vakuum-Mittelfrequenz-Induktionsofen" ]) def test_tokenizer_handles_long_words(de_tokenizer, text): tokens = de_tokenizer(text) assert len(tokens) == 1 @pytest.mark.parametrize('text,length', [ ("»Was ist mit mir geschehen?«, dachte er.", 12), ("“Dies frühzeitige Aufstehen”, dachte er, “macht einen ganz blödsinnig. ", 15) ]) def test_tokenizer_handles_examples(de_tokenizer, text, length): tokens = de_tokenizer(text) assert len(tokens) == length
aikramer2/spaCy
spacy/tests/lang/de/test_text.py
Python
mit
1,571
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import unittest from airflow.utils.weight_rule import WeightRule class TestWeightRule(unittest.TestCase): def test_valid_weight_rules(self): self.assertTrue(WeightRule.is_valid(WeightRule.DOWNSTREAM)) self.assertTrue(WeightRule.is_valid(WeightRule.UPSTREAM)) self.assertTrue(WeightRule.is_valid(WeightRule.ABSOLUTE)) self.assertEqual(len(WeightRule.all_weight_rules()), 3)
sid88in/incubator-airflow
tests/utils/test_weight_rule.py
Python
apache-2.0
1,224
from contextlib import contextmanager import inspect import multiprocessing import os import platform import subprocess import sys import urllib.parse ################################################################################ # # Shared configuration # ################################################################################ def join_flags(*flags): return ' '.join(flags).strip() if os.environ['PLATFORM_NAME'] in ('iphoneos', 'iphonesimulator'): building_for_ios = True else: assert os.environ['PLATFORM_NAME'] == 'macosx' building_for_ios = False assert os.environ['CURRENT_ARCH'] in os.environ['ARCHS'].split() build_arch = platform.machine() cross_building = building_for_ios or (os.environ['CURRENT_ARCH'] != build_arch) assert os.environ['GCC_VERSION'] == 'com.apple.compilers.llvm.clang.1_0' ar = os.environ['DT_TOOLCHAIN_DIR'] + '/usr/bin/ar' cc = os.environ['DT_TOOLCHAIN_DIR'] + '/usr/bin/clang' cxx = os.environ['DT_TOOLCHAIN_DIR'] + '/usr/bin/clang++' make = os.environ['DEVELOPER_DIR'] + '/usr/bin/make' rsync = '/usr/bin/rsync' xcodebuild = os.environ['DEVELOPER_DIR'] + '/usr/bin/xcodebuild' num_cores = str(multiprocessing.cpu_count()) common_flags = '-arch %(CURRENT_ARCH)s -isysroot %(SDKROOT)s' if building_for_ios: common_flags += ' -miphoneos-version-min=%(IPHONEOS_DEPLOYMENT_TARGET)s' else: common_flags += ' -mmacosx-version-min=%(MACOSX_DEPLOYMENT_TARGET)s' common_flags %= os.environ compile_flags = ('-g -Os -fexceptions -fvisibility=hidden ' + '-Werror=unguarded-availability ' + common_flags) if os.environ['ENABLE_BITCODE'] == 'YES': compile_flags += { 'bitcode': ' -fembed-bitcode', 'marker': ' -fembed-bitcode-marker', }.get(os.environ['BITCODE_GENERATION_MODE'], '') cflags = '-std=%(GCC_C_LANGUAGE_STANDARD)s' % os.environ cxxflags = ('-std=%(CLANG_CXX_LANGUAGE_STANDARD)s ' '-stdlib=%(CLANG_CXX_LIBRARY)s' % os.environ) link_flags = common_flags downloaddir = os.path.abspath('download') patchdir = os.path.abspath('patches') xcconfigdir = os.path.abspath('../build/xcode') builddir = os.path.join(os.environ['TARGET_TEMP_DIR'], os.environ['CURRENT_ARCH']) prefix = os.path.join(os.environ['BUILT_PRODUCTS_DIR'], os.environ['CURRENT_ARCH']) frameworksdir = prefix + '/Frameworks' includedir = prefix + '/include' libdir = prefix + '/lib' python_stdlib_dir = libdir + '/python' + os.environ['MW_PYTHON_3_VERSION'] ################################################################################ # # Build helpers # ################################################################################ all_builders = [] def builder(func): argspec = inspect.getfullargspec(func) defaults = dict(zip(argspec[0], argspec[3] or [])) if building_for_ios: if defaults.get('ios', True): all_builders.append(func) else: if defaults.get('macos', True): all_builders.append(func) return func def announce(msg, *args): sys.stderr.write((msg + '\n') % args) sys.stderr.flush() def check_call(args, **kwargs): announce('Running command: %s', ' '.join(repr(a) for a in args)) cmd = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, **kwargs) output = cmd.communicate()[0] if 0 != cmd.returncode: announce('Command exited with status %d and output:\n%s', cmd.returncode, output.decode()) sys.exit(1) @contextmanager def workdir(path): old_path = os.getcwd() announce('Entering directory %r', path) os.chdir(path) yield announce('Leaving directory %r', path) os.chdir(old_path) class DoneFileExists(Exception): pass @contextmanager def done_file(tag): filename = tag + '.done' if os.path.isfile(filename): raise DoneFileExists yield with open(filename, 'w') as fp: fp.write('Done!\n') def always_download_file(url, filepath): check_call(['/usr/bin/curl', '-#', '-L', '-f', '-o', filepath, url]) def download_file(url, filename): filepath = downloaddir + '/' + filename if os.path.isfile(filepath): announce('Already downloaded file %r', filename) else: always_download_file(url, filepath) def download_archive(url_path, filename): download_file(url_path + filename, filename) def download_archive_from_sf(path, version, filename): url = (('http://downloads.sourceforge.net/project/%s/%s/%s' '?use_mirror=autoselect') % (path, version, filename)) return download_file(url, filename) def make_directory(path): if not os.path.isdir(path): check_call(['/bin/mkdir', '-p', path]) def make_directories(*args): for path in args: make_directory(path) def remove_directory(path): if os.path.isdir(path): check_call(['/bin/rm', '-Rf', path]) def remove_directories(*args): for path in args: remove_directory(path) def unpack_tarfile(filename, outputdir): check_call(['/usr/bin/tar', 'xf', downloaddir + '/' + filename]) def unpack_zipfile(filename, outputdir): check_call([ '/usr/bin/unzip', '-q', downloaddir + '/' + filename, '-d', outputdir, ]) def apply_patch(patchfile, strip=1): with open(patchdir + '/' + patchfile) as fp: check_call( args = ['/usr/bin/patch', '-p%d' % strip], stdin = fp, ) def get_platform(arch): return '%s-apple-darwin' % { 'arm64': 'aarch64', }.get(arch, arch) def get_clean_env(): env = os.environ.copy() # The presence of these can break some build tools env.pop('IPHONEOS_DEPLOYMENT_TARGET', None) env.pop('MACOSX_DEPLOYMENT_TARGET', None) if cross_building: env.pop('SDKROOT', None) return env def run_b2(libraries, clean=False): b2_args = [ './b2', #'-d', '2', # Show actual commands run, '-j', num_cores, '--prefix=' + prefix, '--includedir=' + includedir, '--libdir=' + libdir, 'variant=release', 'optimization=space', 'debug-symbols=on', 'link=static', 'threading=multi', 'define=boost=mworks_boost', 'cflags=' + compile_flags, 'cxxflags=' + cxxflags, 'linkflags=' + link_flags, ] b2_args += ['--with-' + l for l in libraries] if clean: b2_args.append('--clean') else: b2_args.append('install') check_call(b2_args) def get_updated_env( extra_compile_flags = '', extra_cflags = '', extra_cxxflags = '', extra_ldflags = '', extra_cppflags = '', ): env = get_clean_env() env.update({ 'CC': cc, 'CXX': cxx, 'CFLAGS': join_flags(compile_flags, extra_compile_flags, cflags, extra_cflags), 'CXXFLAGS': join_flags(compile_flags, extra_compile_flags, cxxflags, extra_cxxflags), 'LDFLAGS': join_flags(link_flags, extra_ldflags), 'CPPFLAGS': join_flags(common_flags, extra_cppflags), }) return env def run_make(targets=[]): check_call([make, '-j', num_cores] + targets) def run_configure_and_make( extra_args = [], command = ['./configure'], extra_compile_flags = '', extra_cflags = '', extra_cxxflags = '', extra_ldflags = '', extra_cppflags = '', ): opts = [ '--prefix=' + prefix, '--includedir=' + includedir, '--libdir=' + libdir, '--disable-dependency-tracking', '--disable-shared', '--enable-static', '--build=' + get_platform(build_arch), ] if cross_building: opts.append('--host=' + get_platform(os.environ['CURRENT_ARCH'])) args = command + opts + extra_args if building_for_ios: # Even if the build and host architectures are the same, as they are # when we're building for iOS arm64 on a macOS arm64 (aka Apple # Silicon) system, we must run configure in cross-compilation mode in # order to build for iOS args.append('cross_compiling=yes') check_call( args = args, env = get_updated_env(extra_compile_flags, extra_cflags, extra_cxxflags, extra_ldflags, extra_cppflags), ) run_make(['install']) def add_object_files_to_libpythonall(exclude=()): object_files = [] for dirpath, dirnames, filenames in os.walk('.'): for name in filenames: if name.endswith('.o') and name not in exclude: object_files.append(os.path.join(dirpath, name)) check_call([ ar, 'rcs', libdir + ('/libpython%s_all.a' % os.environ['MW_PYTHON_3_VERSION']), ] + object_files) ################################################################################ # # Library builders # ################################################################################ @builder def libffi(): version = '3.4.2' srcdir = 'libffi-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://github.com/libffi/libffi/releases/download/v%s/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): run_configure_and_make( extra_args = ['--enable-portable-binary'], extra_cflags = '-std=gnu11', ) @builder def openssl(): version = '1.1.1m' srcdir = 'openssl-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://www.openssl.org/source/', tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): if building_for_ios: assert os.environ['CURRENT_ARCH'] == 'arm64' config_name = 'ios64-cross' else: config_name = 'darwin64-%s-cc' % os.environ['CURRENT_ARCH'] env = get_clean_env() env['AR'] = ar env['CC'] = cc check_call([ './Configure', config_name, '--prefix=' + prefix, 'no-shared', join_flags(compile_flags, cflags, '-std=gnu11'), ], env = env) run_make() run_make(['install_sw']) @builder def python(): version = '3.10.2' srcdir = 'Python-' + version tarfile = srcdir + '.tgz' assert version[:version.rfind('.')] == os.environ['MW_PYTHON_3_VERSION'] with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://www.python.org/ftp/python/%s/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): apply_patch('python_cross_build.patch') apply_patch('python_ctypes.patch') apply_patch('python_static_zlib.patch') if building_for_ios: apply_patch('python_ios_build.patch') apply_patch('python_ios_disabled_modules.patch') apply_patch('python_ios_fixes.patch') apply_patch('python_ios_private_api.patch') apply_patch('python_ios_test_fixes.patch') else: apply_patch('python_macos_11_0_required.patch') apply_patch('python_macos_disabled_modules.patch') apply_patch('python_macos_test_fixes.patch') with workdir(srcdir): extra_args = [ '--enable-optimizations', '--without-ensurepip', '--with-openssl=' + prefix, ] if cross_building: extra_args += [ '--enable-ipv6', 'PYTHON_FOR_BUILD=' + os.environ['MW_PYTHON_3'], 'ac_cv_file__dev_ptmx=no', 'ac_cv_file__dev_ptc=no', ] if not building_for_ios: # Set MACOSX_DEPLOYMENT_TARGET, so that the correct value is # recorded in the installed sysconfig data extra_args.append('MACOSX_DEPLOYMENT_TARGET=' + os.environ['MACOSX_DEPLOYMENT_TARGET']) run_configure_and_make( extra_args = extra_args, # This is required to keep numpy's extension module init funcs # public extra_compile_flags = '-fvisibility=default', ) add_object_files_to_libpythonall( exclude = ['_testembed.o', 'python.o'] ) # Generate list of trusted root certificates (for ssl module) always_download_file( url = 'https://mkcert.org/generate/', filepath = os.path.join(python_stdlib_dir, 'cacert.pem'), ) @builder def numpy(): version = '1.22.2' srcdir = 'numpy-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://github.com/numpy/numpy/releases/download/v%s/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): apply_patch('numpy_build.patch') apply_patch('numpy_test_fixes.patch') if building_for_ios: apply_patch('numpy_ios_fixes.patch') apply_patch('numpy_ios_test_fixes.patch') with workdir(srcdir): env = get_clean_env() env['PYTHONPATH'] = python_stdlib_dir # Don't use Accelerate, as it seems to make things worse rather # than better env['NPY_BLAS_ORDER'] = '' env['NPY_LAPACK_ORDER'] = '' if cross_building: env.update({ '_PYTHON_HOST_PLATFORM': 'darwin-%s' % os.environ['CURRENT_ARCH'], '_PYTHON_SYSCONFIGDATA_NAME': '_sysconfigdata__darwin_darwin', # numpy's configuration tests link test executuables using # bare cc (without cflags). Add common_flags to ensure that # linking uses the correct architecture and SDK. 'CC': join_flags(cc, common_flags) }) check_call([ os.environ['MW_PYTHON_3'], 'setup.py', 'build', '-j', num_cores, 'install', '--prefix=' + prefix, # Force egg info in to a separate directory. (Not sure why # including --root has this affect, but whatever.) '--root=/', ], env = env) add_object_files_to_libpythonall() # The numpy test suite requires hypothesis, pytest, and setuptools, so # install them and their dependencies (but outside of any standard # location, because we don't want to distribute them) check_call([ os.environ['MW_PYTHON_3'], '-m', 'pip', 'install', '--target', os.path.join(prefix, 'pytest'), 'hypothesis', 'pytest', 'setuptools', ]) @builder def boost(): version = '1.78.0' srcdir = 'boost_' + version.replace('.', '_') tarfile = srcdir + '.tar.bz2' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://boostorg.jfrog.io/artifactory/main/release/%s/source/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): os.symlink('boost', 'mworks_boost') env = get_clean_env() if cross_building: # SDKROOT must be set to compile the build system env['SDKROOT'] = subprocess.check_output([ '/usr/bin/xcrun', '--sdk', 'macosx', '--show-sdk-path', ]).strip() check_call([ './bootstrap.sh', '--with-toolset=clang', '--without-icu', '--without-libraries=python', ], env = env, ) with workdir(srcdir): libraries = ['filesystem', 'random', 'regex', 'thread'] if not building_for_ios: libraries += ['serialization'] run_b2(libraries) with workdir(includedir): if not os.path.islink('mworks_boost'): os.symlink('boost', 'mworks_boost') @builder def zeromq(): version = '4.3.4' srcdir = 'zeromq-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://github.com/zeromq/libzmq/releases/download/v%s/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): run_configure_and_make( extra_args = [ '--disable-silent-rules', '--disable-perf', '--disable-curve-keygen', '--disable-curve', ], extra_ldflags = '-lc++', ) @builder def msgpack(): version = '4.1.0' srcdir = 'msgpack-cxx-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://github.com/msgpack/msgpack-c/releases/download/cpp-%s/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): check_call([rsync, '-a', 'include/', includedir]) @builder def libxslt(macos=False): version = '1.1.34' srcdir = 'libxslt-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('ftp://xmlsoft.org/libxslt/', tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): run_configure_and_make( extra_args = [ '--disable-silent-rules', '--without-python', '--without-crypto', '--without-plugins', 'LIBXML_CFLAGS=-I%(SDKROOT)s/usr/include' % os.environ, 'LIBXML_LIBS=-L%(SDKROOT)s/usr/lib -lxml2' % os.environ, ], ) @builder def sqlite(): release_year = 2022 version = '3370200' # 3.37.2 srcdir = 'sqlite-autoconf-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://sqlite.org/%d/' % release_year, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): extra_compile_flags = '-DSQLITE_DQS=0' # Recommended as of 3.29.0 if building_for_ios: extra_compile_flags = join_flags(extra_compile_flags, '-DSQLITE_NOHAVE_SYSTEM') run_configure_and_make( extra_compile_flags = extra_compile_flags, ) @builder def libusb(ios=False): version = '1.0.25' srcdir = 'libusb-' + version tarfile = srcdir + '.tar.bz2' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('https://github.com/libusb/libusb/releases/download/v%s/' % version, tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): run_configure_and_make( extra_args = ['--disable-silent-rules'], extra_cflags = '-std=gnu11', ) @builder def cppunit(ios=False): version = '1.15.1' srcdir = 'cppunit-' + version tarfile = srcdir + '.tar.gz' with done_file(srcdir): if not os.path.isdir(srcdir): download_archive('http://dev-www.libreoffice.org/src/', tarfile) unpack_tarfile(tarfile, srcdir) with workdir(srcdir): run_configure_and_make( extra_compile_flags = '-g0', ) @builder def narrative(ios=False): version = '0.1.2' srcdir = 'Narrative-' + version zipfile = srcdir + '.zip' # Xcode will create a universal binary, so build only once if cross_building: return with done_file(srcdir): if not os.path.isdir(srcdir): download_archive_from_sf('narrative/narrative', urllib.parse.quote(srcdir.replace('-', ' ')), zipfile) unpack_zipfile(zipfile, srcdir) with workdir('/'.join([srcdir, srcdir, 'Narrative'])): check_call([ xcodebuild, '-project', 'Narrative.xcodeproj', '-configuration', 'Release', '-xcconfig', os.path.join(xcconfigdir, 'macOS.xcconfig'), 'clean', 'build', 'INSTALL_PATH=@loader_path/../Frameworks', 'OTHER_CFLAGS=-fno-objc-arc -fno-objc-weak -fvisibility=default', ]) check_call([ rsync, '-a', 'build/Release/Narrative.framework', frameworksdir ]) ################################################################################ # # Main function # ################################################################################ def main(): requested_builders = sys.argv[1:] builder_names = set(buildfunc.__name__ for buildfunc in all_builders) for name in requested_builders: if name not in builder_names: announce('ERROR: invalid builder: %r', name) sys.exit(1) make_directories(downloaddir, builddir) with workdir(builddir): for buildfunc in all_builders: if ((not requested_builders) or (buildfunc.__name__ in requested_builders)): try: buildfunc() except DoneFileExists: pass if not building_for_ios: # Install headers header_installdir = os.path.join(os.environ['MW_INCLUDE_DIR'], os.environ['CURRENT_ARCH']) make_directory(header_installdir) check_call([ rsync, '-a', '-m', '--exclude=ffi*.h', '--exclude=openssl/', includedir + '/', header_installdir, ]) # Install libraries lib_installdir = os.path.join(os.environ['MW_LIB_DIR'], os.environ['CURRENT_ARCH']) make_directory(lib_installdir) check_call([ rsync, '-a', '-m', '--exclude=cmake/', '--exclude=lib*.la', '--exclude=libcrypto.a', '--exclude=libffi.a', '--exclude=libpython*.a', '--exclude=libssl.a', '--exclude=pkgconfig/', '--exclude=python*/', libdir + '/', lib_installdir, ]) # Install frameworks if os.path.isdir(frameworksdir): check_call([ rsync, '-a', '-m', frameworksdir, os.environ['MW_DEVELOPER_DIR'], ]) if __name__ == '__main__': main()
mworks/mworks
supporting_libs/build_supporting_libs.py
Python
mit
24,217
#!/usr/bin/env python import sys import tensorflow as tf import numpy as np from numpy import genfromtxt import requests import csv from sklearn import datasets from sklearn.cross_validation import train_test_split import sklearn from scipy import stats import getopt from StringIO import StringIO import requests # Convert to one hot def convertOneHot(data): y=np.array([int(i[0]) for i in data]) y_onehot=[0]*len(y) for i,j in enumerate(y): y_onehot[i]=[0]*(y.max() + 1) y_onehot[i][j]=1 return (y,y_onehot) # find most common element def mode(arr) : m = max([arr.count(a) for a in arr]) return [x for x in arr if arr.count(x) == m][0] if m>1 else None def main(): # get data from arguments train=str(sys.argv[1]); test=str(sys.argv[2]); train = train.replace('\n',' \r\n') train = train.replace('n',' \r\n') test = test.replace('\n',' \r\n') test = test.replace('n',' \r\n') #print train #print test data = genfromtxt(StringIO(train),delimiter=',') # Training data test_data = genfromtxt(StringIO(test),delimiter=',') # Test data #print data #print test_data x_train=np.array([ i[1::] for i in data]) y_train,y_train_onehot = convertOneHot(data) x_test=np.array([ i[1::] for i in test_data]) y_test,y_test_onehot = convertOneHot(test_data) # A number of features, 5 in this cose (one per finger) # B = number of gesture possibilities A=data.shape[1]-1 # Number of features, Note first is y B=len(y_train_onehot[0]) tf_in = tf.placeholder("float", [None, A]) # Features tf_weight = tf.Variable(tf.zeros([A,B])) tf_bias = tf.Variable(tf.zeros([B])) tf_softmax = tf.nn.softmax(tf.matmul(tf_in,tf_weight) + tf_bias) # Training via backpropagation tf_softmax_correct = tf.placeholder("float", [None,B]) tf_cross_entropy = -tf.reduce_sum(tf_softmax_correct*tf.log(tf_softmax)) # Train using tf.train.GradientDescentOptimizer tf_train_step = tf.train.GradientDescentOptimizer(0.01).minimize(tf_cross_entropy) # Add accuracy checking nodes tf_correct_prediction = tf.equal(tf.argmax(tf_softmax,1), tf.argmax(tf_softmax_correct,1)) tf_accuracy = tf.reduce_mean(tf.cast(tf_correct_prediction, "float")) # Initialize and run init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) #print("...") # Run the training for i in range(6): sess.run(tf_train_step, feed_dict={tf_in: x_train, tf_softmax_correct: y_train_onehot}) #calculate accuracy from test data #result = sess.run(tf_accuracy, feed_dict={tf_in: x_test, tf_softmax_correct: y_test_onehot}) #print "Run {},{}".format(i,result) #make Prediction after training prediction=tf.argmax(tf_softmax,1) guess = prediction.eval(feed_dict={tf_in: x_test}, session=sess) # calculate most common gesture ID print int(stats.mode(guess)[0][0]) #r = requests.post("http://localhost:3000/api/receiveAnswer", data = {"prediction": int(stats.mode(guess)[0][0])}) return 0 if __name__ == "__main__": main()
yuriyminin/leap-gesture
machineLearning.py
Python
mit
3,079
from syn.base_utils import is_hashable #------------------------------------------------------------------------------- # is_hashable def test_is_hashable(): assert is_hashable(3) assert not is_hashable(dict(a = 3)) #------------------------------------------------------------------------------- if __name__ == '__main__': # pragma: no cover from syn.base_utils import run_all_tests run_all_tests(globals(), verbose=True, print_errors=False)
mbodenhamer/syn
syn/base_utils/tests/test_hash.py
Python
mit
463
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import importlib import locale import logging import os import sys import time import warnings from textwrap import dedent from pants.base.exiter import PANTS_FAILED_EXIT_CODE from pants.bin.pants_env_vars import ( DAEMON_ENTRYPOINT, IGNORE_UNRECOGNIZED_ENCODING, PANTSC_PROFILE, RECURSION_LIMIT, ) from pants.bin.pants_runner import PantsRunner from pants.util.contextutil import maybe_profiled class PantsLoader: """Initial entrypoint for pants. Executes a pants_runner by default, or executs a pantsd-specific entrypoint. """ @staticmethod def setup_warnings() -> None: # We want to present warnings to the user, set this up before importing any of our own code, # to ensure all deprecation warnings are seen, including module deprecations. # The "default" action displays a warning for a particular file and line number exactly once. # See https://docs.python.org/3/library/warnings.html#the-warnings-filter for the complete list. # # However, we do turn off deprecation warnings for libraries that Pants uses for which we do # not have a fixed upstream version, typically because the library is no longer maintained. warnings.simplefilter("default", category=DeprecationWarning) # TODO: Eric-Arellano has emailed the author to see if he is willing to accept a PR fixing the # deprecation warnings and to release the fix. If he says yes, remove this once fixed. warnings.filterwarnings("ignore", category=DeprecationWarning, module="ansicolors") # Silence this ubiquitous warning. Several of our 3rd party deps incur this. warnings.filterwarnings( "ignore", category=DeprecationWarning, message="Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated", ) @classmethod def ensure_locale(cls) -> None: """Ensure the locale uses UTF-8 encoding, or prompt for an explicit bypass.""" encoding = locale.getpreferredencoding() if ( encoding.lower() != "utf-8" and os.environ.get(IGNORE_UNRECOGNIZED_ENCODING, None) is None ): raise RuntimeError( dedent( f""" Your system's preferred encoding is `{encoding}`, but Pants requires `UTF-8`. Specifically, Python's `locale.getpreferredencoding()` must resolve to `UTF-8`. You can fix this by setting the LC_* and LANG environment variables, e.g.: LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 Or, bypass it by setting {IGNORE_UNRECOGNIZED_ENCODING}=1. Note that pants may exhibit inconsistent behavior if this check is bypassed. """ ) ) @staticmethod def run_alternate_entrypoint(entrypoint: str) -> None: try: module_path, func_name = entrypoint.split(":", 1) except ValueError: print( f"{DAEMON_ENTRYPOINT} must be of the form `module.path:callable`", file=sys.stderr ) sys.exit(PANTS_FAILED_EXIT_CODE) module = importlib.import_module(module_path) entrypoint_fn = getattr(module, func_name) try: entrypoint_fn() except TypeError: print(f"{DAEMON_ENTRYPOINT} {func_name} is not callable", file=sys.stderr) sys.exit(PANTS_FAILED_EXIT_CODE) @staticmethod def run_default_entrypoint() -> None: logger = logging.getLogger(__name__) with maybe_profiled(os.environ.get(PANTSC_PROFILE)): start_time = time.time() try: runner = PantsRunner(args=sys.argv, env=os.environ) exit_code = runner.run(start_time) except KeyboardInterrupt as e: print(f"Interrupted by user:\n{e}", file=sys.stderr) exit_code = PANTS_FAILED_EXIT_CODE except Exception as e: logger.exception(e) exit_code = PANTS_FAILED_EXIT_CODE sys.exit(exit_code) @classmethod def main(cls) -> None: cls.setup_warnings() cls.ensure_locale() sys.setrecursionlimit(int(os.environ.get(RECURSION_LIMIT, "10000"))) entrypoint = os.environ.pop(DAEMON_ENTRYPOINT, None) if entrypoint: cls.run_alternate_entrypoint(entrypoint) else: cls.run_default_entrypoint() def main() -> None: PantsLoader.main() if __name__ == "__main__": main()
benjyw/pants
src/python/pants/bin/pants_loader.py
Python
apache-2.0
4,812
"""Test pylint.extension.typing - consider-using-alias 'py-version' needs to be set to '3.7' or '3.8' and 'runtime-typing=no'. """ # pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long,unsubscriptable-object import collections import collections.abc import typing from collections.abc import Awaitable from dataclasses import dataclass from typing import Dict, List, Set, Union, TypedDict var1: typing.Dict[str, int] # [consider-using-alias] var2: List[int] # [consider-using-alias] var3: collections.abc.Iterable[int] var4: typing.OrderedDict[str, int] # [consider-using-alias] var5: typing.Awaitable[None] # [consider-using-alias] var6: typing.Iterable[int] # [consider-using-alias] var7: typing.Hashable # [consider-using-alias] var8: typing.ContextManager[str] # [consider-using-alias] var9: typing.Pattern[str] # [consider-using-alias] var10: typing.re.Match[str] # [consider-using-alias] var11: list[int] var12: collections.abc var13: Awaitable[None] var14: collections.defaultdict[str, str] Alias1 = Set[int] Alias2 = Dict[int, List[int]] Alias3 = Union[int, typing.List[str]] Alias4 = List # [consider-using-alias] def func1(arg1: List[int], /, *args: List[int], arg2: set[int], **kwargs: Dict[str, int]) -> typing.Tuple[int]: # -1:[consider-using-alias,consider-using-alias,consider-using-alias,consider-using-alias] pass def func2(arg1: list[int]) -> tuple[int, int]: pass class CustomIntList(typing.List[int]): pass cast_variable = [1, 2, 3] cast_variable = typing.cast(List[int], cast_variable) (lambda x: 2)(List[int]) class CustomNamedTuple(typing.NamedTuple): my_var: List[int] # [consider-using-alias] CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=List[int]) class CustomTypedDict2(TypedDict): my_var: List[int] # [consider-using-alias] @dataclass class CustomDataClass: my_var: List[int] # [consider-using-alias]
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/t/typing/typing_consider_using_alias_without_future.py
Python
mit
1,918
# -*- coding: utf-8 -*- # # Copyright (C) 2012-2015 bendikro bro.devel+yarss2@gmail.com # # This file is part of YaRSS2 and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # from twisted.trial import unittest from deluge.log import LOG import yarss2.util.common import yarss2.yarss_config from yarss2.rssfeed_handling import RSSFeedHandler import common class RSSFeedHandlingTestCase(unittest.TestCase): def setUp(self): # NOQA self.log = LOG self.rssfeedhandler = RSSFeedHandler(self.log) def test_get_rssfeed_parsed(self): file_url = yarss2.util.common.get_resource(common.testdata_rssfeed_filename, path="tests/") rssfeed_data = {"name": "Test", "url": file_url, "site:": "only used whith cookie arguments", "prefer_magnet": False} site_cookies = {"uid": "18463", "passkey": "b830f87d023037f9393749s932"} user_agent = "User_agent_test" parsed_feed = self.rssfeedhandler.get_rssfeed_parsed(rssfeed_data, site_cookies_dict=site_cookies, user_agent=user_agent) # When needing to dump the result in json format # common.json_dump(parsed_feed["items"], "freebsd_rss_items_dump2.json") self.assertTrue("items" in parsed_feed) items = parsed_feed["items"] stored_items = common.load_json_testdata() self.assertTrue(yarss2.util.common.dicts_equals(items, stored_items, debug=False)) self.assertEquals(sorted(parsed_feed["cookie_header"]['Cookie'].split("; ")), ['passkey=b830f87d023037f9393749s932', 'uid=18463']) self.assertEquals(parsed_feed["user_agent"], user_agent) def test_get_link(self): file_url = yarss2.util.common.get_resource(common.testdata_rssfeed_filename, path="tests/") from yarss2.lib.feedparser import feedparser parsed_feed = feedparser.parse(file_url) item = None for e in parsed_feed["items"]: item = e break # Item has enclosure, so it should use that link self.assertEquals(self.rssfeedhandler.get_link(item), item.enclosures[0]["href"]) del item["links"][:] # Item no longer has enclosures, so it should return the regular link self.assertEquals(self.rssfeedhandler.get_link(item), item["link"]) def test_get_size(self): file_url = yarss2.util.common.get_resource("t1.rss", path="tests/data/feeds/") from yarss2.lib.feedparser import feedparser parsed_feed = feedparser.parse(file_url) size = self.rssfeedhandler.get_size(parsed_feed["items"][0]) self.assertEquals(len(size), 1) self.assertEquals(size[0], (4541927915.52, u'4.23 GB')) size = self.rssfeedhandler.get_size(parsed_feed["items"][1]) self.assertEquals(len(size), 1) self.assertEquals(size[0], (402349096.96, u'383.71 MB')) size = self.rssfeedhandler.get_size(parsed_feed["items"][2]) self.assertEquals(len(size), 1) self.assertEquals(size[0], (857007476)) size = self.rssfeedhandler.get_size(parsed_feed["items"][3]) self.assertEquals(len(size), 2) self.assertEquals(size[0], (14353107637)) self.assertEquals(size[1], (13529146982.4, u'12.6 GB')) def get_default_rssfeeds_dict(self): match_option_dict = {} match_option_dict["regex_include"] = "" match_option_dict["regex_exclude"] = "" match_option_dict["regex_include_ignorecase"] = True match_option_dict["regex_exclude_ignorecase"] = True match_option_dict["custom_text_lines"] = None rssfeed_matching = {} rssfeed_matching["0"] = {"matches": False, "link": "", "title": "FreeBSD-9.0-RELEASE-amd64-all"} rssfeed_matching["1"] = {"matches": False, "link": "", "title": "FreeBSD-9.0-RELEASE-i386-all"} rssfeed_matching["2"] = {"matches": False, "link": "", "title": "fREEbsd-9.0-RELEASE-i386-all"} return match_option_dict, rssfeed_matching def test_update_rssfeeds_dict_matching(self): options, rssfeed_parsed = self.get_default_rssfeeds_dict() options["regex_include"] = "FreeBSD" matching, msg = self.rssfeedhandler.update_rssfeeds_dict_matching(rssfeed_parsed, options) self.assertEquals(len(matching.keys()), len(rssfeed_parsed.keys())) # Also make sure the items in 'matching' correspond to the matching items in rssfeed_parsed count = 0 for key in rssfeed_parsed.keys(): if rssfeed_parsed[key]["matches"]: self.assertTrue(key in matching, "The matches dict does not contain the matching key '%s'" % key) count += 1 self.assertEquals(count, len(matching.keys()), "The number of items in matches dict (%d) does not" " match the number of matching items (%d)" % (count, len(matching.keys()))) # Try again with regex_include_ignorecase=False options["regex_include_ignorecase"] = False matching, msg = self.rssfeedhandler.update_rssfeeds_dict_matching(rssfeed_parsed, options) self.assertEquals(len(matching.keys()), len(rssfeed_parsed.keys()) - 1) options["regex_exclude"] = "i386" matching, msg = self.rssfeedhandler.update_rssfeeds_dict_matching(rssfeed_parsed, options) self.assertEquals(len(matching.keys()), len(rssfeed_parsed.keys()) - 2) # Fresh options options, rssfeed_parsed = self.get_default_rssfeeds_dict() # Custom line with unicode characters, norwegian ø and å, as well as Latin Small Letter Lambda with stroke options["custom_text_lines"] = [u"Test line with æ and å, as well as ƛ"] options["regex_include"] = "æ" matching, msg = self.rssfeedhandler.update_rssfeeds_dict_matching(rssfeed_parsed, options) self.assertEquals(len(matching.keys()), 1) for key in matching.keys(): self.assertEquals(matching[key]["title"], options["custom_text_lines"][0]) self.assertEquals(matching[key]["regex_include_match"], (15, 17)) options["regex_include"] = "with.*ƛ" matching, msg = self.rssfeedhandler.update_rssfeeds_dict_matching(rssfeed_parsed, options) self.assertEquals(len(matching.keys()), 1) for key in matching.keys(): self.assertEquals(matching[key]["title"], options["custom_text_lines"][0]) self.assertEquals(matching[key]["regex_include_match"], (10, 39)) # Test exclude span options["regex_include"] = ".*" options["regex_exclude"] = "line.*å" matching, msg = self.rssfeedhandler.update_rssfeeds_dict_matching(rssfeed_parsed, options) for key in rssfeed_parsed.keys(): if not rssfeed_parsed[key]["matches"]: self.assertEquals(rssfeed_parsed[key]["title"], options["custom_text_lines"][0]) self.assertEquals(rssfeed_parsed[key]["regex_exclude_match"], (5, 24)) break def test_fetch_feed_torrents(self): config = common.get_test_config_dict() matche_result = self.rssfeedhandler.fetch_feed_torrents(config, "0") # 0 is the rssfeed key matches = matche_result["matching_torrents"] self.assertTrue(len(matches) == 3) def test_fetch_feed_torrents_custom_user_agent(self): config = common.get_test_config_dict() custom_user_agent = "TEST AGENT" config["rssfeeds"]["0"]["user_agent"] = custom_user_agent matche_result = self.rssfeedhandler.fetch_feed_torrents(config, "0") # 0 is the rssfeed key self.assertEquals(matche_result["user_agent"], custom_user_agent) def test_feedparser_dates(self): file_url = yarss2.util.common.get_resource("rss_with_special_dates.rss", path="tests/data/feeds/") from yarss2.lib.feedparser import feedparser parsed_feed = feedparser.parse(file_url) for item in parsed_feed['items']: # Some RSS feeds do not have a proper timestamp if 'published_parsed' in item: published_parsed = item['published_parsed'] import time test_val = time.struct_time((2014, 4, 10, 3, 44, 14, 3, 100, 0)) self.assertEquals(test_val, published_parsed) break def test_get_rssfeed_parsed_no_items(self): file_url = yarss2.util.common.get_resource("feed_no_items_issue15.rss", path="tests/data/feeds/") rssfeed_data = {"name": "Test", "url": file_url} parsed_feed = self.rssfeedhandler.get_rssfeed_parsed(rssfeed_data) self.assertTrue("items" not in parsed_feed) def test_get_rssfeed_parsed_datetime_no_timezone(self): file_url = yarss2.util.common.get_resource("rss_datetime_parse_no_timezone.rss", path="tests/data/feeds/") rssfeed_data = {"name": "Test", "url": file_url} parsed_feed = self.rssfeedhandler.get_rssfeed_parsed(rssfeed_data) self.assertTrue("items" in parsed_feed) # def test_test_feedparser_parse(self): # #file_url = yarss2.util.common.get_resource(common.testdata_rssfeed_filename, path="tests/") # from yarss2.lib.feedparser import feedparser # file_url = "" # parsed_feed = feedparser.parse(file_url, timeout=10) # item = None # for item in parsed_feed["items"]: # print "item:", type(item) # print "item:", item.keys() # #break # # Item has enclosure, so it should use that link # #self.assertEquals(self.rssfeedhandler.get_link(item), item.enclosures[0]["href"]) # #del item["links"][:] # # Item no longer has enclosures, so it should return the regular link # #self.assertEquals(self.rssfeedhandler.get_link(item), item["link"]) # # def test_test_get_rssfeed_parsed(self): # #file_url = "" # file_url = yarss2.util.common.get_resource("data/feeds/72020rarcategory_tv.xml", path="tests/") # rssfeed_data = {"name": "Test", "url": file_url, "site:": "only used whith cookie arguments", # "user_agent": None, "prefer_magnet": True} # site_cookies = {"uid": "18463", "passkey": "b830f87d023037f9393749s932"} # default_user_agent = self.rssfeedhandler.user_agent # parsed_feed = self.rssfeedhandler.get_rssfeed_parsed(rssfeed_data, site_cookies_dict=site_cookies) # print "parsed_feed:", parsed_feed.keys() # #print "items:", parsed_feed["items"] # for i in parsed_feed["items"]: # print parsed_feed["items"][i] # break # def test_download_link_with_equal_sign(self): # file_url = yarss2.util.common.get_resource("rss_with_equal_sign_in_link.rss", path="tests/data/") # from yarss2.lib.feedparser import feedparser # from yarss2.torrent_handling import TorrentHandler, TorrentDownload # rssfeed_data = {"name": "Test", "url": file_url, "site:": "only used whith cookie arguments"} # parsed_feed = self.rssfeedhandler.get_rssfeed_parsed(rssfeed_data, site_cookies_dict=None) # print "parsed_feed:", parsed_feed["items"] # Name: FreeBSD-9.0-RELEASE-amd64-all # Name: FreeBSD-9.0-RELEASE-i386-all # Name: FreeBSD-9.0-RELEASE-ia64-all # Name: FreeBSD-9.0-RELEASE-powerpc-all # Name: FreeBSD-9.0-RELEASE-powerpc64-all # Name: FreeBSD-9.0-RELEASE-sparc64-all # Name: FreeBSD-9.0-RELEASE-amd64-bootonly # Name: FreeBSD-9.0-RELEASE-amd64-disc1 # Name: FreeBSD-9.0-RELEASE-amd64-dvd1 # Name: FreeBSD-9.0-RELEASE-amd64-memstick # Name: FreeBSD-9.0-RELEASE-i386-bootonly # Name: FreeBSD-9.0-RELEASE-i386-disc1 # Name: FreeBSD-9.0-RELEASE-i386-dvd1 # Name: FreeBSD-9.0-RELEASE-i386-memstick # Name: FreeBSD-9.0-RELEASE-ia64-bootonly # Name: FreeBSD-9.0-RELEASE-ia64-memstick # Name: FreeBSD-9.0-RELEASE-ia64-release # Name: FreeBSD-9.0-RELEASE-powerpc-bootonly # Name: FreeBSD-9.0-RELEASE-powerpc-memstick # Name: FreeBSD-9.0-RELEASE-powerpc-release # Name: FreeBSD-9.0-RELEASE-powerpc64-bootonly # Name: FreeBSD-9.0-RELEASE-powerpc64-memstick # Name: FreeBSD-9.0-RELEASE-powerpc64-release # Name: FreeBSD-9.0-RELEASE-sparc64-bootonly # Name: FreeBSD-9.0-RELEASE-sparc64-disc1
bendikro/deluge-yarss-plugin
yarss2/tests/test_rssfeed_handling.py
Python
gpl-3.0
12,491
# -*- coding: utf-8 -*- import django.dispatch pre_syncdb = django.dispatch.Signal(providing_args=[])
cr8ivecodesmith/django-orm-extensions-save22
django_orm/signals.py
Python
bsd-3-clause
103
# CUPS Cloudprint - Print via Google Cloud Print # Copyright (C) 2011 Simon Cadman # # 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 cups import urllib import logging import sys sys.path.insert(0, ".") from printer import Printer from printermanager import PrinterManager from mockrequestor import MockRequestor from ccputils import Utils global requestors, printerManagerInstance def setup_function(function): # setup mock requestors global requestors requestors = [] # account without special chars mockRequestorInstance1 = MockRequestor() mockRequestorInstance1.setAccount('testaccount1') mockRequestorInstance1.printers = [] requestors.append(mockRequestorInstance1) # with @ symbol mockRequestorInstance2 = MockRequestor() mockRequestorInstance2.setAccount('testaccount2@gmail.com') mockRequestorInstance2.printers = [{'name': 'Save to Google Drive', 'id': '__test_save_docs', 'capabilities': [{'name': 'ns1:Colors', 'type': 'Feature'}]}, ] requestors.append(mockRequestorInstance2) # 1 letter mockRequestorInstance3 = MockRequestor() mockRequestorInstance3.setAccount('t') mockRequestorInstance3.printers = [] requestors.append(mockRequestorInstance3) # instantiate printer item if function != test_instantiate: test_instantiate() def teardown_function(function): global requestors requestors = None logging.shutdown() reload(logging) def test_parseURI(): global printerManagerInstance, requestors accountName, printerid = printerManagerInstance._getAccountNameAndPrinterIdFromURI( Utils.PROTOCOL + "testaccount2%40gmail.com/testid") assert printerid == "testid" assert accountName == "testaccount2@gmail.com" def test_parseLegacyURI(): global printerManagerInstance, requestors # 20140210 format account, printername, printerid, formatid = printerManagerInstance.parseLegacyURI( Utils.OLD_PROTOCOL + "printername/testaccount2%40gmail.com/", requestors) assert formatid == printerManagerInstance.URIFormat20140210 assert account == "testaccount2@gmail.com" assert printername == "printername" assert printerid is None # 20140307 format account, printername, printerid, formatid = printerManagerInstance.parseLegacyURI( Utils.OLD_PROTOCOL + "printername/testaccount2%40gmail.com/testid", requestors) assert formatid == printerManagerInstance.URIFormat20140307 assert account == "testaccount2@gmail.com" assert printername == "printername" assert printerid == "testid" # 20140308 format account, printername, printerid, formatid = printerManagerInstance.parseLegacyURI( Utils.OLD_PROTOCOL + "testaccount2%40gmail.com/testid", requestors) assert formatid == printerManagerInstance.URIFormat20140308 assert account == "testaccount2@gmail.com" assert printerid == "testid" assert printername is None # 20140621+ format account, printername, printerid, formatid = printerManagerInstance.parseLegacyURI( Utils.PROTOCOL + "testaccount2%40gmail.com/testid", requestors) assert formatid == printerManagerInstance.URIFormatLatest assert account == "testaccount2@gmail.com" assert printerid == "testid" assert printername is None def test_getPrinterIDByDetails(): printerid, requestor = printerManagerInstance.getPrinterIDByDetails( "testaccount2@gmail.com", "testid") assert printerid == "testid" assert isinstance(requestor, MockRequestor) assert requestor.getAccount() == 'testaccount2@gmail.com' # test fails printerid, requestor = printerManagerInstance.getPrinterIDByDetails( "accountthatdoesntexist", "testidthatdoesntexist") assert printerid is None assert requestor is None printerid, requestor = printerManagerInstance.getPrinterIDByDetails( "testaccount2@gmail.com", None) assert printerid is None assert requestor is None def test_getCUPSPrintersForAccount(): global printerManagerInstance, requestors foundprinters = printerManagerInstance.getCUPSPrintersForAccount( requestors[0].getAccount()) assert foundprinters == [] # total printer totalPrinters = 0 for requestor in requestors: totalPrinters += len(requestor.printers) fullprintersforaccount = printerManagerInstance.getPrinters(requestors[1].getAccount()) assert len(fullprintersforaccount) == len(requestors[1].printers) fullprinters = printerManagerInstance.getPrinters() assert len(fullprinters) == totalPrinters printers = printerManagerInstance.getPrinters() assert len(printers) == totalPrinters printer = printers[0] # get ppd ppdid = 'MFG:Google;DRV:GCP;CMD:POSTSCRIPT;DES:GoogleCloudPrint;MDL' connection = cups.Connection() ppds = connection.getPPDs(ppd_device_id=ppdid) printerppdname, printerppd = ppds.popitem() # test add printer to cups assert printerManagerInstance.addPrinter( printer['name'], printer, "test location", printerppdname) is not None foundprinters = printerManagerInstance.getCUPSPrintersForAccount( requestors[1].getAccount()) # delete test printer connection.deletePrinter(printerManagerInstance.sanitizePrinterName(printer['name'])) assert isinstance(foundprinters, list) assert len(foundprinters) == 1 assert isinstance(connection, cups.Connection) def test_getPrinter(): global requestors, printerManagerInstance assert printerManagerInstance.getPrinter('test', 'missingaccount') is None assert isinstance(printerManagerInstance.getPrinter( '__test_save_docs', requestors[1].getAccount()), Printer) assert printerManagerInstance.getPrinter('test', requestors[0].getAccount()) is None def test_instantiate(): global requestors, printerManagerInstance # verify adding single requestor works printerManagerInstance = PrinterManager(requestors[0]) assert printerManagerInstance.requestors[0] == requestors[0] assert len(printerManagerInstance.requestors) == 1 # verify adding whole array of requestors works printerManagerInstance = PrinterManager(requestors) assert printerManagerInstance.requestors == requestors assert len(printerManagerInstance.requestors) == len(requestors) def test_GetPrinterByURIFails(): global printerManagerInstance, requestors # ensure invalid account returns None/None printerIdNoneTest = printerManagerInstance.getPrinterByURI( Utils.PROTOCOL + 'testprinter/accountthatdoesntexist') assert printerIdNoneTest is None # ensure invalid printer on valid account returns None/None printerIdNoneTest = printerManagerInstance.getPrinterByURI( Utils.PROTOCOL + 'testprinter/' + urllib.quote(requestors[0].getAccount())) assert printerIdNoneTest is None def test_addPrinterFails(): global printerManagerInstance assert printerManagerInstance.addPrinter('', None, '') is False def test_invalidRequest(): testMock = MockRequestor() assert testMock.doRequest('thisrequestisinvalid') is None def test_printers(): global printerManagerInstance, requestors # test cups connection connection = cups.Connection() cupsprinters = connection.getPrinters() # total printer totalPrinters = 0 for requestor in requestors: totalPrinters += len(requestor.printers) # test getting printers for specific account printersforaccount = printerManagerInstance.getPrinters(requestors[1].getAccount()) assert len(printersforaccount) == len(requestors[1].printers) printers = printerManagerInstance.getPrinters() import re assert len(printers) == totalPrinters for printer in printers: # name assert isinstance(printer['name'], basestring) assert len(printer['name']) > 0 # account assert isinstance(printer.getAccount(), basestring) assert len(printer.getAccount()) > 0 # id assert isinstance(printer['id'], basestring) assert len(printer['id']) > 0 # test encoding and decoding printer details to/from uri uritest = re.compile( Utils.PROTOCOL + "(.*)/" + urllib.quote(printer['id'])) assert isinstance(printer.getURI(), basestring) assert len(printer.getURI()) > 0 assert uritest.match(printer.getURI()) is not None accountName, printerId = printerManagerInstance._getAccountNameAndPrinterIdFromURI( printer.getURI()) assert isinstance(accountName, basestring) assert isinstance(printerId, basestring) assert accountName == printer.getAccount() assert printerId == printer['id'] # get ppd ppdid = 'MFG:Google;DRV:GCP;CMD:POSTSCRIPT;DES:GoogleCloudPrint;MDL' ppds = connection.getPPDs(ppd_device_id=ppdid) printerppdname, printerppd = ppds.popitem() # test add printer to cups assert printerManagerInstance.addPrinter( printer['name'], printer, "test location", printerppdname) is not None testprintername = printerManagerInstance.sanitizePrinterName(printer['name']) # test printer actually added to cups cupsPrinters = connection.getPrinters() found = False for cupsPrinter in cupsPrinters: if (cupsPrinters[cupsPrinter]['printer-info'] == testprintername): found = True break assert found is True # delete test printer connection.deletePrinter(testprintername)
jjscarafia/CUPS-Cloud-Print
testing/test_printermanager.py
Python
gpl-3.0
10,477
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ## # ProblemConfig.py # This file is part of PyTest. # # PyTest # Python编写的OI评测器后端 # Copyright (C) 2011 CUI Hao # # 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: 崔灏 (CUI Hao) # Email: cuihao.leo@gmail.com ## import os import configparser as CP import sys import CompileFunctions import CheckFunctions import glob from ProblemClass import PyTest_Problem from PyTestError import ConfigSyntaxError import resource def LimitIt (cputime=None, mem=None): def retfunc (): if cputime: resource.setrlimit(resource.RLIMIT_CPU, (cputime,cputime)) if mem: resource.setrlimit(resource.RLIMIT_AS, (mem,mem)) return retfunc def Cfg2Prob (cfgfile): if not os.path.isfile(cfgfile): raise ConfigSyntaxError("文件未找到。", cfgfile) prob = PyTest_Problem() config = CP.ConfigParser() config.read(cfgfile) rootpath = os.path.dirname(os.path.abspath(cfgfile)) sys.path.append(rootpath) # Section Info if config.has_section("Info"): prob.Name = config["Info"].get("Name", "Unnamed") prob.Info = config["Info"].get("Info", "") # Section Source if config.has_section("Source"): mod = config["Source"].get("ImportModule", "") func = config["Source"].get("Compile") try: prob.Compile = getattr(__import__(mod), func) except (ImportError, AttributeError, ValueError): prob.Compile = getattr(CompileFunctions, func) for gl in config["Source"].get("Require", "").split(): prob.Require.append(gl) # Section Input inp = [] if config.has_section("Input"): for ep, path in config["Input"].items(): for index, f in enumerate(sorted(glob.glob(os.path.join(rootpath, path)))): try: inp[index][ep] = f except IndexError: inp.append({ep:f}) # Section Output oup = [] if config.has_section("Output"): for ep, path in config["Output"].items(): for index, f in enumerate(sorted(glob.glob(os.path.join(rootpath, path)))): try: oup[index][ep] = f except IndexError: oup.append({ep:f}) for i, o in zip(inp, oup): prob.AddData(i, o) # Section Execute cputime = mem = None if config.has_section("Execute"): try: cputime = \ config["Execute"].getfloat("TimeLimitSec", 0.0) except ValueError: raise ConfigSyntaxError \ ("数字不可识别。", cfgfile, "Execute", "TimeLimitSec", config["Execute"].get("TimeLimitSec")) try: mem = \ config["Execute"].getfloat("MemoryLimitKB", 0.0)*1024 except ValueError: raise ConfigSyntaxError \ ("数字不可识别。", cfgfile, "Execute", "MemoryLimitKB", config["Execute"].get("MemoryLimitKB")) prob.PreExec = LimitIt(cputime, mem) # Section Check if config.has_section("Check"): mod = config["Check"].get("ImportModule", "") func = config["Check"].get("Function") prob.CheckFactor = config["Check"].getfloat("Factor", 1.0) try: prob.CheckFunc = getattr(__import__(mod), func) except (ImportError, AttributeError, ValueError): prob.CheckFunc = getattr(CheckFunctions, func) return prob
cuihaoleo/PyTest
ProblemConfig.py
Python
gpl-3.0
4,291
# # Class of object containing current test state # __copyright__ = """ Copyright (C) 2014 Red Hat, Inc. All Rights Reserved. Written by David Howells (dhowells@redhat.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public Licence version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public Licence for more details. You should have received a copy of the GNU General Public Licence along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from tool_box import * from remount_union import remount_union import sys, os, errno from stat import * from enum import IntEnum # None value is for lower class upper(IntEnum): META=1 DATA=2 class inode: def __init__(self, filetype, symlink_val=None, symlink_to=None): assert(filetype != None) assert(filetype != "s" or symlink_val) self.__filetype = filetype self.__symlink_val = symlink_val self.__symlink_to = symlink_to def filetype(self): return self.__filetype def sym_val(self): return self.__symlink_val def sym_target(self): return self.__symlink_to class dentry: def __init__(self, name, inode=None, root=False, layer=None, on_upper=None): self.__name = name self.__parent = None self.created(inode, layer, on_upper) # By default created objects are pure upper def created(self, inode, layer, on_upper=upper.DATA): self.__i = inode self.__failed_create = False self.__children = dict() self.__is_dir = inode and inode.filetype() == "d" self.__layer = layer self.__upper = on_upper self.__rename_exdev = not on_upper def failed_to_create(self): if self.__i == None: self.__failed_create = True def clear(self): assert(self.__i != None) self.__i = None self.__children = dict() def name(self): return self.__name def filename(self): if self.__parent == None: return "" return self.__parent.filename() + "/" + self.__name def inode(self): return self.__i def filetype(self): if self.__i: return self.__i.filetype() return None def is_negative(self): return self.__i == None def parent(self): return self.__parent def add_child(self, child): assert(child != None) if self.is_dir(): self.__children[child.__name] = child child.__parent = self return child def look_up_child(self, name): if self.is_dir() and name in self.__children: return self.__children[name] return self.add_child(dentry(name, None)) def children(self): return self.__children.values() def unlink_child(self, child): assert(self.is_dir()) assert(self.__children[child.__name] == child) del self.__children[child.__name] child.__parent = None def unlink(self): if self.parent(): self.parent().unlink_child(self) def did_create_fail(self): return self.__failed_create def copied_up(self, layer, copy_up=upper.META): if not self.__upper or layer != self.__layer or self.__upper < copy_up: self.__layer = layer self.__upper = copy_up def replace_with(self, src): old_parent = src.parent() new_parent = self.parent() miss = dentry(src.__name, None, layer = src.__layer, on_upper = src.__upper) old_parent.unlink_child(src) old_parent.add_child(miss) src.__name = self.__name new_parent.unlink_child(self) new_parent.add_child(src) def on_upper(self, layer): if self.__layer != layer: return None return self.__upper def data_on_upper(self, layer): return self.__layer == layer and self.__upper == upper.DATA def layer(self): if self.__upper: return "upper/" + str(self.__layer) return "lower" def is_dir(self): return self.__is_dir def is_reg(self): return self.__i.filetype() == "r" def is_sym(self): return self.__i and self.__i.filetype() == "s" def sym_val(self): return self.__i.sym_val() def sym_target(self): return self.__i.sym_target() def is_neg_or_sym_to_neg(self): if self.is_negative(): return True return self.is_sym() and self.sym_target().is_neg_or_sym_to_neg() def is_reg_or_sym_to_reg(self): if self.__i.filetype() == "r": return True if not self.is_sym(): return False if self.sym_target().is_negative(): return False return self.sym_target().is_reg_or_sym_to_reg() def is_dir_or_sym_to_dir(self): if self.__i.filetype() == "d": return True if not self.is_sym(): return False if self.sym_target().is_negative(): return False return self.sym_target().is_dir_or_sym_to_dir() def get_exdev_on_rename(self): return self.__rename_exdev ############################################################################### # # The main test context # ############################################################################### class test_context: def __init__(self, cfg, termslash=False, direct_mode=False, recycle=False, max_layers=0): self.__cfg = cfg self.__root = dentry("/", inode("d"), root=True) self.__cwd = None self.__filenr = 99 self.__layers_nr = 0 self.__max_layers = max_layers self.__lower_layers = None self.__lower_fs = None self.__upper_layer = None self.__upper_fs = None self.__upper_dir_fs = None self.__upper_file_fs = None self.__verbose = cfg.is_verbose() self.__direct_mode = direct_mode self.__skip_layer_test = cfg.testing_none() self.__same_dev = cfg.is_fusefs() or cfg.is_samefs() or cfg.is_xino() if cfg.is_nested(): # The only nested overlay configuration where all files are on # the same st_dev is when lower overlay is samefs (--samefs), so it # does not use high ino bits for layer fsid AND the nested overlay # has xino enabled (--xino) self.__same_dev = cfg.is_samefs() and cfg.is_xino() self.__termslash = "" self.__recycle = recycle if termslash: self.__termslash = "/" def config(self): return self.__cfg def direct_mode(self): return self.__direct_mode def is_verbose(self): return self.__verbose def verbose(self, *args): if self.__verbose: for i in args: sys.stdout.write(str(i)) def verbosef(self, formatstr, *args): if self.__verbose: sys.stdout.write(formatstr.format(*args)) def output(self, *args): for i in args: sys.stdout.write(str(i)) def outputf(self, formatstr, *args): sys.stdout.write(formatstr.format(*args)) def error(self, *args): sys.stderr.write(program_name + ": ") for i in args: sys.stderr.write(str(i)) sys.exit(1) def errorf(self, formatstr, *args): error(formatstr.format(*args)) def lstat_file(self, path): if path.endswith("/"): path = path[:len(path) - 1] self.verbose("os.lstat(", path, ")\n") return os.lstat(path) def is_whiteout(self, path): st = self.lstat_file(path) return S_ISCHR(st.st_mode) and st.st_rdev == 0 def get_dev_id(self, path): return self.lstat_file(path).st_dev def get_file_ino(self, path): return self.lstat_file(path).st_ino def get_file_size(self, path): return self.lstat_file(path).st_size def get_file_blocks(self, path): return self.lstat_file(path).st_blocks def get_file_atime(self, path): return self.lstat_file(path).st_atime def get_file_mtime(self, path): return self.lstat_file(path).st_mtime # Save device ID for lower fs def note_lower_fs(self, path): self.__lower_fs = self.get_dev_id(path) def lower_fs(self): return self.__lower_fs # Save device IDs for upper fs def note_upper_fs(self, path, dirpath, filepath): self.__upper_fs = self.get_dev_id(path) self.__upper_dir_fs = self.get_dev_id(dirpath) self.__upper_file_fs = self.get_dev_id(filepath) def note_upper_layer(self, path): self.__upper_layer = path def note_lower_layers(self, lowerlayers): self.__lower_layers = lowerlayers def lower_layers(self): return self.__lower_layers def upper_layer(self): return self.__upper_layer def layers_nr(self): return self.__layers_nr def have_more_layers(self): return self.__layers_nr < self.__max_layers def have_more_fs(self): # /upper is same fs as /lower if maxfs < 0 # /upper/N are all same fs (/upper) if maxfs == 0 # /upper/N where N < maxfs are unique fs # /upper/N where N >= maxfs are same fs (/upper) return self.__layers_nr < self.config().maxfs() def curr_layer(self): return str(self.__layers_nr) def next_layer(self): if not self.have_more_layers(): return self.curr_layer() self.__layers_nr += 1 return str(self.__layers_nr) def upper_fs(self): return self.__upper_fs def upper_dir_fs(self): return self.__upper_dir_fs def upper_file_fs(self): return self.__upper_file_fs def skip_layer_test(self): return self.__skip_layer_test def same_dev(self): return self.__same_dev # Display the banner beginning the test def begin_test(self, source, nr, name): ix = source.rfind("/") if ix >= 0: source = source[ix + 1:] msg="TEST " + source + ":" + str(nr) + ": " + name + "\n" self.output(msg) if self.is_verbose(): write_kmsg(msg); self.__filenr += 1 # Increment the test fileset number def incr_filenr(self): self.__filenr += 1 # Get path relative to basedir # Returns None if basedir is not a prefix of path def rel_path(self, path, basedir): l = len(basedir) if len(path) < l or path[:l] != basedir: return None return path[l:] # Get upper path from union path def upper_path(self, path): relpath = self.rel_path(path, self.config().union_mntroot()) if relpath is None: raise TestError(path + ": not on union mount") return self.__upper_layer + relpath # Get various filenames def gen_filename(self, name): return "{:s}/{:s}{:d}".format(self.config().testdir(), name, self.__filenr) def no_file(self): return self.gen_filename("no_foo") def pointless(self): return self.gen_filename("pointless") def reg_file(self): return self.gen_filename("foo") def direct_sym(self): return self.gen_filename("direct_sym") def indirect_sym(self): return self.gen_filename("indirect_sym") def no_dir(self): return self.gen_filename("no_dir") def empty_dir(self): return self.gen_filename("empty") def non_empty_dir(self): return self.gen_filename("dir") def direct_dir_sym(self): return self.gen_filename("direct_dir_sym") def indirect_dir_sym(self): return self.gen_filename("indirect_dir_sym") def rootfile(self): return self.gen_filename("rootfile") # Get various symlink contents def gen_symlink_val(self, filename): (parent, dentry) = self.pathwalk(filename + str(self.__filenr), no_follow=True) assert(dentry.is_sym()) return dentry.sym_val() def pointless_val(self): return self.gen_symlink_val("pointless") def direct_sym_val(self): return self.gen_symlink_val("direct_sym") def indirect_sym_val(self): return self.gen_symlink_val("indirect_sym") def direct_dir_sym_val(self): return self.gen_symlink_val("direct_dir_sym") def indirect_dir_sym_val(self): return self.gen_symlink_val("indirect_dir_sym") # Determine whether there should be a terminal slash def termslash(self): return self.__termslash ########################################################################### # # File state cache # ########################################################################### # Walk over a symlink def pathwalk_symlink(self, cursor, symlink, remnant_filename, args): if symlink in args["symlinks"]: if remnant_filename == "": fake_dentry = dentry(symlink.name()) fake_dentry.failed_to_create() return (cursor, fake_dentry) raise TestError(args["orig_filename"] + ": Recursive symlink") args["symlinks"].add(symlink) content = symlink.sym_val() if content.startswith("/"): cursor = self.__root return self.pathwalk_one(cursor, content + remnant_filename, args) # Walk over the last component of a path def pathwalk_last(self, cursor, filename, args): name = filename if name == ".": return (cursor.parent(), cursor) if name == "..": return (cursor.parent().parent(), cursor.parent()) to = cursor.look_up_child(name) if to.is_negative(): pass elif to.is_sym() and not args["no_follow"]: return self.pathwalk_symlink(cursor, to, "", args) return (cursor, to) # Walk over an intermediate component of a path def pathwalk_one(self, cursor, filename, args): filename = filename.lstrip("/") slash = filename.find("/") if slash == -1: # The tail gets treated differently for nofollow purposes args["parent"] = cursor return self.pathwalk_last(cursor, filename, args) name = filename[:slash] if name == ".": return self.pathwalk_one(cursor, filename[slash:], args) if name == "..": return self.pathwalk_one(cursor.parent(), filename[slash:], args) to = cursor.look_up_child(name) if to.is_sym(): return self.pathwalk_symlink(cursor, to, filename[slash:], args) if to.is_dir(): return self.pathwalk_one(to, filename[slash:], args) if to.is_negative(): if not args["missing_ok"]: raise TestError(to.filename() + ": Missing intermediate path component") # Running awkward tests requires that we tell the kernel to walk # non-directories and directories that don't exist. return self.pathwalk_one(to, filename[slash:], args) # Walk over a path. Returns a tuple of (parent, target). def pathwalk(self, filename, **args): assert(filename) if self.direct_mode(): cursor = dentry(filename) return (cursor, cursor) args["symlinks"] = set() args["orig_filename"] = filename if "no_follow" not in args: args["no_follow"] = False if "dir_fd" not in args: args["dir_fd"] = None if "missing_ok" not in args: args["missing_ok"] = False if filename.startswith("/"): cursor = self.__root elif args["dir_fd"] != None: cursor = args["dir_fd"] else: cursor = self.__cwd return self.pathwalk_one(cursor, filename.rstrip("/"), args) # Record a file's type ("r", "s", "d", None) and symlink target record def record_file(self, filename, filetype, symlink_val=None, symlink_to=None, layer=None, on_upper=None): if filetype == None: i = None else: i = inode(filetype, symlink_val, symlink_to) (parent, dentry) = self.pathwalk(filename, missing_ok=True) dentry.created(i, layer, on_upper) return dentry # Change base directory def set_cwd(self, filename): (parent, target) = self.pathwalk(filename) self.__cwd = target # Recursively delete a tree def rmtree_aux(self, cursor): f = cursor.filename() if cursor.is_dir(): for i in cursor.children(): self.rmtree_aux(i) self.verbosef("os.rmdir({:s})\n", f) os.rmdir(f) try: self.verbosef("os.rmdir({:s})\n", f) os.rmdir(f) except FileNotFoundError: pass elif not cursor.is_negative(): self.verbosef("os.unlink({:s})\n", f) os.unlink(f) try: self.verbosef("os.unlink({:s})\n", f) os.unlink(f) except FileNotFoundError: pass def rmtree(self, filename): self.output("- rmtree ", filename, "\n") self.check_layer(filename) (parent, target) = self.pathwalk(filename) self.rmtree_aux(target) parent.unlink_child(target) self.check_layer(filename) # Check that ino has not changed due to copy up or mount cycle def check_dev_ino(self, filename, dentry, dev, ino, layer, recycle): # Skip the persistent ino check for directory if lower and upper are not using same st_dev if not self.same_dev() and dentry.is_dir() and recycle: return # Skip the check if upper was rotated to lower if layer != self.layers_nr(): return # Compare st_dev/st_ino before copy up / mount cycle to current st_dev/st_ino ino2 = self.get_file_ino(filename) dev2 = self.get_dev_id(filename) if ino != ino2 or (dev != dev2 and not recycle): if dev2 != self.upper_dir_fs() and dev2 != self.upper_file_fs(): raise TestError(filename + ": inode number changed on copy up, but not on upper/union layer") if self.config().is_verify(): raise TestError(filename + ": inode number/layer changed on copy up (got " + str(dev2) + ":" + str(ino2) + ", was " + str(dev) + ":" + str(ino) + ")") # Check that file/data was/not copied up as expected def check_copy_up(self, filename, dentry, layer, blocks): upper_path = self.upper_path(filename) try: upper_blocks = self.get_file_blocks(upper_path) except (FileNotFoundError, NotADirectoryError): if dentry.on_upper(layer): raise TestError(upper_path + ": Upper file is missing") return if not dentry.on_upper(layer): # Directory could have been copied up recursively and we didn't mark it's dentry on_upper if dentry.is_dir() or self.is_whiteout(upper_path): return raise TestError(upper_path + ": Upper file unexpectedly found") if not dentry.is_reg(): return # Metacopy should have st_blocks coming from lowerdata, so upper blocks # should be zero. This check may give false positives with metacopy=on # and upper file whose st_blocks > 0 when xattrs are not stored in inode if self.config().is_metacopy() and not dentry.data_on_upper(layer): if upper_blocks != 0: raise TestError(upper_path + ": Metacopy file blocks non-zero (" + str(upper_blocks) + ")") # Wanted to compare upper_blocks to block, but that test fails sometimes # on xfs because st_blocks can be observed larger than actual blocks for # a brief time after copy up, because of delalloc blocks on the inode # beyond EOF due to speculative preallocation. And sometimes the value # of st_blocks from first stat() did not match the value from second stat() elif bool(upper_blocks) != bool(blocks): raise TestError(upper_path + ": Upper file blocks missmatch (" + str(upper_blocks) + " != " + str(blocks) + ")") ########################################################################### # # Layer check operation # ########################################################################### def check_layer(self, filename, dir_fd=None, symlinks=set()): if self.direct_mode(): return (parent, dentry) = self.pathwalk(filename, no_follow=True, dir_fd=dir_fd, missing_ok=True) name = dentry.filename() try: dev = self.get_dev_id(name) blocks = self.get_file_blocks(name) except (FileNotFoundError, NotADirectoryError): if not dentry.is_negative(): raise TestError(name + ": File is missing") return if dentry.is_negative(): raise TestError(name + ": File unexpectedly found") #self.output("- check_layer ", dentry.filename(), " -", dentry.layer(), " # ", dev, "\n") if self.skip_layer_test(): return layer = self.layers_nr() if self.config().is_verify(): self.check_copy_up(name, dentry, layer, blocks) if dentry.is_dir(): # Directory inodes are always on overlay st_dev if dev != self.upper_dir_fs(): raise TestError(name + ": Directory not on union layer") elif dev == self.lower_fs(): # For non-directory inodes, overlayfs returns pseudo st_dev, # upper st_dev or overlay st_dev, but never the lower fs st_dev if self.config().is_verify(): raise TestError(name + ": File unexpectedly on lower fs") elif dev == self.upper_fs() and dev != self.upper_file_fs(): # Overlayfs used to return upper fs st_dev for pure upper, but now # returns pseduo st_dev for pure upper and never the upper fs st_dev raise TestError(name + ": File unexpectedly on upper fs") elif self.same_dev(): # With samefs or xino setup, all files are on overlay st_dev. if dev != self.upper_dir_fs(): raise TestError(name + ": File not on union layer") else: # With non samefs setup, files are on pseudo st_dev. if self.config().is_nested() and self.config().is_xino(): # Special case: we do not consider nested/non-samefs/xino # as "samedev" because all files from the lower overlay layer # have xino bits overflow and fallback to non-samefs behavior. # But the files from layers on the same fs as upper layer, # do not overflow xino bits and are using overlay st_dev. pass elif dev == self.upper_dir_fs(): raise TestError(name + ": File unexpectedly on union layer") else: # Whether or not dentry.on_upper(), st_dev could be from # lower layer pseudo st_dev, in case upper has origin, # so there is nothing left for us to check here. # TODO: record lower_file_fs() after clean mount on a sample # lower file and check here that dev == self.lower_file_fs() # or dev == self.upper_file_fs() pass if dentry.is_sym() and dentry not in symlinks: symlinks.add(dentry) self.check_layer(dentry.sym_val(), dir_fd=parent, symlinks=symlinks) ########################################################################### # # Open a file operation # ########################################################################### def open_file(self, filename, **args): filename = filename.replace("//", "/") self.check_layer(filename) line = "" flags = 0 rd = False wr = False if "ro" in args: line += " -r" rd = True elif "rw" in args: line += " -r -w" rd = True wr = True elif "wo" in args: line += " -w" wr = True elif "app" in args: wr = True else: raise RuntimeError("One or both of -r and -w must be supplied to open_file") if "app" in args: flags |= os.O_APPEND line += " -a" wr = True layer = self.layers_nr() copy_up = None if rd and wr: flags |= os.O_RDWR copy_up = upper.DATA elif rd: flags |= os.O_RDONLY else: flags |= os.O_WRONLY copy_up = upper.DATA create = False if "dir" in args: line += " -d" flags |= os.O_DIRECTORY if "crt" in args: line += " -c" flags |= os.O_CREAT create = True if "ex" in args: line += " -e" flags |= os.O_EXCL if "tr" in args: line += " -t" flags |= os.O_TRUNC copy_up = upper.DATA mode = 0 if "mode" in args: mode = args["mode"] line += " -m " + str(mode) if "read" in args: line += " -R " + args["read"] if "write" in args: line += " -W " + args["write"] if "err" not in args: args["err"] = None want_error = args["err"] missing_ok = (want_error==errno.ENOENT) or create (parent, dentry) = self.pathwalk(filename, missing_ok=missing_ok) # Determine the error we might expect. This is complicated by the fact # that we have to automatically change the error if we expect a failure # due to a path with a terminal slash. # # Further, it's possible to get EXDEV on renaming a directory that # mirrors an underlying directory. # if dentry.get_exdev_on_rename() and "xerr" in args and not self.__skip_layer_test: args["err"] = args["xerr"] if filename.endswith("/"): if not dentry.is_negative(): if create: args["err"] = errno.EISDIR elif dentry.is_dir_or_sym_to_dir(): pass else: args["err"] = errno.ENOTDIR elif dentry.is_negative(): if create: args["err"] = errno.EISDIR elif dentry.did_create_fail(): args["err"] = errno.ENOENT if "as_bin" in args: line += " -B" want_error = args["err"] if want_error: line += " -E " + errno.errorcode[want_error] self.output(" ./run --open-file ", filename, line, "\n") # Open the file try: if "as_bin" in args: self.verbosef("os.setegid(1)") os.setegid(1) self.verbosef("os.seteuid(1)") os.seteuid(1) self.verbosef("os.open({:s},{:x},{:o})\n", filename, flags, mode) fd = os.open(filename, flags, mode) if "as_bin" in args: self.verbosef("os.seteuid(0)") os.seteuid(0) self.verbosef("os.setegid(0)") os.setegid(0) if want_error: raise TestError(filename + ": Expected error (" + os.strerror(want_error) + ") was not produced") if not self.direct_mode(): if dentry.is_negative(): if not create: raise TestError(filename + ": File was created without O_CREAT") dentry.created(inode("f"), layer) else: if copy_up: dentry.copied_up(layer, copy_up) except OSError as oe: if "as_bin" in args: self.verbosef("os.seteuid(0)") os.seteuid(0) self.verbosef("os.setegid(0)") os.setegid(0) actual = os.strerror(oe.errno) if not want_error: raise TestError(filename + ": Unexpected error: " + actual) wanted = os.strerror(want_error) if want_error != oe.errno: raise TestError(filename + ": Unexpected error (expecting " + wanted + "): " + actual) fd = None if create: dentry.failed_to_create() self.check_layer(filename) # Write the data to it, if any if fd != None and "write" in args: data = args["write"].encode() self.verbose("os.write(", fd, ",", data, ")\n"); res = os.write(fd, data) l = len(data) if res != l: raise TestError(filename + ": File write length incorrect (" + str(res) + " != " + str(l) + ")") # Read the contents back from it and compare if requested if fd != None and "read" in args: data = args["read"].encode() l = len(data) self.verbose("os.fstat(", fd, ")\n"); st = os.fstat(fd) if st.st_size != l: raise TestError(filename + ": File size wrong (got " + str(st.st_size) + ", want " + str(l) + ")") self.verbose("os.lseek(", fd, ",0,0)\n"); os.lseek(fd, 0, os.SEEK_SET) self.verbose("os.read(", fd, ",", l, ")\n"); content = os.read(fd, l) if len(content) != l: raise TestError(filename + ": File read length incorrect (" + str(len(content)) + " != " + str(l) + ")") if content != data: raise TestError(filename + ": File contents differ (expected '" + data.decode() + "', got '" + content.decode() + "')") if fd != None: self.verbose("os.close(", fd, ")\n"); os.close(fd) self.check_layer(filename) # Open a directory def open_dir(self, filename, **args): self.open_file(filename, dir=1, **args) ########################################################################### # # Determine the error that should be produced for a single-filename # function that doesn't create the file where the filename has an incorrect # slash appended. # # Pass to vfs_op_prelude() with guess=guess1_error # ########################################################################### def guess1_error(self, dentry, has_ts, dentry2, has_ts2): if not has_ts: return None if dentry.is_negative(): return errno.ENOENT if dentry.is_sym(): return errno.ENOTDIR if dentry.is_reg_or_sym_to_reg(): return errno.ENOTDIR return None ########################################################################### # # Determine the error that should be produced for a single-filename # function that doesn't create the file where the filename has an incorrect # slash appended. # # Pass to vfs_op_prelude() with guess=guess1_error_create # ########################################################################### def guess1_error_create(self, dentry, has_ts, dentry2, has_ts2): if not has_ts: return None if not dentry.is_negative(): if dentry.is_sym(): return errno.ENOTDIR elif dentry.is_reg_or_sym_to_reg(): return errno.EISDIR elif dentry.is_negative(): return errno.EISDIR return None ########################################################################### # # VFS Operation common bits # ########################################################################### def vfs_op_prelude(self, line, filename, args, filename2=None, no_follow=True, guess=None, create=False): line = line.replace("//", "/") if "follow" in args: no_follow = False if "no_follow" in args: no_follow = True if "err" not in args: args["err"] = None want_error = args["err"] missing_ok = filename2 == None and ((want_error != None) or create) filename = filename.replace("//", "/") (parent, dentry) = self.pathwalk(filename, no_follow=no_follow, missing_ok=missing_ok) has_ts=filename.endswith("/") if filename2 != None: filename2 = filename2.replace("//", "/") (parent2, dentry2) = self.pathwalk(filename2, no_follow=no_follow, missing_ok=True) has_ts2=filename.endswith("/") else: parent2 = None dentry2 = None has_ts2 = None # Determine the error we might expect. This is complicated by the fact # that we have to automatically change the error if we expect a failure # due to a path with a terminal slash. # # Further, it's possible to get EXDEV on renaming a directory that # mirrors an underlying directory. # if dentry.get_exdev_on_rename() and "xerr" in args and not self.__skip_layer_test: args["err"] = args["xerr"] override = guess(dentry, has_ts, dentry2, has_ts2) if override: args["err"] = override want_error = args["err"] # Build the commandline to repeat the test if "follow" in args: line += " -L" elif "no_follow" in args: line += " -l" if "no_automount" in args: line += " -A" if "content" in args: line += " -R " + args["content"] if "as_bin" in args: line += " -B" if want_error: line += " -E " + errno.errorcode[want_error] self.output(" ./run --", line, "\n") self.check_layer(filename) if filename2 != None: self.check_layer(filename) if "as_bin" in args: self.verbosef("os.setegid(1)") os.setegid(1) self.verbosef("os.seteuid(1)") os.seteuid(1) if filename2 != None: return (dentry, dentry2) else: return dentry # Determine how to handle success def vfs_op_success(self, filename, dentry, args, filetype="f", create=False, copy_up=None, hardlink_to=None): if "as_bin" in args: self.verbosef("os.seteuid(0)") os.seteuid(0) self.verbosef("os.setegid(0)") os.setegid(0) want_error = args["err"] if want_error: raise TestError(filename + ": Expected error (" + os.strerror(want_error) + ") was not produced") layer = self.layers_nr() if dentry.is_negative(): if not create: if filetype == "d": raise TestError(filename + ": Directory was created unexpectedly") elif filetype == "s": raise TestError(filename + ": Symlink was created unexpectedly") else: raise TestError(filename + ": File was created unexpectedly") if not hardlink_to: dentry.created(inode(filetype), layer) else: dentry.created(hardlink_to.inode(), layer, on_upper = hardlink_to.on_upper(layer)) else: if copy_up: dentry.copied_up(layer, copy_up) self.check_layer(filename) # Determine how to handle an error def vfs_op_error(self, oe, filename, dentry, args, create=False): if "as_bin" in args: self.verbosef("os.seteuid(0)") os.seteuid(0) self.verbosef("os.setegid(0)") os.setegid(0) actual = os.strerror(oe.errno) want_error = args["err"] if not want_error and oe.errno != errno.EXDEV: raise TestError(filename + ": Unexpected error: " + actual) if want_error != oe.errno and oe.errno == errno.EXDEV: raise TestError(filename + ": Unexpected error: " + actual + "; Run tests with --xdev to skip dir rename tests") wanted = os.strerror(want_error) if want_error != oe.errno and want_error != errno.ENOTEMPTY and oe.errno != errno.EEXIST: raise TestError(filename + ": Unexpected error (expecting " + wanted + "): " + actual) if create: dentry.failed_to_create() self.check_layer(filename) ########################################################################### # # Change file mode operation # ########################################################################### def chmod(self, filename, mode, **args): line = "chmod " + filename + " 0{:o}".format(mode) dentry = self.vfs_op_prelude(line, filename, args, guess=self.guess1_error_create) try: self.verbosef("os.chmod({:s},0{:o})\n", filename, mode) os.chmod(filename, mode, follow_symlinks=("no_follow" in args)) self.vfs_op_success(filename, dentry, args, copy_up=upper.META) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) ########################################################################### # # Create hard link operation # ########################################################################### def link(self, filename, filename2, **args): # Guess the error that should be produced with terminal slashes added def guess_error(dentry, has_ts, dentry2, has_ts2): if not has_ts and not has_ts2: return None if has_ts2 and dentry.is_dir(): if dentry2.is_negative(): return errno.ENOENT if dentry2.is_reg_or_sym_to_reg(): return errno.EEXIST if has_ts: if dentry.is_negative(): return errno.ENOENT if dentry.is_neg_or_sym_to_neg(): return errno.ENOENT if not dentry.is_dir(): return errno.ENOTDIR if has_ts2: if dentry2.is_negative(): return errno.EISDIR if dentry2.is_sym(): return errno.ENOTDIR if dentry2.is_reg_or_sym_to_reg(): return errno.EISDIR return None line = "link " + filename + " " + filename2 (dentry, dentry2) = self.vfs_op_prelude(line, filename, args, filename2, guess=guess_error, create=True) follow_symlinks = False if "follow" in args: follow_symlinks = True if "no_follow" in args: follow_symlinks = False try: self.verbosef("os.link({:s},{:s})\n", filename, filename2) dev = self.get_dev_id(filename) ino = self.get_file_ino(filename) layer = self.layers_nr() os.link(filename, filename2, follow_symlinks=follow_symlinks) dentry.copied_up(layer) self.vfs_op_success(filename, dentry, args, copy_up=upper.META) self.vfs_op_success(filename2, dentry2, args, create=True, filetype=dentry.filetype(), hardlink_to=dentry) recycle = self.__recycle if "recycle" in args: recycle = args["recycle"] if recycle: # Cycle mount after link remount_union(self) # Check that ino has not changed through copy up, link and mount cycle self.check_dev_ino(filename, dentry, dev, ino, layer, recycle) self.check_dev_ino(filename2, dentry2, dev, ino, layer, recycle) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) self.vfs_op_error(oe, filename2, dentry2, args, create=True) ########################################################################### # # Make directory operation # ########################################################################### def mkdir(self, filename, mode, **args): # Guess the error that should be produced with terminal slashes added def guess_error(dentry, has_ts, dentry2, has_ts2): return None line = "mkdir " + filename + " 0{:o}".format(mode) dentry = self.vfs_op_prelude(line, filename, args, guess=guess_error, create=True) try: self.verbosef("os.mkdir({:s},0{:o})\n", filename, mode) os.mkdir(filename, mode) self.vfs_op_success(filename, dentry, args, filetype="d", create=True) if "recycle" not in args: args["recycle"] = self.__recycle if args["recycle"]: # Cycle mount and possibly rotate upper after create directory remount_union(self, rotate_upper=True) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args, create=True) ########################################################################### # # Readlink operation # ########################################################################### def readlink(self, filename, **args): # Guess the error that should be produced with terminal slashes added def guess_error(dentry, has_ts, dentry2, has_ts2): if not has_ts: return None if dentry.is_negative(): return errno.ENOENT if dentry.is_sym(): if dentry.is_dir_or_sym_to_dir(): return errno.EINVAL if dentry.is_neg_or_sym_to_neg(): return errno.ENOENT return errno.ENOTDIR if dentry.is_reg_or_sym_to_reg(): return errno.ENOTDIR return None line = "readlink " + filename dentry = self.vfs_op_prelude(line, filename, args, no_follow=True, guess=guess_error) try: self.verbose("os.readlink(", filename, ")\n") content = os.readlink(filename) self.vfs_op_success(filename, dentry, args) if content != args["content"]: raise TestError(filename + ": symlink has wrong content (has '" + content + "' not '" + args["content"] + "')") except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) ########################################################################### # # Rename operation # ########################################################################### def rename(self, filename, filename2, **args): # Guess the error that should be produced with terminal slashes added def guess_error(dentry, has_ts, dentry2, has_ts2): if not has_ts and not has_ts2: return None if dentry.is_dir(): return None if dentry.is_negative(): return errno.ENOENT if dentry.is_sym() or dentry.is_reg_or_sym_to_reg(): return errno.ENOTDIR if dentry2.is_negative(): return errno.EISDIR if dentry2.is_sym(): return errno.ENOTDIR if dentry2.is_reg_or_sym_to_reg(): return errno.EISDIR return None line = "rename " + filename + " " + filename2 (dentry, dentry2) = self.vfs_op_prelude( line, filename, args, filename2, no_follow=True, guess=guess_error, create=True) try: self.verbosef("os.rename({:s},{:s})\n", filename, filename2) filetype = dentry.filetype() dev = self.get_dev_id(filename) ino = self.get_file_ino(filename) layer = self.layers_nr() os.rename(filename, filename2) if dentry != dentry2: dentry.copied_up(layer) dentry2.replace_with(dentry) self.vfs_op_success(filename, dentry, args) self.vfs_op_success(filename2, dentry2, args, create=True, filetype=filetype, hardlink_to=dentry) recycle = self.__recycle if "recycle" in args: recycle = args["recycle"] if recycle: # Cycle mount and possibly rotate upper after rename remount_union(self, rotate_upper=True) # Check that ino has not changed through copy up, rename and mount cycle self.check_dev_ino(filename2, dentry2, dev, ino, layer, recycle) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) self.vfs_op_error(oe, filename2, dentry2, args, create=True) ########################################################################### # # Remove directory operation # ########################################################################### def rmdir(self, filename, **args): # Guess the error that should be produced with terminal slashes added def guess_error(dentry, has_ts, dentry2, has_ts2): if not has_ts: return None if dentry.is_dir(): return None if not dentry.is_negative(): return errno.ENOTDIR return None line = "rmdir " + filename dentry = self.vfs_op_prelude(line, filename, args, no_follow=True, guess=guess_error) try: self.verbosef("os.rmdir({:s})\n", filename) os.rmdir(filename) dentry.unlink() self.vfs_op_success(filename, dentry, args) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) ########################################################################### # # File truncate operation # ########################################################################### def truncate(self, filename, size, **args): line = "truncate " + filename + " " + str(size) dentry = self.vfs_op_prelude(line, filename, args, guess=self.guess1_error) try: self.verbose("os.truncate(", filename, ",", size, ")\n") os.truncate(filename, size) self.vfs_op_success(filename, dentry, args, copy_up=upper.DATA) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) ########################################################################### # # Remove file operation # ########################################################################### def unlink(self, filename, **args): line = "unlink " + filename dentry = self.vfs_op_prelude(line, filename, args, no_follow=True, guess=self.guess1_error) try: self.verbosef("os.unlink({:s})\n", filename) os.unlink(filename) dentry.unlink() self.vfs_op_success(filename, dentry, args) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args) ########################################################################### # # Set file times operation # ########################################################################### def utimes(self, filename, **args): line = "utimes " + filename follow = True if "no_follow" in args: follow = False if "follow" in args: follow = True dentry = self.vfs_op_prelude(line, filename, args, no_follow=(not follow), guess=self.guess1_error) try: self.verbosef("os.utime({:s},follow_symlinks={:d})\n", filename, follow) os.utime(filename, follow_symlinks=follow) self.vfs_op_success(filename, dentry, args, copy_up=upper.META) except OSError as oe: self.vfs_op_error(oe, filename, dentry, args)
amir73il/unionmount-testsuite
context.py
Python
gpl-2.0
49,529
from __future__ import absolute_import, division, print_function import tensorflow as tf from deep_rl.misc.utils import get_vars_from_scope, slice_2d def create_vpg_graph(n_action, policy_model, value_model, policy_opt, value_opt): """ Implements Vanilla Policy Gradient """ actions = tf.placeholder(tf.int32, shape=(None), name="actions") advantages = tf.placeholder(tf.float32, shape=(None), name="advantages") returns = tf.placeholder(tf.float32, shape=(None), name="returns") with tf.variable_scope('policy'): p_input, probs = policy_model() with tf.variable_scope('value'): v_input, value = value_model() p_vars = get_vars_from_scope('policy') v_vars = get_vars_from_scope('value') N = tf.shape(p_input)[0] p_vals = slice_2d(probs, tf.range(0, N), actions) surr_loss = -tf.log(p_vals) pf_loss_op = tf.reduce_mean(surr_loss * advantages, name="pf_loss_op") pf_train_op = policy_opt.minimize(pf_loss_op, var_list=p_vars, name="pf_train_op") vf_loss_op = tf.reduce_mean((value - returns)**2) vf_train_op = value_opt.minimize(vf_loss_op, var_list=v_vars, name="vf_train_op") return dict(actions=actions, advantages=advantages, returns=returns, policy_input=p_input, probs=probs, value_input=v_input, value=value, policy_train_op=pf_train_op, value_train_op=vf_train_op)
domluna/deep_rl
deep_rl/graphs/vpg.py
Python
mit
1,497
#!/usr/bin/python import math import sys import MobilityScenGenerator import DrawScenario def getNodes(anp, asp_hops, w1, w2, w3): return math.exp(w1) * math.pow(anp, w2) * math.pow(asp_hops, w3) def getArea(anp, asp_hops, w1, w2, w3): return math.exp(w1) * math.pow(anp, w2) * math.pow(asp_hops, w3) def main(): print '**********************************************************' print ' Standard scenario generator' print '**********************************************************' anp = float(raw_input('Average Network Partitioning ANP: ')) if anp < 0.0 or anp > 1.0: print 'ANP (Average Network Partitioning is a percentage ratio [0-1]' sys.exit() asp_hops = float(raw_input('Average Shortest Path Hops: ')) if asp_hops < 0: print 'Average Shortest Path Hops must be positive' sys.exit() print '' print '' print 'Generating scenario with ANP = %.2f and ASPhops = %d' % (anp, asp_hops) nodes, area, width_R = generateScenario(anp, asp_hops) print 'Nodes: %d' % nodes print 'Area: %.2f R^2' % (area) print 'Width: %.2f R' % width_R ################# generate scenarios transmissionRange = 100 width = width_R * transmissionRange outputFiles = MobilityScenGenerator.generateNS2MobilityScenario(nodes, 100.0, width, width, 0.000001, 0.000001, 200.0, 1) #for outputFile in outputFiles: # DrawScenario.drawScenario(outputFile, outputFile + '.png', width, width) def generateScenario(anp, asp_hops): node_exps = [-0.164, -0.417, 2.468] area_exps = [0.567, -0.0769, 2.159] nodes = getNodes(anp, asp_hops, *node_exps) area = getArea(anp, asp_hops, *area_exps) side = math.sqrt(area) return math.ceil(nodes), area, round(side) if __name__ == '__main__': main()
unaguil/hyperion-ns2
experiments/tools/StardardScenario.py
Python
apache-2.0
1,745
# -*- coding: utf-8 -*- ############################################################################## # # OpenGSRP, Open Source Management Solution # Copyright (C) 2012- OpenGSRP SA (<http://www.opengsrp.org>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################# from socketserver import _ServerSelector, ForkingTCPServer, BaseRequestHandler, StreamRequestHandler, DatagramRequestHandler, ForkingMixIn, ThreadingMixIn, BaseServer, TCPServer, ForkingTCPServer, ThreadingTCPServer, UnixStreamServer, UnixDatagramServer, ForkingUDPServer,ThreadingUDPServer from pysimplesoap.server import HTTPServer,SOAPHandler from pysimplesoap.server import SoapDispatcher import sys import os import traceback import socket import logging import ssl import pickle import json import select from io import StringIO from tools.translations import trlocal as _ if not "EPOLLRDHUP" in dir(select): select.EPOLLRDHUP = 0x2000 _logger = logging.getLogger("listener."+__name__) class RPCStreamRequestHandler(StreamRequestHandler): def handle(self): epoll = select.epoll() epoll.register(self.connection.fileno(), select.EPOLLIN|select.EPOLLRDHUP) while not self.server._BaseServer__shutdown_request: try: events = _eintr_retry(epoll.poll, self.server.timeout ) for fileno, event in events: if event & select.EPOLLRDHUP: ci = self.connection.getsockname() _logger.info(_("Connection closed host:%s port:%s") % (ci[0],ci[1])) self.server._BaseServer__shutdown_request = True break elif event & select.EPOLLIN: umsg = self.server.serializer._readfromfp(self.server, self.rfile) if self.server._BaseServer__shutdown_request: break _logger.info('IMessage: %s' % (umsg,)) if umsg and len(umsg) == 1: rmsg = self.server._dispatcher._execute(umsg[0]) elif umsg and len(umsg) == 2: rmsg = self.server._dispatcher._execute(umsg[0],umsg[1]) _logger.info('RMessage: %s' % (rmsg,)) self.server.serializer._writetofp(rmsg, self.wfile) except: _logger.critical(traceback.format_exc()) print('TRACEBACK',traceback.format_exc()) self.server.serializer._writetofp(['E', traceback.format_exc()],self.wfile) epoll.unregister(self.connection.fileno()) epoll.close() class UDPService(object): def getCountSID(self): return('getCountSID') def getListSID(self, start, end): return('getListSID START=%s, END=%s' % (start,end)) UDPSrv = UDPService() class RPCDatagramRequestHandler(DatagramRequestHandler): _methods = {'getCountSID':UDPSrv.getCountSID,'getListSID':UDPSrv.getListSID} def handle(self): #umsg = self._read() umsg = self.server.serializer._readfromfp(self.server, self.rfile) print('IMESSAGE', umsg) if self._methods.has_key(umsg[0][0]): if umsg.__len__() > 1: rmsg =self._methods[umsg[0][0]](**(umsg[1])) else: rmsg = self._methods[umsg[0][0]]() #self._write(rmsg) print('RMESSAGE', rmsg) self.server.serializer._writetofp(rmsg, self.wfile) def _read(self): self.rfile.reset() return self.server.serializer.load(self.rfile) def _write(self, msg): return self.server.serializer.dump(msg, self.wfile) class SSLTCPServer(TCPServer): def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, keyfile = None, certfile = None, cert_reqs = 0, ssl_version = 2, ca_certs = None, do_handshake_on_connect = True, suppress_ragged_eofs = True, ciphers = None ): """Constructor. May be extended, do not override.""" super(SSLTCPServer, self).__init__(server_address, RequestHandlerClass) self.keyfile = keyfile self.certfile = certfile self.server_side = True self.cert_reqs = cert_reqs self.ssl_version = ssl_version self.ca_certs = ca_certs self.do_handshake_on_connect = do_handshake_on_connect self.suppress_ragged_eofs = suppress_ragged_eofs self.ciphers = ciphers self.socket = socket.socket(self.address_family, self.socket_type) if bind_and_activate: self.server_bind() self.server_activate() def server_bind(self): """Called by constructor to bind the socket. May be overridden. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) self.server_address = self.socket.getsockname() def server_activate(self): """Called by constructor to activate the server. May be overridden. """ self.socket.listen(self.request_queue_size) def server_close(self): """Called to clean-up the server. May be overridden. """ self.socket.close() def get_request(self): """Get the request and client address from the socket. """ client, name = self.socket.accept() return ssl.SSLSocket(sock = client, keyfile = self.keyfile, certfile = self.certfile, server_side = self.server_side, cert_reqs = self.cert_reqs, ssl_version = self.ssl_version, ca_certs = self.ca_certs, do_handshake_on_connect = self.do_handshake_on_connect, suppress_ragged_eofs = self.suppress_ragged_eofs, ciphers = self.ciphers), name if hasattr(socket, 'AF_UNIX'): class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass class ForkingSSLTCPServer(ForkingMixIn, SSLTCPServer): pass class ThreadingSSLTCPServer(ThreadingMixIn, SSLTCPServer): pass if hasattr(socket, 'AF_INET6'): class ForkingTCPV6Server(ForkingTCPServer): address_family = socket.AF_INET6 class ThreadingTCPV6Server(ThreadingTCPServer): address_family = socket.AF_INET6 class ForkingSSLTCPV6Server(ForkingSSLTCPServer): address_family = socket.AF_INET6 class ThreadingSSLTCPV6Server(ThreadingSSLTCPServer): address_family = socket.AF_INET6 class ForkingUDPV6Server(ForkingUDPServer): address_family = socket.AF_INET6 class ThreadingUDPV6Server(ThreadingUDPServer): address_family = socket.AF_INET6 #class ForkingSOAPServer(SOAPServerBase, ForkingTCPServer): #def __init__(self, addr = ('localhost', 8000), #RequestHandler = SOAPRequestHandler, log = 0, encoding = 'UTF-8', #config = Config, namespace = None, ssl_context = None): ## Test the encoding, raising an exception if it's not known #if encoding != None: #''.encode(encoding) #if ssl_context != None and not config.SSLserver: #raise AttributeError("SSL server not supported by this Python installation") #self.namespace = namespace #self.objmap = {} #self.funcmap = {} #self.ssl_context = ssl_context #self.encoding = encoding #self.config = config #self.log = log #self.allow_reuse_address= 1 #ForkingTCPServer.__init__(self, addr, RequestHandler)
neo5g/server-gsrp5
server-gsrp5/services/netrpc.py
Python
agpl-3.0
7,534
import numpy as np from scipy.special import jn, jvp, jn_zeros from scipy.integrate import quad import matlibplot.pyplot as plt class TE(object): def __init__(self,l,m,n,R,L): self.l = l self.m = m self.n = n k1 = jn_zeros(m,l)/R k3 = n*np.pi/L def E_r(self, r, theta, z): return -self.l * jn(l,k1*r)/(k1*r) * np.sin(self.l * theta) * np.sin( k3 * z) def E_theta(self, r, theta, z): return -(jvp(self.l,k1*r,1])/k1) * np.cos(self.l* theta)*np.sin(k3*z) def E_z(self): return 0 def H_r(self, r, theta, z): return k3 def H_th(self): return asdf def H_z(self): return asdf def Norm(self, V): from scipy.integrate import quad func = something return quad(func,0,V) class TE_Geometry_Factor(TE): def __init__(self, radialoffset, lengthoffset): self.r_off = radialoffset self.z_off = lengthoffset def Geom_Factor(self, k): from scipy.integrate import quad return quad(np.exp(I*x)/(np.abs(x- y)*E_z(x)*E_z(y), 0, V) def Plot(self)
amalagon/TE_class
TE_class.py
Python
mit
1,222
#!/usr/bin/env python # encoding: utf-8 """ dbset.py Created by Razor <bg1tpt AT gmail.com> on 2008-03-31 Copyright (c) 2008 xBayDNS Team. All rights reserved. """ import bsddb, pickle, os class Set(): def __init__(self): self._dbname = os.tmpnam() try: self._dbobj = bsddb.btopen(self._dbname) except: pass def add(self, element): if element == None: return False element_str = pickle.dumps(element) print type(element_str) self._dbobj[element_str] = '1' return True def __getitem__(self, element): if element == None: return False element_str = pickle.dumps(element) return self._dbobj[element_str]
changtailiang/xbaydns
xbaydns/tools/dbset.py
Python
bsd-2-clause
760
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from ._vmware_cloud_simple import VMwareCloudSimple from ._version import VERSION __version__ = VERSION __all__ = ['VMwareCloudSimple'] try: from ._patch import patch_sdk # type: ignore patch_sdk() except ImportError: pass
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-vmwarecloudsimple/azure/mgmt/vmwarecloudsimple/__init__.py
Python
mit
706
from pyspider.libs.base_handler import * from my import My from bs4 import BeautifulSoup '''茂名''' class Handler(My): name = "MM" @every(minutes=24 * 60) def on_start(self): self.crawl('http://csgh.maoming.gov.cn/active/show.ashx?action=certList&pwd=&chk=1&key=&no=&sid=1&page=1', callback=self.plan_page, age=1, save={'type':self.table_name[0], 'source':'GH'}) self.crawl('http://csgh.maoming.gov.cn/active/show.ashx?action=certList&pwd=&chk=1&key=&no=&sid=2&page=1', callback=self.plan_page, age=1, save={'type':self.table_name[1], 'source':'GH'}) self.crawl('http://csgh.maoming.gov.cn/active/show.ashx?action=certList&pwd=&chk=1&key=&no=&sid=3&page=1', callback=self.plan_page, age=1, save={'type':self.table_name[2], 'source':'GH'}) self.crawl('http://csgh.maoming.gov.cn/active/show.ashx?action=certList&pwd=&chk=1&key=&no=&sid=4&page=1', callback=self.plan_page, age=1, save={'type':self.table_name[4], 'source':'GH'}) self.crawl('http://gtzyj.maoming.gov.cn/newsAction.do?method=queryNews&classId=020010350000000960&page=1', callback=self.land_page, save={'type':self.table_name[14], 'source':'GT'}, age=1, fetch_type='js') self.crawl('http://jianshe.maoming.gov.cn/class.asp?classid=109&page=1', callback=self.build_page, save={'type':self.table_name[15], 'source':'JS'}, age=1) def build_page(self, response): soup = BeautifulSoup(response.text, 'html.parser') t = soup('div', 'page')[0].find_all('a')[-1]['href'] page_count = int(self.get_params(link=t)[1]['page']) print(page_count) url, params = self.get_params(response) for i in range(2, page_count + 1): params['page'] = str(i) self.crawl(url, params=params, age=1, save=response.save, callback=self.buid_list_page) lists = soup('ul', 'newactivity')[0].find_all('a', {'target':'_blank'}) for i in lists: link = self.real_path(response.url, i['href']) self.crawl(link, save=response.save, callback=self.content_page) def buid_list_page(self, response): soup = BeautifulSoup(response.text, 'html.parser') lists = soup('ul', 'newactivity')[0].find_all('a', {'target':'_blank'}) for i in lists: link = self.real_path(response.url, i['href']) self.crawl(link, save=response.save, callback=self.content_page) def land_page(self, response): soup = BeautifulSoup(response.text) page_count = int(soup('input', {'name':'totalPages'})[0]['value']) data = {} data['classId'] = soup('input', {'name':'classId'})[0]['value'] data['textGeneralType'] = soup('input', {'name':'textGeneralType'})[0]['value'] data['curPageNo'] = soup('input', {'name':'curPageNo'})[0]['value'] data['totalCnts'] = soup('input', {'name':'totalCnts'})[0]['value'] data['totalPages'] = soup('input', {'name':'totalPages'})[0]['value'] data['cntPerPage'] = soup('input', {'name':'cntPerPage'})[0]['value'] data['SplitFlag'] = '1' data['orderBy'] = soup('input', {'name':'orderBy'})[0]['value'] data['descOrAsc'] = soup('input', {'name':'descOrAsc'})[0]['value'] print(data['curPageNo']) url, params = self.get_params(response) for i in range(2, page_count + 1): data['gotoPage'] = str(i) params['page'] = str(i) self.crawl(url, params=params, data=data, method='POST', save=response.save, callback=self.land_list_page, age=1, fetch_type='js') lists = soup('div', 'text') for i in lists: link = self.real_path(response.url, i.find_all('a')[0]['href']) # print(link) self.crawl(link, callback=self.content_page, save=response.save, fetch_type='js') def land_list_page(self, response): soup = BeautifulSoup(response.text) print(soup('input', {'name':'curPageNo'})[0]['value']) lists = soup('div', 'text') for i in lists: link = self.real_path(response.url, i.find_all('a')[0]['href']) # print(link) self.crawl(link, callback=self.content_page, save=response.save, fetch_type='js') def plan_page(self, response): soup = BeautifulSoup(response.text) t = soup('div', {'class':'pagebar'})[0].get_text() k = t.split(' ')[0] page_count = int(k[1: len(k) - 3]) pages = int(page_count / 21) if page_count % 21 == 0 else int(page_count / 21) + 1 url = response.url[:-1] for i in range(2, pages+ 1): link = url + str(i) self.crawl(link, callback=self.plan_list_page, age=1, save=response.save) domain = 'http://csgh.maoming.gov.cn/' links = soup('table', {'id':'bookindex'})[0].find_all('a') for i in links: link = domain + i['href'] # print(link) self.crawl(link, callback=self.content_page, save=response.save) def plan_list_page(self, response): soup = BeautifulSoup(response.text) domain = 'http://csgh.maoming.gov.cn/' links = soup('table', {'id':'bookindex'})[0].find_all('a') for i in links: link = domain + i['href'] # print(link) self.crawl(link, callback=self.content_page, save=response.save)
euangelion666/PySpider-test
pyspider_MM.py
Python
apache-2.0
5,568
import logging import os import urllib2 import json import time import datetime from base_controller import CacheableHandler, LoggedInHandler from consts.client_type import ClientType from google.appengine.api import memcache from google.appengine.api import urlfetch from google.appengine.ext import ndb from google.appengine.ext.webapp import template from helpers.model_to_dict import ModelToDict from helpers.mytba_helper import MyTBAHelper from models.account import Account from models.api_auth_access import ApiAuthAccess from models.event import Event from models.favorite import Favorite from models.mobile_client import MobileClient from models.sitevar import Sitevar from models.typeahead_entry import TypeaheadEntry class AccountInfoHandler(LoggedInHandler): """ For getting account info. Only provides logged in status for now. """ def get(self): self.response.headers['content-type'] = 'application/json; charset="utf-8"' user = self.user_bundle.user self.response.out.write(json.dumps({ 'logged_in': True if user else False, 'user_id': user.user_id() if user else None })) class AccountRegisterFCMToken(LoggedInHandler): """ For adding/updating an FCM token """ def post(self): if not self.user_bundle.user: self.response.set_status(401) return user_id = self.user_bundle.user.user_id() fcm_token = self.request.get('fcm_token') uuid = self.request.get('uuid') display_name = self.request.get('display_name') client_type = ClientType.WEB query = MobileClient.query( MobileClient.user_id == user_id, MobileClient.device_uuid == uuid, MobileClient.client_type == client_type) if query.count() == 0: # Record doesn't exist yet, so add it MobileClient( parent=ndb.Key(Account, user_id), user_id=user_id, messaging_id=fcm_token, client_type=client_type, device_uuid=uuid, display_name=display_name).put() else: # Record already exists, update it client = query.fetch(1)[0] client.messaging_id = fcm_token client.display_name = display_name client.put() class AccountFavoritesHandler(LoggedInHandler): """ For getting an account's favorites """ def get(self, model_type): if not self.user_bundle.user: self.response.set_status(401) return favorites = Favorite.query( Favorite.model_type==int(model_type), ancestor=ndb.Key(Account, self.user_bundle.user.user_id())).fetch() self.response.out.write(json.dumps([ModelToDict.favoriteConverter(fav) for fav in favorites])) class AccountFavoritesAddHandler(LoggedInHandler): """ For adding an account's favorites """ def post(self): if not self.user_bundle.user: self.response.set_status(401) return model_type = int(self.request.get("model_type")) model_key = self.request.get("model_key") user_id = self.user_bundle.user.user_id() fav = Favorite( parent=ndb.Key(Account, user_id), user_id=user_id, model_key=model_key, model_type=model_type ) MyTBAHelper.add_favorite(fav) class AccountFavoritesDeleteHandler(LoggedInHandler): """ For deleting an account's favorites """ def post(self): if not self.user_bundle.user: self.response.set_status(401) return model_key = self.request.get("model_key") model_type = int(self.request.get("model_type")) user_id = self.user_bundle.user.user_id() MyTBAHelper.remove_favorite(user_id, model_key, model_type) class LiveEventHandler(CacheableHandler): """ Returns the necessary details to render live components Uses timestamp for aggressive caching """ CACHE_VERSION = 1 CACHE_KEY_FORMAT = "live-event:{}:{}" # (event_key, timestamp) CACHE_HEADER_LENGTH = 60 * 10 def __init__(self, *args, **kw): super(LiveEventHandler, self).__init__(*args, **kw) self._cache_expiration = self.CACHE_HEADER_LENGTH def get(self, event_key, timestamp): if int(timestamp) > time.time(): self.abort(404) self._partial_cache_key = self.CACHE_KEY_FORMAT.format(event_key, timestamp) super(LiveEventHandler, self).get(event_key, timestamp) def _render(self, event_key, timestamp): self.response.headers['content-type'] = 'application/json; charset="utf-8"' event = Event.get_by_id(event_key) matches = [] for match in event.matches: matches.append({ 'name': match.short_name, 'alliances': match.alliances, 'order': match.play_order, 'time_str': match.time_string, }) event_dict = { # 'rankings': event.rankings, # 'matchstats': event.matchstats, 'matches': matches, } return json.dumps(event_dict) class TypeaheadHandler(CacheableHandler): """ Currently just returns a list of all teams and events Needs to be optimized at some point. Tried a trie but the datastructure was too big to fit into memcache efficiently """ CACHE_VERSION = 2 CACHE_KEY_FORMAT = "typeahead_entries:{}" # (search_key) CACHE_HEADER_LENGTH = 60 * 60 * 24 def __init__(self, *args, **kw): super(TypeaheadHandler, self).__init__(*args, **kw) self._cache_expiration = self.CACHE_HEADER_LENGTH def get(self, search_key): search_key = urllib2.unquote(search_key) self._partial_cache_key = self.CACHE_KEY_FORMAT.format(search_key) super(TypeaheadHandler, self).get(search_key) def _render(self, search_key): self.response.headers['content-type'] = 'application/json; charset="utf-8"' entry = TypeaheadEntry.get_by_id(search_key) if entry is None: return '[]' else: self._last_modified = entry.updated return entry.data_json class WebcastHandler(CacheableHandler): """ Returns the HTML necessary to generate the webcast embed for a given event """ CACHE_VERSION = 1 CACHE_KEY_FORMAT = "webcast_{}_{}" # (event_key) CACHE_HEADER_LENGTH = 60 * 5 def __init__(self, *args, **kw): super(WebcastHandler, self).__init__(*args, **kw) self._cache_expiration = 60 * 60 * 24 def get(self, event_key, webcast_number): self._partial_cache_key = self.CACHE_KEY_FORMAT.format(event_key, webcast_number) super(WebcastHandler, self).get(event_key, webcast_number) def _render(self, event_key, webcast_number): self.response.headers.add_header('content-type', 'application/json', charset='utf-8') output = {} if not webcast_number.isdigit(): return json.dumps(output) webcast_number = int(webcast_number) - 1 event = Event.get_by_id(event_key) if event and event.webcast: webcast = event.webcast[webcast_number] if 'type' in webcast and 'channel' in webcast: output['player'] = self._renderPlayer(webcast) else: special_webcasts_future = Sitevar.get_by_id_async('gameday.special_webcasts') special_webcasts = special_webcasts_future.get_result() if special_webcasts: special_webcasts = special_webcasts.contents['webcasts'] else: special_webcasts = [] special_webcasts_dict = {} for webcast in special_webcasts: special_webcasts_dict[webcast['key_name']] = webcast if event_key in special_webcasts_dict: webcast = special_webcasts_dict[event_key] if 'type' in webcast and 'channel' in webcast: output['player'] = self._renderPlayer(webcast) return json.dumps(output) def _renderPlayer(self, webcast): webcast_type = webcast['type'] template_values = {'webcast': webcast} path = os.path.join(os.path.dirname(__file__), '../templates/webcast/' + webcast_type + '.html') return template.render(path, template_values) def memcacheFlush(self, event_key): keys = [self._render_cache_key(self.CACHE_KEY_FORMAT.format(event_key, n)) for n in range(10)] memcache.delete_multi(keys) return keys class YouTubePlaylistHandler(LoggedInHandler): """ For Hitting the YouTube API to get a list of video keys associated with a playlist """ def get(self): if not self.user_bundle.user: self.response.set_status(401) return playlist_id = self.request.get("playlist_id") if not playlist_id: self.response.set_status(400) return video_ids = [] headers = {} yt_key = Sitevar.get_by_id("google.secrets") if not yt_key: self.response.set_status(500) return next_page_token = "" # format with playlist id, page token, api key url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId={}&&pageToken={}&fields=items%2Fsnippet%2FresourceId%2Citems%2Fsnippet%2Ftitle%2CnextPageToken&key={}" while True: try: result = urlfetch.fetch(url.format(playlist_id, next_page_token, yt_key.contents["api_key"]), headers=headers, deadline=5) except Exception, e: self.response.set_status(500) return [] if result.status_code != 200: self.response.set_status(result.status_code) return [] video_result = json.loads(result.content) video_ids += [video for video in video_result["items"] if video["snippet"]["resourceId"]["kind"] == "youtube#video"] if "nextPageToken" not in video_result: break next_page_token = video_result["nextPageToken"] self.response.out.write(json.dumps(video_ids)) class AllowedApiWriteEventsHandler(LoggedInHandler): """ Get the events the current user is allowed to edit via the trusted API """ def get(self): if not self.user_bundle.user: self.response.out.write(json.dumps([])) return now = datetime.datetime.now() auth_tokens = ApiAuthAccess.query(ApiAuthAccess.owner == self.user_bundle.account.key, ndb.OR(ApiAuthAccess.expiration == None, ApiAuthAccess.expiration >= now)).fetch() event_keys = [] for token in auth_tokens: event_keys.extend(token.event_list) events = ndb.get_multi(event_keys) details = {} for event in events: details[event.key_name] = "{} {}".format(event.year, event.name) self.response.out.write(json.dumps(details))
verycumbersome/the-blue-alliance
controllers/ajax_controller.py
Python
mit
11,365
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from product.models import ProductPlugin from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ class ProductPluginForm(ModelForm): class Meta: model = ProductPlugin class ProductPlugin(CMSPluginBase): model = ProductPlugin name = _("Products") render_template = "products/product-plugin.html" def render(self, context, instance, placeholder): context.update({ 'instance': instance, 'products': instance.get_products() }) return context plugin_pool.register_plugin(ProductPlugin)
amaozhao/basecms
product/cms_plugins.py
Python
mit
681
#!/usr/bin/env python import sys PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.bytecodes import dvm from androguard.core.analysis import analysis from androguard.util import read TEST = "examples/android/TestsAndroguard/bin/classes.dex" j = dvm.DalvikVMFormat(read(TEST, binary=False)) x = analysis.VMAnalysis(j) j.set_vmanalysis(x) # SHOW CLASSES (verbose and pretty) j.pretty_show() # SHOW METHODS for i in j.get_methods(): i.pretty_show()
xtiankisutsa/MARA_Framework
tools/androguard/demos/dalvikvm_format_3.py
Python
lgpl-3.0
478
#!/usr/bin/python # # Copyright 2013 Rackspace Australia # # 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 inspect import sys from nova.db.sqlalchemy import models from oslo.config import cfg CONF = cfg.CONF def load_configuration(): configs = {} for name, obj in inspect.getmembers(models): if not inspect.isclass(obj): continue if not issubclass(obj, models.NovaBase): continue attrs_missing = [] for required_attr in ['__tablename__', '__confidential__']: if not hasattr(obj, required_attr): attrs_missing.append(required_attr) if attrs_missing: if CONF.debug: print ('Required attributes %s missing from %s' % (', '.join(attrs_missing), name)) continue configs[obj.__tablename__] = obj.__confidential__ return configs def map_tables_to_model_names(tables): results = {} for name, obj in inspect.getmembers(models): if hasattr(obj, '__tablename__'): if obj.__tablename__ in tables: results[obj.__tablename__] = name return results def main(): CONF(sys.argv[1:], project='fuzzy-happiness') print load_configuration()
rcbau/fuzzy-happiness
fuzzy_happiness/attributes.py
Python
apache-2.0
1,766
# Copyright (C) 2012, Jesper Friis # (see accompanying license files for ASE). """ Determines space group of an atoms object using the FINDSYM program from the ISOTROPY (http://stokes.byu.edu/iso/isotropy.html) software package by H. T. Stokes and D. M. Hatch, Brigham Young University, USA. In order to use this module, you have to download the ISOTROPY package from http://stokes.byu.edu/iso/isotropy.html and set the environment variable ISODATA to the path of the directory containing findsym and data_space.txt (NB: the path should end with a slash (/)). Example ------- >>> from ase.lattice.spacegroup import crystal >>> from ase.utils.geometry import cut # Start with simple fcc Al >>> al = crystal('Al', [(0,0,0)], spacegroup=225, cellpar=4.05) >>> d = findsym(al) >>> d['spacegroup'] 225 # No problem with a more complex structure... >>> skutterudite = crystal(('Co', 'Sb'), ... basis=[(0.25,0.25,0.25), (0.0, 0.335, 0.158)], ... spacegroup=204, ... cellpar=9.04) >>> d = findsym(skutterudite) >>> d['spacegroup'] 204 # ... or a non-conventional cut slab = cut(skutterudite, a=(1, 1, 0), b=(0, 2, 0), c=(0, 0, 1)) d = findsym(slab) >>> d['spacegroup'] 204 """ import os import subprocess import numpy as np import ase __all__ = ['findsym', 'unique'] def make_input(atoms, tol=1e-3, centering='P', types=None): """Returns input to findsym. See findsym() for a description of the arguments.""" if types is None: types = atoms.numbers s = [] s.append(atoms.get_name()) s.append('%g tolerance' % tol) s.append('2 form of lattice parameters: to be entered as lengths ' 'and angles') s.append('%g %g %g %g %g %g a,b,c,alpha,beta,gamma' % tuple(ase.lattice.spacegroup.cell.cell_to_cellpar(atoms.cell))) s.append('2 form of vectors defining unit cell') # ?? s.append('%s centering (P=unknown)' % centering) s.append('%d number of atoms in primitive unit cell' % len(atoms)) s.append(' '.join(str(n) for n in types) + ' type of each atom') for p in atoms.get_scaled_positions(): s.append('%10.5f %10.5f %10.5f' % tuple(p)) return '\n'.join(s) def run(atoms, tol=1e-3, centering='P', types=None, isodata_dir=None): """Runs FINDSYM and returns its standard output.""" if isodata_dir is None: isodata_dir = os.getenv('ISODATA') if isodata_dir is None: isodata_dir = '.' isodata_dir = os.path.normpath(isodata_dir) findsym = os.path.join(isodata_dir, 'findsym') data_space = os.path.join(isodata_dir, 'data_space.txt') for path in findsym, data_space: if not os.path.exists(path): raise IOError('no such file: %s. Have you set the ISODATA ' 'environment variable to the directory containing ' 'findsym and data_space.txt?' % path) env = os.environ.copy() env['ISODATA'] = isodata_dir + os.sep p = subprocess.Popen([findsym], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env) stdout = p.communicate(make_input(atoms, tol, centering, types))[0] #if os.path.exists('findsym.log'): # os.remove('findsym.log') return stdout def parse(output): """Parse output from FINDSYM (Version 3.2.3, August 2007) and return a dict. See docstring for findsym() for a description of the tokens.""" import StringIO d = {} f = StringIO.StringIO(output) line = f.readline() while not line.startswith('Lattice parameters'): line = f.readline() assert line, 'Cannot find line starting with "Lattice parameters"' d['cellpar'] = np.array([float(v) for v in f.readline().split()]) #d['centering'] = f.readline().split()[1] # seems not to make sence... # Determine number of atoms from atom types, since the number of # atoms is written with only 3 digits, which crashes the parser # for more than 999 atoms while not line.startswith('Type of each atom'): line = f.readline() assert line, 'Cannot find line starting with "Type of each atom"' line = f.readline() types = [] while not line.startswith('Position of each atom'): types.extend([int(n) for n in line.split()]) line = f.readline() assert line, 'Cannot find line starting with "Position of each atom"' natoms = len(types) while not line.startswith('Space Group '): line = f.readline() assert line, 'Cannot find line starting with "Space Group "' tokens = line.split() d['spacegroup'] = int(tokens[2]) #d['symbol_nonconventional'] = tokens[3] d['symbol'] = tokens[4] d['origin'] = np.array([float(v) for v in f.readline().split()[2:]]) f.readline() d['abc'] = np.array([[float(v) for v in f.readline().split()] for i in range(3)]).T while not line.startswith('Wyckoff position'): line = f.readline() assert line, 'Cannot find line starting with "Wyckoff position"' d['wyckoff'] = [] d['tags'] = -np.ones(natoms, dtype=int) tag = 0 while not line.startswith('---'): tokens = line.split() line = f.readline() assert line, 'Cannot find line starting with "Wyckoff position"' d['wyckoff'].append(tokens[2].rstrip(',')) while not line.startswith('Wyckoff position') and not line.startswith('---'): tokens = line.split() n = int(tokens[0]) d['tags'][n-1] = tag line = f.readline() tag += 1 return d def findsym(atoms, tol=1e-3, centering='P', types=None, isodata_dir=None): """Returns a dict describing the symmetry of *atoms*. Arguments --------- atoms: Atoms instance Atoms instance to find space group of. tol: float Accuracy to which dimensions of the unit cell and positions of atoms are known. Units in Angstrom. centering: 'P' | 'I' | 'F' | 'A' | 'B' | 'C' | 'R' Known centering: P (no known centering), I (body-centered), F (face-centered), A,B,C (base centered), R (rhombohedral centered with coordinates of centered points at (2/3,1/3,1/3) and (1/3,2/3,2/3)). types: None | sequence of integers Sequence of arbitrary positive integers identifying different atomic sites, so that a symmetry operation that takes one atom into another with different type would be forbidden. Returned dict items ------------------- abc: 3x3 float array The vectors a, b, c defining the cell in scaled coordinates. cellpar: 6 floats Cell parameters a, b, c, alpha, beta, gamma with lengths in Angstrom and angles in degree. origin: 3 floats Origin of the space group with respect to the origin in the input data. Coordinates are dimensionless, given in terms of the lattice parameters of the unit cell in the input. spacegroup: int Space group number from the International Tables of Crystallography. symbol: str Hermann-Mauguin symbol (no spaces). tags: int array Array of site numbers for each atom. Only atoms within the first conventional unit cell are tagged, the rest have -1 as tag. wyckoff: list List of wyckoff symbols for each site. """ output = run(atoms, tol, centering, types, isodata_dir) d = parse(output) return d def unique(atoms, tol=1e-3, centering='P', types=None, isodata_dir=None): """Returns an Atoms object containing only one atom from each unique site. """ d = findsym(atoms, tol=tol, centering=centering, types=types, isodata_dir=isodata_dir) mask = np.concatenate(([True], np.diff(d['tags']) != 0)) * (d['tags'] >= 0) at = atoms[mask] a, b, c, alpha, beta, gamma = d['cellpar'] A, B, C = d['abc'] A *= a B *= b C *= c from numpy.linalg import norm from numpy import cos, pi assert abs(np.dot(A, B) - (norm(A) * norm(B) * cos(gamma * pi / 180.))) < 1e-5 assert abs(np.dot(A, C) - (norm(A) * norm(C) * cos(beta * pi / 180.))) < 1e-5 assert abs(np.dot(B, C) - (norm(B) * norm(C) * cos(alpha * pi / 180.))) < 1e-5 at.cell = np.array([A, B, C]) for k in 'origin', 'spacegroup', 'wyckoff': at.info[k] = d[k] at.info['unit_cell'] = 'unique' scaled = at.get_scaled_positions() at.set_scaled_positions(scaled) return at if __name__ == '__main__': import doctest print 'doctest: ', doctest.testmod()
grhawk/ASE
tools/ase/lattice/spacegroup/findsym.py
Python
gpl-2.0
8,652
#!/usr/bin/env python # -*- coding:utf-8 -*- """ initialize handlers """ import tornado.web import tornado.escape import tornado.ioloop from lib import verify, encrypt, mail from db import db_machine from lib.salt_api import SaltAPI as sapi import json import check from lib.logger import log from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor class InitializeHandler(tornado.web.RequestHandler): executor = ThreadPoolExecutor(5) def data_received(self, chunk): pass def __init__(self, application, request, **kwargs): super(InitializeHandler, self).__init__(application, request, **kwargs) self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with, content-type") self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE') self.token = self.get_secure_cookie("access_token") self.handler_permission = '8' self.get_permission = '8.1' self.post_permission = '8.2' def get(self): ip = self.get_argument('ip', None) software = self.get_argument('software', None) status = self.get_argument('status', 0) result = db_machine.update_initialize_status(ip, software, status) if result: ok = True info = 'Update initialize status successful' else: ok = False info = 'Update initialize status failed' self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) def post(self): post_initialize_permission = '8.2.1' post_install_permission = '8.2.2' ok, info = check.check_login(self.token) if not ok: self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) return ok, info = check.check_content_type(self.request) if not ok: self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) return body = json.loads(self.request.body) action, data = body['action'], body['data'] if action == 'initialize': local_permission_list = [self.handler_permission, self.post_permission, post_initialize_permission] ok, info, _ = verify.has_permission(self.token, local_permission_list) if not ok: self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) return tornado.ioloop.IOLoop.instance().add_callback(self.machine_initialize(data['ip'])) ok = True info = "Initializing..." self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) return if action == 'install': local_permission_list = [self.handler_permission, self.post_permission, post_install_permission] ok, info, _ = verify.has_permission(self.token, local_permission_list) if not ok: self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) return tornado.ioloop.IOLoop.instance().add_callback(self.install_software(data['ip'], data['software'])) ok = True info = 'Software installing...' self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) return ok = False info = 'Unsupported task action' self.finish(tornado.escape.json_encode({'ok': ok, 'info': info})) @run_on_executor def machine_initialize(self, ip): result = sapi.run_script([ip], 'salt://scripts/initialize.sh', 'initialize') log.info(result) @run_on_executor def install_software(self, ip, software): result = sapi.run_script([ip], 'salt://scripts/install_software.sh', software) log.info(result) def options(self): pass handlers = [ ('/api/initialize', InitializeHandler), ]
guoxu3/oms_backend
oms/handlers/initialize.py
Python
mit
3,953
import MySQLdb import config.db_config as dbconf def connect(autocommit=True): db = MySQLdb.connect(host=dbconf.HOST, port=dbconf.PORT, user=dbconf.USERNAME, passwd=dbconf.PASSWORD, db=dbconf.DATABASE) db.autocommit(autocommit) return db def disconnect(connection): if connection: connection.close()
Python3Development/KodiAPI
libs/db_connector.py
Python
gpl-3.0
327
import numpy as np from numpy.testing import assert_equal, assert_, run_module_suite import unittest from qutip import * import qutip.settings as qset if qset.has_openmp: from qutip.cy.openmp.benchmark import _spmvpy, _spmvpy_openmp @unittest.skipIf(qset.has_openmp == False, 'OPENMP not available.') def test_openmp_spmv(): "OPENMP : spmvpy_openmp == spmvpy" for k in range(100): L = rand_herm(10,0.25).data vec = rand_ket(L.shape[0],0.25).full().ravel() out = np.zeros_like(vec) out_openmp = np.zeros_like(vec) _spmvpy(L.data, L.indices, L.indptr, vec, 1, out) _spmvpy_openmp(L.data, L.indices, L.indptr, vec, 1, out_openmp, 2) assert_(np.allclose(out, out_openmp, 1e-15)) @unittest.skipIf(qset.has_openmp == False, 'OPENMP not available.') def test_openmp_mesolve(): "OPENMP : mesolve" N = 100 wc = 1.0 * 2 * np.pi # cavity frequency wa = 1.0 * 2 * np.pi # atom frequency g = 0.05 * 2 * np.pi # coupling strength kappa = 0.005 # cavity dissipation rate gamma = 0.05 # atom dissipation rate n_th_a = 1 # temperature in frequency units use_rwa = 0 # operators a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) # Hamiltonian if use_rwa: H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag()) else: H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() + a) * (sm + sm.dag()) c_op_list = [] rate = kappa * (1 + n_th_a) if rate > 0.0: c_op_list.append(np.sqrt(rate) * a) rate = kappa * n_th_a if rate > 0.0: c_op_list.append(np.sqrt(rate) * a.dag()) rate = gamma if rate > 0.0: c_op_list.append(np.sqrt(rate) * sm) n = N - 2 psi0 = tensor(basis(N, n), basis(2, 1)) tlist = np.linspace(0, 1, 100) opts = Options(use_openmp=False) out = mesolve(H, psi0, tlist, c_op_list, [a.dag() * a, sm.dag() * sm], options=opts) opts = Options(use_openmp=True) out_omp = mesolve(H, psi0, tlist, c_op_list, [a.dag() * a, sm.dag() * sm], options=opts) assert_(np.allclose(out.expect[0],out_omp.expect[0])) assert_(np.allclose(out.expect[1],out_omp.expect[1])) @unittest.skipIf(qset.has_openmp == False, 'OPENMP not available.') def test_openmp_mesolve_td(): "OPENMP : mesolve (td)" N = 100 wc = 1.0 * 2 * np.pi # cavity frequency wa = 1.0 * 2 * np.pi # atom frequency g = 0.5 * 2 * np.pi # coupling strength kappa = 0.005 # cavity dissipation rate gamma = 0.05 # atom dissipation rate n_th_a = 1 # temperature in frequency units use_rwa = 0 # operators a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) # Hamiltonian H0 = wc * a.dag() * a + wa * sm.dag() * sm H1 = g * (a.dag() + a) * (sm + sm.dag()) H = [H0, [H1,'sin(t)']] c_op_list = [] rate = kappa * (1 + n_th_a) if rate > 0.0: c_op_list.append(np.sqrt(rate) * a) rate = kappa * n_th_a if rate > 0.0: c_op_list.append(np.sqrt(rate) * a.dag()) rate = gamma if rate > 0.0: c_op_list.append(np.sqrt(rate) * sm) n = N - 10 psi0 = tensor(basis(N, n), basis(2, 1)) tlist = np.linspace(0, 1, 100) opts = Options(use_openmp=True) out_omp = mesolve(H, psi0, tlist, c_op_list, [a.dag() * a, sm.dag() * sm], options=opts) opts = Options(use_openmp=False) out = mesolve(H, psi0, tlist, c_op_list, [a.dag() * a, sm.dag() * sm], options=opts) assert_(np.allclose(out.expect[0],out_omp.expect[0])) assert_(np.allclose(out.expect[1],out_omp.expect[1])) if __name__ == "__main__": run_module_suite()
cgranade/qutip
qutip/tests/test_openmp.py
Python
bsd-3-clause
3,771
"""Tests for embargo app views. """ import unittest from mock import patch from django.test import TestCase from django.core.urlresolvers import reverse from django.conf import settings from mako.exceptions import TopLevelLookupException import ddt from util.testing import UrlResetMixin from embargo import messages @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') @ddt.ddt class CourseAccessMessageViewTest(UrlResetMixin, TestCase): """Tests for the courseware access message view. These end-points serve static content. While we *could* check the text on each page, this will require changes to the test every time the text on the page changes. Instead, we load each page we expect to be available (based on the configuration in `embargo.messages`) and verify that we get the correct status code. This will catch errors in the message configuration (for example, moving a template and forgetting to update the configuration appropriately). """ @patch.dict(settings.FEATURES, {'ENABLE_COUNTRY_ACCESS': True}) def setUp(self): super(CourseAccessMessageViewTest, self).setUp('embargo') @ddt.data(*messages.ENROLL_MESSAGES.keys()) def test_enrollment_messages(self, msg_key): self._load_page('enrollment', msg_key) @ddt.data(*messages.COURSEWARE_MESSAGES.keys()) def test_courseware_messages(self, msg_key): self._load_page('courseware', msg_key) @ddt.data('enrollment', 'courseware') def test_invalid_message_key(self, access_point): self._load_page(access_point, 'invalid', expected_status=404) @patch.dict(settings.FEATURES, {'USE_CUSTOM_THEME': True}) @ddt.data('enrollment', 'courseware') def test_custom_theme_override(self, access_point): # Custom override specified for the "embargo" message # for backwards compatibility with previous versions # of the embargo app. # This template isn't available by default, but we can at least # verify that the view will look for it when the USE_CUSTOM_THEME # feature flag is specified. with self.assertRaisesRegexp(TopLevelLookupException, 'static_templates/theme-embargo.html'): self._load_page(access_point, 'embargo') @patch.dict(settings.FEATURES, {'USE_CUSTOM_THEME': True}) @ddt.data('enrollment', 'courseware') def test_custom_theme_override_not_specified(self, access_point): # No custom override specified for the "default" message self._load_page(access_point, 'default') def _load_page(self, access_point, message_key, expected_status=200): """Load the message page and check the status code. """ url = reverse('embargo_blocked_message', kwargs={ 'access_point': access_point, 'message_key': message_key }) response = self.client.get(url) self.assertEqual( response.status_code, expected_status, msg=( u"Unexpected status code when loading '{url}': " u"expected {expected} but got {actual}" ).format( url=url, expected=expected_status, actual=response.status_code ) )
mtlchun/edx
common/djangoapps/embargo/tests/test_views.py
Python
agpl-3.0
3,300
#!/usr/bin/env python3 # Copyright (c) 2015-2017 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 BIP66 (DER SIG). Test that the DERSIG soft-fork activates at (regtest) height 1251. """ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.mininode import * from test_framework.blocktools import create_coinbase, create_block from test_framework.script import CScript from io import BytesIO DERSIG_HEIGHT = 1251 # Reject codes that we might receive in this test REJECT_INVALID = 16 REJECT_OBSOLETE = 17 REJECT_NONSTANDARD = 64 # A canonical signature consists of: # <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype> def unDERify(tx): """ Make the signature in vin 0 of a tx non-DER-compliant, by adding padding after the S-value. """ scriptSig = CScript(tx.vin[0].scriptSig) newscript = [] for i in scriptSig: if (len(newscript) == 0): newscript.append(i[0:-1] + b'\0' + i[-1:]) else: newscript.append(i) tx.vin[0].scriptSig = CScript(newscript) def create_transaction(node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransactionwithwallet(rawtx) tx = CTransaction() tx.deserialize(BytesIO(hex_str_to_bytes(signresult['hex']))) return tx class BIP66Test(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [['-promiscuousmempoolflags=1', '-whitelist=127.0.0.1']] self.setup_clean_chain = True def run_test(self): self.nodes[0].add_p2p_connection(P2PInterface()) network_thread_start() # wait_for_verack ensures that the P2P connection is fully up. self.nodes[0].p2p.wait_for_verack() self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2) self.coinbase_blocks = self.nodes[0].generate(DERSIG_HEIGHT - 2) self.nodeaddress = self.nodes[0].getnewaddress() self.log.info("Test that a transaction with non-DER signature can still appear in a block") spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) unDERify(spendtx) spendtx.rehash() tip = self.nodes[0].getbestblockhash() block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1 block = create_block(int(tip, 16), create_coinbase(DERSIG_HEIGHT - 1), block_time) block.nVersion = 2 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(self.nodes[0].getbestblockhash(), block.hash) self.log.info("Test that blocks must now be at least version 3") tip = block.sha256 block_time += 1 block = create_block(tip, create_coinbase(DERSIG_HEIGHT), block_time) block.nVersion = 2 block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip) wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock) with mininode_lock: assert_equal(self.nodes[0].p2p.last_message["reject"].code, REJECT_OBSOLETE) assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'bad-version(0x00000002)') assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256) del self.nodes[0].p2p.last_message["reject"] self.log.info("Test that transactions with non-DER signatures cannot appear in a block") block.nVersion = 3 spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) unDERify(spendtx) spendtx.rehash() # First we show that this tx is valid except for DERSIG by getting it # accepted to the mempool (which we can achieve with # -promiscuousmempoolflags). self.nodes[0].p2p.send_and_ping(msg_tx(spendtx)) assert spendtx.hash in self.nodes[0].getrawmempool() # Now we verify that a block with this transaction is invalid. block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip) wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock) with mininode_lock: # We can receive different reject messages depending on whether # bitcoind is running with multiple script check threads. If script # check threads are not in use, then transaction script validation # happens sequentially, and bitcoind produces more specific reject # reasons. assert self.nodes[0].p2p.last_message["reject"].code in [REJECT_INVALID, REJECT_NONSTANDARD] assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256) if self.nodes[0].p2p.last_message["reject"].code == REJECT_INVALID: # Generic rejection when a block is invalid assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'block-validation-failed') else: assert b'Non-canonical DER signature' in self.nodes[0].p2p.last_message["reject"].reason self.log.info("Test that a version 3 block with a DERSIG-compliant transaction is accepted") block.vtx[1] = create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.nodes[0].p2p.send_and_ping(msg_block(block)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256) if __name__ == '__main__': BIP66Test().main()
randy-waterhouse/bitcoin
test/functional/feature_dersig.py
Python
mit
6,367
from antlr4 import * from sqlparser.antlr.MySQLParser import MySQLParser from sqlparser.antlr.MySQLLexer import MySQLLexer from sqlparser.antlr.MySQLParserVisitor import MySQLParserVisitor, TableInfo class FieldPath(object): """Class for field path """ def __init__(self, db, tb, fd): """Constructor. Args: db (str): Database's name. tb (str): Table's name. fd (str): Field's name. """ self.db = db self.tb = tb self.fd = fd def __str__(self): return self.db + '.' + self.tb + '.' + self.fd def __repr__(self): return self.db + '.' + self.tb + '.' + self.fd def __hash__(self): return hash((self.db, self.tb, self.fd)) def __eq__(self, other): return (self.db, self.tb, self.fd) == (other.db, other.tb, other.fd) def get_er_from_sql(default_db_name, sql): """This function gets entity relationship from one sql line. Args: default_db_name (unicode): The default database name. sql (unicode): The sql line to be parse. Returns: A list of pairs of :class:`FieldPath`. For example: [(FieldPath(u'database0', 'table0', 'field0'), FieldPath(u'database0', 'table1', 'field1'))] A way might be used is >>> print get_er_from_sql(default_db_name = u'', sql = u'select a.id, b.name from db.ac a join db.bc b on a.id=b.id or a.id=b.iid where a.cnt > 10') [(('db', 'ac', 'id'), ('db', 'bc', 'id')), (('db', 'ac', 'id'), ('db', 'bc', 'iid'))] """ def form_field_path(default_db_name, path): sub_names = path.split('.') # check and form (db_name, tb_name, field_name) if len(sub_names) < 2: return elif len(sub_names) == 2: if default_db_name == '': return sub_names.insert(0, default_db_name) return FieldPath(*sub_names) sql = sql if isinstance(sql, unicode) else sql.decode('utf-8') input = InputStream(sql.lower()) lexer = MySQLLexer(input) stream = CommonTokenStream(lexer) parser = MySQLParser(stream) tree = parser.stat() v = MySQLParserVisitor() v.visit(tree) ers = [] for condition in TableInfo.on_conditions: tokens = [_.strip() for _ in condition.split('=')] er = [] for token in tokens: sub_names = token.split('.') tb_name = '.'.join(sub_names[:-1]) field_path = None if tb_name in TableInfo.table_name_to_alias: field_path = form_field_path(default_db_name, token) elif tb_name in TableInfo.table_alias_to_name: field_path = form_field_path(default_db_name, TableInfo.table_alias_to_name[tb_name] + '.' + sub_names[-1]) if field_path: er.append(field_path) if len(er) == 2: ers.append(tuple(er)) # clear TableInfo.reset() return ers
StefanLim0/mysql-er
sqlparser/ERExtractor.py
Python
mit
2,964
from unittest import TestCase from openrevman.availability_processor.availability_processor import AvailabilityProcessor from openrevman.control_computer.solver import Solver, create_problem_with_data from openrevman.forecaster.forecaster import Forecaster from openrevman.inventory.inventory import Inventory from openrevman.recorder.recorder import Record from openrevman.recorder.recorder import Recorder class TestSystem(TestCase): def setUp(self): self.forecaster = Forecaster() self.solver = Solver(None) self.inventory = Inventory(products=["p1", "p2"], remaining_capacity=[10, 10]) self.recorder = Recorder() self.ap = AvailabilityProcessor(None, None) def test_get_availability(self): # return self.ap.is_available() pass def test_book(self): booking = Record(record_type="Booking", products=["p1"]) self.recorder.record(booking) self.inventory.update_inventory(bookings=[booking]) assert self.inventory.product_inventory["p1"] == 9 assert self.inventory.product_inventory["p2"] == 10 pass def test_updateparameter(self): self.forecaster.update_parameter() pass def test_get_price(self): pass def test_update_controls(self): demand_data, demand_utilization_data = self.forecaster.forecast() capacity_data = self.inventory.get_capacity() problem = create_problem_with_data(demand_data, capacity_data, demand_utilization_data) self.solver.optimize_controls(problem) # self.ap.controls = self.solver.controls pass
3like3beer/openrevman
openrevman/test.py
Python
gpl-3.0
1,629
import os import shutil from autotest.client.shared import error from autotest.client import utils from virttest import data_dir, virsh from virttest import aexpect, utils_misc, utils_selinux from virttest.aexpect import ShellError from virttest.remote import LoginError from virttest.utils_test import libvirt from virttest.virt_vm import VMError from virttest.libvirt_xml.vm_xml import VMXML from virttest.libvirt_xml.devices.controller import Controller from virttest.libvirt_xml.devices.disk import Disk from virttest.libvirt_xml.devices.input import Input def run(test, params, env): """ Test for hotplug usb device. """ # get the params from params vm_name = params.get("main_vm", "virt-tests-vm1") vm = env.get_vm(vm_name) usb_type = params.get("usb_type", "kbd") attach_type = params.get("attach_type", "attach_device") attach_count = int(params.get("attach_count", "1")) if usb_type == "storage": model = params.get("model", "nec-xhci") index = params.get("index", "1") status_error = ("yes" == params.get("status_error", "no")) vm_xml = VMXML.new_from_inactive_dumpxml(vm_name) vm_xml_backup = vm_xml.copy() # Set selinux of host. backup_sestatus = utils_selinux.get_status() utils_selinux.set_status("permissive") if usb_type == "storage": controllers = vm_xml.get_devices(device_type="controller") devices = vm_xml.get_devices() for dev in controllers: if dev.type == "usb" and dev.index == "1": devices.remove(dev) controller = Controller("controller") controller.type = "usb" controller.index = index controller.model = model devices.append(controller) vm_xml.set_devices(devices) try: session = vm.wait_for_login() except (LoginError, VMError, ShellError), e: raise error.TestFail("Test failed: %s" % str(e)) def is_hotplug_ok(): try: output = session.cmd_output("fdisk -l | grep -c '^Disk /dev/.* 1 M'") if int(output.strip()) != attach_count: return False else: return True except aexpect.ShellTimeoutError, detail: raise error.TestFail("unhotplug failed: %s, " % detail) tmp_dir = os.path.join(data_dir.get_tmp_dir(), "usb_hotplug_files") if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) try: result = None dev_xml = None opt = "--hmp" for i in range(attach_count): if usb_type == "storage": path = os.path.join(tmp_dir, "%s.img" % i) libvirt.create_local_disk("file", path, size="1M", disk_format="qcow2") os.chmod(path, 0666) if attach_type == "qemu_monitor": if usb_type == "storage": attach_cmd = "drive_add" attach_cmd += (" 0 id=drive-usb-%s,if=none,file=%s" % (i, path)) result = virsh.qemu_monitor_command(vm_name, attach_cmd, options=opt) if result.exit_status or (result.stdout.find("OK") == -1): raise error.CmdError(result.command, result) attach_cmd = "device_add usb-storage," attach_cmd += ("id=drive-usb-%s,bus=usb1.0,drive=drive-usb-%s" % (i, i)) else: attach_cmd = "device_add" attach_cmd += " usb-%s,bus=usb1.0,id=%s%s" % (usb_type, usb_type, i) result = virsh.qemu_monitor_command(vm_name, attach_cmd, options=opt) if result.exit_status: raise error.CmdError(result.command, result) else: attributes = {'type_name': "usb", 'bus': "1", 'port': "0"} if usb_type == "storage": dev_xml = Disk(type_name="file") dev_xml.device = "disk" dev_xml.source = dev_xml.new_disk_source(**{"attrs": {'file': path}}) dev_xml.driver = {"name": "qemu", "type": 'qcow2', "cache": "none"} dev_xml.target = {"dev": 'sdb', "bus": "usb"} dev_xml.address = dev_xml.new_disk_address(**{"attrs": attributes}) else: if usb_type == "mouse": dev_xml = Input("mouse") elif usb_type == "tablet": dev_xml = Input("tablet") else: dev_xml = Input("keyboard") dev_xml.input_bus = "usb" dev_xml.address = dev_xml.new_input_address(**{"attrs": attributes}) result = virsh.attach_device(vm_name, dev_xml.xml) if result.exit_status: raise error.CmdError(result.command, result) if status_error and usb_type == "storage": if utils_misc.wait_for(is_hotplug_ok, timeout=30): # Sometimes we meet an error but the ret in $? is 0. raise error.TestFail("\nAttach device successfully in negative case." "\nExcept it fail when attach count exceed maximum." "\nDetail: %s" % result) for i in range(attach_count): attach_cmd = "device_del" if attach_type == "qemu_monitor": if usb_type == "storage": attach_cmd += (" drive-usb-%s" % i) else: if usb_type == "mouse": attach_cmd += " mouse" elif usb_type == "tablet": attach_cmd += " tablet" else: attach_cmd += " keyboard" result = virsh.qemu_monitor_command(vm_name, attach_cmd, options=opt) if result.exit_status: raise error.CmdError(result.command, result) else: result = virsh.detach_device(vm_name, dev_xml.xml) if result.exit_status: raise error.CmdError(result.command, result) except error.CmdError, e: if not status_error: # live attach of device 'input' is not supported ret = result.stderr.find("Operation not supported") if usb_type != "storage" and ret > -1: pass else: raise error.TestFail("failed to attach device.\nDetail: %s." % result) finally: session.close() if os.path.isdir(tmp_dir): shutil.rmtree(tmp_dir) utils_selinux.set_status(backup_sestatus) vm_xml_backup.sync()
will-Do/tp-libvirt_v2v
libvirt/tests/src/libvirt_usb_hotplug_device.py
Python
gpl-2.0
6,751
# Amara, universalsubtitles.org # # Copyright (C) 2016 Participatory Culture Foundation # # 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/agpl-3.0.html. from django.conf.urls import * urlpatterns = patterns('staff.views', url(r'^$', 'index', name='index'))
wevoice/wesub
apps/staff/urls.py
Python
agpl-3.0
865
# -*- coding: utf-8 -*- from datetime import datetime from bson import ObjectId from tornado.web import HTTPError from handlers.base import JsonHandler from models.admin import AdminModel from models.session import AdminSessionModel from common import hashers class RegisterHandler(JsonHandler): async def post(self, *args, **kwargs): email = self.json_decoded_body.get('email', None) if not email or len(email) == 0: raise HTTPError(400, 'invalid email') name = self.json_decoded_body.get('name', None) if not name or len(name) == 0: raise HTTPError(400, 'invalid name') password = self.json_decoded_body.get('password', None) if not password or len(password) == 0 or not hashers.validate_password(password): raise HTTPError(400, 'invalid password') password2 = self.json_decoded_body.get('password2', None) if not password or len(password) == 0 or not hashers.validate_password(password): raise HTTPError(400, 'invalid password2') if password != password2: raise HTTPError(400, 'password and password2 not matched') duplicated_admin = await AdminModel.find_one({'email': email}) if duplicated_admin: raise HTTPError(400, 'duplicated email') admin = AdminModel(raw_data=dict( email=email, name=name )) admin.set_password(password) await admin.insert() self.response['data'] = admin.data self.write_json() class LoginHandler(JsonHandler): async def post(self, *args, **kwargs): self.clear_cookie(self.COOKIE_KEYS['SESSION_KEY']) email = self.json_decoded_body.get('email', None) if not email or len(email) == 0: raise HTTPError(400, 'invalid email') password = self.json_decoded_body.get('password', None) if not password or len(password) == 0 or not hashers.validate_password(password): raise HTTPError(400, 'invalid password') admin = await AdminModel.find_one({'email': email}) if not admin: raise HTTPError(400, 'no exist admin user') if not hashers.check_password(password, admin['password']): raise HTTPError(400, 'invalid password') self.current_user = admin session = AdminSessionModel() session.data['admin_oid'] = admin['_id'] session_oid = await session.insert() self.set_cookie(self.COOKIE_KEYS['SESSION_KEY'], str(session_oid)) self.response['data'] = admin self.write_json() async def options(self, *args, **kwargs): self.response['message'] = 'OK' self.write_json()
takearest118/coconut
handlers/a/auth.py
Python
gpl-3.0
2,718
# Copyright 2011-2012 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Tests for Distribution page.""" __metaclass__ = type from fixtures import FakeLogger from lazr.restful.interfaces import IJSONRequestCache import soupmatchers from testtools.matchers import ( MatchesAny, Not, ) from zope.schema.vocabulary import SimpleVocabulary from lp.app.browser.lazrjs import vocabulary_to_choice_edit_items from lp.registry.enums import EXCLUSIVE_TEAM_POLICY from lp.registry.interfaces.series import SeriesStatus from lp.services.webapp import canonical_url from lp.testing import ( login_celebrity, login_person, TestCaseWithFactory, ) from lp.testing.layers import DatabaseFunctionalLayer from lp.testing.views import create_initialized_view class TestDistributionPage(TestCaseWithFactory): """A TestCase for the distribution index page.""" layer = DatabaseFunctionalLayer def setUp(self): super(TestDistributionPage, self).setUp() self.distro = self.factory.makeDistribution( name="distro", displayname=u'distro') self.simple_user = self.factory.makePerson() # Use a FakeLogger fixture to prevent Memcached warnings to be # printed to stdout while browsing pages. self.useFixture(FakeLogger()) def test_distributionpage_addseries_link(self): # An admin sees the +addseries link. self.admin = login_celebrity('admin') view = create_initialized_view( self.distro, '+index', principal=self.admin) series_matches = soupmatchers.HTMLContains( soupmatchers.Tag( 'link to add a series', 'a', attrs={'href': canonical_url(self.distro, view_name='+addseries')}, text='Add series'), soupmatchers.Tag( 'Active series and milestones widget', 'h2', text='Active series and milestones'), ) self.assertThat(view.render(), series_matches) def test_distributionpage_addseries_link_noadmin(self): # A non-admin does not see the +addseries link nor the series # header (since there is no series yet). login_person(self.simple_user) view = create_initialized_view( self.distro, '+index', principal=self.simple_user) add_series_match = soupmatchers.HTMLContains( soupmatchers.Tag( 'link to add a series', 'a', attrs={'href': canonical_url(self.distro, view_name='+addseries')}, text='Add series')) series_header_match = soupmatchers.HTMLContains( soupmatchers.Tag( 'Active series and milestones widget', 'h2', text='Active series and milestones')) self.assertThat( view.render(), Not(MatchesAny(add_series_match, series_header_match))) def test_distributionpage_series_list_noadmin(self): # A non-admin does see the series list when there is a series. self.factory.makeDistroSeries(distribution=self.distro, status=SeriesStatus.CURRENT) login_person(self.simple_user) view = create_initialized_view( self.distro, '+index', principal=self.simple_user) add_series_match = soupmatchers.HTMLContains( soupmatchers.Tag( 'link to add a series', 'a', attrs={'href': canonical_url(self.distro, view_name='+addseries')}, text='Add series')) series_header_match = soupmatchers.HTMLContains( soupmatchers.Tag( 'Active series and milestones widget', 'h2', text='Active series and milestones')) self.assertThat(view.render(), series_header_match) self.assertThat(view.render(), Not(add_series_match)) class TestDistributionView(TestCaseWithFactory): """Tests the DistributionView.""" layer = DatabaseFunctionalLayer def setUp(self): super(TestDistributionView, self).setUp() self.distro = self.factory.makeDistribution( name="distro", displayname=u'distro') def test_view_data_model(self): # The view's json request cache contains the expected data. view = create_initialized_view(self.distro, '+index') cache = IJSONRequestCache(view.request) policy_items = [(item.name, item) for item in EXCLUSIVE_TEAM_POLICY] team_membership_policy_data = vocabulary_to_choice_edit_items( SimpleVocabulary.fromItems(policy_items), value_fn=lambda item: item.name) self.assertContentEqual( team_membership_policy_data, cache.objects['team_membership_policy_data'])
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/registry/browser/tests/test_distribution.py
Python
agpl-3.0
4,874
class Parser: def parse_file(self, filename): """ function parses (filename) and returns dictionary with emotion-values """ t = open(filename, 'r').read().split() values = list(map(lambda x : int(x), t)) emotions = ['em1', 'em2', 'em3', 'em4', 'em5', 'em6', ] return dict(zip(emotions, values))
HackRoboy/EmotionGame
parser.py
Python
mit
481
"""Request body processing for CherryPy. .. versionadded:: 3.2 Application authors have complete control over the parsing of HTTP request entities. In short, :attr:`cherrypy.request.body<cherrypy._cprequest.Request.body>` is now always set to an instance of :class:`RequestBody<cherrypy._cpreqbody.RequestBody>`, and *that* class is a subclass of :class:`Entity<cherrypy._cpreqbody.Entity>`. When an HTTP request includes an entity body, it is often desirable to provide that information to applications in a form other than the raw bytes. Different content types demand different approaches. Examples: * For a GIF file, we want the raw bytes in a stream. * An HTML form is better parsed into its component fields, and each text field decoded from bytes to unicode. * A JSON body should be deserialized into a Python dict or list. When the request contains a Content-Type header, the media type is used as a key to look up a value in the :attr:`request.body.processors<cherrypy._cpreqbody.Entity.processors>` dict. If the full media type is not found, then the major type is tried; for example, if no processor is found for the 'image/jpeg' type, then we look for a processor for the 'image' types altogether. If neither the full type nor the major type has a matching processor, then a default processor is used (:func:`default_proc<cherrypy._cpreqbody.Entity.default_proc>`). For most types, this means no processing is done, and the body is left unread as a raw byte stream. Processors are configurable in an 'on_start_resource' hook. Some processors, especially those for the 'text' types, attempt to decode bytes to unicode. If the Content-Type request header includes a 'charset' parameter, this is used to decode the entity. Otherwise, one or more default charsets may be attempted, although this decision is up to each processor. If a processor successfully decodes an Entity or Part, it should set the :attr:`charset<cherrypy._cpreqbody.Entity.charset>` attribute on the Entity or Part to the name of the successful charset, so that applications can easily re-encode or transcode the value if they wish. If the Content-Type of the request entity is of major type 'multipart', then the above parsing process, and possibly a decoding process, is performed for each part. For both the full entity and multipart parts, a Content-Disposition header may be used to fill :attr:`name<cherrypy._cpreqbody.Entity.name>` and :attr:`filename<cherrypy._cpreqbody.Entity.filename>` attributes on the request.body or the Part. .. _custombodyprocessors: Custom Processors ================= You can add your own processors for any specific or major MIME type. Simply add it to the :attr:`processors<cherrypy._cprequest.Entity.processors>` dict in a hook/tool that runs at ``on_start_resource`` or ``before_request_body``. Here's the built-in JSON tool for an example:: def json_in(force=True, debug=False): request = cherrypy.serving.request def json_processor(entity): \"""Read application/json data into request.json.\""" if not entity.headers.get("Content-Length", ""): raise cherrypy.HTTPError(411) body = entity.fp.read() try: request.json = json_decode(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') if force: request.body.processors.clear() request.body.default_proc = cherrypy.HTTPError( 415, 'Expected an application/json content type') request.body.processors['application/json'] = json_processor We begin by defining a new ``json_processor`` function to stick in the ``processors`` dictionary. All processor functions take a single argument, the ``Entity`` instance they are to process. It will be called whenever a request is received (for those URI's where the tool is turned on) which has a ``Content-Type`` of "application/json". First, it checks for a valid ``Content-Length`` (raising 411 if not valid), then reads the remaining bytes on the socket. The ``fp`` object knows its own length, so it won't hang waiting for data that never arrives. It will return when all data has been read. Then, we decode those bytes using Python's built-in ``json`` module, and stick the decoded result onto ``request.json`` . If it cannot be decoded, we raise 400. If the "force" argument is True (the default), the ``Tool`` clears the ``processors`` dict so that request entities of other ``Content-Types`` aren't parsed at all. Since there's no entry for those invalid MIME types, the ``default_proc`` method of ``cherrypy.request.body`` is called. But this does nothing by default (usually to provide the page handler an opportunity to handle it.) But in our case, we want to raise 415, so we replace ``request.body.default_proc`` with the error (``HTTPError`` instances, when called, raise themselves). If we were defining a custom processor, we can do so without making a ``Tool``. Just add the config entry:: request.body.processors = {'application/json': json_processor} Note that you can only replace the ``processors`` dict wholesale this way, not update the existing one. """ try: from io import DEFAULT_BUFFER_SIZE except ImportError: DEFAULT_BUFFER_SIZE = 8192 import re import sys import tempfile try: from urllib import unquote_plus except ImportError: def unquote_plus(bs): """Bytes version of urllib.parse.unquote_plus.""" bs = bs.replace(ntob('+'), ntob(' ')) atoms = bs.split(ntob('%')) for i in range(1, len(atoms)): item = atoms[i] try: pct = int(item[:2], 16) atoms[i] = bytes([pct]) + item[2:] except ValueError: pass return ntob('').join(atoms) import cherrypy from cherrypy._cpcompat import text_or_bytes, ntob, ntou from cherrypy.lib import httputil # ------------------------------- Processors -------------------------------- # def process_urlencoded(entity): """Read application/x-www-form-urlencoded data into entity.params.""" qs = entity.fp.read() for charset in entity.attempt_charsets: try: params = {} for aparam in qs.split(ntob('&')): for pair in aparam.split(ntob(';')): if not pair: continue atoms = pair.split(ntob('='), 1) if len(atoms) == 1: atoms.append(ntob('')) key = unquote_plus(atoms[0]).decode(charset) value = unquote_plus(atoms[1]).decode(charset) if key in params: if not isinstance(params[key], list): params[key] = [params[key]] params[key].append(value) else: params[key] = value except UnicodeDecodeError: pass else: entity.charset = charset break else: raise cherrypy.HTTPError( 400, "The request entity could not be decoded. The following " "charsets were attempted: %s" % repr(entity.attempt_charsets)) # Now that all values have been successfully parsed and decoded, # apply them to the entity.params dict. for key, value in params.items(): if key in entity.params: if not isinstance(entity.params[key], list): entity.params[key] = [entity.params[key]] entity.params[key].append(value) else: entity.params[key] = value def process_multipart(entity): """Read all multipart parts into entity.parts.""" ib = "" if 'boundary' in entity.content_type.params: # http://tools.ietf.org/html/rfc2046#section-5.1.1 # "The grammar for parameters on the Content-type field is such that it # is often necessary to enclose the boundary parameter values in quotes # on the Content-type line" ib = entity.content_type.params['boundary'].strip('"') if not re.match("^[ -~]{0,200}[!-~]$", ib): raise ValueError('Invalid boundary in multipart form: %r' % (ib,)) ib = ('--' + ib).encode('ascii') # Find the first marker while True: b = entity.readline() if not b: return b = b.strip() if b == ib: break # Read all parts while True: part = entity.part_class.from_fp(entity.fp, ib) entity.parts.append(part) part.process() if part.fp.done: break def process_multipart_form_data(entity): """Read all multipart/form-data parts into entity.parts or entity.params. """ process_multipart(entity) kept_parts = [] for part in entity.parts: if part.name is None: kept_parts.append(part) else: if part.filename is None: # It's a regular field value = part.fullvalue() else: # It's a file upload. Retain the whole part so consumer code # has access to its .file and .filename attributes. value = part if part.name in entity.params: if not isinstance(entity.params[part.name], list): entity.params[part.name] = [entity.params[part.name]] entity.params[part.name].append(value) else: entity.params[part.name] = value entity.parts = kept_parts def _old_process_multipart(entity): """The behavior of 3.2 and lower. Deprecated and will be changed in 3.3.""" process_multipart(entity) params = entity.params for part in entity.parts: if part.name is None: key = ntou('parts') else: key = part.name if part.filename is None: # It's a regular field value = part.fullvalue() else: # It's a file upload. Retain the whole part so consumer code # has access to its .file and .filename attributes. value = part if key in params: if not isinstance(params[key], list): params[key] = [params[key]] params[key].append(value) else: params[key] = value # -------------------------------- Entities --------------------------------- # class Entity(object): """An HTTP request body, or MIME multipart body. This class collects information about the HTTP request entity. When a given entity is of MIME type "multipart", each part is parsed into its own Entity instance, and the set of parts stored in :attr:`entity.parts<cherrypy._cpreqbody.Entity.parts>`. Between the ``before_request_body`` and ``before_handler`` tools, CherryPy tries to process the request body (if any) by calling :func:`request.body.process<cherrypy._cpreqbody.RequestBody.process>`. This uses the ``content_type`` of the Entity to look up a suitable processor in :attr:`Entity.processors<cherrypy._cpreqbody.Entity.processors>`, a dict. If a matching processor cannot be found for the complete Content-Type, it tries again using the major type. For example, if a request with an entity of type "image/jpeg" arrives, but no processor can be found for that complete type, then one is sought for the major type "image". If a processor is still not found, then the :func:`default_proc<cherrypy._cpreqbody.Entity.default_proc>` method of the Entity is called (which does nothing by default; you can override this too). CherryPy includes processors for the "application/x-www-form-urlencoded" type, the "multipart/form-data" type, and the "multipart" major type. CherryPy 3.2 processes these types almost exactly as older versions. Parts are passed as arguments to the page handler using their ``Content-Disposition.name`` if given, otherwise in a generic "parts" argument. Each such part is either a string, or the :class:`Part<cherrypy._cpreqbody.Part>` itself if it's a file. (In this case it will have ``file`` and ``filename`` attributes, or possibly a ``value`` attribute). Each Part is itself a subclass of Entity, and has its own ``process`` method and ``processors`` dict. There is a separate processor for the "multipart" major type which is more flexible, and simply stores all multipart parts in :attr:`request.body.parts<cherrypy._cpreqbody.Entity.parts>`. You can enable it with:: cherrypy.request.body.processors['multipart'] = _cpreqbody.process_multipart in an ``on_start_resource`` tool. """ # http://tools.ietf.org/html/rfc2046#section-4.1.2: # "The default character set, which must be assumed in the # absence of a charset parameter, is US-ASCII." # However, many browsers send data in utf-8 with no charset. attempt_charsets = ['utf-8'] """A list of strings, each of which should be a known encoding. When the Content-Type of the request body warrants it, each of the given encodings will be tried in order. The first one to successfully decode the entity without raising an error is stored as :attr:`entity.charset<cherrypy._cpreqbody.Entity.charset>`. This defaults to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_), but ``['us-ascii', 'utf-8']`` for multipart parts. """ charset = None """The successful decoding; see "attempt_charsets" above.""" content_type = None """The value of the Content-Type request header. If the Entity is part of a multipart payload, this will be the Content-Type given in the MIME headers for this part. """ default_content_type = 'application/x-www-form-urlencoded' """This defines a default ``Content-Type`` to use if no Content-Type header is given. The empty string is used for RequestBody, which results in the request body not being read or parsed at all. This is by design; a missing ``Content-Type`` header in the HTTP request entity is an error at best, and a security hole at worst. For multipart parts, however, the MIME spec declares that a part with no Content-Type defaults to "text/plain" (see :class:`Part<cherrypy._cpreqbody.Part>`). """ filename = None """The ``Content-Disposition.filename`` header, if available.""" fp = None """The readable socket file object.""" headers = None """A dict of request/multipart header names and values. This is a copy of the ``request.headers`` for the ``request.body``; for multipart parts, it is the set of headers for that part. """ length = None """The value of the ``Content-Length`` header, if provided.""" name = None """The "name" parameter of the ``Content-Disposition`` header, if any.""" params = None """ If the request Content-Type is 'application/x-www-form-urlencoded' or multipart, this will be a dict of the params pulled from the entity body; that is, it will be the portion of request.params that come from the message body (sometimes called "POST params", although they can be sent with various HTTP method verbs). This value is set between the 'before_request_body' and 'before_handler' hooks (assuming that process_request_body is True).""" processors = {'application/x-www-form-urlencoded': process_urlencoded, 'multipart/form-data': process_multipart_form_data, 'multipart': process_multipart, } """A dict of Content-Type names to processor methods.""" parts = None """A list of Part instances if ``Content-Type`` is of major type "multipart".""" part_class = None """The class used for multipart parts. You can replace this with custom subclasses to alter the processing of multipart parts. """ def __init__(self, fp, headers, params=None, parts=None): # Make an instance-specific copy of the class processors # so Tools, etc. can replace them per-request. self.processors = self.processors.copy() self.fp = fp self.headers = headers if params is None: params = {} self.params = params if parts is None: parts = [] self.parts = parts # Content-Type self.content_type = headers.elements('Content-Type') if self.content_type: self.content_type = self.content_type[0] else: self.content_type = httputil.HeaderElement.from_str( self.default_content_type) # Copy the class 'attempt_charsets', prepending any Content-Type # charset dec = self.content_type.params.get("charset", None) if dec: self.attempt_charsets = [dec] + [c for c in self.attempt_charsets if c != dec] else: self.attempt_charsets = self.attempt_charsets[:] # Length self.length = None clen = headers.get('Content-Length', None) # If Transfer-Encoding is 'chunked', ignore any Content-Length. if ( clen is not None and 'chunked' not in headers.get('Transfer-Encoding', '') ): try: self.length = int(clen) except ValueError: pass # Content-Disposition self.name = None self.filename = None disp = headers.elements('Content-Disposition') if disp: disp = disp[0] if 'name' in disp.params: self.name = disp.params['name'] if self.name.startswith('"') and self.name.endswith('"'): self.name = self.name[1:-1] if 'filename' in disp.params: self.filename = disp.params['filename'] if ( self.filename.startswith('"') and self.filename.endswith('"') ): self.filename = self.filename[1:-1] # The 'type' attribute is deprecated in 3.2; remove it in 3.3. type = property( lambda self: self.content_type, doc="A deprecated alias for " ":attr:`content_type<cherrypy._cpreqbody.Entity.content_type>`." ) def read(self, size=None, fp_out=None): return self.fp.read(size, fp_out) def readline(self, size=None): return self.fp.readline(size) def readlines(self, sizehint=None): return self.fp.readlines(sizehint) def __iter__(self): return self def __next__(self): line = self.readline() if not line: raise StopIteration return line def next(self): return self.__next__() def read_into_file(self, fp_out=None): """Read the request body into fp_out (or make_file() if None). Return fp_out. """ if fp_out is None: fp_out = self.make_file() self.read(fp_out=fp_out) return fp_out def make_file(self): """Return a file-like object into which the request body will be read. By default, this will return a TemporaryFile. Override as needed. See also :attr:`cherrypy._cpreqbody.Part.maxrambytes`.""" return tempfile.TemporaryFile() def fullvalue(self): """Return this entity as a string, whether stored in a file or not.""" if self.file: # It was stored in a tempfile. Read it. self.file.seek(0) value = self.file.read() self.file.seek(0) else: value = self.value value = self.decode_entity(value) return value def decode_entity(self , value): """Return a given byte encoded value as a string""" for charset in self.attempt_charsets: try: value = value.decode(charset) except UnicodeDecodeError: pass else: self.charset = charset return value else: raise cherrypy.HTTPError( 400, "The request entity could not be decoded. The following " "charsets were attempted: %s" % repr(self.attempt_charsets) ) def process(self): """Execute the best-match processor for the given media type.""" proc = None ct = self.content_type.value try: proc = self.processors[ct] except KeyError: toptype = ct.split('/', 1)[0] try: proc = self.processors[toptype] except KeyError: pass if proc is None: self.default_proc() else: proc(self) def default_proc(self): """Called if a more-specific processor is not found for the ``Content-Type``. """ # Leave the fp alone for someone else to read. This works fine # for request.body, but the Part subclasses need to override this # so they can move on to the next part. pass class Part(Entity): """A MIME part entity, part of a multipart entity.""" # "The default character set, which must be assumed in the absence of a # charset parameter, is US-ASCII." attempt_charsets = ['us-ascii', 'utf-8'] """A list of strings, each of which should be a known encoding. When the Content-Type of the request body warrants it, each of the given encodings will be tried in order. The first one to successfully decode the entity without raising an error is stored as :attr:`entity.charset<cherrypy._cpreqbody.Entity.charset>`. This defaults to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_), but ``['us-ascii', 'utf-8']`` for multipart parts. """ boundary = None """The MIME multipart boundary.""" default_content_type = 'text/plain' """This defines a default ``Content-Type`` to use if no Content-Type header is given. The empty string is used for RequestBody, which results in the request body not being read or parsed at all. This is by design; a missing ``Content-Type`` header in the HTTP request entity is an error at best, and a security hole at worst. For multipart parts, however (this class), the MIME spec declares that a part with no Content-Type defaults to "text/plain". """ # This is the default in stdlib cgi. We may want to increase it. maxrambytes = 1000 """The threshold of bytes after which point the ``Part`` will store its data in a file (generated by :func:`make_file<cherrypy._cprequest.Entity.make_file>`) instead of a string. Defaults to 1000, just like the :mod:`cgi` module in Python's standard library. """ def __init__(self, fp, headers, boundary): Entity.__init__(self, fp, headers) self.boundary = boundary self.file = None self.value = None @classmethod def from_fp(cls, fp, boundary): headers = cls.read_headers(fp) return cls(fp, headers, boundary) @classmethod def read_headers(cls, fp): headers = httputil.HeaderMap() while True: line = fp.readline() if not line: # No more data--illegal end of headers raise EOFError("Illegal end of headers.") if line == ntob('\r\n'): # Normal end of headers break if not line.endswith(ntob('\r\n')): raise ValueError("MIME requires CRLF terminators: %r" % line) if line[0] in ntob(' \t'): # It's a continuation line. v = line.strip().decode('ISO-8859-1') else: k, v = line.split(ntob(":"), 1) k = k.strip().decode('ISO-8859-1') v = v.strip().decode('ISO-8859-1') existing = headers.get(k) if existing: v = ", ".join((existing, v)) headers[k] = v return headers def read_lines_to_boundary(self, fp_out=None): """Read bytes from self.fp and return or write them to a file. If the 'fp_out' argument is None (the default), all bytes read are returned in a single byte string. If the 'fp_out' argument is not None, it must be a file-like object that supports the 'write' method; all bytes read will be written to the fp, and that fp is returned. """ endmarker = self.boundary + ntob("--") delim = ntob("") prev_lf = True lines = [] seen = 0 while True: line = self.fp.readline(1 << 16) if not line: raise EOFError("Illegal end of multipart body.") if line.startswith(ntob("--")) and prev_lf: strippedline = line.strip() if strippedline == self.boundary: break if strippedline == endmarker: self.fp.finish() break line = delim + line if line.endswith(ntob("\r\n")): delim = ntob("\r\n") line = line[:-2] prev_lf = True elif line.endswith(ntob("\n")): delim = ntob("\n") line = line[:-1] prev_lf = True else: delim = ntob("") prev_lf = False if fp_out is None: lines.append(line) seen += len(line) if seen > self.maxrambytes: fp_out = self.make_file() for line in lines: fp_out.write(line) else: fp_out.write(line) if fp_out is None: result = ntob('').join(lines) return result else: fp_out.seek(0) return fp_out def default_proc(self): """Called if a more-specific processor is not found for the ``Content-Type``. """ if self.filename: # Always read into a file if a .filename was given. self.file = self.read_into_file() else: result = self.read_lines_to_boundary() if isinstance(result, text_or_bytes): self.value = result else: self.file = result def read_into_file(self, fp_out=None): """Read the request body into fp_out (or make_file() if None). Return fp_out. """ if fp_out is None: fp_out = self.make_file() self.read_lines_to_boundary(fp_out=fp_out) return fp_out Entity.part_class = Part try: inf = float('inf') except ValueError: # Python 2.4 and lower class Infinity(object): def __cmp__(self, other): return 1 def __sub__(self, other): return self inf = Infinity() comma_separated_headers = [ 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Accept-Ranges', 'Allow', 'Cache-Control', 'Connection', 'Content-Encoding', 'Content-Language', 'Expect', 'If-Match', 'If-None-Match', 'Pragma', 'Proxy-Authenticate', 'Te', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Vary', 'Via', 'Warning', 'Www-Authenticate' ] class SizedReader: def __init__(self, fp, length, maxbytes, bufsize=DEFAULT_BUFFER_SIZE, has_trailers=False): # Wrap our fp in a buffer so peek() works self.fp = fp self.length = length self.maxbytes = maxbytes self.buffer = ntob('') self.bufsize = bufsize self.bytes_read = 0 self.done = False self.has_trailers = has_trailers def read(self, size=None, fp_out=None): """Read bytes from the request body and return or write them to a file. A number of bytes less than or equal to the 'size' argument are read off the socket. The actual number of bytes read are tracked in self.bytes_read. The number may be smaller than 'size' when 1) the client sends fewer bytes, 2) the 'Content-Length' request header specifies fewer bytes than requested, or 3) the number of bytes read exceeds self.maxbytes (in which case, 413 is raised). If the 'fp_out' argument is None (the default), all bytes read are returned in a single byte string. If the 'fp_out' argument is not None, it must be a file-like object that supports the 'write' method; all bytes read will be written to the fp, and None is returned. """ if self.length is None: if size is None: remaining = inf else: remaining = size else: remaining = self.length - self.bytes_read if size and size < remaining: remaining = size if remaining == 0: self.finish() if fp_out is None: return ntob('') else: return None chunks = [] # Read bytes from the buffer. if self.buffer: if remaining is inf: data = self.buffer self.buffer = ntob('') else: data = self.buffer[:remaining] self.buffer = self.buffer[remaining:] datalen = len(data) remaining -= datalen # Check lengths. self.bytes_read += datalen if self.maxbytes and self.bytes_read > self.maxbytes: raise cherrypy.HTTPError(413) # Store the data. if fp_out is None: chunks.append(data) else: fp_out.write(data) # Read bytes from the socket. while remaining > 0: chunksize = min(remaining, self.bufsize) try: data = self.fp.read(chunksize) except Exception: e = sys.exc_info()[1] if e.__class__.__name__ == 'MaxSizeExceeded': # Post data is too big raise cherrypy.HTTPError( 413, "Maximum request length: %r" % e.args[1]) else: raise if not data: self.finish() break datalen = len(data) remaining -= datalen # Check lengths. self.bytes_read += datalen if self.maxbytes and self.bytes_read > self.maxbytes: raise cherrypy.HTTPError(413) # Store the data. if fp_out is None: chunks.append(data) else: fp_out.write(data) if fp_out is None: return ntob('').join(chunks) def readline(self, size=None): """Read a line from the request body and return it.""" chunks = [] while size is None or size > 0: chunksize = self.bufsize if size is not None and size < self.bufsize: chunksize = size data = self.read(chunksize) if not data: break pos = data.find(ntob('\n')) + 1 if pos: chunks.append(data[:pos]) remainder = data[pos:] self.buffer += remainder self.bytes_read -= len(remainder) break else: chunks.append(data) return ntob('').join(chunks) def readlines(self, sizehint=None): """Read lines from the request body and return them.""" if self.length is not None: if sizehint is None: sizehint = self.length - self.bytes_read else: sizehint = min(sizehint, self.length - self.bytes_read) lines = [] seen = 0 while True: line = self.readline() if not line: break lines.append(line) seen += len(line) if seen >= sizehint: break return lines def finish(self): self.done = True if self.has_trailers and hasattr(self.fp, 'read_trailer_lines'): self.trailers = {} try: for line in self.fp.read_trailer_lines(): if line[0] in ntob(' \t'): # It's a continuation line. v = line.strip() else: try: k, v = line.split(ntob(":"), 1) except ValueError: raise ValueError("Illegal header line.") k = k.strip().title() v = v.strip() if k in comma_separated_headers: existing = self.trailers.get(envname) if existing: v = ntob(", ").join((existing, v)) self.trailers[k] = v except Exception: e = sys.exc_info()[1] if e.__class__.__name__ == 'MaxSizeExceeded': # Post data is too big raise cherrypy.HTTPError( 413, "Maximum request length: %r" % e.args[1]) else: raise class RequestBody(Entity): """The entity of the HTTP request.""" bufsize = 8 * 1024 """The buffer size used when reading the socket.""" # Don't parse the request body at all if the client didn't provide # a Content-Type header. See # https://github.com/cherrypy/cherrypy/issues/790 default_content_type = '' """This defines a default ``Content-Type`` to use if no Content-Type header is given. The empty string is used for RequestBody, which results in the request body not being read or parsed at all. This is by design; a missing ``Content-Type`` header in the HTTP request entity is an error at best, and a security hole at worst. For multipart parts, however, the MIME spec declares that a part with no Content-Type defaults to "text/plain" (see :class:`Part<cherrypy._cpreqbody.Part>`). """ maxbytes = None """Raise ``MaxSizeExceeded`` if more bytes than this are read from the socket. """ def __init__(self, fp, headers, params=None, request_params=None): Entity.__init__(self, fp, headers, params) # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 # When no explicit charset parameter is provided by the # sender, media subtypes of the "text" type are defined # to have a default charset value of "ISO-8859-1" when # received via HTTP. if self.content_type.value.startswith('text/'): for c in ('ISO-8859-1', 'iso-8859-1', 'Latin-1', 'latin-1'): if c in self.attempt_charsets: break else: self.attempt_charsets.append('ISO-8859-1') # Temporary fix while deprecating passing .parts as .params. self.processors['multipart'] = _old_process_multipart if request_params is None: request_params = {} self.request_params = request_params def process(self): """Process the request entity based on its Content-Type.""" # "The presence of a message-body in a request is signaled by the # inclusion of a Content-Length or Transfer-Encoding header field in # the request's message-headers." # It is possible to send a POST request with no body, for example; # however, app developers are responsible in that case to set # cherrypy.request.process_body to False so this method isn't called. h = cherrypy.serving.request.headers if 'Content-Length' not in h and 'Transfer-Encoding' not in h: raise cherrypy.HTTPError(411) self.fp = SizedReader(self.fp, self.length, self.maxbytes, bufsize=self.bufsize, has_trailers='Trailer' in h) super(RequestBody, self).process() # Body params should also be a part of the request_params # add them in here. request_params = self.request_params for key, value in self.params.items(): # Python 2 only: keyword arguments must be byte strings (type # 'str'). if sys.version_info < (3, 0): if isinstance(key, unicode): key = key.encode('ISO-8859-1') if key in request_params: if not isinstance(request_params[key], list): request_params[key] = [request_params[key]] request_params[key].append(value) else: request_params[key] = value
heytcass/homeassistant-config
deps/cherrypy/_cpreqbody.py
Python
mit
37,427
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 0, transform = "Logit", sigma = 0.0, exog_count = 0, ar_order = 0);
antoinecarme/pyaf
tests/artificial/transf_Logit/trend_LinearTrend/cycle_0/ar_/test_artificial_32_Logit_LinearTrend_0__0.py
Python
bsd-3-clause
260
import os from unittest import mock from django.conf import settings from django.core.files.storage import get_storage_class from django.test import TestCase from django.test.utils import override_settings from readthedocs.projects.models import HTMLFile, ImportedFile, Project from readthedocs.projects.tasks import ( _create_imported_files, _create_intersphinx_data, _sync_imported_files, ) from readthedocs.sphinx_domains.models import SphinxDomain base_dir = os.path.dirname(os.path.dirname(__file__)) class ImportedFileTests(TestCase): fixtures = ['eric', 'test_data'] storage = get_storage_class(settings.RTD_BUILD_MEDIA_STORAGE)() def setUp(self): self.project = Project.objects.get(slug='pip') self.version = self.project.versions.first() self.test_dir = os.path.join(base_dir, 'files') self._copy_storage_dir() def _manage_imported_files( self, version, commit, build, search_ranking=None, search_ignore=None ): """Helper function for the tests to create and sync ImportedFiles.""" search_ranking = search_ranking or {} search_ignore = search_ignore or [] _create_imported_files( version=version, commit=commit, build=build, search_ranking=search_ranking, search_ignore=search_ignore, ) _sync_imported_files(version, build) def _copy_storage_dir(self): """Copy the test directory (rtd_tests/files) to storage""" self.storage.copy_directory( self.test_dir, self.project.get_storage_path( type_='html', version_slug=self.version.slug, include_file=False, ), ) def test_properly_created(self): # Only 2 files in the directory is HTML (test.html, api/index.html) self.assertEqual(ImportedFile.objects.count(), 0) self._manage_imported_files(version=self.version, commit='commit01', build=1) self.assertEqual(ImportedFile.objects.count(), 2) self._manage_imported_files(version=self.version, commit='commit01', build=2) self.assertEqual(ImportedFile.objects.count(), 2) self.project.cdn_enabled = True self.project.save() def test_update_commit(self): self.assertEqual(ImportedFile.objects.count(), 0) self._manage_imported_files(self.version, 'commit01', 1) self.assertEqual(ImportedFile.objects.first().commit, 'commit01') self._manage_imported_files(self.version, 'commit02', 2) self.assertEqual(ImportedFile.objects.first().commit, 'commit02') def test_page_default_rank(self): search_ranking = {} self.assertEqual(HTMLFile.objects.count(), 0) self._manage_imported_files(self.version, 'commit01', 1, search_ranking) self.assertEqual(HTMLFile.objects.count(), 2) self.assertEqual(HTMLFile.objects.filter(rank=0).count(), 2) def test_page_custom_rank_glob(self): search_ranking = { '*index.html': 5, } self._manage_imported_files(self.version, 'commit01', 1, search_ranking) self.assertEqual(HTMLFile.objects.count(), 2) file_api = HTMLFile.objects.get(path='api/index.html') file_test = HTMLFile.objects.get(path='test.html') self.assertEqual(file_api.rank, 5) self.assertEqual(file_test.rank, 0) def test_page_custom_rank_several(self): search_ranking = { 'test.html': 5, 'api/index.html': 2, } self._manage_imported_files(self.version, 'commit01', 1, search_ranking) self.assertEqual(HTMLFile.objects.count(), 2) file_api = HTMLFile.objects.get(path='api/index.html') file_test = HTMLFile.objects.get(path='test.html') self.assertEqual(file_api.rank, 2) self.assertEqual(file_test.rank, 5) def test_page_custom_rank_precedence(self): search_ranking = { '*.html': 5, 'api/index.html': 2, } self._manage_imported_files(self.version, 'commit01', 1, search_ranking) self.assertEqual(HTMLFile.objects.count(), 2) file_api = HTMLFile.objects.get(path='api/index.html') file_test = HTMLFile.objects.get(path='test.html') self.assertEqual(file_api.rank, 2) self.assertEqual(file_test.rank, 5) def test_page_custom_rank_precedence_inverted(self): search_ranking = { 'api/index.html': 2, '*.html': 5, } self._manage_imported_files(self.version, 'commit01', 1, search_ranking) self.assertEqual(HTMLFile.objects.count(), 2) file_api = HTMLFile.objects.get(path='api/index.html') file_test = HTMLFile.objects.get(path='test.html') self.assertEqual(file_api.rank, 5) self.assertEqual(file_test.rank, 5) def test_search_page_ignore(self): search_ignore = [ 'api/index.html' ] self._manage_imported_files( self.version, 'commit01', 1, search_ignore=search_ignore, ) self.assertEqual(HTMLFile.objects.count(), 2) file_api = HTMLFile.objects.get(path='api/index.html') file_test = HTMLFile.objects.get(path='test.html') self.assertTrue(file_api.ignore) self.assertFalse(file_test.ignore) def test_update_content(self): test_dir = os.path.join(base_dir, 'files') self.assertEqual(ImportedFile.objects.count(), 0) with open(os.path.join(test_dir, 'test.html'), 'w+') as f: f.write('Woo') self._copy_storage_dir() self._manage_imported_files(self.version, 'commit01', 1) self.assertEqual(ImportedFile.objects.count(), 2) with open(os.path.join(test_dir, 'test.html'), 'w+') as f: f.write('Something Else') self._copy_storage_dir() self._manage_imported_files(self.version, 'commit02', 2) self.assertEqual(ImportedFile.objects.count(), 2) @override_settings(PRODUCTION_DOMAIN='readthedocs.org') @override_settings(RTD_INTERSPHINX_URL='https://readthedocs.org') @mock.patch('readthedocs.projects.tasks.os.path.exists') def test_create_intersphinx_data(self, mock_exists): mock_exists.return_Value = True # Test data for objects.inv file test_objects_inv = { 'cpp:function': { 'sphinx.test.function': [ 'dummy-proj-1', 'dummy-version-1', 'test.html#epub-faq', # file generated by ``sphinx.builders.html.StandaloneHTMLBuilder`` 'dummy-func-name-1', ] }, 'py:function': { 'sample.test.function': [ 'dummy-proj-2', 'dummy-version-2', 'test.html#sample-test-func', # file generated by ``sphinx.builders.html.StandaloneHTMLBuilder`` 'dummy-func-name-2' ] }, 'js:function': { 'testFunction': [ 'dummy-proj-3', 'dummy-version-3', 'api/#test-func', # file generated by ``sphinx.builders.dirhtml.DirectoryHTMLBuilder`` 'dummy-func-name-3' ] } } with mock.patch( 'sphinx.ext.intersphinx.fetch_inventory', return_value=test_objects_inv ) as mock_fetch_inventory: _create_imported_files( version=self.version, commit='commit01', build=1, search_ranking={}, search_ignore=[], ) _create_intersphinx_data(self.version, 'commit01', 1) # there will be two html files, # `api/index.html` and `test.html` self.assertEqual( HTMLFile.objects.all().count(), 2 ) self.assertEqual( HTMLFile.objects.filter(path='test.html').count(), 1 ) self.assertEqual( HTMLFile.objects.filter(path='api/index.html').count(), 1 ) html_file_api = HTMLFile.objects.filter(path='api/index.html').first() self.assertEqual( SphinxDomain.objects.all().count(), 3 ) self.assertEqual( SphinxDomain.objects.filter(html_file=html_file_api).count(), 1 ) mock_fetch_inventory.assert_called_once() self.assertRegex( mock_fetch_inventory.call_args[0][2], r'^https://readthedocs\.org/media/.*/objects\.inv$' ) self.assertEqual(ImportedFile.objects.count(), 2) @override_settings(RTD_INTERSPHINX_URL='http://localhost:8080') @mock.patch('readthedocs.projects.tasks.os.path.exists') def test_custom_intersphinx_url(self, mock_exists): mock_exists.return_Value = True with mock.patch( 'sphinx.ext.intersphinx.fetch_inventory', return_value={} ) as mock_fetch_inventory: _create_intersphinx_data(self.version, 'commit01', 1) mock_fetch_inventory.assert_called_once() self.assertRegex( mock_fetch_inventory.call_args[0][2], '^http://localhost:8080/media/.*/objects.inv$' )
rtfd/readthedocs.org
readthedocs/rtd_tests/tests/test_imported_file.py
Python
mit
9,677
#!/bin/python #-*-coding: utf-8-*- def uniSegSents(compete_sent_seg): feature1 = [u'总评', u'创新力', u'知名度', u'名气', u'品牌'] feature2 = [u'硬件', u'内存', u'cup', u'电池', u'重量',u'尺寸',u'材质'] feature3 = [u'用户体验', u'游戏', u'应用', u'手感', u'外观', u'操控性',u'流畅度', u'售后'] #feature4 = [u'系统', u'操控性', u'流畅度'] feaComp1, feaComp2, feaComp3, feaComp4 = [], [], [], [], [] for c in compete_sent_seg: for f in feature1: index = [i for i, w in enumerate(c) if w == f] if (len(index) != 0): for i in index: c[i] = feature1[0] feaComp1.append(c) for f in feature2: index = [i for i, w in enumerate(c) if w == f] if (len(index) != 0): for i in index: c[i] = feature2[0] feaComp2.append(c) for f in feature3: index = [i for i, w in enumerate(c) if w == f] if (len(index) != 0): for i in index: c[i] = feature3[0] feaComp3.append(c) for f in feature4: index = [i for i, w in enumerate(c) if w == f] if (len(index) != 0): for i in index: c[i] = feature4[0] feaComp4.append(c) return feaComp1, feaComp2, feaComp3, feaComp4 def getScoremydict(filepath): fp = open(filepath, 'r') mydict = {} for line in fp.readlines(): if (line == '\n'): continue key, value = (line.decode('utf-8')).replace(u'\n', '').split(' ') mydict[key] = value return mydict def scoreSent(feaCompSent, mydict): product = [u'苹果', u'三星'] score, scoreA, scoreB = 0, 0, 0 for s in feaCompSent: index0 = [i for i, w in enumerate(s) if w == product[0]] index1 = [i for i, w in enumerate(s) if w == product[1]] for w in s: if w in mydict.keys(): score += mydict[w] if (index0 < index1): scoreA += score else: scoreB += score score = 0 return scoreA, scoreB print product[0], '得分: ', scoreA print product[1], '得分: ', scoreB
hao-app/baiduCrawl
featureScore.py
Python
gpl-2.0
2,319
# -*- coding: utf-8 -*- # Copyright 2022 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. # # Generated code. DO NOT EDIT! # # Snippet for UpdateTrigger # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-eventarc # [START eventarc_v1_generated_Eventarc_UpdateTrigger_async] from google.cloud import eventarc_v1 async def sample_update_trigger(): # Create a client client = eventarc_v1.EventarcAsyncClient() # Initialize request argument(s) request = eventarc_v1.UpdateTriggerRequest( validate_only=True, ) # Make the request operation = client.update_trigger(request=request) print("Waiting for operation to complete...") response = await operation.result() # Handle the response print(response) # [END eventarc_v1_generated_Eventarc_UpdateTrigger_async]
googleapis/python-eventarc
samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py
Python
apache-2.0
1,538
from django.contrib import admin from main.models import Problem, TestData class TestDataInline(admin.TabularInline): model = TestData fields = ('order', 'input_file', 'output_file', 'create_time',) readonly_fields = ('create_time',) @admin.register(Problem) class ProblemAdmin(admin.ModelAdmin): list_display = ('number', 'title', 'time_limit', 'memory_limit', 'released', 'deadline', 'contributor', 'testdata_num', 'accept_rate', 'is_deleted',) list_display_links = ('number', 'title',) list_editable = ('released', 'contributor', 'is_deleted',) fields = ('number', 'title', 'time_limit', 'memory_limit', 'desc', 'input_desc', 'output_desc', 'input_sample', 'output_sample', 'hint', 'deadline', 'released', 'is_deleted', 'contributor', 'create_time', 'submit_cnt', 'accept_cnt', 'compare_file',) readonly_fields = ('create_time', 'submit_cnt', 'accept_cnt',) inlines = [TestDataInline,]
prajnamort/LambdaOJ2
main/admin/problem.py
Python
mit
1,026
import cv2 import cv2.cv as cv from CapraVision.server.filters.parameter import Parameter class RemoveObstacle: """Remove obstacles from an image""" def __init__(self): self.threshold = Parameter("Threshold",0,255,12) self.vertical_blur = Parameter("Vertical Blur",1,255,18) self.horizontal_blur = Parameter("Horizontal Blur",1,255,3) def execute(self, image): copy = cv2.cvtColor(image, cv.CV_RGB2HSV) copy = cv2.blur(copy, (int(self.horizontal_blur.get_current_value()), int(self.vertical_blur.get_current_value()))) h, _, _ = cv2.split(copy) h[h > self.threshold.get_current_value()] = 0 contours, _ = cv2.findContours( h, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: x,y,w,h = cv2.boundingRect(contour) miny = y - h if miny < 0: miny = 0 maxy = y + h if maxy > image.shape[0]: maxy = image.shape[0] minx = x if minx < 0: minx = 0 maxx = x + w if maxx > image.shape[1]: maxx = image.shape[1] image[miny:maxy, minx:maxx] = 0 return image
clubcapra/Ibex
src/seagoatvision_ros/scripts/CapraVision/server/filters/implementation/removeobstacle.py
Python
gpl-3.0
1,385
# # Imports ########################################################### import logging import pkg_resources from django.template import Context, Template # Globals ########################################################### log = logging.getLogger(__name__) # Functions ######################################################### def load_resource(resource_path): """ Gets the content of a resource """ resource_content = pkg_resources.resource_string(__name__, resource_path) return str(resource_content.decode('utf-8')) def render_template(template_path, context={}): """ Evaluate a template by resource path, applying the provided context """ template_str = load_resource(template_path) template = Template(template_str) return template.render(Context(context)) class AttrDict(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__dict__ = self
edx-solutions/xblock-drag-and-drop
drag_and_drop/utils.py
Python
agpl-3.0
953
from utils import enter_depend_test, STEPS, RESULT, SETUP enter_depend_test() from depend_test_framework.test_object import Action, CheckPoint, TestObject, Mist, MistDeadEndException, MistClearException from depend_test_framework.dependency import Provider, Consumer from depend_test_framework.base_class import ParamsRequire @Action.decorator(1) @ParamsRequire.decorator(['guest_name', 'numa']) @Consumer.decorator('$guest_name.config', Consumer.REQUIRE) @Provider.decorator('$guest_name.config.numa', Provider.SET) def set_guest_numa(params, env): """ """ pass
LuyaoHuang/depend-test-framework
examples/numa.py
Python
mit
578
from __future__ import absolute_import import datetime from sentry.utils.compat import mock import six from django.core.urlresolvers import reverse from django.db.models import F from django.conf import settings from django.utils import timezone from sentry.auth.authenticators import ( TotpInterface, RecoveryCodeInterface, SmsInterface, ) from sentry.models import Authenticator, Organization from sentry.testutils import APITestCase class UserAuthenticatorDetailsTest(APITestCase): def setUp(self): self.user = self.create_user(email="test@example.com", is_superuser=False) self.login_as(user=self.user) def _assert_security_email_sent(self, email_type, email_log): assert email_log.info.call_count == 1 assert "mail.queued" in email_log.info.call_args[0] assert email_log.info.call_args[1]["extra"]["message_type"] == email_type def _require_2fa_for_organization(self): organization = self.create_organization(name="test monkey", owner=self.user) organization.update(flags=F("flags").bitor(Organization.flags.require_2fa)) def test_wrong_auth_id(self): url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": "totp"}, ) resp = self.client.get(url) assert resp.status_code == 404 def test_get_authenticator_details(self): interface = TotpInterface() interface.enroll(self.user) auth = interface.authenticator url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": auth.id}, ) resp = self.client.get(url) assert resp.status_code == 200 assert resp.data["isEnrolled"] assert resp.data["id"] == "totp" assert resp.data["authId"] == six.text_type(auth.id) # should not have these because enrollment assert "totp_secret" not in resp.data assert "form" not in resp.data assert "qrcode" not in resp.data @mock.patch("sentry.utils.email.logger") def test_get_recovery_codes(self, email_log): interface = RecoveryCodeInterface() interface.enroll(self.user) url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": interface.authenticator.id}, ) resp = self.client.get(url) assert resp.status_code == 200 assert resp.data["id"] == "recovery" assert resp.data["authId"] == six.text_type(interface.authenticator.id) assert len(resp.data["codes"]) assert email_log.info.call_count == 0 def test_u2f_get_devices(self): auth = Authenticator.objects.create( type=3, # u2f user=self.user, config={ "devices": [ { "binding": { "publicKey": u"aowekroawker", "keyHandle": u"aowkeroakewrokaweokrwoer", "appId": u"https://dev.getsentry.net:8000/auth/2fa/u2fappid.json", }, "name": u"Amused Beetle", "ts": 1512505334, } ] }, ) url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": auth.id}, ) resp = self.client.get(url) assert resp.status_code == 200 assert resp.data["id"] == "u2f" assert resp.data["authId"] == six.text_type(auth.id) assert len(resp.data["devices"]) assert resp.data["devices"][0]["name"] == "Amused Beetle" # should not have these because enrollment assert "challenge" not in resp.data assert "response" not in resp.data def test_get_device_name(self): auth = Authenticator.objects.create( type=3, # u2f user=self.user, config={ "devices": [ { "binding": { "publicKey": "aowekroawker", "keyHandle": "devicekeyhandle", "appId": "https://dev.getsentry.net:8000/auth/2fa/u2fappid.json", }, "name": "Amused Beetle", "ts": 1512505334, }, { "binding": { "publicKey": "publickey", "keyHandle": "aowerkoweraowerkkro", "appId": "https://dev.getsentry.net:8000/auth/2fa/u2fappid.json", }, "name": "Sentry", "ts": 1512505334, }, ] }, ) assert auth.interface.get_device_name("devicekeyhandle") == "Amused Beetle" assert auth.interface.get_device_name("aowerkoweraowerkkro") == "Sentry" @mock.patch("sentry.utils.email.logger") def test_u2f_remove_device(self, email_log): auth = Authenticator.objects.create( type=3, # u2f user=self.user, config={ "devices": [ { "binding": { "publicKey": "aowekroawker", "keyHandle": "devicekeyhandle", "appId": "https://dev.getsentry.net:8000/auth/2fa/u2fappid.json", }, "name": "Amused Beetle", "ts": 1512505334, }, { "binding": { "publicKey": "publickey", "keyHandle": "aowerkoweraowerkkro", "appId": "https://dev.getsentry.net:8000/auth/2fa/u2fappid.json", }, "name": "Sentry", "ts": 1512505334, }, ] }, ) url = reverse( "sentry-api-0-user-authenticator-device-details", kwargs={ "user_id": self.user.id, "auth_id": auth.id, "interface_device_id": "devicekeyhandle", }, ) resp = self.client.delete(url) assert resp.status_code == 204 authenticator = Authenticator.objects.get(id=auth.id) assert len(authenticator.interface.get_registered_devices()) == 1 self._assert_security_email_sent("mfa-removed", email_log) # Can't remove last device url = reverse( "sentry-api-0-user-authenticator-device-details", kwargs={ "user_id": self.user.id, "auth_id": auth.id, "interface_device_id": "aowerkoweraowerkkro", }, ) resp = self.client.delete(url) assert resp.status_code == 500 # only one send self._assert_security_email_sent("mfa-removed", email_log) def test_sms_get_phone(self): interface = SmsInterface() interface.phone_number = "5551231234" interface.enroll(self.user) url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": interface.authenticator.id}, ) resp = self.client.get(url) assert resp.status_code == 200 assert resp.data["id"] == "sms" assert resp.data["authId"] == six.text_type(interface.authenticator.id) assert resp.data["phone"] == "5551231234" # should not have these because enrollment assert "totp_secret" not in resp.data assert "form" not in resp.data @mock.patch("sentry.utils.email.logger") def test_recovery_codes_regenerate(self, email_log): interface = RecoveryCodeInterface() interface.enroll(self.user) url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": interface.authenticator.id}, ) resp = self.client.get(url) assert resp.status_code == 200 old_codes = resp.data["codes"] old_created_at = resp.data["createdAt"] resp = self.client.get(url) assert old_codes == resp.data["codes"] assert old_created_at == resp.data["createdAt"] # regenerate codes tomorrow = timezone.now() + datetime.timedelta(days=1) with mock.patch.object(timezone, "now", return_value=tomorrow): resp = self.client.put(url) resp = self.client.get(url) assert old_codes != resp.data["codes"] assert old_created_at != resp.data["createdAt"] self._assert_security_email_sent("recovery-codes-regenerated", email_log) @mock.patch("sentry.utils.email.logger") def test_delete(self, email_log): new_options = settings.SENTRY_OPTIONS.copy() new_options["sms.twilio-account"] = "twilio-account" user = self.create_user(email="a@example.com", is_superuser=True) with self.settings(SENTRY_OPTIONS=new_options): auth = Authenticator.objects.create(type=2, user=user) # sms available_auths = Authenticator.objects.all_interfaces_for_user( user, ignore_backup=True ) self.assertEqual(len(available_auths), 1) self.login_as(user=user, superuser=True) url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": user.id, "auth_id": auth.id}, ) resp = self.client.delete(url, format="json") assert resp.status_code == 204, (resp.status_code, resp.content) assert not Authenticator.objects.filter(id=auth.id).exists() self._assert_security_email_sent("mfa-removed", email_log) @mock.patch("sentry.utils.email.logger") def test_cannot_delete_without_superuser(self, email_log): user = self.create_user(email="a@example.com", is_superuser=False) auth = Authenticator.objects.create(type=3, user=user) # u2f actor = self.create_user(email="b@example.com", is_superuser=False) self.login_as(user=actor) url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": user.id, "auth_id": auth.id}, ) resp = self.client.delete(url, format="json") assert resp.status_code == 403, (resp.status_code, resp.content) assert Authenticator.objects.filter(id=auth.id).exists() assert email_log.info.call_count == 0 @mock.patch("sentry.utils.email.logger") def test_require_2fa__cannot_delete_last_auth(self, email_log): self._require_2fa_for_organization() # enroll in one auth method interface = TotpInterface() interface.enroll(self.user) auth = interface.authenticator url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": auth.id}, ) resp = self.client.delete(url, format="json") assert resp.status_code == 403, (resp.status_code, resp.content) assert b"requires 2FA" in resp.content assert Authenticator.objects.filter(id=auth.id).exists() assert email_log.info.call_count == 0 @mock.patch("sentry.utils.email.logger") def test_require_2fa__delete_with_multiple_auth__ok(self, email_log): self._require_2fa_for_organization() new_options = settings.SENTRY_OPTIONS.copy() new_options["sms.twilio-account"] = "twilio-account" with self.settings(SENTRY_OPTIONS=new_options): # enroll in two auth methods interface = SmsInterface() interface.phone_number = "5551231234" interface.enroll(self.user) interface = TotpInterface() interface.enroll(self.user) auth = interface.authenticator url = reverse( "sentry-api-0-user-authenticator-details", kwargs={"user_id": self.user.id, "auth_id": auth.id}, ) resp = self.client.delete(url, format="json") assert resp.status_code == 204, (resp.status_code, resp.content) assert not Authenticator.objects.filter(id=auth.id).exists() self._assert_security_email_sent("mfa-removed", email_log) @mock.patch("sentry.utils.email.logger") def test_require_2fa__delete_device__ok(self, email_log): self._require_2fa_for_organization() self.test_u2f_remove_device()
beeftornado/sentry
tests/sentry/api/endpoints/test_user_authenticator_details.py
Python
bsd-3-clause
12,973
#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', type='fanout') message = ' '.join(sys.argv[1:]) or "Hello World!" channel.basic_publish(exchange='logs', routing_key='', body=message) print " [x] Sent %r " % (message,) connection.close()
pjberry/rabbitmq-tutorial-python
emit_log.py
Python
apache-2.0
390
from django.conf import settings from django.core.signing import BadSignature, TimestampSigner from django.db import transaction from django.utils.translation import ugettext_lazy as _ from python_freeipa import exceptions as freeipa_exceptions from rest_framework import serializers from waldur_core.core import models as core_models from waldur_core.core import utils as core_utils from waldur_core.core.utils import pwgen from waldur_core.structure.models import ProjectRole from waldur_core.users import models from waldur_freeipa import tasks from waldur_freeipa.backend import FreeIPABackend from waldur_freeipa.models import Profile from waldur_freeipa.utils import generate_username def get_invitation_context(invitation, sender): if invitation.project_role is not None: context = dict(type=_('project'), name=invitation.project.name) role_prefix = ( _('project') if invitation.project_role == ProjectRole.MANAGER else _('system') ) context['role'] = '%s %s' % (role_prefix, invitation.get_project_role_display()) else: context = dict( type=_('organization'), name=invitation.customer.name, role=invitation.get_customer_role_display(), ) context['sender'] = sender context['invitation'] = invitation return context def get_invitation_token(invitation, user): signer = TimestampSigner() payload = '%s.%s' % (user.uuid.hex, invitation.uuid.hex) return signer.sign(payload) def parse_invitation_token(token): signer = TimestampSigner() try: payload = signer.unsign( token, max_age=settings.WALDUR_CORE['INVITATION_MAX_AGE'] ) except BadSignature: raise serializers.ValidationError('Invalid signature.') parts = payload.split('.') if len(parts) != 2: raise serializers.ValidationError('Invalid payload.') user_uuid = parts[0] invitation_uuid = parts[1] if not core_utils.is_uuid_like(user_uuid): raise serializers.ValidationError('Invalid user UUID.') try: user = core_models.User.objects.filter( uuid=parts[0], is_active=True, is_staff=True ).get() except core_models.User.DoesNotExist: raise serializers.ValidationError('Invalid user UUID.') if not core_utils.is_uuid_like(invitation_uuid): raise serializers.ValidationError('Invalid invitation UUID.') try: invitation = models.Invitation.objects.get( uuid=parts[1], state=models.Invitation.State.REQUESTED ) except models.Invitation.DoesNotExist: raise serializers.ValidationError('Invalid invitation UUID.') return user, invitation def normalize_username(username): return ''.join(c if c.isalnum() else '_' for c in username.lower()) def generate_safe_username(username): username = generate_username(username) # Maximum length for FreeIPA username is 32 chars if len(username) > 32: prefix_length = len(settings.WALDUR_FREEIPA['USERNAME_PREFIX']) username = generate_username(pwgen(32 - prefix_length)) return username @transaction.atomic def get_or_create_user(invitation): if invitation.civil_number: user = core_models.User.objects.filter( civil_number=invitation.civil_number ).first() if user: return user, False user = core_models.User.objects.filter(email=invitation.email).first() if user: return user, False username = normalize_username(invitation.email) user = core_models.User.objects.filter(username=username).first() if user: return user, False payload = { field: getattr(invitation, field) for field in ( 'full_name', 'native_name', 'organization', 'civil_number', 'job_title', 'phone_number', ) } user = core_models.User.objects.create_user( username=username, email=invitation.email, registration_method='FREEIPA', **payload ) user.set_unusable_password() user.save() return user, True @transaction.atomic def get_or_create_profile(user, username, password): profile = Profile.objects.filter(user=user).first() if profile: return profile, False profile = Profile.objects.create(user=user, username=username,) try: FreeIPABackend().create_profile(profile, password=password) tasks.schedule_sync() except freeipa_exceptions.DuplicateEntry: pass return profile, True def get_invitation_link(uuid): return core_utils.format_homeport_link('invitation/{uuid}/', uuid=uuid)
opennode/nodeconductor-assembly-waldur
src/waldur_core/users/utils.py
Python
mit
4,753
'''Typecodes for dates and times. ''' from pyAMI.extern.ZSI import _copyright, _floattypes, _inttypes, _get_idstr, EvaluateException from pyAMI.extern.ZSI.TC import TypeCode, SimpleType from wstools.Namespaces import SCHEMA import operator, re, time as _time from time import mktime as _mktime, localtime as _localtime, gmtime as _gmtime from datetime import tzinfo as _tzinfo, timedelta as _timedelta,\ datetime as _datetime from math import modf as _modf _niltime = [ 0, 0, 0, # year month day 0, 0, 0, # hour minute second 0, 0, 0 # weekday, julian day, dst flag ] #### Code added to check current timezone offset _zero = _timedelta(0) _dstoffset = _stdoffset = _timedelta(seconds=-_time.timezone) if _time.daylight: _dstoffset = _timedelta(seconds=-_time.altzone) _dstdiff = _dstoffset - _stdoffset class _localtimezone(_tzinfo): """ """ def dst(self, dt): """datetime -> DST offset in minutes east of UTC.""" tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) if tt.tm_isdst > 0: return _dstdiff return _zero #def fromutc(...) #datetime in UTC -> datetime in local time. def tzname(self, dt): """datetime -> string name of time zone.""" tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) return _time.tzname[tt.tm_isdst > 0] def utcoffset(self, dt): """datetime -> minutes east of UTC (negative for west of UTC).""" tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) if tt.tm_isdst > 0: return _dstoffset return _stdoffset class _fixedoffset(_tzinfo): """Fixed offset in minutes east from UTC. A class building tzinfo objects for fixed-offset time zones. Note that _fixedoffset(0, "UTC") is a different way to build a UTC tzinfo object. """ #def __init__(self, offset, name): def __init__(self, offset): self.__offset = _timedelta(minutes=offset) #self.__name = name def dst(self, dt): """datetime -> DST offset in minutes east of UTC.""" return _zero def tzname(self, dt): """datetime -> string name of time zone.""" #return self.__name return "server" def utcoffset(self, dt): """datetime -> minutes east of UTC (negative for west of UTC).""" return self.__offset def _dict_to_tuple(d): '''Convert a dictionary to a time tuple. Depends on key values in the regexp pattern! ''' retval = _niltime[:] for k,i in ( ('Y', 0), ('M', 1), ('D', 2), ('h', 3), ('m', 4), ): v = d.get(k) if v: retval[i] = int(v) v = d.get('s') if v: msec,sec = _modf(float(v)) retval[6],retval[5] = int(round(msec*1000)), int(sec) v = d.get('tz') if v and v != 'Z': h,m = map(int, v.split(':')) # check for time zone offset, if within the same timezone, # ignore offset specific calculations offset=_localtimezone().utcoffset(_datetime.now()) local_offset_hour = offset.seconds/3600 local_offset_min = (offset.seconds%3600)%60 if local_offset_hour > 12: local_offset_hour -= 24 if local_offset_hour != h or local_offset_min != m: if h<0: #TODO: why is this set to server #foff = _fixedoffset(-((abs(h)*60+m)),"server") foff = _fixedoffset(-((abs(h)*60+m))) else: #TODO: why is this set to server #foff = _fixedoffset((abs(h)*60+m),"server") foff = _fixedoffset((abs(h)*60+m)) dt = _datetime(retval[0],retval[1],retval[2],retval[3],retval[4], retval[5],0,foff) # update dict with calculated timezone localdt=dt.astimezone(_localtimezone()) retval[0] = localdt.year retval[1] = localdt.month retval[2] = localdt.day retval[3] = localdt.hour retval[4] = localdt.minute retval[5] = localdt.second if d.get('neg', 0): retval[0:5] = map(operator.__neg__, retval[0:5]) return tuple(retval) class Duration(SimpleType): '''Time duration. ''' parselist = [ (None,'duration') ] lex_pattern = re.compile('^' r'(?P<neg>-?)P' \ r'((?P<Y>\d+)Y)?' r'((?P<M>\d+)M)?' r'((?P<D>\d+)D)?' \ r'(?P<T>T?)' r'((?P<h>\d+)H)?' r'((?P<m>\d+)M)?' \ r'((?P<s>\d*(\.\d+)?)S)?' '$') type = (SCHEMA.XSD3, 'duration') def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. ''' if text is None: return None m = Duration.lex_pattern.match(text) if m is None: raise EvaluateException('Illegal duration', ps.Backtrace(elt)) d = m.groupdict() if d['T'] and (d['h'] is None and d['m'] is None and d['s'] is None): raise EvaluateException('Duration has T without time') try: retval = _dict_to_tuple(d) except ValueError, e: raise EvaluateException(str(e)) if self.pyclass is not None: return self.pyclass(retval) return retval def get_formatted_content(self, pyobj): if type(pyobj) in _floattypes or type(pyobj) in _inttypes: pyobj = _gmtime(pyobj) d = {} pyobj = tuple(pyobj) if 1 in map(lambda x: x < 0, pyobj[0:6]): pyobj = map(abs, pyobj) neg = '-' else: neg = '' val = '%sP%dY%dM%dDT%dH%dM%dS' % \ ( neg, pyobj[0], pyobj[1], pyobj[2], pyobj[3], pyobj[4], pyobj[5]) return val class Gregorian(SimpleType): '''Gregorian times. ''' lex_pattern = tag = format = None def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. ''' if text is None: return None m = self.lex_pattern.match(text) if not m: raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt)) try: retval = _dict_to_tuple(m.groupdict()) except ValueError, e: #raise EvaluateException(str(e)) raise if self.pyclass is not None: return self.pyclass(retval) return retval def get_formatted_content(self, pyobj): if type(pyobj) in _floattypes or type(pyobj) in _inttypes: pyobj = _gmtime(pyobj) d = {} pyobj = tuple(pyobj) if 1 in map(lambda x: x < 0, pyobj[0:6]): pyobj = map(abs, pyobj) d['neg'] = '-' else: d['neg'] = '' ms = pyobj[6] if not ms: d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2], 'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], } return self.format % d if ms > 999: raise ValueError, 'milliseconds must be a integer between 0 and 999' d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2], 'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], 'ms':ms, } return self.format_ms % d class gDateTime(Gregorian): '''A date and time. ''' parselist = [ (None,'dateTime') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' 'T' \ r'(?P<h>\d\d):' r'(?P<m>\d\d):' r'(?P<s>\d*(\.\d+)?)' \ r'(?P<tz>(Z|([-+]\d\d:\d\d))?)' '$') tag, format = 'dateTime', '%(Y)04d-%(M)02d-%(D)02dT%(h)02d:%(m)02d:%(s)02dZ' format_ms = format[:-1] + '.%(ms)03dZ' type = (SCHEMA.XSD3, 'dateTime') class gDate(Gregorian): '''A date. ''' parselist = [ (None,'date') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'date', '%(Y)04d-%(M)02d-%(D)02dZ' type = (SCHEMA.XSD3, 'date') class gYearMonth(Gregorian): '''A date. ''' parselist = [ (None,'gYearMonth') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})-' r'(?P<M>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'gYearMonth', '%(Y)04d-%(M)02dZ' type = (SCHEMA.XSD3, 'gYearMonth') class gYear(Gregorian): '''A date. ''' parselist = [ (None,'gYear') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'gYear', '%(Y)04dZ' type = (SCHEMA.XSD3, 'gYear') class gMonthDay(Gregorian): '''A gMonthDay. ''' parselist = [ (None,'gMonthDay') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ r'--(?P<M>\d\d)-' r'(?P<D>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'gMonthDay', '---%(M)02d-%(D)02dZ' type = (SCHEMA.XSD3, 'gMonthDay') class gDay(Gregorian): '''A gDay. ''' parselist = [ (None,'gDay') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ r'---(?P<D>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'gDay', '---%(D)02dZ' type = (SCHEMA.XSD3, 'gDay') class gMonth(Gregorian): '''A gMonth. ''' parselist = [ (None,'gMonth') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ r'---(?P<M>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'gMonth', '---%(M)02dZ' type = (SCHEMA.XSD3, 'gMonth') class gTime(Gregorian): '''A time. ''' parselist = [ (None,'time') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ r'(?P<h>\d\d):' r'(?P<m>\d\d):' r'(?P<s>\d*(\.\d+)?)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') tag, format = 'time', '%(h)02d:%(m)02d:%(s)02dZ' format_ms = format[:-1] + '.%(ms)03dZ' type = (SCHEMA.XSD3, 'time')
ndawe/pyAMI
pyAMI/extern/ZSI/TCtimes.py
Python
gpl-3.0
10,315
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # Tom Cobb - initial API and implementation and/or initial documentation # Gary Yendell - initial API and implementation and/or initial documentation # Charles Mita - initial API and implementation and/or initial documentation # ### __version__ = '3.1'
dls-controls/scanpointgenerator
scanpointgenerator/version.py
Python
apache-2.0
338
# # An attempt at re-implementing LZJB compression in native Python. # # Created in May 2014 by Emil Brink <emil@obsession.se>. See LICENSE. # # --------------------------------------------------------------------- # # Copyright (c) 2014-2016, Emil Brink # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided # that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and # the following disclaimer. # # 2. 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. # # 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 HOLDER 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. BYTE_BITS = 8 MATCH_BITS = 6 MATCH_MIN = 3 MATCH_MAX = (1 << MATCH_BITS) + (MATCH_MIN - 1) MATCH_RANGE = range(MATCH_MIN, MATCH_MAX + 1) # Length 64, fine on 2.x. OFFSET_MASK = (1 << (16 - MATCH_BITS)) - 1 LEMPEL_SIZE = 1024 def size_encode(size, dst=None): """ Encodes the given size in little-endian variable-length encoding. The dst argument can be an existing bytearray to append the size. If it's omitted (or None), a new bytearray is created and used. Returns the destination bytearray. """ if dst is None: dst = bytearray() done = False while not done: dst.append(size & 0x7f) size >>= 7 done = size == 0 dst[-1] |= 0x80 return dst def size_decode(src): """ Decodes a size (encoded with size_encode()) from the start of src. Returns a tuple (size, len) where size is the size that was decoded, and len is the number of bytes from src that were consumed. """ dst_size = 0 pos = 0 # Extract prefixed encoded size, if present. val = 1 while True: c = src[pos] pos += 1 if c & 0x80: dst_size += val * (c & 0x7f) break dst_size += val * c val <<= 7 return dst_size, pos def lzjb_compress(src, dst=None): """ Compresses src, the source bytearray. If dst is not None, it's assumed to be the output bytearray and bytes are appended to it using dst.append(). If it is None, a new bytearray is created. The destination bytearray is returned. """ if dst is None: dst = bytearray() lempel = [0] * LEMPEL_SIZE copymap = 0 copymask = 1 << (BYTE_BITS - 1) pos = 0 # Current input offset. while pos < len(src): copymask <<= 1 if copymask == (1 << BYTE_BITS): copymask = 1 copymap = len(dst) dst.append(0) if pos > len(src) - MATCH_MAX: dst.append(src[pos]) pos += 1 continue hsh = (src[pos] << 16) + (src[pos + 1] << 8) + src[pos + 2] hsh += hsh >> 9 hsh += hsh >> 5 hsh &= LEMPEL_SIZE - 1 offset = (pos - lempel[hsh]) & OFFSET_MASK lempel[hsh] = pos cpy = pos - offset if cpy >= 0 and cpy != pos and src[pos:pos + 3] == src[cpy:cpy + 3]: dst[copymap] |= copymask for mlen in MATCH_RANGE: if src[pos + mlen] != src[cpy + mlen]: break dst.append(((mlen - MATCH_MIN) << (BYTE_BITS - MATCH_BITS)) | (offset >> BYTE_BITS)) dst.append(offset & 255) pos += mlen else: dst.append(src[pos]) pos += 1 return dst def lzjb_decompress(src, dlen, dst=None): """ Decompresses src, a bytearray of compressed data. The dst argument can be an optional bytearray which will have the output appended. If it's None, a new bytearray is created. The output bytearray is returned. """ if dst is None: dst = bytearray() pos = 0 dpos = 0 copymap = 0 copymask = 1 << (BYTE_BITS - 1) while pos < len(src): copymask <<= 1 if copymask == (1 << BYTE_BITS): copymask = 1 copymap = src[pos] pos += 1 if copymap & copymask: mlen = (src[pos] >> (BYTE_BITS - MATCH_BITS)) + MATCH_MIN offset = ((src[pos] << BYTE_BITS) | src[pos + 1]) & OFFSET_MASK pos += 2 cpy = dpos - offset if cpy < 0: return None while mlen > 0 and dpos < dlen: dst.append(dst[cpy]) dpos += 1 cpy += 1 mlen -= 1 elif dpos < dlen: dst.append(src[pos]) dpos += 1 pos += 1 return dst
hiliev/py-zfs-rescue
zfs/lzjb.py
Python
bsd-3-clause
5,428
import setuptools setuptools.setup( name='dnabc', version="0.0.5", description='Demultiplex pooled DNA sequencing data', author='Kyle Bittinger', author_email='kylebittinger@gmail.com', url='https://github.com/PennChopMicrobiomeProgram', packages=['dnabclib'], entry_points={ 'console_scripts': [ 'dnabc.py=dnabclib.main:main', 'split_samplelanes.py=dnabclib.split_samplelanes:main', ], }, classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Bio-Informatics', ], license='GPLv2+', )
ctanes/dnabc
setup.py
Python
gpl-2.0
854
""" Course API Serializers. Representing course catalog data """ import urllib from django.core.urlresolvers import reverse from rest_framework import serializers from openedx.core.djangoapps.models.course_details import CourseDetails from openedx.core.lib.api.fields import AbsoluteURLField class _MediaSerializer(serializers.Serializer): # pylint: disable=abstract-method """ Nested serializer to represent a media object. """ def __init__(self, uri_attribute, *args, **kwargs): super(_MediaSerializer, self).__init__(*args, **kwargs) self.uri_attribute = uri_attribute uri = serializers.SerializerMethodField(source='*') def get_uri(self, course_overview): """ Get the representation for the media resource's URI """ return getattr(course_overview, self.uri_attribute) class ImageSerializer(serializers.Serializer): # pylint: disable=abstract-method """ Collection of URLs pointing to images of various sizes. The URLs will be absolute URLs with the host set to the host of the current request. If the values to be serialized are already absolute URLs, they will be unchanged. """ raw = AbsoluteURLField() small = AbsoluteURLField() large = AbsoluteURLField() class _CourseApiMediaCollectionSerializer(serializers.Serializer): # pylint: disable=abstract-method """ Nested serializer to represent a collection of media objects """ course_image = _MediaSerializer(source='*', uri_attribute='course_image_url') course_video = _MediaSerializer(source='*', uri_attribute='course_video_url') image = ImageSerializer(source='image_urls') class CourseSerializer(serializers.Serializer): # pylint: disable=abstract-method """ Serializer for Course objects providing minimal data about the course. Compare this with CourseDetailSerializer. """ blocks_url = serializers.SerializerMethodField() effort = serializers.CharField() end = serializers.DateTimeField() enrollment_start = serializers.DateTimeField() enrollment_end = serializers.DateTimeField() id = serializers.CharField() # pylint: disable=invalid-name media = _CourseApiMediaCollectionSerializer(source='*') name = serializers.CharField(source='display_name_with_default_escaped') number = serializers.CharField(source='display_number_with_default') org = serializers.CharField(source='display_org_with_default') short_description = serializers.CharField() start = serializers.DateTimeField() start_display = serializers.CharField() start_type = serializers.CharField() pacing = serializers.CharField() mobile_available = serializers.BooleanField() hidden = serializers.SerializerMethodField() # 'course_id' is a deprecated field, please use 'id' instead. course_id = serializers.CharField(source='id', read_only=True) def get_hidden(self, course_overview): """ Get the representation for SerializerMethodField `hidden` Represents whether course is hidden in LMS """ catalog_visibility = course_overview.catalog_visibility return catalog_visibility in ['about', 'none'] def get_blocks_url(self, course_overview): """ Get the representation for SerializerMethodField `blocks_url` """ base_url = '?'.join([ reverse('blocks_in_course'), urllib.urlencode({'course_id': course_overview.id}), ]) return self.context['request'].build_absolute_uri(base_url) class CourseDetailSerializer(CourseSerializer): # pylint: disable=abstract-method """ Serializer for Course objects providing additional details about the course. This serializer makes additional database accesses (to the modulestore) and returns more data (including 'overview' text). Therefore, for performance and bandwidth reasons, it is expected that this serializer is used only when serializing a single course, and not for serializing a list of courses. """ overview = serializers.SerializerMethodField() def get_overview(self, course_overview): """ Get the representation for SerializerMethodField `overview` """ # Note: This makes a call to the modulestore, unlike the other # fields from CourseSerializer, which get their data # from the CourseOverview object in SQL. return CourseDetails.fetch_about_attribute(course_overview.id, 'overview')
fintech-circle/edx-platform
lms/djangoapps/course_api/serializers.py
Python
agpl-3.0
4,536
"""Integration tests for LinkedIn providers.""" from third_party_auth.tests.specs import base def get_localized_name(name): """Returns the localizedName from the name object""" locale = "{}_{}".format( name["preferredLocale"]["language"], name["preferredLocale"]["country"] ) return name['localized'].get(locale, '') class LinkedInOauth2IntegrationTest(base.Oauth2IntegrationTest): """Integration tests for provider.LinkedInOauth2.""" def setUp(self): super(LinkedInOauth2IntegrationTest, self).setUp() self.provider = self.configure_linkedin_provider( enabled=True, visible=True, key='linkedin_oauth2_key', secret='linkedin_oauth2_secret', ) TOKEN_RESPONSE_DATA = { 'access_token': 'access_token_value', 'expires_in': 'expires_in_value', } USER_RESPONSE_DATA = { 'lastName': { "localized": { "en_US": "Doe" }, "preferredLocale": { "country": "US", "language": "en" } }, 'id': 'id_value', 'firstName': { "localized": { "en_US": "Doe" }, "preferredLocale": { "country": "US", "language": "en" } }, } def get_username(self): response_data = self.get_response_data() first_name = get_localized_name(response_data.get('firstName')) last_name = get_localized_name(response_data.get('lastName')) return first_name + last_name
Edraak/edraak-platform
common/djangoapps/third_party_auth/tests/specs/test_linkedin.py
Python
agpl-3.0
1,648
#! /usr/bin/env python3 # coding=UTF-8 from time import sleep #import thread # in python 3 it is called 'threading' import threading # python libxcb bindings (xcffib): import xcffib import xcffib.xproto import xcffib.xtest import os import sys #================<CONFIG>================# filename="/home/wyatt/.touchnavid" # no_wm : # when set to True, program does not have a window border and is moved by additional buttons. # when set to False, program is draggable via your window manager. # default is True. global no_wm # no_wm=True no_wm=False # extended_controls: # when true, extended functionality buttons are present global extended_controls extended_controls=True # corner_controls : # when set to True, the corner controls (always visible when no_wm is set) are visible, regardless # of if the WM is managing the window. global corner_controls corner_controls=True # hax : # when set to 1, program kills the program 'mate-panel' and relauunches it when entering and exiting # fullscreen to stop it from sitting above the fullscreen window. 'mate-panel' is hardcoded, like most # of the rest of this program. Sorry. I'm just amazed this program works at all, honestly. It's based # on one of the earliest programs I wrote that I still have source code for! It works more like # assembly language or Commodore BASIC than Python... global hax hax=0 # Will the next 'wide' button press fit to height or fit to width? global wideset wideset=0 # delay_ms : # window selection delay, in milliseconds. After hitting the 'select' button you have this many # milliseconds to set input focus to the window you want to control. Default is 3000 (3 seconds.) global delay_ms delay_ms=3000 #================</CONFIG>===============# # if(hax==1): # import os # only needed for an ugly hack to kill mate-panel when entering # fullscreen. # this is not part of config. It is an easy way for the program to retain an idea of when it is in # fullscreen and not. Lazy, though. global full_screen full_screen=0 global portrait portrait=False # connection might be used anywhere (of course). global connection connection = xcffib.connect() global window_selected global inputWindow # allow passing window ID as argument to script. This allows for reloading the # 'widget' without having to re-select the window to control each time. if (len(sys.argv) == 3 ) : if (sys.argv[1]=="-win") : window_selected=True inputWindow=int(sys.argv[2]) if (sys.argv[1]=="-rot") : if (sys.argv[2]=="portrait") : portrait=True else : portrait=False elif (len(sys.argv) == 5) : if (sys.argv[1]=="-win") : window_selected=True inputWindow=int(sys.argv[2]) elif (sys.argv[3]=="-win") : window_selected=True inputWindow=int(sys.argv[4]) if (sys.argv[1]=="-rot") : if (sys.argv[2]=="portrait") : portrait=True else : portrait=False elif (sys.argv[3]=="-rot") : if (sys.argv[4]=="portrait") : portrait=True else : portrait=False else: window_selected=False portrait=False if (not window_selected): # cli args override this methodology if(not os.path.exists(filename)): f=open(filename,'w') else: f=open(filename,'r') f.seek(0) teststr=f.readline() if teststr=='' or teststr=='\n': print("Could not read a window ID from "+filename+". Clearing file." ) f.close() f=open(filename,'w') else: inputWindow=teststr window_selected=True def winget(): global delay_ms root.after(delay_ms,getwindow) def getwindow(): global f # persist file global filename global inputWindow global window_selected connection.flush() windowCookie = connection.core.GetInputFocus().reply() # 'focus' is the window's ID. inputWindow = windowCookie.focus window_selected=True print(inputWindow) f.close() # erase file f=open(filename,'w') f.write(str(inputWindow)+'\n') f.close() f=open(filename,'r') def pressKey(keyCode): XTEST_EVENTS = { 'KeyPress': 2, 'KeyRelease': 3, 'ButtonPress': 4, 'ButtonRelease': 5, 'MotionNotify': 6 } # send keycode to X server xtest.FakeInput(XTEST_EVENTS['KeyPress'],keyCode,xcffib.CurrentTime, inputWindow, 0,0,0,is_checked=True) xtest.FakeInput(XTEST_EVENTS['KeyRelease'],keyCode,xcffib.CurrentTime, inputWindow, 0,0,0,is_checked=True) connection.flush() def left(): global shell global window_selected if(window_selected==True): # set focused window xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typeleft() else: print("No window has been selected! Select a window and then try again.") def right(): global shell global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typeright() else: print("No window has been selected! Select a window and then try again.") def killPanel(): # hax again global hax if(hax == 1): os.system("killall mate-panel") def pixelsize(): global shell global root global hax global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typea() else: print("No window has been selected! Select a window and then try again.") def zoomin(): global shell global root global hax global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typeplus() else: print("No window has been selected! Select a window and then try again.") def zoomout(): global shell global root global hax global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typeminus() else: print("No window has been selected! Select a window and then try again.") def fitwidth(): global shell global root global hax global window_selected global wideset if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) if(wideset==0): typew() wideset=1 else: typeh() wideset=0 else: print("No window has been selected! Select a window and then try again.") def bestfit(): global shell global root global hax global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typeb() else: print("No window has been selected! Select a window and then try again.") def rotate(): global shell global root global hax global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typer() else: print("No window has been selected! Select a window and then try again.") def fullscreen(): global shell global full_screen global root global hax global window_selected if(window_selected==True): xtest.conn.core.SetInputFocus(xcffib.xproto.InputFocus.Parent, inputWindow, xcffib.CurrentTime) typef() else: print("No window has been selected! Select a window and then try again.") def typeleft(): # 117 is the 'Page Up' key on a ANSI layout keyboard (U.S. layout 101-key IBM PC 'Enhanced Keyboard.') pressKey(112) def typeright(): # 117 is the 'Page Down' key on a ANSI layout keyboard (U.S. layout 101-key IBM PC 'Enhanced Keyboard.') pressKey(117) def typeb(): pressKey(56) def typea(): pressKey(38) def typeplus(): #numpad plus has a unique keycode, unlike +/= key pressKey(86) def typeminus(): pressKey(20) def typef(): # 41 is the 'f' key on a ANSI layout keyboard (U.S. layout 101-key IBM PC 'Enhanced Keyboard.') pressKey(41) def typer(): # 'r' ansi pressKey(27) def typew(): # 'w' ansi pressKey(25) def typeh(): # 'h' ansi pressKey(43) def topleft(): root.geometry('+0+0') def topright(): root.geometry('-0+0') def btmleft(): root.geometry('+0-0') def btmright(): root.geometry('-0-0') def callback(): return def reload(): global inputWindow global root root.destroy() root=Tk() # reload root["bg"]="#424242" root.configure(background="#424242") root.title("touchnav") python = sys.executable # os.execl(python, python, * sys.argv) # Pass try: str(inputWindow) except NameError: inputWindow="" if(str(inputWindow) == ""): if(portrait==False): os.execl(python, python, sys.argv[0]) else: os.execl(python, python, sys.argv[0], "-rot", "portrait") else: if(portrait==False): os.execl(python, python, sys.argv[0], "-win", str(inputWindow)) else: os.execl(python, python, sys.argv[0], "-win", str(inputWindow), "-rot", "portrait") global xtest xtest=connection(xcffib.xtest.key) # global inputWindow # python 2 #from Tkinter import * # python 3 from tkinter import * global root root=Tk() #holder root.configure(background='#424242') root.title("touchnav") root.resizable(width=FALSE, height=FALSE) root.resizable(0,0) if(no_wm == True): # { # do not let the window manager take control of the window. root.overrideredirect(True) root.attributes('-fullscreen', True) # root.overrideredirect(no_wm) # } root.wm_attributes("-type",['_NET_WM_WINDOW_TYPE_DOCK']) root.wm_attributes("-topmost", 1) # always on top, works for me (tm) buttonframe=Frame(root,bg="#424242") buttonframe1=Frame(buttonframe,bg="#424242") buttonframe2=Frame(buttonframe,bg="#424242") buttonframe3=Frame(buttonframe,bg="#424242") if(portrait == False): buttonframe.grid(row=0,column=1) buttonframe1.grid(row=0,column=0,rowspan=2) buttonframe2.grid(row=0,column=2,rowspan=2) buttonframe3.grid(row=0,column=10,rowspan=2) else: buttonframe.grid(row=1,column=0) buttonframe1.grid(row=10,column=0,rowspan=2) buttonframe2.grid(row=2,column=0,rowspan=2) buttonframe3.grid(row=15,column=0,rowspan=2) if(portrait == False): # # 'move window' buttons # only needed if you have the window manager control of the window disabled. if(no_wm == True or corner_controls == True): # { Button(buttonframe2,text="↖",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=topleft).grid(row=0,column=3) Button(buttonframe2,text="↗",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=topright).grid(row=0,column=4) Button(buttonframe2,text="↙",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=btmleft).grid(row=1,column=3) Button(buttonframe2,text="↘",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=btmright).grid(row=1,column=4) # Button(buttonframe2,text="1:1",height=1,width=1,justify=LEFT,font=(None,8),command=pixelsize).grid(row=0,column=5,rowspan=1) # Button(buttonframe2,text="Fit",height=1,width=1,justify=LEFT,font=(None,8),command=bestfit).grid(row=1,column=5,rowspan=1) # Button(buttonframe2,text="+",height=1,width=1,justify=LEFT,font=(None,8),command=zoomin).grid(row=0,column=6,rowspan=1) # Button(buttonframe2,text="−",height=1,width=1,justify=LEFT,font=(None,8),command=zoomout).grid(row=1,column=6,rowspan=1) Button(buttonframe3,text="❌",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=root.destroy).grid(row=0,column=7,rowspan=1) Button(buttonframe3,text="⟳",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=reload).grid(row=1,column=7,rowspan=1) # } if( extended_controls == True ): Button(buttonframe2,text="1:1",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=pixelsize).grid(row=0,column=5,rowspan=1) Button(buttonframe2,text="fit",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=bestfit).grid(row=1,column=5,rowspan=1) Button(buttonframe2,text="r",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=rotate).grid(row=0,column=6,rowspan=1) Button(buttonframe2,text="w/h",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=fitwidth).grid(row=1,column=6,rowspan=1) Button(buttonframe2,text="+",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=zoomin).grid(row=0,column=7,columnspan=2) Button(buttonframe2,text="−",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=zoomout).grid(row=1,column=7,columnspan=2) Button(buttonframe2,text="Select",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=3,justify=LEFT,font=(None,8),command=winget).grid(row=0,column=2) Button(buttonframe2,text="FullScr",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=3,justify=LEFT,font=(None,8),command=fullscreen).grid(row=1,column=2) Button(buttonframe1,text="<-------",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=3,width=3,justify=LEFT,font=(None,8),command=left).grid(row=0,column=0) Button(buttonframe1,text="------->",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=3,width=3,justify=LEFT,font=(None,8),command=right).grid(row=0,column=1) #Button(buttonframe1,text="<-----",height=1,width=2,justify=LEFT,font=(None,8),command=left).grid(row=0,column=0) #Button(buttonframe1,text="----->",height=1,width=2,justify=LEFT,font=(None,8),command=right).grid(row=1,column=0) else: if(no_wm == True or corner_controls == True): Button(buttonframe2,text="↖",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=topleft).grid(row=3,column=0) Button(buttonframe2,text="↗",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=topright).grid(row=3,column=1) Button(buttonframe2,text="↙",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=btmleft).grid(row=4,column=0) Button(buttonframe2,text="↘",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=btmright).grid(row=4,column=1) # Button(buttonframe2,text="1:1",height=1,width=1,justify=LEFT,font=(None,8),command=pixelsize).grid(row=5,column=0,rowspan=1) # Button(buttonframe2,text="Fit",height=1,width=1,justify=LEFT,font=(None,8),command=bestfit).grid(row=5,column=1,rowspan=1) # Button(buttonframe2,text="+",height=1,width=1,justify=LEFT,font=(None,8),command=zoomin).grid(row=6,column=0,rowspan=1) # Button(buttonframe2,text="−",height=1,width=1,justify=LEFT,font=(None,8),command=zoomout).grid(row=6,column=1,rowspan=1) Button(buttonframe3,text="❌",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=root.destroy).grid(row=1,column=1,rowspan=1) Button(buttonframe3,text="⟳",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=reload).grid(row=1,column=0,rowspan=1) # } if( extended_controls == True ): Button(buttonframe2,text="1:1",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=pixelsize).grid(row=5,column=0,rowspan=1) Button(buttonframe2,text="fit",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=bestfit).grid(row=5,column=1,rowspan=1) # Button(buttonframe2,text="fit",height=1,width=3,justify=LEFT,font=(None,8),command=bestfit).grid(row=5,column=1,rowspan=1) Button(buttonframe2,text="r",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=rotate).grid(row=6,column=6,rowspan=1) Button(buttonframe2,text="w/h",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=fitwidth).grid(row=6,column=6,rowspan=1) Button(buttonframe2,text="+",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=zoomin).grid(row=7,column=0,rowspan=1) Button(buttonframe2,text="−",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=zoomout).grid(row=7,column=1,rowspan=1) Button(buttonframe3,text="Sel",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=winget).grid(row=0,column=0) Button(buttonframe3,text="FSc",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=1,width=1,justify=LEFT,font=(None,8),command=fullscreen).grid(row=0,column=1) Button(buttonframe1,text="<-----",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=3,width=3,justify=LEFT,font=(None,8),command=left).grid(row=0,column=0) Button(buttonframe1,text="----->",relief="flat",highlightbackground="#282828",bg="#424242",activebackground="#424242",fg="#848484",activeforeground="#848484",height=3,width=3,justify=LEFT,font=(None,8),command=right).grid(row=1,column=0) #Button(buttonframe1,text="<-----",height=1,width=2,justify=LEFT,font=(None,8),command=left).grid(row=0,column=0) #Button(buttonframe1,text="----->",height=1,width=2,justify=LEFT,font=(None,8),command=right).grid(row=1,column=0) def on_close(): # connection is disconnected when the TK window closes. # the program (and thus connection) can also be aborted via ctrl+\ (SIGQUIT) # in a terminal. # inputWindow saved to file for next run (useful for restarts) global f f.close() # close file descriptor for persist file if window_selected: # inputWindow is set persistfile.close() connection.disconnect() root.destroy() root.mainloop() #important for closing the root=Tk()
wyatt8740/mcomix-touchnav
mcomix-touchnav-linux-py3.py
Python
mit
21,536
from numpy import dot, zeros, trace, array, sum, eye from ..core.logio import logger from ..core.material import Material from ..core.tensor import array_rep, det, I6 class MooneyRivlinMaterial(Material): name = "mooney-rivlin" def __init__(self, **parameters): """Set up the Mooney Rivlin material """ param_names = ['C10', 'C01', 'D1'] self.params = {} for param_name in param_names: value = parameters.pop(param_name, 0.) self.params[param_name] = value if parameters: unused = ', '.join(parameters.keys()) logger.warning('Unused parameters: {0}'.format(unused)) # Check inputs C10 = self.params['C10'] C01 = self.params['C01'] D1 = self.params['D1'] errors = 0 if D1 <= 0.: errors += 1 logger.error('D1 must be > 0') G = 2. * (C10 + C01) if G <= 0: errors += 1 logger.error('2 (C10 + C01) > 0') if errors: raise ValueError("stopping due to previous errors") def eval(self, time, dtime, temp, dtemp, F0, F, stran, d, stress, statev, **kwargs): """Compute updated stress given the updated deformation""" # elastic properties C10 = self.params['C10'] C01 = self.params['C01'] D1 = self.params['D1'] # elastic stiffness ddsdde = None # Reshape the deformation gradient F = F.reshape(3,3) Jac = det(F) # left Cauchy deformation B = dot(F, F.T) Bsq = dot(B, B) incompressible = D1 > 1e4 * (C10 + C01) if incompressible: # enforce incompressibility Jac = 1 # Invariants of B I1 = trace(B) I2 = .5 * (I1 ** 2 - trace(Bsq)) # Invariants of Cbar scale = sign(abs(Jac) ** (1. / 3.), Jac) I1B = I1 / (scale ** 2) I2B = I2 / (scale ** 4) # convert symmetric tensors to arrays BBsq = array_rep(Bsq, (6,)) / scale ** 4 BB = array_rep(B, (6,)) / scale ** 2 if not incompressible: p = -2. / D1 * (Jac - 1.) else: p = 0. pb = p + 2. / 3. / Jac * (C10 * I1B + 2. * C01 * I2B) stress = 2. / Jac * ((C10 + C01 * I1B) * BB - C01 * BBsq) - pb * I6 return stress, statev, ddsdde def sign(x, y): return x if y > 0. else -x
matmodlab/matmodlab2
matmodlab2/materials/mooney_rivlin.py
Python
bsd-3-clause
2,458
#!/usr/bin/env python import socket, sys, cPickle, time, logging, signal, Queue, string from threading import Thread import PickleSocket, IdHash import jpype, pytos class MessageDispatch( Thread ) : def __init__( self , resources , queue , logger , threadIds ) : Thread.__init__( self ) self.__inQueue = queue self.__logger = logger self.__shutdown = False self.__QUEUE_TIMEOUT = 2 self.__threadIds = threadIds # downcase all the resource names self.__resources = {} for (key,value) in resources.iteritems() : self.__resources.update({ string.lower(key) : value }) def destroy( self ) : self.__shutdown = True def __destroy( self ) : self.__logger.info( "shutting down" ) del self.__threadIds[ id(self) ] #self.__logger.warn( "could not clean up myself for my parent" ) def run( self ) : if not jpype.isThreadAttachedToJVM() : jpype.attachThreadToJVM() while not self.__shutdown : # -------------------------------------------------- # read in and check new RPC messages # -------------------------------------------------- try: # try to get a new message from the inQueue and either block until a new message arrives # eventually timeout, so you can check if this thread is being shutdown try: ( returnPickleSocket , msg ) = self.__inQueue.get( True , self.__QUEUE_TIMEOUT ) except Queue.Empty : continue ( objName , methodName , arg_tuple , arg_dict ) = msg objName = string.lower(objName) self.__logger.debug( "Received RPC tuple %s" % repr(msg) ) if not isinstance( arg_tuple , tuple ) : raise ValueError if not isinstance( arg_dict , dict ) : raise ValueError except ValueError, inst : self.__logger.error( "Ignoring message: Received ill-formed RPC message" ) continue # -------------------------------------------------- # execute the RPC command # -------------------------------------------------- if objName in self.__resources : self.__logger.debug( "Evaluating %s.%s" % (objName , methodName) ) obj = self.__resources[ objName ] try: f = eval( "obj." + methodName ) result = f( *arg_tuple , **arg_dict ) self.__logger.debug( "returning results: " + repr( result ) ) try : returnPickleSocket.send( result ) except Exception, inst : self.__logger.error( "Could not send return value (see below)" ) self.__logger.error( inst.__str__ ) except AttributeError , inst : self.__logger.error( "Ignoring message: Object %s does not have the %s method" % (objName,methodName) ) except TypeError , inst : self.__logger.error( "Ignoring message: Ill-formed arguments to %s.%s" % (objName,methodName) ) except inst : self.__logger.error( "Call to %s.%s failed (see below)" % (objName,methodName) ) self.__logger.error( inst.__str__ ) else: self.__logger.error( "Ignoring message: Object %s does not exist" % objName ) self.__destroy() class ConnectionHandler( Thread ) : def __init__( self , conn , addr , logger , queue , threadIds ) : Thread.__init__( self ) self.__inQueue = queue self.__logger = logger self.__pickleSocket = PickleSocket.PickleSocket( conn ) self.__threadIds = threadIds def destroy( self ) : # this will trigger the recv() call in the run() method to throw an exception; # letting us safely end the loop and shutdown self.__logger.info( "forced to shut down my connection" ) self.__pickleSocket.destroy() def __destroy( self ) : self.__logger.info( "shutting down" ) self.__logger.info( "shutting down connection" ) self.__pickleSocket.destroy() self.__logger.debug( "Removing myself from the active thread list" ) del self.__threadIds[ id(self) ] def run( self ) : while True: try : # wait for a new message from client self.__logger.debug( "Waiting for new messages; pickleSocket.recv()" ) newMsg = self.__pickleSocket.recv( 5*60 ) # wait up to 5 minutes, before killing the socket self.__logger.debug( "received new message: %s" % repr(newMsg) ) # put the new message on the dispatch queue try : self.__inQueue.put_nowait(( self.__pickleSocket , newMsg )) except Queue.Full : self.__logger.warn( "queue full -- dropping new message: %s" % repr(newMsg) ) # except ( EOFError , socket.error , PickleSocket.Destroyed , PickleSocket.Timeout ) : except : self.__logger.info( "connection closed" ) break self.__destroy() class ResourceServer( object ) : def __init__( self , port , msgQueueLen , resources , logFileName = None , logFileBytes = 50*1024 ) : self.__resources = resources self.__inQueue = Queue.Queue( msgQueueLen ) #self.__host = socket.gethostname() #self.__host = "192.168.0.2" self.__host = "" self.__port = port self.__children = {} # keep track of child threads using their ids self.__socket = None # -------------------------------------------------- # Setup the logger # -------------------------------------------------- logging.basicConfig( level=logging.DEBUG , format="%(asctime)s %(levelname)s %(name)s %(message)s" ) if logFileName : from logging import handlers logFile = handlers.RotatingFileHandler( logFileName , maxBytes = logFileBytes ) logFile.setLevel( logging.DEBUG ) formatter = logging.Formatter( "%(asctime)s %(levelname)s %(name)s %(message)s" ) logFile.setFormatter(formatter) logging.getLogger("").addHandler( logFile ) self.__logger = logging.getLogger( "ResourceServer" ) # -------------------------------------------------- # Setup signal handlers to shutdown the server nicely # -------------------------------------------------- signal.signal( signal.SIGTERM , self.__destroy ) signal.signal( signal.SIGQUIT , self.__destroy ) signal.signal( signal.SIGINT , self.__destroy ) def __destroy( self , sigNum , stackFrame ) : self.__logger.warn( "Shutting down" ) # shutdown the server socket self.__logger.debug( "Closing server socket" ) if self.__socket : self.__socket.close() # shutdown children for (cid , child) in self.__children.copy().iteritems() : self.__logger.debug( "Shutting down %s child" % repr(child) ) child.destroy() self.__children = None # exit time.sleep( 5 ) #give the other threads a second before shutting down and killing the logger sys.exit(0) def start( self ) : # start the message dispatcher thread self.__logger.info( "starting the dispatcher" ) messageDispatch = MessageDispatch( self.__resources , self.__inQueue , logging.getLogger( "MessageDispatcher" ) , self.__children ) self.__children.update({ id(messageDispatch) : messageDispatch }) # messageDispatch.setDaemon( True ) messageDispatch.start() # Create a socket for the server self.__logger.info( "opening the server socket" ) try : self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error : self.__socket = None # Bind server socket to its host,port & make it a listening socket try : self.__socket.bind((self.__host, self.__port)) self.__socket.listen(1) except socket.error : self.__socket.close() self.__socket = None # Check if socket is OK if self.__socket is None: self.__logger.error( "could not open socket" ) self.__destroy( None , None ) else : self.__logger.info( "listening on port %i" % self.__port ) # Listen/connect to clients while True : try : conn, addr = self.__socket.accept() self.__logger.info( "connected to by %s" % repr(addr) ) self.__logger.debug( "spawning a handler for connection %s" % repr(addr) ) handler = ConnectionHandler( conn , addr , logging.getLogger( "ConnectionHandler-%s:%s" % addr ) , self.__inQueue , self.__children ) self.__children.update({ id(handler) : handler }) handler.start() except socket.error : break if __name__ == "__main__" : logFileName = None if len(sys.argv) > 2 : print "USAGE: %s [logFile]" % sys.argv[0] sys.exit(1) elif len(sys.argv) == 2 : logFileName = sys.argv[1] import Config, Util resources = Util.getResources() s = ResourceServer( Config.PORT , Config.SERVER_MSG_QUEUE_LENGTH , resources , logFileName , Config.LOG_FILE_BYTES ) s.start()
fresskarma/tinyos-1.x
contrib/ucb/apps/Monstro/lib/Robot/Server.py
Python
bsd-3-clause
9,943
"""Classes for managing templates and their runtime and compile time options. """ import os import sys import weakref from functools import partial from functools import reduce from typing import Any from markupsafe import Markup from . import nodes from .compiler import CodeGenerator from .compiler import generate from .defaults import BLOCK_END_STRING from .defaults import BLOCK_START_STRING from .defaults import COMMENT_END_STRING from .defaults import COMMENT_START_STRING from .defaults import DEFAULT_FILTERS from .defaults import DEFAULT_NAMESPACE from .defaults import DEFAULT_POLICIES from .defaults import DEFAULT_TESTS from .defaults import KEEP_TRAILING_NEWLINE from .defaults import LINE_COMMENT_PREFIX from .defaults import LINE_STATEMENT_PREFIX from .defaults import LSTRIP_BLOCKS from .defaults import NEWLINE_SEQUENCE from .defaults import TRIM_BLOCKS from .defaults import VARIABLE_END_STRING from .defaults import VARIABLE_START_STRING from .exceptions import TemplateNotFound from .exceptions import TemplateRuntimeError from .exceptions import TemplatesNotFound from .exceptions import TemplateSyntaxError from .exceptions import UndefinedError from .lexer import get_lexer from .lexer import TokenStream from .nodes import EvalContext from .parser import Parser from .runtime import Context from .runtime import new_context from .runtime import Undefined from .utils import concat from .utils import consume from .utils import have_async_gen from .utils import import_string from .utils import internalcode from .utils import LRUCache from .utils import missing # for direct template usage we have up to ten living environments _spontaneous_environments = LRUCache(10) def get_spontaneous_environment(cls, *args): """Return a new spontaneous environment. A spontaneous environment is used for templates created directly rather than through an existing environment. :param cls: Environment class to create. :param args: Positional arguments passed to environment. """ key = (cls, args) try: return _spontaneous_environments[key] except KeyError: _spontaneous_environments[key] = env = cls(*args) env.shared = True return env def create_cache(size): """Return the cache class for the given size.""" if size == 0: return None if size < 0: return {} return LRUCache(size) def copy_cache(cache): """Create an empty copy of the given cache.""" if cache is None: return None elif type(cache) is dict: return {} return LRUCache(cache.capacity) def load_extensions(environment, extensions): """Load the extensions from the list and bind it to the environment. Returns a dict of instantiated environments. """ result = {} for extension in extensions: if isinstance(extension, str): extension = import_string(extension) result[extension.identifier] = extension(environment) return result def fail_for_missing_callable(thing, name): msg = f"no {thing} named {name!r}" if isinstance(name, Undefined): try: name._fail_with_undefined_error() except Exception as e: msg = f"{msg} ({e}; did you forget to quote the callable name?)" raise TemplateRuntimeError(msg) def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass( environment.undefined, Undefined ), "undefined must be a subclass of undefined because filters depend on it." assert ( environment.block_start_string != environment.variable_start_string != environment.comment_start_string ), "block, variable and comment start strings must be different" assert environment.newline_sequence in { "\r", "\r\n", "\n", }, "newline_sequence set to unknown line ending string." return environment class Environment: r"""The core component of Jinja is the `Environment`. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior. Here are the possible initialization parameters: `block_start_string` The string marking the beginning of a block. Defaults to ``'{%'``. `block_end_string` The string marking the end of a block. Defaults to ``'%}'``. `variable_start_string` The string marking the beginning of a print statement. Defaults to ``'{{'``. `variable_end_string` The string marking the end of a print statement. Defaults to ``'}}'``. `comment_start_string` The string marking the beginning of a comment. Defaults to ``'{#'``. `comment_end_string` The string marking the end of a comment. Defaults to ``'#}'``. `line_statement_prefix` If given and a string, this will be used as prefix for line based statements. See also :ref:`line-statements`. `line_comment_prefix` If given and a string, this will be used as prefix for line based comments. See also :ref:`line-statements`. .. versionadded:: 2.2 `trim_blocks` If this is set to ``True`` the first newline after a block is removed (block, not variable tag!). Defaults to `False`. `lstrip_blocks` If this is set to ``True`` leading spaces and tabs are stripped from the start of a line to a block. Defaults to `False`. `newline_sequence` The sequence that starts a newline. Must be one of ``'\r'``, ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a useful default for Linux and OS X systems as well as web applications. `keep_trailing_newline` Preserve the trailing newline when rendering templates. The default is ``False``, which causes a single newline, if present, to be stripped from the end of the template. .. versionadded:: 2.7 `extensions` List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at :ref:`the extensions documentation <jinja-extensions>`. `optimized` should the optimizer be enabled? Default is ``True``. `undefined` :class:`Undefined` or a subclass of it that is used to represent undefined values in the template. `finalize` A callable that can be used to process the result of a variable expression before it is output. For example one can convert ``None`` implicitly into an empty string here. `autoescape` If set to ``True`` the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping see :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return ``True`` or ``False`` depending on autoescape should be enabled by default. .. versionchanged:: 2.4 `autoescape` can now be a function `loader` The template loader for this environment. `cache_size` The size of the cache. Per default this is ``400`` which means that if more than 400 templates are loaded the loader will clean out the least recently used template. If the cache size is set to ``0`` templates are recompiled all the time, if the cache size is ``-1`` the cache will not be cleaned. .. versionchanged:: 2.8 The cache size was increased to 400 from a low 50. `auto_reload` Some loaders load templates from locations where the template sources may change (ie: file system or database). If ``auto_reload`` is set to ``True`` (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it's possible to disable that. `bytecode_cache` If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don't have to be parsed if they were not changed. See :ref:`bytecode-cache` for more information. `enable_async` If set to true this enables async template execution which allows using async functions and generators. """ #: if this environment is sandboxed. Modifying this variable won't make #: the environment sandboxed though. For a real sandboxed environment #: have a look at jinja2.sandbox. This flag alone controls the code #: generation by the compiler. sandboxed = False #: True if the environment is just an overlay overlayed = False #: the environment this environment is linked to if it is an overlay linked_to = None #: shared environments have this set to `True`. A shared environment #: must not be modified shared = False #: the class that is used for code generation. See #: :class:`~jinja2.compiler.CodeGenerator` for more information. code_generator_class = CodeGenerator #: the context class that is used for templates. See #: :class:`~jinja2.runtime.Context` for more information. context_class = Context template_class = Any def __init__( self, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, lstrip_blocks=LSTRIP_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, keep_trailing_newline=KEEP_TRAILING_NEWLINE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False, loader=None, cache_size=400, auto_reload=True, bytecode_cache=None, enable_async=False, ): # !!Important notice!! # The constructor accepts quite a few arguments that should be # passed by keyword rather than position. However it's important to # not change the order of arguments because it's used at least # internally in those cases: # - spontaneous environments (i18n extension and Template) # - unittests # If parameter changes are required only add parameters at the end # and don't change the arguments (or the defaults!) of the arguments # existing already. # lexer / parser information self.block_start_string = block_start_string self.block_end_string = block_end_string self.variable_start_string = variable_start_string self.variable_end_string = variable_end_string self.comment_start_string = comment_start_string self.comment_end_string = comment_end_string self.line_statement_prefix = line_statement_prefix self.line_comment_prefix = line_comment_prefix self.trim_blocks = trim_blocks self.lstrip_blocks = lstrip_blocks self.newline_sequence = newline_sequence self.keep_trailing_newline = keep_trailing_newline # runtime information self.undefined = undefined self.optimized = optimized self.finalize = finalize self.autoescape = autoescape # defaults self.filters = DEFAULT_FILTERS.copy() self.tests = DEFAULT_TESTS.copy() self.globals = DEFAULT_NAMESPACE.copy() # set the loader provided self.loader = loader self.cache = create_cache(cache_size) self.bytecode_cache = bytecode_cache self.auto_reload = auto_reload # configurable policies self.policies = DEFAULT_POLICIES.copy() # load extensions self.extensions = load_extensions(self, extensions) self.enable_async = enable_async self.is_async = self.enable_async and have_async_gen if self.is_async: # runs patch_all() to enable async support from . import asyncsupport # noqa: F401 _environment_sanity_check(self) def add_extension(self, extension): """Adds an extension after the environment was created. .. versionadded:: 2.5 """ self.extensions.update(load_extensions(self, [extension])) def extend(self, **attributes): """Add the items to the instance of the environment if they do not exist yet. This is used by :ref:`extensions <writing-extensions>` to register callbacks and configuration values without breaking inheritance. """ for key, value in attributes.items(): if not hasattr(self, key): setattr(self, key, value) def overlay( self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_blocks=missing, lstrip_blocks=missing, extensions=missing, optimized=missing, undefined=missing, finalize=missing, autoescape=missing, loader=missing, cache_size=missing, auto_reload=missing, bytecode_cache=missing, ): """Create a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions. Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through. """ args = dict(locals()) del args["self"], args["cache_size"], args["extensions"] rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.overlayed = True rv.linked_to = self for key, value in args.items(): if value is not missing: setattr(rv, key, value) if cache_size is not missing: rv.cache = create_cache(cache_size) else: rv.cache = copy_cache(self.cache) rv.extensions = {} for key, value in self.extensions.items(): rv.extensions[key] = value.bind(rv) if extensions is not missing: rv.extensions.update(load_extensions(rv, extensions)) return _environment_sanity_check(rv) lexer = property(get_lexer, doc="The lexer for this environment.") def iter_extensions(self): """Iterates over the extensions by priority.""" return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) def getitem(self, obj, argument): """Get an item or attribute of an object but prefer the item.""" try: return obj[argument] except (AttributeError, TypeError, LookupError): if isinstance(argument, str): try: attr = str(argument) except Exception: pass else: try: return getattr(obj, attr) except AttributeError: pass return self.undefined(obj=obj, name=argument) def getattr(self, obj, attribute): """Get an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a bytestring. """ try: return getattr(obj, attribute) except AttributeError: pass try: return obj[attribute] except (TypeError, LookupError, AttributeError): return self.undefined(obj=obj, name=attribute) def call_filter( self, name, value, args=None, kwargs=None, context=None, eval_ctx=None ): """Invokes a filter on a value the same way the compiler does. This might return a coroutine if the filter is running from an environment in async mode and the filter supports async execution. It's your responsibility to await this if needed. .. versionadded:: 2.7 """ func = self.filters.get(name) if func is None: fail_for_missing_callable("filter", name) args = [value] + list(args or ()) if getattr(func, "contextfilter", False) is True: if context is None: raise TemplateRuntimeError( "Attempted to invoke context filter without context" ) args.insert(0, context) elif getattr(func, "evalcontextfilter", False) is True: if eval_ctx is None: if context is not None: eval_ctx = context.eval_ctx else: eval_ctx = EvalContext(self) args.insert(0, eval_ctx) elif getattr(func, "environmentfilter", False) is True: args.insert(0, self) return func(*args, **(kwargs or {})) def call_test(self, name, value, args=None, kwargs=None): """Invokes a test on a value the same way the compiler does it. .. versionadded:: 2.7 """ func = self.tests.get(name) if func is None: fail_for_missing_callable("test", name) return func(value, *(args or ()), **(kwargs or {})) @internalcode def parse(self, source, name=None, filename=None): """Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates. If you are :ref:`developing Jinja extensions <writing-extensions>` this gives you a good overview of the node tree generated. """ try: return self._parse(source, name, filename) except TemplateSyntaxError: self.handle_exception(source=source) def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, filename).parse() def lex(self, source, name=None, filename=None): """Lex the given sourcecode and return a generator that yields tokens as tuples in the form ``(lineno, token_type, value)``. This can be useful for :ref:`extension development <writing-extensions>` and debugging templates. This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the :meth:`preprocess` method. """ source = str(source) try: return self.lexer.tokeniter(source, name, filename) except TemplateSyntaxError: self.handle_exception(source=source) def preprocess(self, source, name=None, filename=None): """Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but *not* for :meth:`lex` because there you usually only want the actual source tokenized. """ return reduce( lambda s, e: e.preprocess(s, name, filename), self.iter_extensions(), str(source), ) def _tokenize(self, source, name, filename=None, state=None): """Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. """ source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(source, name, filename, state) for ext in self.iter_extensions(): stream = ext.filter_stream(stream) if not isinstance(stream, TokenStream): stream = TokenStream(stream, name, filename) return stream def _generate(self, source, name, filename, defer_init=False): """Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5 """ return generate( source, self, name, filename, defer_init=defer_init, optimized=self.optimized, ) def _compile(self, source, filename): """Internal hook that can be overridden to hook a different compile method in. .. versionadded:: 2.5 """ return compile(source, filename, "exec") @internalcode def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted. The return value of this method is a python code object. If the `raw` parameter is `True` the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally. `defer_init` is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set. .. versionadded:: 2.4 `defer_init` parameter added. """ source_hint = None try: if isinstance(source, str): source_hint = source source = self._parse(source, name, filename) source = self._generate(source, name, filename, defer_init=defer_init) if raw: return source if filename is None: filename = "<template>" return self._compile(source, filename) except TemplateSyntaxError: self.handle_exception(source=source_hint) def compile_expression(self, source, undefined_to_none=True): """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1 """ parser = Parser(self, source, state="variable") try: expr = parser.parse_expression() if not parser.stream.eos: raise TemplateSyntaxError( "chunk after expression", parser.stream.current.lineno, None, None ) expr.set_environment(self) except TemplateSyntaxError: if sys.exc_info() is not None: self.handle_exception(source=source) body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)] template = self.from_string(nodes.Template(body, lineno=1)) return TemplateExpression(template, undefined_to_none) def compile_templates( self, target, extensions=None, filter_func=None, zip="deflated", log_function=None, ignore_errors=True, ): """Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, `zip` can be set to ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. .. versionadded:: 2.4 """ from .loaders import ModuleLoader if log_function is None: def log_function(x): pass def write_file(filename, data): if zip: info = ZipInfo(filename) info.external_attr = 0o755 << 16 zip_file.writestr(info, data) else: if isinstance(data, str): data = data.encode("utf8") with open(os.path.join(target, filename), "wb") as f: f.write(data) if zip is not None: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED zip_file = ZipFile( target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip] ) log_function(f"Compiling into Zip archive {target!r}") else: if not os.path.isdir(target): os.makedirs(target) log_function(f"Compiling into folder {target!r}") try: for name in self.list_templates(extensions, filter_func): source, filename, _ = self.loader.get_source(self, name) try: code = self.compile(source, name, filename, True, True) except TemplateSyntaxError as e: if not ignore_errors: raise log_function(f'Could not compile "{name}": {e}') continue filename = ModuleLoader.get_module_filename(name) write_file(filename, code) log_function(f'Compiled "{name}" as {filename}') finally: if zip: zip_file.close() log_function("Finished compiling templates") def list_templates(self, extensions=None, filter_func=None): """Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either `extensions` is set to a list of file extensions for templates, or a `filter_func` can be provided which is a callable that is passed a template name and should return `True` if it should end up in the result list. If the loader does not support that, a :exc:`TypeError` is raised. .. versionadded:: 2.4 """ names = self.loader.list_templates() if extensions is not None: if filter_func is not None: raise TypeError( "either extensions or filter_func can be passed, but not both" ) def filter_func(x): return "." in x and x.rsplit(".", 1)[1] in extensions if filter_func is not None: names = [name for name in names if filter_func(name)] return names def handle_exception(self, source=None): """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ from .debug import rewrite_traceback_stack raise rewrite_traceback_stack(source=source) def join_path(self, template, parent): """Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here. """ return template @internalcode def _load_template(self, name, globals): if self.loader is None: raise TypeError("no loader for this environment specified") cache_key = (weakref.ref(self.loader), name) if self.cache is not None: template = self.cache.get(cache_key) if template is not None and ( not self.auto_reload or template.is_up_to_date ): return template template = self.loader.load(self, name, globals) if self.cache is not None: self.cache[cache_key] = template return template @internalcode def get_template(self, name, parent=None, globals=None): """Load a template from the loader. If a loader is configured this method asks the loader for the template and returns a :class:`Template`. If the `parent` parameter is not `None`, :meth:`join_path` is called to get the real template name before loading. The `globals` parameter can be used to provide template wide globals. These variables are available in the context at render time. If the template does not exist a :exc:`TemplateNotFound` exception is raised. .. versionchanged:: 2.4 If `name` is a :class:`Template` object it is returned from the function unchanged. """ if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) return self._load_template(name, self.make_globals(globals)) @internalcode def select_template(self, names, parent=None, globals=None): """Works like :meth:`get_template` but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a :exc:`TemplatesNotFound` exception. .. versionchanged:: 2.11 If names is :class:`Undefined`, an :exc:`UndefinedError` is raised instead. If no templates were found and names contains :class:`Undefined`, the message is more helpful. .. versionchanged:: 2.4 If `names` contains a :class:`Template` object it is returned from the function unchanged. .. versionadded:: 2.3 """ if isinstance(names, Undefined): names._fail_with_undefined_error() if not names: raise TemplatesNotFound( message="Tried to select from an empty list of templates." ) globals = self.make_globals(globals) for name in names: if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) try: return self._load_template(name, globals) except (TemplateNotFound, UndefinedError): pass raise TemplatesNotFound(names) @internalcode def get_or_select_template(self, template_name_or_list, parent=None, globals=None): """Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3 """ if isinstance(template_name_or_list, (str, Undefined)): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals) def from_string(self, source, globals=None, template_class=None): """Load a template from a string. This parses the source given and returns a :class:`Template` object. """ globals = self.make_globals(globals) cls = template_class or self.template_class return cls.from_code(self, self.compile(source), globals, None) def make_globals(self, d): """Return a dict for the globals.""" if not d: return self.globals return dict(self.globals, **d) class Template: """The central template object. This class represents a compiled template and is used to evaluate it. Normally the template object is generated from an :class:`Environment` but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it's not possible to specify a loader. Every template object has a few methods and members that are guaranteed to exist. However it's important that a template object should be considered immutable. Modifications on the object are not supported. Template objects created from the constructor rather than an environment do have an `environment` attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings. >>> template = Template('Hello {{ name }}!') >>> template.render(name='John Doe') == u'Hello John Doe!' True >>> stream = template.stream(name='John Doe') >>> next(stream) == u'Hello John Doe!' True >>> next(stream) Traceback (most recent call last): ... StopIteration """ #: Type of environment to create when creating a template directly #: rather than through an existing environment. environment_class = Environment def __new__( cls, source, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, lstrip_blocks=LSTRIP_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, keep_trailing_newline=KEEP_TRAILING_NEWLINE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False, enable_async=False, ): env = get_spontaneous_environment( cls.environment_class, block_start_string, block_end_string, variable_start_string, variable_end_string, comment_start_string, comment_end_string, line_statement_prefix, line_comment_prefix, trim_blocks, lstrip_blocks, newline_sequence, keep_trailing_newline, frozenset(extensions), optimized, undefined, finalize, autoescape, None, 0, False, None, enable_async, ) return env.from_string(source, template_class=cls) @classmethod def from_code(cls, environment, code, globals, uptodate=None): """Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object. """ namespace = {"environment": environment, "__file__": code.co_filename} exec(code, namespace) rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv @classmethod def from_module_dict(cls, environment, module_dict, globals): """Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4 """ return cls._from_namespace(environment, module_dict, globals) @classmethod def _from_namespace(cls, environment, namespace, globals): t = object.__new__(cls) t.environment = environment t.globals = globals t.name = namespace["name"] t.filename = namespace["__file__"] t.blocks = namespace["blocks"] # render function and module t.root_render_func = namespace["root"] t._module = None # debug and loader helpers t._debug_info = namespace["debug_info"] t._uptodate = None # store the reference namespace["environment"] = environment namespace["__jinja_template__"] = t return t def render(self, *args, **kwargs): """This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights='that say nih') template.render({'knights': 'that say nih'}) This will return the rendered template as a string. """ vars = dict(*args, **kwargs) try: return concat(self.root_render_func(self.new_context(vars))) except Exception: self.environment.handle_exception() def render_async(self, *args, **kwargs): """This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled. Example usage:: await template.render_async(knights='that say nih; asynchronously') """ # see asyncsupport for the actual implementation raise NotImplementedError( "This feature is not available for this version of Python" ) def stream(self, *args, **kwargs): """Works exactly like :meth:`generate` but returns a :class:`TemplateStream`. """ return TemplateStream(self.generate(*args, **kwargs)) def generate(self, *args, **kwargs): """For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as strings. It accepts the same arguments as :meth:`render`. """ vars = dict(*args, **kwargs) try: yield from self.root_render_func(self.new_context(vars)) except Exception: yield self.environment.handle_exception() def generate_async(self, *args, **kwargs): """An async version of :meth:`generate`. Works very similarly but returns an async iterator instead. """ # see asyncsupport for the actual implementation raise NotImplementedError( "This feature is not available for this version of Python" ) def new_context(self, vars=None, shared=False, locals=None): """Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as is to the context without adding the globals. `locals` can be a dict of local variables for internal usage. """ return new_context( self.environment, self.name, self.blocks, vars, shared, self.globals, locals ) def make_module(self, vars=None, shared=False, locals=None): """This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method. """ return TemplateModule(self, self.new_context(vars, shared, locals)) def make_module_async(self, vars=None, shared=False, locals=None): """As template module creation can invoke template code for asynchronous executions this method must be used instead of the normal :meth:`make_module` one. Likewise the module attribute becomes unavailable in async mode. """ # see asyncsupport for the actual implementation raise NotImplementedError( "This feature is not available for this version of Python" ) @internalcode def _get_default_module(self, ctx=None): """If a context is passed in, this means that the template was imported. Imported templates have access to the current template's globals by default, but they can only be accessed via the context during runtime. If there are new globals, we need to create a new module because the cached module is already rendered and will not have access to globals from the current context. This new module is not cached as :attr:`_module` because the template can be imported elsewhere, and it should have access to only the current template's globals. """ if ctx is not None: globals = { key: ctx.parent[key] for key in ctx.globals_keys - self.globals.keys() } if globals: return self.make_module(globals) if self._module is not None: return self._module self._module = rv = self.make_module() return rv @property def module(self): """The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> str(t.module) '23' >>> t.module.foo() == u'42' True This attribute is not available if async mode is enabled. """ return self._get_default_module() def get_corresponding_lineno(self, lineno): """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1 @property def is_up_to_date(self): """If this variable is `False` there is a newer version available.""" if self._uptodate is None: return True return self._uptodate() @property def debug_info(self): """The debug info mapping.""" if self._debug_info: return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")] return [] def __repr__(self): if self.name is None: name = f"memory:{id(self):x}" else: name = repr(self.name) return f"<{self.__class__.__name__} {name}>" class TemplateModule: """Represents an imported template. All the exported names of the template are available as attributes on this object. Additionally converting it into a string renders the contents. """ def __init__(self, template, context, body_stream=None): if body_stream is None: if context.environment.is_async: raise RuntimeError( "Async mode requires a body stream " "to be passed to a template module. Use " "the async methods of the API you are " "using." ) body_stream = list(template.root_render_func(context)) self._body_stream = body_stream self.__dict__.update(context.get_exported()) self.__name__ = template.name def __html__(self): return Markup(concat(self._body_stream)) def __str__(self): return concat(self._body_stream) def __repr__(self): if self.__name__ is None: name = f"memory:{id(self):x}" else: name = repr(self.__name__) return f"<{self.__class__.__name__} {name}>" class TemplateExpression: """The :meth:`jinja2.Environment.compile_expression` method returns an instance of this object. It encapsulates the expression-like access to the template with an expression it wraps. """ def __init__(self, template, undefined_to_none): self._template = template self._undefined_to_none = undefined_to_none def __call__(self, *args, **kwargs): context = self._template.new_context(dict(*args, **kwargs)) consume(self._template.root_render_func(context)) rv = context.vars["result"] if self._undefined_to_none and isinstance(rv, Undefined): rv = None return rv class TemplateStream: """A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one string is yielded. If buffering is enabled with a buffer size of 5, five items are combined into a new string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration. """ def __init__(self, gen): self._gen = gen self.disable_buffering() def dump(self, fp, encoding=None, errors="strict"): """Dump the complete stream into a file or file-like object. Per default strings are written, if you want to encode before writing specify an `encoding`. Example usage:: Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') """ close = False if isinstance(fp, str): if encoding is None: encoding = "utf-8" fp = open(fp, "wb") close = True try: if encoding is not None: iterable = (x.encode(encoding, errors) for x in self) else: iterable = self if hasattr(fp, "writelines"): fp.writelines(iterable) else: for item in iterable: fp.write(item) finally: if close: fp.close() def disable_buffering(self): """Disable the output buffering.""" self._next = partial(next, self._gen) self.buffered = False def _buffered_generator(self, size): buf = [] c_size = 0 push = buf.append while 1: try: while c_size < size: c = next(self._gen) push(c) if c: c_size += 1 except StopIteration: if not c_size: return yield concat(buf) del buf[:] c_size = 0 def enable_buffering(self, size=5): """Enable buffering. Buffer `size` items before yielding them.""" if size <= 1: raise ValueError("buffer size too small") self.buffered = True self._next = partial(next, self._buffered_generator(size)) def __iter__(self): return self def __next__(self): return self._next() # hook in default template class. if anyone reads this comment: ignore that # it's possible to use custom templates ;-) Environment.template_class = Template
pallets/jinja2
src/jinja2/environment.py
Python
bsd-3-clause
49,423
""" Discussion API internal interface """ from collections import defaultdict from urllib import urlencode from urlparse import urlunparse from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.http import Http404 import itertools from enum import Enum from openedx.core.djangoapps.user_api.accounts.views import AccountViewSet from rest_framework.exceptions import PermissionDenied from opaque_keys import InvalidKeyError from opaque_keys.edx.locator import CourseKey from courseware.courses import get_course_with_access from discussion_api.exceptions import ThreadNotFoundError, CommentNotFoundError, DiscussionDisabledError from discussion_api.forms import CommentActionsForm, ThreadActionsForm from discussion_api.permissions import ( can_delete, get_editable_fields, get_initializable_comment_fields, get_initializable_thread_fields, ) from discussion_api.serializers import CommentSerializer, ThreadSerializer, get_context, DiscussionTopicSerializer from django_comment_client.base.views import ( track_comment_created_event, track_thread_created_event, track_voted_event, ) from django_comment_common.signals import ( thread_created, thread_edited, thread_deleted, thread_voted, comment_created, comment_edited, comment_voted, comment_deleted, ) from django_comment_client.utils import get_accessible_discussion_xblocks, is_commentable_cohorted from lms.djangoapps.discussion_api.pagination import DiscussionAPIPagination from lms.lib.comment_client.comment import Comment from lms.lib.comment_client.thread import Thread from lms.lib.comment_client.utils import CommentClientRequestError from openedx.core.djangoapps.course_groups.cohorts import get_cohort_id from openedx.core.lib.exceptions import CourseNotFoundError, PageNotFoundError, DiscussionNotFoundError class DiscussionTopic(object): """ Class for discussion topic structure """ def __init__(self, topic_id, name, thread_list_url, children=None): self.id = topic_id # pylint: disable=invalid-name self.name = name self.thread_list_url = thread_list_url self.children = children or [] # children are of same type i.e. DiscussionTopic class DiscussionEntity(Enum): """ Enum for different types of discussion related entities """ thread = 'thread' comment = 'comment' def _get_course(course_key, user): """ Get the course descriptor, raising CourseNotFoundError if the course is not found or the user cannot access forums for the course, and DiscussionDisabledError if the discussion tab is disabled for the course. """ try: course = get_course_with_access(user, 'load', course_key, check_if_enrolled=True) except Http404: raise CourseNotFoundError("Course not found.") if not any([tab.type == 'discussion' and tab.is_enabled(course, user) for tab in course.tabs]): raise DiscussionDisabledError("Discussion is disabled for the course.") return course def _get_thread_and_context(request, thread_id, retrieve_kwargs=None): """ Retrieve the given thread and build a serializer context for it, returning both. This function also enforces access control for the thread (checking both the user's access to the course and to the thread's cohort if applicable). Raises ThreadNotFoundError if the thread does not exist or the user cannot access it. """ retrieve_kwargs = retrieve_kwargs or {} try: if "with_responses" not in retrieve_kwargs: retrieve_kwargs["with_responses"] = False if "mark_as_read" not in retrieve_kwargs: retrieve_kwargs["mark_as_read"] = False cc_thread = Thread(id=thread_id).retrieve(**retrieve_kwargs) course_key = CourseKey.from_string(cc_thread["course_id"]) course = _get_course(course_key, request.user) context = get_context(course, request, cc_thread) if ( not context["is_requester_privileged"] and cc_thread["group_id"] and is_commentable_cohorted(course.id, cc_thread["commentable_id"]) ): requester_cohort = get_cohort_id(request.user, course.id) if requester_cohort is not None and cc_thread["group_id"] != requester_cohort: raise ThreadNotFoundError("Thread not found.") return cc_thread, context except CommentClientRequestError: # params are validated at a higher level, so the only possible request # error is if the thread doesn't exist raise ThreadNotFoundError("Thread not found.") def _get_comment_and_context(request, comment_id): """ Retrieve the given comment and build a serializer context for it, returning both. This function also enforces access control for the comment (checking both the user's access to the course and to the comment's thread's cohort if applicable). Raises CommentNotFoundError if the comment does not exist or the user cannot access it. """ try: cc_comment = Comment(id=comment_id).retrieve() _, context = _get_thread_and_context(request, cc_comment["thread_id"]) return cc_comment, context except CommentClientRequestError: raise CommentNotFoundError("Comment not found.") def _is_user_author_or_privileged(cc_content, context): """ Check if the user is the author of a content object or a privileged user. Returns: Boolean """ return ( context["is_requester_privileged"] or context["cc_requester"]["id"] == cc_content["user_id"] ) def get_thread_list_url(request, course_key, topic_id_list=None, following=False): """ Returns the URL for the thread_list_url field, given a list of topic_ids """ path = reverse("thread-list") query_list = ( [("course_id", unicode(course_key))] + [("topic_id", topic_id) for topic_id in topic_id_list or []] + ([("following", following)] if following else []) ) return request.build_absolute_uri(urlunparse(("", "", path, "", urlencode(query_list), ""))) def get_course(request, course_key): """ Return general discussion information for the course. Parameters: request: The django request object used for build_absolute_uri and determining the requesting user. course_key: The key of the course to get information for Returns: The course information; see discussion_api.views.CourseView for more detail. Raises: CourseNotFoundError: if the course does not exist or is not accessible to the requesting user """ course = _get_course(course_key, request.user) return { "id": unicode(course_key), "blackouts": [ {"start": blackout["start"].isoformat(), "end": blackout["end"].isoformat()} for blackout in course.get_discussion_blackout_datetimes() ], "thread_list_url": get_thread_list_url(request, course_key), "following_thread_list_url": get_thread_list_url(request, course_key, following=True), "topics_url": request.build_absolute_uri( reverse("course_topics", kwargs={"course_id": course_key}) ) } def get_courseware_topics(request, course_key, course, topic_ids): """ Returns a list of topic trees for courseware-linked topics. Parameters: request: The django request objects used for build_absolute_uri. course_key: The key of the course to get discussion threads for. course: The course for which topics are requested. topic_ids: A list of topic IDs for which details are requested. This is optional. If None then all course topics are returned. Returns: A list of courseware topics and a set of existing topics among topic_ids. """ courseware_topics = [] existing_topic_ids = set() def get_xblock_sort_key(xblock): """ Get the sort key for the xblock (falling back to the discussion_target setting if absent) """ return xblock.sort_key or xblock.discussion_target def get_sorted_xblocks(category): """Returns key sorted xblocks by category""" return sorted(xblocks_by_category[category], key=get_xblock_sort_key) discussion_xblocks = get_accessible_discussion_xblocks(course, request.user) xblocks_by_category = defaultdict(list) for xblock in discussion_xblocks: xblocks_by_category[xblock.discussion_category].append(xblock) for category in sorted(xblocks_by_category.keys()): children = [] for xblock in get_sorted_xblocks(category): if not topic_ids or xblock.discussion_id in topic_ids: discussion_topic = DiscussionTopic( xblock.discussion_id, xblock.discussion_target, get_thread_list_url(request, course_key, [xblock.discussion_id]), ) children.append(discussion_topic) if topic_ids and xblock.discussion_id in topic_ids: existing_topic_ids.add(xblock.discussion_id) if not topic_ids or children: discussion_topic = DiscussionTopic( None, category, get_thread_list_url(request, course_key, [item.discussion_id for item in get_sorted_xblocks(category)]), children, ) courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data) return courseware_topics, existing_topic_ids def get_non_courseware_topics(request, course_key, course, topic_ids): """ Returns a list of topic trees that are not linked to courseware. Parameters: request: The django request objects used for build_absolute_uri. course_key: The key of the course to get discussion threads for. course: The course for which topics are requested. topic_ids: A list of topic IDs for which details are requested. This is optional. If None then all course topics are returned. Returns: A list of non-courseware topics and a set of existing topics among topic_ids. """ non_courseware_topics = [] existing_topic_ids = set() for name, entry in sorted(course.discussion_topics.items(), key=lambda item: item[1].get("sort_key", item[0])): if not topic_ids or entry['id'] in topic_ids: discussion_topic = DiscussionTopic( entry["id"], name, get_thread_list_url(request, course_key, [entry["id"]]) ) non_courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data) if topic_ids and entry["id"] in topic_ids: existing_topic_ids.add(entry["id"]) return non_courseware_topics, existing_topic_ids def get_course_topics(request, course_key, topic_ids=None): """ Returns the course topic listing for the given course and user; filtered by 'topic_ids' list if given. Parameters: course_key: The key of the course to get topics for user: The requesting user, for access control topic_ids: A list of topic IDs for which topic details are requested Returns: A course topic listing dictionary; see discussion_api.views.CourseTopicViews for more detail. Raises: DiscussionNotFoundError: If topic/s not found for given topic_ids. """ course = _get_course(course_key, request.user) courseware_topics, existing_courseware_topic_ids = get_courseware_topics(request, course_key, course, topic_ids) non_courseware_topics, existing_non_courseware_topic_ids = get_non_courseware_topics( request, course_key, course, topic_ids ) if topic_ids: not_found_topic_ids = topic_ids - (existing_courseware_topic_ids | existing_non_courseware_topic_ids) if not_found_topic_ids: raise DiscussionNotFoundError( "Discussion not found for '{}'.".format(", ".join(str(id) for id in not_found_topic_ids)) ) return { "courseware_topics": courseware_topics, "non_courseware_topics": non_courseware_topics, } def _get_user_profile_dict(request, usernames): """ Gets user profile details for a list of usernames and creates a dictionary with profile details against username. Parameters: request: The django request object. usernames: A string of comma separated usernames. Returns: A dict with username as key and user profile details as value. """ request.GET = request.GET.copy() # Make a mutable copy of the GET parameters. request.GET['username'] = usernames user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data return {user['username']: user for user in user_profile_details} def _user_profile(user_profile): """ Returns the user profile object. For now, this just comprises the profile_image details. """ return { 'profile': { 'image': user_profile['profile_image'] } } def _get_users(discussion_entity_type, discussion_entity, username_profile_dict): """ Returns users with profile details for given discussion thread/comment. Parameters: discussion_entity_type: DiscussionEntity Enum value for Thread or Comment. discussion_entity: Serialized thread/comment. username_profile_dict: A dict with user profile details against username. Returns: A dict of users with username as key and user profile details as value. """ users = {} if discussion_entity['author']: users[discussion_entity['author']] = _user_profile(username_profile_dict[discussion_entity['author']]) if ( discussion_entity_type == DiscussionEntity.comment and discussion_entity['endorsed'] and discussion_entity['endorsed_by'] ): users[discussion_entity['endorsed_by']] = _user_profile(username_profile_dict[discussion_entity['endorsed_by']]) return users def _add_additional_response_fields( request, serialized_discussion_entities, usernames, discussion_entity_type, include_profile_image ): """ Adds additional data to serialized discussion thread/comment. Parameters: request: The django request object. serialized_discussion_entities: A list of serialized Thread/Comment. usernames: A list of usernames involved in threads/comments (e.g. as author or as comment endorser). discussion_entity_type: DiscussionEntity Enum value for Thread or Comment. include_profile_image: (boolean) True if requested_fields has 'profile_image' else False. Returns: A list of serialized discussion thread/comment with additional data if requested. """ if include_profile_image: username_profile_dict = _get_user_profile_dict(request, usernames=','.join(usernames)) for discussion_entity in serialized_discussion_entities: discussion_entity['users'] = _get_users(discussion_entity_type, discussion_entity, username_profile_dict) return serialized_discussion_entities def _include_profile_image(requested_fields): """ Returns True if requested_fields list has 'profile_image' entity else False """ return requested_fields and 'profile_image' in requested_fields def _serialize_discussion_entities(request, context, discussion_entities, requested_fields, discussion_entity_type): """ It serializes Discussion Entity (Thread or Comment) and add additional data if requested. For a given list of Thread/Comment; it serializes and add additional information to the object as per requested_fields list (i.e. profile_image). Parameters: request: The django request object context: The context appropriate for use with the thread or comment discussion_entities: List of Thread or Comment objects requested_fields: Indicates which additional fields to return for each thread. discussion_entity_type: DiscussionEntity Enum value for Thread or Comment Returns: A list of serialized discussion entities """ results = [] usernames = [] include_profile_image = _include_profile_image(requested_fields) for entity in discussion_entities: if discussion_entity_type == DiscussionEntity.thread: serialized_entity = ThreadSerializer(entity, context=context).data elif discussion_entity_type == DiscussionEntity.comment: serialized_entity = CommentSerializer(entity, context=context).data results.append(serialized_entity) if include_profile_image: if serialized_entity['author'] and serialized_entity['author'] not in usernames: usernames.append(serialized_entity['author']) if ( 'endorsed' in serialized_entity and serialized_entity['endorsed'] and 'endorsed_by' in serialized_entity and serialized_entity['endorsed_by'] and serialized_entity['endorsed_by'] not in usernames ): usernames.append(serialized_entity['endorsed_by']) results = _add_additional_response_fields( request, results, usernames, discussion_entity_type, include_profile_image ) return results def get_thread_list( request, course_key, page, page_size, topic_id_list=None, text_search=None, following=False, view=None, order_by="last_activity_at", order_direction="desc", requested_fields=None, ): """ Return the list of all discussion threads pertaining to the given course Parameters: request: The django request objects used for build_absolute_uri course_key: The key of the course to get discussion threads for page: The page number (1-indexed) to retrieve page_size: The number of threads to retrieve per page topic_id_list: The list of topic_ids to get the discussion threads for text_search A text search query string to match following: If true, retrieve only threads the requester is following view: filters for either "unread" or "unanswered" threads order_by: The key in which to sort the threads by. The only values are "last_activity_at", "comment_count", and "vote_count". The default is "last_activity_at". order_direction: The direction in which to sort the threads by. The default and only value is "desc". This will be removed in a future major version. requested_fields: Indicates which additional fields to return for each thread. (i.e. ['profile_image']) Note that topic_id_list, text_search, and following are mutually exclusive. Returns: A paginated result containing a list of threads; see discussion_api.views.ThreadViewSet for more detail. Raises: ValidationError: if an invalid value is passed for a field. ValueError: if more than one of the mutually exclusive parameters is provided CourseNotFoundError: if the requesting user does not have access to the requested course PageNotFoundError: if page requested is beyond the last """ exclusive_param_count = sum(1 for param in [topic_id_list, text_search, following] if param) if exclusive_param_count > 1: # pragma: no cover raise ValueError("More than one mutually exclusive param passed to get_thread_list") cc_map = {"last_activity_at": "activity", "comment_count": "comments", "vote_count": "votes"} if order_by not in cc_map: raise ValidationError({ "order_by": ["Invalid value. '{}' must be 'last_activity_at', 'comment_count', or 'vote_count'".format(order_by)] }) if order_direction != "desc": raise ValidationError({ "order_direction": ["Invalid value. '{}' must be 'desc'".format(order_direction)] }) course = _get_course(course_key, request.user) context = get_context(course, request) query_params = { "user_id": unicode(request.user.id), "group_id": ( None if context["is_requester_privileged"] else get_cohort_id(request.user, course.id) ), "page": page, "per_page": page_size, "text": text_search, "sort_key": cc_map.get(order_by), } if view: if view in ["unread", "unanswered"]: query_params[view] = "true" else: ValidationError({ "view": ["Invalid value. '{}' must be 'unread' or 'unanswered'".format(view)] }) if following: paginated_results = context["cc_requester"].subscribed_threads(query_params) else: query_params["course_id"] = unicode(course.id) query_params["commentable_ids"] = ",".join(topic_id_list) if topic_id_list else None query_params["text"] = text_search paginated_results = Thread.search(query_params) # The comments service returns the last page of results if the requested # page is beyond the last page, but we want be consistent with DRF's general # behavior and return a PageNotFoundError in that case if paginated_results.page != page: raise PageNotFoundError("Page not found (No results on this page).") results = _serialize_discussion_entities( request, context, paginated_results.collection, requested_fields, DiscussionEntity.thread ) paginator = DiscussionAPIPagination( request, paginated_results.page, paginated_results.num_pages, paginated_results.thread_count ) return paginator.get_paginated_response({ "results": results, "text_search_rewrite": paginated_results.corrected_text, }) def get_comment_list(request, thread_id, endorsed, page, page_size, requested_fields=None): """ Return the list of comments in the given thread. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. thread_id: The id of the thread to get comments for. endorsed: Boolean indicating whether to get endorsed or non-endorsed comments (or None for all comments). Must be None for a discussion thread and non-None for a question thread. page: The page number (1-indexed) to retrieve page_size: The number of comments to retrieve per page requested_fields: Indicates which additional fields to return for each comment. (i.e. ['profile_image']) Returns: A paginated result containing a list of comments; see discussion_api.views.CommentViewSet for more detail. """ response_skip = page_size * (page - 1) cc_thread, context = _get_thread_and_context( request, thread_id, retrieve_kwargs={ "with_responses": True, "recursive": False, "user_id": request.user.id, "response_skip": response_skip, "response_limit": page_size, } ) # Responses to discussion threads cannot be separated by endorsed, but # responses to question threads must be separated by endorsed due to the # existing comments service interface if cc_thread["thread_type"] == "question": if endorsed is None: raise ValidationError({"endorsed": ["This field is required for question threads."]}) elif endorsed: # CS does not apply resp_skip and resp_limit to endorsed responses # of a question post responses = cc_thread["endorsed_responses"][response_skip:(response_skip + page_size)] resp_total = len(cc_thread["endorsed_responses"]) else: responses = cc_thread["non_endorsed_responses"] resp_total = cc_thread["non_endorsed_resp_total"] else: if endorsed is not None: raise ValidationError( {"endorsed": ["This field may not be specified for discussion threads."]} ) responses = cc_thread["children"] resp_total = cc_thread["resp_total"] # The comments service returns the last page of results if the requested # page is beyond the last page, but we want be consistent with DRF's general # behavior and return a PageNotFoundError in that case if not responses and page != 1: raise PageNotFoundError("Page not found (No results on this page).") num_pages = (resp_total + page_size - 1) / page_size if resp_total else 1 results = _serialize_discussion_entities(request, context, responses, requested_fields, DiscussionEntity.comment) paginator = DiscussionAPIPagination(request, page, num_pages, resp_total) return paginator.get_paginated_response(results) def _check_fields(allowed_fields, data, message): """ Checks that the keys given in data is in allowed_fields Arguments: allowed_fields (set): A set of allowed fields data (dict): The data to compare the allowed_fields against message (str): The message to return if there are any invalid fields Raises: ValidationError if the given data contains a key that is not in allowed_fields """ non_allowed_fields = {field: [message] for field in data.keys() if field not in allowed_fields} if non_allowed_fields: raise ValidationError(non_allowed_fields) def _check_initializable_thread_fields(data, context): # pylint: disable=invalid-name """ Checks if the given data contains a thread field that is not initializable by the requesting user Arguments: data (dict): The data to compare the allowed_fields against context (dict): The context appropriate for use with the thread which includes the requesting user Raises: ValidationError if the given data contains a thread field that is not initializable by the requesting user """ _check_fields( get_initializable_thread_fields(context), data, "This field is not initializable." ) def _check_initializable_comment_fields(data, context): # pylint: disable=invalid-name """ Checks if the given data contains a comment field that is not initializable by the requesting user Arguments: data (dict): The data to compare the allowed_fields against context (dict): The context appropriate for use with the comment which includes the requesting user Raises: ValidationError if the given data contains a comment field that is not initializable by the requesting user """ _check_fields( get_initializable_comment_fields(context), data, "This field is not initializable." ) def _check_editable_fields(cc_content, data, context): """ Raise ValidationError if the given update data contains a field that is not editable by the requesting user """ _check_fields( get_editable_fields(cc_content, context), data, "This field is not editable." ) def _do_extra_actions(api_content, cc_content, request_fields, actions_form, context, request): """ Perform any necessary additional actions related to content creation or update that require a separate comments service request. """ for field, form_value in actions_form.cleaned_data.items(): if field in request_fields and form_value != api_content[field]: api_content[field] = form_value if field == "following": _handle_following_field(form_value, context["cc_requester"], cc_content) elif field == "abuse_flagged": _handle_abuse_flagged_field(form_value, context["cc_requester"], cc_content) elif field == "voted": _handle_voted_field(form_value, cc_content, api_content, request, context) elif field == "read": _handle_read_field(api_content, form_value, context["cc_requester"], cc_content) else: raise ValidationError({field: ["Invalid Key"]}) def _handle_following_field(form_value, user, cc_content): """follow/unfollow thread for the user""" if form_value: user.follow(cc_content) else: user.unfollow(cc_content) def _handle_abuse_flagged_field(form_value, user, cc_content): """mark or unmark thread/comment as abused""" if form_value: cc_content.flagAbuse(user, cc_content) else: cc_content.unFlagAbuse(user, cc_content, removeAll=False) def _handle_voted_field(form_value, cc_content, api_content, request, context): """vote or undo vote on thread/comment""" signal = thread_voted if cc_content.type == 'thread' else comment_voted signal.send(sender=None, user=context["request"].user, post=cc_content) if form_value: context["cc_requester"].vote(cc_content, "up") api_content["vote_count"] += 1 else: context["cc_requester"].unvote(cc_content) api_content["vote_count"] -= 1 track_voted_event( request, context["course"], cc_content, vote_value="up", undo_vote=False if form_value else True ) def _handle_read_field(api_content, form_value, user, cc_content): """ Marks thread as read for the user """ if form_value and not cc_content['read']: user.read(cc_content) # When a thread is marked as read, all of its responses and comments # are also marked as read. api_content["unread_comment_count"] = 0 def create_thread(request, thread_data): """ Create a thread. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. thread_data: The data for the created thread. Returns: The created thread; see discussion_api.views.ThreadViewSet for more detail. """ course_id = thread_data.get("course_id") user = request.user if not course_id: raise ValidationError({"course_id": ["This field is required."]}) try: course_key = CourseKey.from_string(course_id) course = _get_course(course_key, user) except InvalidKeyError: raise ValidationError({"course_id": ["Invalid value."]}) context = get_context(course, request) _check_initializable_thread_fields(thread_data, context) if ( "group_id" not in thread_data and is_commentable_cohorted(course_key, thread_data.get("topic_id")) ): thread_data = thread_data.copy() thread_data["group_id"] = get_cohort_id(user, course_key) serializer = ThreadSerializer(data=thread_data, context=context) actions_form = ThreadActionsForm(thread_data) if not (serializer.is_valid() and actions_form.is_valid()): raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items())) serializer.save() cc_thread = serializer.instance thread_created.send(sender=None, user=user, post=cc_thread) api_thread = serializer.data _do_extra_actions(api_thread, cc_thread, thread_data.keys(), actions_form, context, request) track_thread_created_event(request, course, cc_thread, actions_form.cleaned_data["following"]) return api_thread def create_comment(request, comment_data): """ Create a comment. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. comment_data: The data for the created comment. Returns: The created comment; see discussion_api.views.CommentViewSet for more detail. """ thread_id = comment_data.get("thread_id") if not thread_id: raise ValidationError({"thread_id": ["This field is required."]}) cc_thread, context = _get_thread_and_context(request, thread_id) # if a thread is closed; no new comments could be made to it if cc_thread['closed']: raise PermissionDenied _check_initializable_comment_fields(comment_data, context) serializer = CommentSerializer(data=comment_data, context=context) actions_form = CommentActionsForm(comment_data) if not (serializer.is_valid() and actions_form.is_valid()): raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items())) serializer.save() cc_comment = serializer.instance comment_created.send(sender=None, user=request.user, post=cc_comment) api_comment = serializer.data _do_extra_actions(api_comment, cc_comment, comment_data.keys(), actions_form, context, request) track_comment_created_event(request, context["course"], cc_comment, cc_thread["commentable_id"], followed=False) return api_comment def update_thread(request, thread_id, update_data): """ Update a thread. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. thread_id: The id for the thread to update. update_data: The data to update in the thread. Returns: The updated thread; see discussion_api.views.ThreadViewSet for more detail. """ cc_thread, context = _get_thread_and_context(request, thread_id) _check_editable_fields(cc_thread, update_data, context) serializer = ThreadSerializer(cc_thread, data=update_data, partial=True, context=context) actions_form = ThreadActionsForm(update_data) if not (serializer.is_valid() and actions_form.is_valid()): raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items())) # Only save thread object if some of the edited fields are in the thread data, not extra actions if set(update_data) - set(actions_form.fields): serializer.save() # signal to update Teams when a user edits a thread thread_edited.send(sender=None, user=request.user, post=cc_thread) api_thread = serializer.data _do_extra_actions(api_thread, cc_thread, update_data.keys(), actions_form, context, request) # always return read as True (and therefore unread_comment_count=0) as reasonably # accurate shortcut, rather than adding additional processing. api_thread['read'] = True api_thread['unread_comment_count'] = 0 return api_thread def update_comment(request, comment_id, update_data): """ Update a comment. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. comment_id: The id for the comment to update. update_data: The data to update in the comment. Returns: The updated comment; see discussion_api.views.CommentViewSet for more detail. Raises: CommentNotFoundError: if the comment does not exist or is not accessible to the requesting user PermissionDenied: if the comment is accessible to but not editable by the requesting user ValidationError: if there is an error applying the update (e.g. raw_body is empty or thread_id is included) """ cc_comment, context = _get_comment_and_context(request, comment_id) _check_editable_fields(cc_comment, update_data, context) serializer = CommentSerializer(cc_comment, data=update_data, partial=True, context=context) actions_form = CommentActionsForm(update_data) if not (serializer.is_valid() and actions_form.is_valid()): raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items())) # Only save comment object if some of the edited fields are in the comment data, not extra actions if set(update_data) - set(actions_form.fields): serializer.save() comment_edited.send(sender=None, user=request.user, post=cc_comment) api_comment = serializer.data _do_extra_actions(api_comment, cc_comment, update_data.keys(), actions_form, context, request) return api_comment def get_thread(request, thread_id, requested_fields=None): """ Retrieve a thread. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. thread_id: The id for the thread to retrieve requested_fields: Indicates which additional fields to return for thread. (i.e. ['profile_image']) """ # Possible candidate for optimization with caching: # Param with_responses=True required only to add "response_count" to response. cc_thread, context = _get_thread_and_context( request, thread_id, retrieve_kwargs={ "with_responses": True, "user_id": unicode(request.user.id), } ) return _serialize_discussion_entities(request, context, [cc_thread], requested_fields, DiscussionEntity.thread)[0] def get_response_comments(request, comment_id, page, page_size, requested_fields=None): """ Return the list of comments for the given thread response. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. comment_id: The id of the comment/response to get child comments for. page: The page number (1-indexed) to retrieve page_size: The number of comments to retrieve per page requested_fields: Indicates which additional fields to return for each child comment. (i.e. ['profile_image']) Returns: A paginated result containing a list of comments """ try: cc_comment = Comment(id=comment_id).retrieve() cc_thread, context = _get_thread_and_context( request, cc_comment["thread_id"], retrieve_kwargs={ "with_responses": True, "recursive": True, } ) if cc_thread["thread_type"] == "question": thread_responses = itertools.chain(cc_thread["endorsed_responses"], cc_thread["non_endorsed_responses"]) else: thread_responses = cc_thread["children"] response_comments = [] for response in thread_responses: if response["id"] == comment_id: response_comments = response["children"] break response_skip = page_size * (page - 1) paged_response_comments = response_comments[response_skip:(response_skip + page_size)] if len(paged_response_comments) == 0 and page != 1: raise PageNotFoundError("Page not found (No results on this page).") results = _serialize_discussion_entities( request, context, paged_response_comments, requested_fields, DiscussionEntity.comment ) comments_count = len(response_comments) num_pages = (comments_count + page_size - 1) / page_size if comments_count else 1 paginator = DiscussionAPIPagination(request, page, num_pages, comments_count) return paginator.get_paginated_response(results) except CommentClientRequestError: raise CommentNotFoundError("Comment not found") def delete_thread(request, thread_id): """ Delete a thread. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. thread_id: The id for the thread to delete Raises: PermissionDenied: if user does not have permission to delete thread """ cc_thread, context = _get_thread_and_context(request, thread_id) if can_delete(cc_thread, context): cc_thread.delete() thread_deleted.send(sender=None, user=request.user, post=cc_thread) else: raise PermissionDenied def delete_comment(request, comment_id): """ Delete a comment. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. comment_id: The id of the comment to delete Raises: PermissionDenied: if user does not have permission to delete thread """ cc_comment, context = _get_comment_and_context(request, comment_id) if can_delete(cc_comment, context): cc_comment.delete() comment_deleted.send(sender=None, user=request.user, post=cc_comment) else: raise PermissionDenied
tanmaykm/edx-platform
lms/djangoapps/discussion_api/api.py
Python
agpl-3.0
40,733