How to use options method in root

Best JavaScript code snippet using root

__init__.py

Source:__init__.py Github

copy

Full Screen

1# coding=utf-82# --------------------------------------------------------------------------3# Copyright (c) Microsoft Corporation. All rights reserved.4# Licensed under the MIT License. See License.txt in the project root for5# license information.6#7# Code generated by Microsoft (R) AutoRest Code Generator.8# Changes may cause incorrect behavior and will be lost if the code is9# regenerated.10# --------------------------------------------------------------------------11from .pool_usage_metrics import PoolUsageMetrics12from .image_reference import ImageReference13from .node_agent_sku import NodeAgentSku14from .authentication_token_settings import AuthenticationTokenSettings15from .usage_statistics import UsageStatistics16from .resource_statistics import ResourceStatistics17from .pool_statistics import PoolStatistics18from .job_statistics import JobStatistics19from .name_value_pair import NameValuePair20from .delete_certificate_error import DeleteCertificateError21from .certificate import Certificate22from .application_package_reference import ApplicationPackageReference23from .application_summary import ApplicationSummary24from .certificate_add_parameter import CertificateAddParameter25from .file_properties import FileProperties26from .node_file import NodeFile27from .schedule import Schedule28from .job_constraints import JobConstraints29from .resource_file import ResourceFile30from .environment_setting import EnvironmentSetting31from .exit_options import ExitOptions32from .exit_code_mapping import ExitCodeMapping33from .exit_code_range_mapping import ExitCodeRangeMapping34from .exit_conditions import ExitConditions35from .auto_user_specification import AutoUserSpecification36from .user_identity import UserIdentity37from .linux_user_configuration import LinuxUserConfiguration38from .user_account import UserAccount39from .task_constraints import TaskConstraints40from .output_file_blob_container_destination import OutputFileBlobContainerDestination41from .output_file_destination import OutputFileDestination42from .output_file_upload_options import OutputFileUploadOptions43from .output_file import OutputFile44from .job_manager_task import JobManagerTask45from .job_preparation_task import JobPreparationTask46from .job_release_task import JobReleaseTask47from .task_scheduling_policy import TaskSchedulingPolicy48from .start_task import StartTask49from .certificate_reference import CertificateReference50from .metadata_item import MetadataItem51from .cloud_service_configuration import CloudServiceConfiguration52from .os_disk import OSDisk53from .windows_configuration import WindowsConfiguration54from .virtual_machine_configuration import VirtualMachineConfiguration55from .network_security_group_rule import NetworkSecurityGroupRule56from .inbound_nat_pool import InboundNATPool57from .pool_endpoint_configuration import PoolEndpointConfiguration58from .network_configuration import NetworkConfiguration59from .pool_specification import PoolSpecification60from .auto_pool_specification import AutoPoolSpecification61from .pool_information import PoolInformation62from .job_specification import JobSpecification63from .recent_job import RecentJob64from .job_schedule_execution_information import JobScheduleExecutionInformation65from .job_schedule_statistics import JobScheduleStatistics66from .cloud_job_schedule import CloudJobSchedule67from .job_schedule_add_parameter import JobScheduleAddParameter68from .job_scheduling_error import JobSchedulingError69from .job_execution_information import JobExecutionInformation70from .cloud_job import CloudJob71from .job_add_parameter import JobAddParameter72from .task_failure_information import TaskFailureInformation73from .job_preparation_task_execution_information import JobPreparationTaskExecutionInformation74from .job_release_task_execution_information import JobReleaseTaskExecutionInformation75from .job_preparation_and_release_task_execution_information import JobPreparationAndReleaseTaskExecutionInformation76from .task_counts import TaskCounts77from .auto_scale_run_error import AutoScaleRunError78from .auto_scale_run import AutoScaleRun79from .resize_error import ResizeError80from .cloud_pool import CloudPool81from .pool_add_parameter import PoolAddParameter82from .affinity_information import AffinityInformation83from .task_execution_information import TaskExecutionInformation84from .compute_node_information import ComputeNodeInformation85from .multi_instance_settings import MultiInstanceSettings86from .task_statistics import TaskStatistics87from .task_id_range import TaskIdRange88from .task_dependencies import TaskDependencies89from .cloud_task import CloudTask90from .task_add_parameter import TaskAddParameter91from .task_add_collection_parameter import TaskAddCollectionParameter92from .error_message import ErrorMessage93from .batch_error_detail import BatchErrorDetail94from .batch_error import BatchError, BatchErrorException95from .task_add_result import TaskAddResult96from .task_add_collection_result import TaskAddCollectionResult97from .subtask_information import SubtaskInformation98from .cloud_task_list_subtasks_result import CloudTaskListSubtasksResult99from .task_information import TaskInformation100from .start_task_information import StartTaskInformation101from .compute_node_error import ComputeNodeError102from .inbound_endpoint import InboundEndpoint103from .compute_node_endpoint_configuration import ComputeNodeEndpointConfiguration104from .compute_node import ComputeNode105from .compute_node_user import ComputeNodeUser106from .compute_node_get_remote_login_settings_result import ComputeNodeGetRemoteLoginSettingsResult107from .job_schedule_patch_parameter import JobSchedulePatchParameter108from .job_schedule_update_parameter import JobScheduleUpdateParameter109from .job_disable_parameter import JobDisableParameter110from .job_terminate_parameter import JobTerminateParameter111from .job_patch_parameter import JobPatchParameter112from .job_update_parameter import JobUpdateParameter113from .pool_enable_auto_scale_parameter import PoolEnableAutoScaleParameter114from .pool_evaluate_auto_scale_parameter import PoolEvaluateAutoScaleParameter115from .pool_resize_parameter import PoolResizeParameter116from .pool_update_properties_parameter import PoolUpdatePropertiesParameter117from .pool_upgrade_os_parameter import PoolUpgradeOSParameter118from .pool_patch_parameter import PoolPatchParameter119from .task_update_parameter import TaskUpdateParameter120from .node_update_user_parameter import NodeUpdateUserParameter121from .node_reboot_parameter import NodeRebootParameter122from .node_reimage_parameter import NodeReimageParameter123from .node_disable_scheduling_parameter import NodeDisableSchedulingParameter124from .node_remove_parameter import NodeRemoveParameter125from .application_list_options import ApplicationListOptions126from .application_get_options import ApplicationGetOptions127from .pool_list_usage_metrics_options import PoolListUsageMetricsOptions128from .pool_get_all_lifetime_statistics_options import PoolGetAllLifetimeStatisticsOptions129from .pool_add_options import PoolAddOptions130from .pool_list_options import PoolListOptions131from .pool_delete_options import PoolDeleteOptions132from .pool_exists_options import PoolExistsOptions133from .pool_get_options import PoolGetOptions134from .pool_patch_options import PoolPatchOptions135from .pool_disable_auto_scale_options import PoolDisableAutoScaleOptions136from .pool_enable_auto_scale_options import PoolEnableAutoScaleOptions137from .pool_evaluate_auto_scale_options import PoolEvaluateAutoScaleOptions138from .pool_resize_options import PoolResizeOptions139from .pool_stop_resize_options import PoolStopResizeOptions140from .pool_update_properties_options import PoolUpdatePropertiesOptions141from .pool_upgrade_os_options import PoolUpgradeOsOptions142from .pool_remove_nodes_options import PoolRemoveNodesOptions143from .account_list_node_agent_skus_options import AccountListNodeAgentSkusOptions144from .job_get_all_lifetime_statistics_options import JobGetAllLifetimeStatisticsOptions145from .job_delete_options import JobDeleteOptions146from .job_get_options import JobGetOptions147from .job_patch_options import JobPatchOptions148from .job_update_options import JobUpdateOptions149from .job_disable_options import JobDisableOptions150from .job_enable_options import JobEnableOptions151from .job_terminate_options import JobTerminateOptions152from .job_add_options import JobAddOptions153from .job_list_options import JobListOptions154from .job_list_from_job_schedule_options import JobListFromJobScheduleOptions155from .job_list_preparation_and_release_task_status_options import JobListPreparationAndReleaseTaskStatusOptions156from .job_get_task_counts_options import JobGetTaskCountsOptions157from .certificate_add_options import CertificateAddOptions158from .certificate_list_options import CertificateListOptions159from .certificate_cancel_deletion_options import CertificateCancelDeletionOptions160from .certificate_delete_options import CertificateDeleteOptions161from .certificate_get_options import CertificateGetOptions162from .file_delete_from_task_options import FileDeleteFromTaskOptions163from .file_get_from_task_options import FileGetFromTaskOptions164from .file_get_properties_from_task_options import FileGetPropertiesFromTaskOptions165from .file_delete_from_compute_node_options import FileDeleteFromComputeNodeOptions166from .file_get_from_compute_node_options import FileGetFromComputeNodeOptions167from .file_get_properties_from_compute_node_options import FileGetPropertiesFromComputeNodeOptions168from .file_list_from_task_options import FileListFromTaskOptions169from .file_list_from_compute_node_options import FileListFromComputeNodeOptions170from .job_schedule_exists_options import JobScheduleExistsOptions171from .job_schedule_delete_options import JobScheduleDeleteOptions172from .job_schedule_get_options import JobScheduleGetOptions173from .job_schedule_patch_options import JobSchedulePatchOptions174from .job_schedule_update_options import JobScheduleUpdateOptions175from .job_schedule_disable_options import JobScheduleDisableOptions176from .job_schedule_enable_options import JobScheduleEnableOptions177from .job_schedule_terminate_options import JobScheduleTerminateOptions178from .job_schedule_add_options import JobScheduleAddOptions179from .job_schedule_list_options import JobScheduleListOptions180from .task_add_options import TaskAddOptions181from .task_list_options import TaskListOptions182from .task_add_collection_options import TaskAddCollectionOptions183from .task_delete_options import TaskDeleteOptions184from .task_get_options import TaskGetOptions185from .task_update_options import TaskUpdateOptions186from .task_list_subtasks_options import TaskListSubtasksOptions187from .task_terminate_options import TaskTerminateOptions188from .task_reactivate_options import TaskReactivateOptions189from .compute_node_add_user_options import ComputeNodeAddUserOptions190from .compute_node_delete_user_options import ComputeNodeDeleteUserOptions191from .compute_node_update_user_options import ComputeNodeUpdateUserOptions192from .compute_node_get_options import ComputeNodeGetOptions193from .compute_node_reboot_options import ComputeNodeRebootOptions194from .compute_node_reimage_options import ComputeNodeReimageOptions195from .compute_node_disable_scheduling_options import ComputeNodeDisableSchedulingOptions196from .compute_node_enable_scheduling_options import ComputeNodeEnableSchedulingOptions197from .compute_node_get_remote_login_settings_options import ComputeNodeGetRemoteLoginSettingsOptions198from .compute_node_get_remote_desktop_options import ComputeNodeGetRemoteDesktopOptions199from .compute_node_list_options import ComputeNodeListOptions200from .application_summary_paged import ApplicationSummaryPaged201from .pool_usage_metrics_paged import PoolUsageMetricsPaged202from .cloud_pool_paged import CloudPoolPaged203from .node_agent_sku_paged import NodeAgentSkuPaged204from .cloud_job_paged import CloudJobPaged205from .job_preparation_and_release_task_execution_information_paged import JobPreparationAndReleaseTaskExecutionInformationPaged206from .certificate_paged import CertificatePaged207from .node_file_paged import NodeFilePaged208from .cloud_job_schedule_paged import CloudJobSchedulePaged209from .cloud_task_paged import CloudTaskPaged210from .compute_node_paged import ComputeNodePaged211from .batch_service_client_enums import (212 OSType,213 AccessScope,214 CertificateState,215 CertificateFormat,216 JobAction,217 DependencyAction,218 AutoUserScope,219 ElevationLevel,220 OutputFileUploadCondition,221 ComputeNodeFillType,222 CertificateStoreLocation,223 CertificateVisibility,224 CachingType,225 InboundEndpointProtocol,226 NetworkSecurityGroupRuleAccess,227 PoolLifetimeOption,228 OnAllTasksComplete,229 OnTaskFailure,230 JobScheduleState,231 ErrorCategory,232 JobState,233 JobPreparationTaskState,234 TaskExecutionResult,235 JobReleaseTaskState,236 TaskCountValidationStatus,237 PoolState,238 AllocationState,239 TaskState,240 TaskAddStatus,241 SubtaskState,242 StartTaskState,243 ComputeNodeState,244 SchedulingState,245 DisableJobOption,246 ComputeNodeDeallocationOption,247 ComputeNodeRebootOption,248 ComputeNodeReimageOption,249 DisableComputeNodeSchedulingOption,250)251__all__ = [252 'PoolUsageMetrics',253 'ImageReference',254 'NodeAgentSku',255 'AuthenticationTokenSettings',256 'UsageStatistics',257 'ResourceStatistics',258 'PoolStatistics',259 'JobStatistics',260 'NameValuePair',261 'DeleteCertificateError',262 'Certificate',263 'ApplicationPackageReference',264 'ApplicationSummary',265 'CertificateAddParameter',266 'FileProperties',267 'NodeFile',268 'Schedule',269 'JobConstraints',270 'ResourceFile',271 'EnvironmentSetting',272 'ExitOptions',273 'ExitCodeMapping',274 'ExitCodeRangeMapping',275 'ExitConditions',276 'AutoUserSpecification',277 'UserIdentity',278 'LinuxUserConfiguration',279 'UserAccount',280 'TaskConstraints',281 'OutputFileBlobContainerDestination',282 'OutputFileDestination',283 'OutputFileUploadOptions',284 'OutputFile',285 'JobManagerTask',286 'JobPreparationTask',287 'JobReleaseTask',288 'TaskSchedulingPolicy',289 'StartTask',290 'CertificateReference',291 'MetadataItem',292 'CloudServiceConfiguration',293 'OSDisk',294 'WindowsConfiguration',295 'VirtualMachineConfiguration',296 'NetworkSecurityGroupRule',297 'InboundNATPool',298 'PoolEndpointConfiguration',299 'NetworkConfiguration',300 'PoolSpecification',301 'AutoPoolSpecification',302 'PoolInformation',303 'JobSpecification',304 'RecentJob',305 'JobScheduleExecutionInformation',306 'JobScheduleStatistics',307 'CloudJobSchedule',308 'JobScheduleAddParameter',309 'JobSchedulingError',310 'JobExecutionInformation',311 'CloudJob',312 'JobAddParameter',313 'TaskFailureInformation',314 'JobPreparationTaskExecutionInformation',315 'JobReleaseTaskExecutionInformation',316 'JobPreparationAndReleaseTaskExecutionInformation',317 'TaskCounts',318 'AutoScaleRunError',319 'AutoScaleRun',320 'ResizeError',321 'CloudPool',322 'PoolAddParameter',323 'AffinityInformation',324 'TaskExecutionInformation',325 'ComputeNodeInformation',326 'MultiInstanceSettings',327 'TaskStatistics',328 'TaskIdRange',329 'TaskDependencies',330 'CloudTask',331 'TaskAddParameter',332 'TaskAddCollectionParameter',333 'ErrorMessage',334 'BatchErrorDetail',335 'BatchError', 'BatchErrorException',336 'TaskAddResult',337 'TaskAddCollectionResult',338 'SubtaskInformation',339 'CloudTaskListSubtasksResult',340 'TaskInformation',341 'StartTaskInformation',342 'ComputeNodeError',343 'InboundEndpoint',344 'ComputeNodeEndpointConfiguration',345 'ComputeNode',346 'ComputeNodeUser',347 'ComputeNodeGetRemoteLoginSettingsResult',348 'JobSchedulePatchParameter',349 'JobScheduleUpdateParameter',350 'JobDisableParameter',351 'JobTerminateParameter',352 'JobPatchParameter',353 'JobUpdateParameter',354 'PoolEnableAutoScaleParameter',355 'PoolEvaluateAutoScaleParameter',356 'PoolResizeParameter',357 'PoolUpdatePropertiesParameter',358 'PoolUpgradeOSParameter',359 'PoolPatchParameter',360 'TaskUpdateParameter',361 'NodeUpdateUserParameter',362 'NodeRebootParameter',363 'NodeReimageParameter',364 'NodeDisableSchedulingParameter',365 'NodeRemoveParameter',366 'ApplicationListOptions',367 'ApplicationGetOptions',368 'PoolListUsageMetricsOptions',369 'PoolGetAllLifetimeStatisticsOptions',370 'PoolAddOptions',371 'PoolListOptions',372 'PoolDeleteOptions',373 'PoolExistsOptions',374 'PoolGetOptions',375 'PoolPatchOptions',376 'PoolDisableAutoScaleOptions',377 'PoolEnableAutoScaleOptions',378 'PoolEvaluateAutoScaleOptions',379 'PoolResizeOptions',380 'PoolStopResizeOptions',381 'PoolUpdatePropertiesOptions',382 'PoolUpgradeOsOptions',383 'PoolRemoveNodesOptions',384 'AccountListNodeAgentSkusOptions',385 'JobGetAllLifetimeStatisticsOptions',386 'JobDeleteOptions',387 'JobGetOptions',388 'JobPatchOptions',389 'JobUpdateOptions',390 'JobDisableOptions',391 'JobEnableOptions',392 'JobTerminateOptions',393 'JobAddOptions',394 'JobListOptions',395 'JobListFromJobScheduleOptions',396 'JobListPreparationAndReleaseTaskStatusOptions',397 'JobGetTaskCountsOptions',398 'CertificateAddOptions',399 'CertificateListOptions',400 'CertificateCancelDeletionOptions',401 'CertificateDeleteOptions',402 'CertificateGetOptions',403 'FileDeleteFromTaskOptions',404 'FileGetFromTaskOptions',405 'FileGetPropertiesFromTaskOptions',406 'FileDeleteFromComputeNodeOptions',407 'FileGetFromComputeNodeOptions',408 'FileGetPropertiesFromComputeNodeOptions',409 'FileListFromTaskOptions',410 'FileListFromComputeNodeOptions',411 'JobScheduleExistsOptions',412 'JobScheduleDeleteOptions',413 'JobScheduleGetOptions',414 'JobSchedulePatchOptions',415 'JobScheduleUpdateOptions',416 'JobScheduleDisableOptions',417 'JobScheduleEnableOptions',418 'JobScheduleTerminateOptions',419 'JobScheduleAddOptions',420 'JobScheduleListOptions',421 'TaskAddOptions',422 'TaskListOptions',423 'TaskAddCollectionOptions',424 'TaskDeleteOptions',425 'TaskGetOptions',426 'TaskUpdateOptions',427 'TaskListSubtasksOptions',428 'TaskTerminateOptions',429 'TaskReactivateOptions',430 'ComputeNodeAddUserOptions',431 'ComputeNodeDeleteUserOptions',432 'ComputeNodeUpdateUserOptions',433 'ComputeNodeGetOptions',434 'ComputeNodeRebootOptions',435 'ComputeNodeReimageOptions',436 'ComputeNodeDisableSchedulingOptions',437 'ComputeNodeEnableSchedulingOptions',438 'ComputeNodeGetRemoteLoginSettingsOptions',439 'ComputeNodeGetRemoteDesktopOptions',440 'ComputeNodeListOptions',441 'ApplicationSummaryPaged',442 'PoolUsageMetricsPaged',443 'CloudPoolPaged',444 'NodeAgentSkuPaged',445 'CloudJobPaged',446 'JobPreparationAndReleaseTaskExecutionInformationPaged',447 'CertificatePaged',448 'NodeFilePaged',449 'CloudJobSchedulePaged',450 'CloudTaskPaged',451 'ComputeNodePaged',452 'OSType',453 'AccessScope',454 'CertificateState',455 'CertificateFormat',456 'JobAction',457 'DependencyAction',458 'AutoUserScope',459 'ElevationLevel',460 'OutputFileUploadCondition',461 'ComputeNodeFillType',462 'CertificateStoreLocation',463 'CertificateVisibility',464 'CachingType',465 'InboundEndpointProtocol',466 'NetworkSecurityGroupRuleAccess',467 'PoolLifetimeOption',468 'OnAllTasksComplete',469 'OnTaskFailure',470 'JobScheduleState',471 'ErrorCategory',472 'JobState',473 'JobPreparationTaskState',474 'TaskExecutionResult',475 'JobReleaseTaskState',476 'TaskCountValidationStatus',477 'PoolState',478 'AllocationState',479 'TaskState',480 'TaskAddStatus',481 'SubtaskState',482 'StartTaskState',483 'ComputeNodeState',484 'SchedulingState',485 'DisableJobOption',486 'ComputeNodeDeallocationOption',487 'ComputeNodeRebootOption',488 'ComputeNodeReimageOption',489 'DisableComputeNodeSchedulingOption',...

Full Screen

Full Screen

ec2_vpc_dhcp_options.py

Source:ec2_vpc_dhcp_options.py Github

copy

Full Screen

...222 """223 vpcs = vpc_conn.get_all_vpcs(vpc_ids=[vpc_id])224 if len(vpcs) != 1 or vpcs[0].dhcp_options_id == "default":225 return None226 dhcp_options = vpc_conn.get_all_dhcp_options(dhcp_options_ids=[vpcs[0].dhcp_options_id])227 if len(dhcp_options) != 1:228 return None229 return dhcp_options[0]230def match_dhcp_options(vpc_conn, tags=None, options=None):231 """232 Finds a DHCP Options object that optionally matches the tags and options provided233 """234 dhcp_options = vpc_conn.get_all_dhcp_options()235 for dopts in dhcp_options:236 if (not tags) or get_resource_tags(vpc_conn, dopts.id) == tags:237 if (not options) or dopts.options == options:238 return(True, dopts)239 return(False, None)240def remove_dhcp_options_by_id(vpc_conn, dhcp_options_id):241 associations = vpc_conn.get_all_vpcs(filters={'dhcpOptionsId': dhcp_options_id})242 if len(associations) > 0:243 return False244 else:245 vpc_conn.delete_dhcp_options(dhcp_options_id)246 return True247def main():248 argument_spec = ec2_argument_spec()249 argument_spec.update(dict(250 dhcp_options_id=dict(type='str', default=None),251 domain_name=dict(type='str', default=None),252 dns_servers=dict(type='list', default=None),253 ntp_servers=dict(type='list', default=None),254 netbios_name_servers=dict(type='list', default=None),255 netbios_node_type=dict(type='int', default=None),256 vpc_id=dict(type='str', default=None),257 delete_old=dict(type='bool', default=True),258 inherit_existing=dict(type='bool', default=False),259 tags=dict(type='dict', default=None, aliases=['resource_tags']),260 state=dict(type='str', default='present', choices=['present', 'absent'])261 )262 )263 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)264 params = module.params265 found = False266 changed = False267 new_options = collections.defaultdict(lambda: None)268 region, ec2_url, boto_params = get_aws_connection_info(module)269 connection = connect_to_aws(boto.vpc, region, **boto_params)270 existing_options = None271 # First check if we were given a dhcp_options_id272 if not params['dhcp_options_id']:273 # No, so create new_options from the parameters274 if params['dns_servers'] is not None:275 new_options['domain-name-servers'] = params['dns_servers']276 if params['netbios_name_servers'] is not None:277 new_options['netbios-name-servers'] = params['netbios_name_servers']278 if params['ntp_servers'] is not None:279 new_options['ntp-servers'] = params['ntp_servers']280 if params['domain_name'] is not None:281 # needs to be a list for comparison with boto objects later282 new_options['domain-name'] = [ params['domain_name'] ]283 if params['netbios_node_type'] is not None:284 # needs to be a list for comparison with boto objects later285 new_options['netbios-node-type'] = [ str(params['netbios_node_type']) ]286 # If we were given a vpc_id then we need to look at the options on that287 if params['vpc_id']:288 existing_options = fetch_dhcp_options_for_vpc(connection, params['vpc_id'])289 # if we've been asked to inherit existing options, do that now290 if params['inherit_existing']:291 if existing_options:292 for option in [ 'domain-name-servers', 'netbios-name-servers', 'ntp-servers', 'domain-name', 'netbios-node-type']:293 if existing_options.options.get(option) and new_options[option] != [] and (not new_options[option] or [''] == new_options[option]):294 new_options[option] = existing_options.options.get(option)295 # Do the vpc's dhcp options already match what we're asked for? if so we are done296 if existing_options and new_options == existing_options.options:297 module.exit_json(changed=changed, new_options=new_options, dhcp_options_id=existing_options.id)298 # If no vpc_id was given, or the options don't match then look for an existing set using tags299 found, dhcp_option = match_dhcp_options(connection, params['tags'], new_options)300 # Now let's cover the case where there are existing options that we were told about by id301 # If a dhcp_options_id was supplied we don't look at options inside, just set tags (if given)302 else:303 supplied_options = connection.get_all_dhcp_options(filters={'dhcp-options-id':params['dhcp_options_id']})304 if len(supplied_options) != 1:305 if params['state'] != 'absent':306 module.fail_json(msg=" a dhcp_options_id was supplied, but does not exist")307 else:308 found = True309 dhcp_option = supplied_options[0]310 if params['state'] != 'absent' and params['tags']:311 ensure_tags(connection, dhcp_option.id, params['tags'], False, module.check_mode)312 # Now we have the dhcp options set, let's do the necessary313 # if we found options we were asked to remove then try to do so314 if params['state'] == 'absent':315 if not module.check_mode:316 if found:317 changed = remove_dhcp_options_by_id(connection, dhcp_option.id)318 module.exit_json(changed=changed, new_options={})319 # otherwise if we haven't found the required options we have something to do320 elif not module.check_mode and not found:321 # create some dhcp options if we weren't able to use existing ones322 if not found:323 # Convert netbios-node-type and domain-name back to strings324 if new_options['netbios-node-type']:325 new_options['netbios-node-type'] = new_options['netbios-node-type'][0]326 if new_options['domain-name']:327 new_options['domain-name'] = new_options['domain-name'][0]328 # create the new dhcp options set requested329 dhcp_option = connection.create_dhcp_options(330 new_options['domain-name'],331 new_options['domain-name-servers'],332 new_options['ntp-servers'],333 new_options['netbios-name-servers'],334 new_options['netbios-node-type'])335 changed = True336 if params['tags']:337 ensure_tags(connection, dhcp_option.id, params['tags'], False, module.check_mode)338 # If we were given a vpc_id, then attach the options we now have to that before we finish339 if params['vpc_id'] and not module.check_mode:340 changed = True341 connection.associate_dhcp_options(dhcp_option.id, params['vpc_id'])342 # and remove old ones if that was requested343 if params['delete_old'] and existing_options:344 remove_dhcp_options_by_id(connection, existing_options.id)345 module.exit_json(changed=changed, new_options=new_options, dhcp_options_id=dhcp_option.id)346from ansible.module_utils.basic import *347from ansible.module_utils.ec2 import *348if __name__ == "__main__":...

Full Screen

Full Screen

test_options.py

Source:test_options.py Github

copy

Full Screen

1# Copyright (c) Twisted Matrix Laboratories.2# See LICENSE for details.3"""4Tests for L{twisted.application.twist._options}.5"""6from sys import stdout, stderr7from twisted.internet import reactor8from twisted.copyright import version9from twisted.python.usage import UsageError10from twisted.logger import LogLevel, textFileLogObserver, jsonFileLogObserver11from twisted.test.proto_helpers import MemoryReactor12from ...reactors import NoSuchReactor13from ...service import ServiceMaker14from ...runner._exit import ExitStatus15from ...runner.test.test_runner import DummyExit16from ...twist import _options17from .._options import TwistOptions18import twisted.trial.unittest19class OptionsTests(twisted.trial.unittest.TestCase):20 """21 Tests for L{TwistOptions}.22 """23 def patchExit(self):24 """25 Patch L{_twist.exit} so we can capture usage and prevent actual exits.26 """27 self.exit = DummyExit()28 self.patch(_options, "exit", self.exit)29 def patchOpen(self):30 """31 Patch L{_options.open} so we can capture usage and prevent actual opens.32 """33 self.opened = []34 def fakeOpen(name, mode=None):35 if name == "nocanopen":36 raise IOError(None, None, name)37 self.opened.append((name, mode))38 return NotImplemented39 self.patch(_options, "openFile", fakeOpen)40 def patchInstallReactor(self):41 """42 Patch C{_options.installReactor} so we can capture usage and prevent43 actual installs.44 """45 self.installedReactors = {}46 def installReactor(name):47 if name != "fusion":48 raise NoSuchReactor()49 reactor = MemoryReactor()50 self.installedReactors[name] = reactor51 return reactor52 self.patch(_options, "installReactor", installReactor)53 def test_synopsis(self):54 """55 L{TwistOptions.getSynopsis} appends arguments.56 """57 options = TwistOptions()58 self.assertTrue(59 options.getSynopsis().endswith(" plugin [plugin_options]")60 )61 def test_version(self):62 """63 L{TwistOptions.opt_version} exits with L{ExitStatus.EX_OK} and prints64 the version.65 """66 self.patchExit()67 options = TwistOptions()68 options.opt_version()69 self.assertEquals(self.exit.status, ExitStatus.EX_OK)70 self.assertEquals(self.exit.message, version)71 def test_reactor(self):72 """73 L{TwistOptions.installReactor} installs the chosen reactor and sets74 the reactor name.75 """76 self.patchInstallReactor()77 options = TwistOptions()78 options.opt_reactor("fusion")79 self.assertEqual(set(self.installedReactors), set(["fusion"]))80 self.assertEquals(options["reactorName"], "fusion")81 def test_installCorrectReactor(self):82 """83 L{TwistOptions.installReactor} installs the chosen reactor after the84 command line options have been parsed.85 """86 self.patchInstallReactor()87 options = TwistOptions()88 options.subCommand = "test-subcommand"89 options.parseOptions(["--reactor=fusion"])90 self.assertEqual(set(self.installedReactors), set(["fusion"]))91 def test_installReactorBogus(self):92 """93 L{TwistOptions.installReactor} raises UsageError if an unknown reactor94 is specified.95 """96 self.patchInstallReactor()97 options = TwistOptions()98 self.assertRaises(UsageError, options.opt_reactor, "coal")99 def test_installReactorDefault(self):100 """101 L{TwistOptions.installReactor} returns the currently installed reactor102 when the default reactor name is specified.103 """104 options = TwistOptions()105 self.assertIdentical(reactor, options.installReactor('default'))106 def test_logLevelValid(self):107 """108 L{TwistOptions.opt_log_level} sets the corresponding log level.109 """110 options = TwistOptions()111 options.opt_log_level("warn")112 self.assertIdentical(options["logLevel"], LogLevel.warn)113 def test_logLevelInvalid(self):114 """115 L{TwistOptions.opt_log_level} with an invalid log level name raises116 UsageError.117 """118 options = TwistOptions()119 self.assertRaises(UsageError, options.opt_log_level, "cheese")120 def _testLogFile(self, name, expectedStream):121 """122 Set log file name and check the selected output stream.123 @param name: The name of the file.124 @param expectedStream: The expected stream.125 """126 options = TwistOptions()127 options.opt_log_file(name)128 self.assertIdentical(options["logFile"], expectedStream)129 def test_logFileStdout(self):130 """131 L{TwistOptions.opt_log_file} given C{"-"} as a file name uses stdout.132 """133 self._testLogFile("-", stdout)134 def test_logFileStderr(self):135 """136 L{TwistOptions.opt_log_file} given C{"+"} as a file name uses stderr.137 """138 self._testLogFile("+", stderr)139 def test_logFileNamed(self):140 """141 L{TwistOptions.opt_log_file} opens the given file name in append mode.142 """143 self.patchOpen()144 options = TwistOptions()145 options.opt_log_file("mylog")146 self.assertEqual([("mylog", "a")], self.opened)147 def test_logFileCantOpen(self):148 """149 L{TwistOptions.opt_log_file} exits with L{ExitStatus.EX_IOERR} if150 unable to open the log file due to an L{EnvironmentError}.151 """152 self.patchExit()153 self.patchOpen()154 options = TwistOptions()155 options.opt_log_file("nocanopen")156 self.assertEquals(self.exit.status, ExitStatus.EX_IOERR)157 self.assertTrue(158 self.exit.message.startswith(159 "Unable to open log file 'nocanopen': "160 )161 )162 def _testLogFormat(self, format, expectedObserver):163 """164 Set log file format and check the selected observer.165 @param format: The format of the file.166 @param expectedObserver: The expected observer.167 """168 options = TwistOptions()169 options.opt_log_format(format)170 self.assertIdentical(171 options["fileLogObserverFactory"], expectedObserver172 )173 self.assertEqual(options["logFormat"], format)174 def test_logFormatText(self):175 """176 L{TwistOptions.opt_log_format} given C{"text"} uses a177 L{textFileLogObserver}.178 """179 self._testLogFormat("text", textFileLogObserver)180 def test_logFormatJSON(self):181 """182 L{TwistOptions.opt_log_format} given C{"text"} uses a183 L{textFileLogObserver}.184 """185 self._testLogFormat("json", jsonFileLogObserver)186 def test_logFormatInvalid(self):187 """188 L{TwistOptions.opt_log_format} given an invalid format name raises189 L{UsageError}.190 """191 options = TwistOptions()192 self.assertRaises(UsageError, options.opt_log_format, "frommage")193 def test_selectDefaultLogObserverNoOverride(self):194 """195 L{TwistOptions.selectDefaultLogObserver} will not override an already196 selected observer.197 """198 self.patchOpen()199 options = TwistOptions()200 options.opt_log_format("text") # Ask for text201 options.opt_log_file("queso") # File, not a tty202 options.selectDefaultLogObserver()203 # Because we didn't select a file that is a tty, the default is JSON,204 # but since we asked for text, we should get text.205 self.assertIdentical(206 options["fileLogObserverFactory"], textFileLogObserver207 )208 self.assertEqual(options["logFormat"], "text")209 def test_selectDefaultLogObserverDefaultWithTTY(self):210 """211 L{TwistOptions.selectDefaultLogObserver} will not override an already212 selected observer.213 """214 class TTYFile(object):215 def isatty(self):216 return True217 # stdout may not be a tty, so let's make sure it thinks it is218 self.patch(_options, "stdout", TTYFile())219 options = TwistOptions()220 options.opt_log_file("-") # stdout, a tty221 options.selectDefaultLogObserver()222 self.assertIdentical(223 options["fileLogObserverFactory"], textFileLogObserver224 )225 self.assertEqual(options["logFormat"], "text")226 def test_selectDefaultLogObserverDefaultWithoutTTY(self):227 """228 L{TwistOptions.selectDefaultLogObserver} will not override an already229 selected observer.230 """231 self.patchOpen()232 options = TwistOptions()233 options.opt_log_file("queso") # File, not a tty234 options.selectDefaultLogObserver()235 self.assertIdentical(236 options["fileLogObserverFactory"], jsonFileLogObserver237 )238 self.assertEqual(options["logFormat"], "json")239 def test_pluginsType(self):240 """241 L{TwistOptions.plugins} is a mapping of available plug-ins.242 """243 options = TwistOptions()244 plugins = options.plugins245 for name in plugins:246 self.assertIsInstance(name, str)247 self.assertIsInstance(plugins[name], ServiceMaker)248 def test_pluginsIncludeWeb(self):249 """250 L{TwistOptions.plugins} includes a C{"web"} plug-in.251 This is an attempt to verify that something we expect to be in the list252 is in there without enumerating all of the built-in plug-ins.253 """254 options = TwistOptions()255 self.assertIn("web", options.plugins)256 def test_subCommandsType(self):257 """258 L{TwistOptions.subCommands} is an iterable of tuples as expected by259 L{twisted.python.usage.Options}.260 """261 options = TwistOptions()262 for name, shortcut, parser, doc in options.subCommands:263 self.assertIsInstance(name, str)264 self.assertIdentical(shortcut, None)265 self.assertTrue(callable(parser))266 self.assertIsInstance(doc, str)267 def test_subCommandsIncludeWeb(self):268 """269 L{TwistOptions.subCommands} includes a sub-command for every plug-in.270 """271 options = TwistOptions()272 plugins = set(options.plugins)273 subCommands = set(274 name for name, shortcut, parser, doc in options.subCommands275 )276 self.assertEqual(subCommands, plugins)277 def test_postOptionsNoSubCommand(self):278 """279 L{TwistOptions.postOptions} raises L{UsageError} is it has no280 sub-command.281 """282 self.patchInstallReactor()283 options = TwistOptions()...

Full Screen

Full Screen

options_test.py

Source:options_test.py Github

copy

Full Screen

...100 options = OptionParser()101 options.define('foo', default=1, type=int, callback=values.append)102 options.foo = 2103 self.assertEqual(values, [2])104 def _sample_options(self):105 options = OptionParser()106 options.define('a', default=1)107 options.define('b', default=2)108 return options109 def test_iter(self):110 options = self._sample_options()111 # OptionParsers always define 'help'.112 self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))113 def test_getitem(self):114 options = self._sample_options()115 self.assertEqual(1, options['a'])116 def test_setitem(self):117 options = OptionParser()118 options.define('foo', default=1, type=int)119 options['foo'] = 2120 self.assertEqual(options['foo'], 2)121 def test_items(self):122 options = self._sample_options()123 # OptionParsers always define 'help'.124 expected = [('a', 1), ('b', 2), ('help', options.help)]125 actual = sorted(options.items())126 self.assertEqual(expected, actual)127 def test_as_dict(self):128 options = self._sample_options()129 expected = {'a': 1, 'b': 2, 'help': options.help}130 self.assertEqual(expected, options.as_dict())131 def test_group_dict(self):132 options = OptionParser()133 options.define('a', default=1)134 options.define('b', group='b_group', default=2)135 frame = sys._getframe(0)136 this_file = frame.f_code.co_filename137 self.assertEqual(set(['b_group', '', this_file]), options.groups())138 b_group_dict = options.group_dict('b_group')139 self.assertEqual({'b': 2}, b_group_dict)140 self.assertEqual({}, options.group_dict('nonexistent'))141 @unittest.skipIf(mock is None, 'mock package not present')142 def test_mock_patch(self):...

Full Screen

Full Screen

ckeygen.py

Source:ckeygen.py Github

copy

Full Screen

1# -*- test-case-name: twisted.conch.test.test_ckeygen -*-2# Copyright (c) Twisted Matrix Laboratories.3# See LICENSE for details.4"""5Implementation module for the `ckeygen` command.6"""7from __future__ import print_function8import sys, os, getpass, socket9from functools import wraps10from imp import reload11if getpass.getpass == getpass.unix_getpass:12 try:13 import termios # hack around broken termios14 termios.tcgetattr, termios.tcsetattr15 except (ImportError, AttributeError):16 sys.modules['termios'] = None17 reload(getpass)18from twisted.conch.ssh import keys19from twisted.python import failure, filepath, log, usage20from twisted.python.compat import raw_input, _PY321supportedKeyTypes = dict()22def _keyGenerator(keyType):23 def assignkeygenerator(keygenerator):24 @wraps(keygenerator)25 def wrapper(*args, **kwargs):26 return keygenerator(*args, **kwargs)27 supportedKeyTypes[keyType] = wrapper28 return wrapper29 return assignkeygenerator30class GeneralOptions(usage.Options):31 synopsis = """Usage: ckeygen [options]32 """33 longdesc = "ckeygen manipulates public/private keys in various ways."34 optParameters = [['bits', 'b', None, 'Number of bits in the key to create.'],35 ['filename', 'f', None, 'Filename of the key file.'],36 ['type', 't', None, 'Specify type of key to create.'],37 ['comment', 'C', None, 'Provide new comment.'],38 ['newpass', 'N', None, 'Provide new passphrase.'],39 ['pass', 'P', None, 'Provide old passphrase.'],40 ['format', 'o', 'sha256-base64', 'Fingerprint format of key file.']]41 optFlags = [['fingerprint', 'l', 'Show fingerprint of key file.'],42 ['changepass', 'p', 'Change passphrase of private key file.'],43 ['quiet', 'q', 'Quiet.'],44 ['no-passphrase', None, "Create the key with no passphrase."],45 ['showpub', 'y', 'Read private key file and print public key.']]46 compData = usage.Completions(47 optActions={"type": usage.CompleteList(list(supportedKeyTypes.keys()))})48def run():49 options = GeneralOptions()50 try:51 options.parseOptions(sys.argv[1:])52 except usage.UsageError as u:53 print('ERROR: %s' % u)54 options.opt_help()55 sys.exit(1)56 log.discardLogs()57 log.deferr = handleError # HACK58 if options['type']:59 if options['type'].lower() in supportedKeyTypes:60 print('Generating public/private %s key pair.' % (options['type']))61 supportedKeyTypes[options['type'].lower()](options)62 else:63 sys.exit(64 'Key type was %s, must be one of %s'65 % (options['type'], ', '.join(supportedKeyTypes.keys())))66 elif options['fingerprint']:67 printFingerprint(options)68 elif options['changepass']:69 changePassPhrase(options)70 elif options['showpub']:71 displayPublicKey(options)72 else:73 options.opt_help()74 sys.exit(1)75def enumrepresentation(options):76 if options['format'] == 'md5-hex':77 options['format'] = keys.FingerprintFormats.MD5_HEX78 return options79 elif options['format'] == 'sha256-base64':80 options['format'] = keys.FingerprintFormats.SHA256_BASE6481 return options82 else:83 raise keys.BadFingerPrintFormat(84 'Unsupported fingerprint format: %s' % (options['format'],))85def handleError():86 global exitStatus87 exitStatus = 288 log.err(failure.Failure())89 raise90@_keyGenerator('rsa')91def generateRSAkey(options):92 from cryptography.hazmat.backends import default_backend93 from cryptography.hazmat.primitives.asymmetric import rsa94 if not options['bits']:95 options['bits'] = 102496 keyPrimitive = rsa.generate_private_key(97 key_size=int(options['bits']),98 public_exponent=65537,99 backend=default_backend(),100 )101 key = keys.Key(keyPrimitive)102 _saveKey(key, options)103@_keyGenerator('dsa')104def generateDSAkey(options):105 from cryptography.hazmat.backends import default_backend106 from cryptography.hazmat.primitives.asymmetric import dsa107 if not options['bits']:108 options['bits'] = 1024109 keyPrimitive = dsa.generate_private_key(110 key_size=int(options['bits']),111 backend=default_backend(),112 )113 key = keys.Key(keyPrimitive)114 _saveKey(key, options)115@_keyGenerator('ecdsa')116def generateECDSAkey(options):117 from cryptography.hazmat.backends import default_backend118 from cryptography.hazmat.primitives.asymmetric import ec119 if not options['bits']:120 options['bits'] = 256121 # OpenSSH supports only mandatory sections of RFC5656.122 # See https://www.openssh.com/txt/release-5.7123 curve = b'ecdsa-sha2-nistp' + str(options['bits']).encode('ascii')124 keyPrimitive = ec.generate_private_key(125 curve=keys._curveTable[curve],126 backend=default_backend()127 )128 key = keys.Key(keyPrimitive)129 _saveKey(key, options)130def printFingerprint(options):131 if not options['filename']:132 filename = os.path.expanduser('~/.ssh/id_rsa')133 options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)134 if os.path.exists(options['filename']+'.pub'):135 options['filename'] += '.pub'136 options = enumrepresentation(options)137 try:138 key = keys.Key.fromFile(options['filename'])139 print('%s %s %s' % (140 key.size(),141 key.fingerprint(options['format']),142 os.path.basename(options['filename'])))143 except keys.BadKeyError:144 sys.exit('bad key')145def changePassPhrase(options):146 if not options['filename']:147 filename = os.path.expanduser('~/.ssh/id_rsa')148 options['filename'] = raw_input(149 'Enter file in which the key is (%s): ' % filename)150 try:151 key = keys.Key.fromFile(options['filename'])152 except keys.EncryptedKeyError as e:153 # Raised if password not supplied for an encrypted key154 if not options.get('pass'):155 options['pass'] = getpass.getpass('Enter old passphrase: ')156 try:157 key = keys.Key.fromFile(158 options['filename'], passphrase=options['pass'])159 except keys.BadKeyError:160 sys.exit('Could not change passphrase: old passphrase error')161 except keys.EncryptedKeyError as e:162 sys.exit('Could not change passphrase: %s' % (e,))163 except keys.BadKeyError as e:164 sys.exit('Could not change passphrase: %s' % (e,))165 if not options.get('newpass'):166 while 1:167 p1 = getpass.getpass(168 'Enter new passphrase (empty for no passphrase): ')169 p2 = getpass.getpass('Enter same passphrase again: ')170 if p1 == p2:171 break172 print('Passphrases do not match. Try again.')173 options['newpass'] = p1174 try:175 newkeydata = key.toString('openssh', extra=options['newpass'])176 except Exception as e:177 sys.exit('Could not change passphrase: %s' % (e,))178 try:179 keys.Key.fromString(newkeydata, passphrase=options['newpass'])180 except (keys.EncryptedKeyError, keys.BadKeyError) as e:181 sys.exit('Could not change passphrase: %s' % (e,))182 with open(options['filename'], 'wb') as fd:183 fd.write(newkeydata)184 print('Your identification has been saved with the new passphrase.')185def displayPublicKey(options):186 if not options['filename']:187 filename = os.path.expanduser('~/.ssh/id_rsa')188 options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)189 try:190 key = keys.Key.fromFile(options['filename'])191 except keys.EncryptedKeyError:192 if not options.get('pass'):193 options['pass'] = getpass.getpass('Enter passphrase: ')194 key = keys.Key.fromFile(195 options['filename'], passphrase = options['pass'])196 displayKey = key.public().toString('openssh')197 if _PY3:198 displayKey = displayKey.decode("ascii")199 print(displayKey)200def _saveKey(key, options):201 """202 Persist a SSH key on local filesystem.203 @param key: Key which is persisted on local filesystem.204 @type key: C{keys.Key} implementation.205 @param options:206 @type options: L{dict}207 """208 KeyTypeMapping = {'EC': 'ecdsa', 'RSA': 'rsa', 'DSA': 'dsa'}209 keyTypeName = KeyTypeMapping[key.type()]210 if not options['filename']:211 defaultPath = os.path.expanduser(u'~/.ssh/id_%s' % (keyTypeName,))212 newPath = raw_input(213 'Enter file in which to save the key (%s): ' % (defaultPath,))214 options['filename'] = newPath.strip() or defaultPath215 if os.path.exists(options['filename']):216 print('%s already exists.' % (options['filename'],))217 yn = raw_input('Overwrite (y/n)? ')218 if yn[0].lower() != 'y':219 sys.exit()220 if options.get('no-passphrase'):221 options['pass'] = b''222 elif not options['pass']:223 while 1:224 p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ')225 p2 = getpass.getpass('Enter same passphrase again: ')226 if p1 == p2:227 break228 print('Passphrases do not match. Try again.')229 options['pass'] = p1230 comment = '%s@%s' % (getpass.getuser(), socket.gethostname())231 filepath.FilePath(options['filename']).setContent(232 key.toString('openssh', options['pass']))233 os.chmod(options['filename'], 33152)234 filepath.FilePath(options['filename'] + '.pub').setContent(235 key.public().toString('openssh', comment))236 options = enumrepresentation(options)237 print('Your identification has been saved in %s' % (options['filename'],))238 print('Your public key has been saved in %s.pub' % (options['filename'],))239 print('The key fingerprint in %s is:' % (options['format'],))240 print(key.fingerprint(options['format']))241if __name__ == '__main__':...

Full Screen

Full Screen

client_options.py

Source:client_options.py Github

copy

Full Screen

...51def _parse_read_concern(options):52 """Parse read concern options."""53 concern = options.get('readconcernlevel')54 return ReadConcern(concern)55def _parse_ssl_options(options):56 """Parse ssl options."""57 use_ssl = options.get('ssl')58 if use_ssl is not None:59 validate_boolean('ssl', use_ssl)60 certfile = options.get('ssl_certfile')61 keyfile = options.get('ssl_keyfile')62 passphrase = options.get('ssl_pem_passphrase')63 ca_certs = options.get('ssl_ca_certs')64 cert_reqs = options.get('ssl_cert_reqs')65 match_hostname = options.get('ssl_match_hostname', True)66 crlfile = options.get('ssl_crlfile')67 ssl_kwarg_keys = [k for k in options68 if k.startswith('ssl_') and options[k]]69 if use_ssl == False and ssl_kwarg_keys:70 raise ConfigurationError("ssl has not been enabled but the "71 "following ssl parameters have been set: "72 "%s. Please set `ssl=True` or remove."73 % ', '.join(ssl_kwarg_keys))74 if ssl_kwarg_keys and use_ssl is None:75 # ssl options imply ssl = True76 use_ssl = True77 if use_ssl is True:78 ctx = get_ssl_context(79 certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile)80 return ctx, match_hostname81 return None, match_hostname82def _parse_pool_options(options):83 """Parse connection pool options."""84 max_pool_size = options.get('maxpoolsize', common.MAX_POOL_SIZE)85 min_pool_size = options.get('minpoolsize', common.MIN_POOL_SIZE)86 max_idle_time_ms = options.get('maxidletimems', common.MAX_IDLE_TIME_MS)87 if max_pool_size is not None and min_pool_size > max_pool_size:88 raise ValueError("minPoolSize must be smaller or equal to maxPoolSize")89 connect_timeout = options.get('connecttimeoutms', common.CONNECT_TIMEOUT)90 socket_keepalive = options.get('socketkeepalive', True)91 socket_timeout = options.get('sockettimeoutms')92 wait_queue_timeout = options.get('waitqueuetimeoutms')93 wait_queue_multiple = options.get('waitqueuemultiple')94 event_listeners = options.get('event_listeners')95 appname = options.get('appname')96 ssl_context, ssl_match_hostname = _parse_ssl_options(options)97 return PoolOptions(max_pool_size,98 min_pool_size,99 max_idle_time_ms,100 connect_timeout, socket_timeout,101 wait_queue_timeout, wait_queue_multiple,102 ssl_context, ssl_match_hostname, socket_keepalive,103 _EventListeners(event_listeners),104 appname)105class ClientOptions(object):106 """ClientOptions"""107 def __init__(self, username, password, database, options):108 self.__options = options109 self.__codec_options = _parse_codec_options(options)110 self.__credentials = _parse_credentials(111 username, password, database, options)112 self.__local_threshold_ms = options.get(113 'localthresholdms', common.LOCAL_THRESHOLD_MS)114 # self.__server_selection_timeout is in seconds. Must use full name for115 # common.SERVER_SELECTION_TIMEOUT because it is set directly by tests.116 self.__server_selection_timeout = options.get(117 'serverselectiontimeoutms', common.SERVER_SELECTION_TIMEOUT)118 self.__pool_options = _parse_pool_options(options)119 self.__read_preference = _parse_read_preference(options)120 self.__replica_set_name = options.get('replicaset')121 self.__write_concern = _parse_write_concern(options)122 self.__read_concern = _parse_read_concern(options)123 self.__connect = options.get('connect')124 self.__heartbeat_frequency = options.get(125 'heartbeatfrequencyms', common.HEARTBEAT_FREQUENCY)126 @property127 def _options(self):128 """The original options used to create this ClientOptions."""129 return self.__options130 @property131 def connect(self):132 """Whether to begin discovering a MongoDB topology automatically."""133 return self.__connect134 @property135 def codec_options(self):136 """A :class:`~bson.codec_options.CodecOptions` instance."""137 return self.__codec_options138 @property139 def credentials(self):140 """A :class:`~pymongo.auth.MongoCredentials` instance or None."""141 return self.__credentials142 @property143 def local_threshold_ms(self):144 """The local threshold for this instance."""145 return self.__local_threshold_ms146 @property147 def server_selection_timeout(self):148 """The server selection timeout for this instance in seconds."""149 return self.__server_selection_timeout150 @property151 def heartbeat_frequency(self):152 """The monitoring frequency in seconds."""153 return self.__heartbeat_frequency154 @property155 def pool_options(self):156 """A :class:`~pymongo.pool.PoolOptions` instance."""157 return self.__pool_options158 @property159 def read_preference(self):160 """A read preference instance."""161 return self.__read_preference162 @property163 def replica_set_name(self):164 """Replica set name or None."""165 return self.__replica_set_name166 @property167 def write_concern(self):168 """A :class:`~pymongo.write_concern.WriteConcern` instance."""169 return self.__write_concern...

Full Screen

Full Screen

openid_connect.py

Source:openid_connect.py Github

copy

Full Screen

1import paypalrestsdk.util as util2from paypalrestsdk.resource import Resource3from paypalrestsdk.api import default as default_api4from paypalrestsdk.api import Api5from paypalrestsdk.config import __version__6from six import string_types7class Base(Resource):8 user_agent = "PayPalSDK/openid-connect-python %s (%s)" % (__version__, Api.library_details)9 @classmethod10 def post(cls, action, options=None, headers=None, api=None):11 api = api or default_api()12 url = util.join_url(endpoint(api), action)13 body = util.urlencode(options or {})14 headers = util.merge_dict({15 'User-Agent': cls.user_agent,16 'Content-Type': 'application/x-www-form-urlencoded'}, headers or {})17 data = api.http_call(url, 'POST', data=body, headers=headers)18 return cls(data, api=api)19class Tokeninfo(Base):20 """Token service for Log In with PayPal, API docs at21 https://developer.paypal.com/docs/api/#identity22 """23 path = "v1/identity/openidconnect/tokenservice"24 @classmethod25 def create(cls, options=None, api=None):26 options = options or {}27 api = api or default_api()28 if isinstance(options, string_types):29 options = {'code': options}30 options = util.merge_dict({31 'grant_type': 'authorization_code',32 'client_id': client_id(api),33 'client_secret': client_secret(api)34 }, options)35 return cls.post(cls.path, options, api=api)36 @classmethod37 def create_with_refresh_token(cls, options=None, api=None):38 options = options or {}39 api = api or default_api()40 if isinstance(options, string_types):41 options = {'refresh_token': options}42 options = util.merge_dict({43 'grant_type': 'refresh_token',44 'client_id': client_id(api),45 'client_secret': client_secret(api)46 }, options)47 return cls.post(cls.path, options, api=api)48 @classmethod49 def authorize_url(cls, options=None, api=None):50 return authorize_url(options or {}, api=api)51 def logout_url(self, options=None, api=None):52 return logout_url(util.merge_dict({'id_token': self.id_token}, options or {}), api=api)53 def refresh(self, options=None, api=None):54 options = util.merge_dict({'refresh_token': self.refresh_token}, options or {})55 tokeninfo = self.__class__.create_with_refresh_token(options, api=api)56 self.merge(tokeninfo.to_dict())57 return self58 def userinfo(self, options=None, api=None):59 return Userinfo.get(util.merge_dict({'access_token': self.access_token}, options or {}), api=api)60class Userinfo(Base):61 """Retrive user profile attributes for Log In with PayPal62 """63 path = "v1/identity/openidconnect/userinfo"64 @classmethod65 def get(cls, options=None, api=None):66 options = options or {}67 if isinstance(options, string_types):68 options = {'access_token': options}69 options = util.merge_dict({'schema': 'openid'}, options)70 api = api or default_api()71 return cls.post(cls.path, options, api=api)72def endpoint(api=None):73 api = api or default_api()74 return api.options.get("openid_endpoint", api.endpoint)75def client_id(api=None):76 api = api or default_api()77 return api.options.get("openid_client_id", api.client_id)78def client_secret(api=None):79 api = api or default_api()80 return api.options.get("openid_client_secret", api.client_secret)81def redirect_uri(api=None):82 api = api or default_api()83 return api.options.get("openid_redirect_uri")84start_session_path = "/signin/authorize"85end_session_path = "/webapps/auth/protocol/openidconnect/v1/endsession"86def session_url(path, options=None, api=None):87 api = api or default_api()88 if api.mode == "live":89 path = util.join_url("https://www.paypal.com", path)90 else:91 path = util.join_url("https://www.sandbox.paypal.com", path)92 return util.join_url_params(path, options or {})93def authorize_url(options=None, api=None):94 api = api or default_api()95 options = util.merge_dict({96 'response_type': 'code',97 'scope': 'openid',98 'client_id': client_id(api),99 'redirect_uri': redirect_uri(api)100 }, options or {})101 return session_url(start_session_path, options, api=api)102def logout_url(options=None, api=None):103 api = api or default_api()104 options = util.merge_dict({105 'logout': 'true',106 'redirect_uri': redirect_uri(api)107 }, options or {})...

Full Screen

Full Screen

TestCmdLine.py

Source:TestCmdLine.py Github

copy

Full Screen

...16 no_value = object()17 for name, orig_value in self._options_backup.items():18 if getattr(Options, name, no_value) != orig_value:19 setattr(Options, name, orig_value)20 def test_short_options(self):21 options, sources = parse_command_line([22 '-V', '-l', '-+', '-t', '-v', '-v', '-v', '-p', '-D', '-a', '-3',23 ])24 self.assertFalse(sources)25 self.assertTrue(options.show_version)26 self.assertTrue(options.use_listing_file)27 self.assertTrue(options.cplus)28 self.assertTrue(options.timestamps)29 self.assertTrue(options.verbose >= 3)30 self.assertTrue(Options.embed_pos_in_docstring)31 self.assertFalse(Options.docstrings)32 self.assertTrue(Options.annotate)33 self.assertEqual(options.language_level, 3)34 options, sources = parse_command_line([35 '-f', '-2', 'source.pyx',36 ])37 self.assertTrue(sources)38 self.assertTrue(len(sources) == 1)39 self.assertFalse(options.timestamps)40 self.assertEqual(options.language_level, 2)41 def test_long_options(self):42 options, sources = parse_command_line([43 '--version', '--create-listing', '--cplus', '--embed', '--timestamps',44 '--verbose', '--verbose', '--verbose',45 '--embed-positions', '--no-docstrings', '--annotate', '--lenient',46 ])47 self.assertFalse(sources)48 self.assertTrue(options.show_version)49 self.assertTrue(options.use_listing_file)50 self.assertTrue(options.cplus)51 self.assertEqual(Options.embed, 'main')52 self.assertTrue(options.timestamps)53 self.assertTrue(options.verbose >= 3)54 self.assertTrue(Options.embed_pos_in_docstring)55 self.assertFalse(Options.docstrings)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1app.options('/', function(req, res) {2 res.set('Access-Control-Allow-Origin', '*');3 res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');4 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');5 res.set('Access-Control-Max-Age', '3600');6 res.status(204).send('');7});8app.options('/test', function(req, res) {9 res.set('Access-Control-Allow-Origin', '*');10 res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');11 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');12 res.set('Access-Control-Max-Age', '3600');13 res.status(204).send('');14});15app.options('/test1', function(req, res) {16 res.set('Access-Control-Allow-Origin', '*');17 res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');18 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');19 res.set('Access-Control-Max-Age', '3600');20 res.status(204).send('');21});22app.options('/test2', function(req, res) {23 res.set('Access-Control-Allow-Origin', '*');24 res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');25 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');26 res.set('Access-Control-Max-Age', '3600');27 res.status(204).send('');28});29app.options('/test3', function(req, res) {30 res.set('Access-Control-Allow-Origin', '*');31 res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');32 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');33 res.set('Access-Control-Max-Age', '3600');34 res.status(204).send('');35});36app.options('/test4', function(req, res) {37 res.set('Access-Control-Allow-Origin', '*');38 res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');39 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');40 res.set('Access-Control-M

Full Screen

Using AI Code Generation

copy

Full Screen

1app.options('/', (req, res) => {2 res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');3 res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');4 res.header('Access-Control-Allow-Origin', '*');5 res.status(200).send();6});7app.get('/', (req, res) => {8 res.header('Access-Control-Allow-Origin', '*');9 res.status(200).send('Hello World!');10});11app.post('/', (req, res) => {12 res.header('Access-Control-Allow-Origin', '*');13 res.status(200).send('Hello World!');14});15app.put('/', (req, res) => {16 res.header('Access-Control-Allow-Origin', '*');17 res.status(200).send('Hello World!');18});19app.delete('/', (req, res) => {20 res.header('Access-Control-Allow-Origin', '*');21 res.status(200).send('Hello World!');22});23app.options('/api', (req, res) => {24 res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');25 res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');26 res.header('Access-Control-Allow-Origin', '*');27 res.status(200).send();28});29app.get('/api', (req, res) => {30 res.header('Access-Control-Allow-Origin', '*');31 res.status(200).send('Hello World!');32});33app.post('/api', (req, res) => {34 res.header('Access-Control-Allow-Origin', '*');35 res.status(200).send('Hello World!');36});37app.put('/api', (req, res) => {38 res.header('Access-Control-Allow-Origin', '*');39 res.status(200).send('Hello World!');40});41app.delete('/api', (req, res) => {42 res.header('Access-Control-Allow-Origin',

Full Screen

Using AI Code Generation

copy

Full Screen

1var express = require('express');2var router = express.Router();3var cors = require('cors');4var app = express();5app.use(cors());6router.options('/', function(req, res) {7 res.header('Access-Control-Allow-Origin', '*');8 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');9 res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');10 res.sendStatus(200);11});12module.exports = router;13var express = require('express');14var path = require('path');15var favicon = require('serve-favicon');16var logger = require('morgan');17var cookieParser = require('cookie-parser');18var bodyParser = require('body-parser');19var index = require('./routes/index');20var test = require('./routes/test');21var app = express();22app.set('views', path.join(__dirname, 'views'));23app.set('view engine', 'jade');24app.use(logger('dev'));25app.use(bodyParser.json());26app.use(bodyParser.urlencoded({ extended: false }));27app.use(cookieParser());28app.use(express.static(path.join(__dirname, 'public')));29app.use('/', index);30app.use('/test', test);31app.use(function(req, res, next) {32 var err = new Error('Not Found');33 err.status = 404;34 next(err);35});36app.use(function(err, req, res, next) {37 res.locals.message = err.message;38 res.locals.error = req.app.get('env') === 'development' ? err : {};39 res.status(err.status || 500);40 res.render('error');41});42module.exports = app;43var express = require('express');44var router = express.Router();45var cors = require('cors');46var app = express();47app.use(cors());48router.options('/', function(req, res) {49 res.header('Access-Control-Allow-Origin', '*');50 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');51 res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content

Full Screen

Using AI Code Generation

copy

Full Screen

1var express = require('express');2var app = express();3app.options('/', function(req, res) {4 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');5 res.send(200);6});7app.listen(3000);8var express = require('express');9var app = express();10app.options('/subdir', function(req, res) {11 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');12 res.send(200);13});14app.listen(3000);15var express = require('express');16var app = express();17app.options('/subdir', function(req, res) {18 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');19 res.send(200);20});21app.listen(3000);22var express = require('express');23var app = express();24app.options('/subdir', function(req, res) {25 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');26 res.send(200);27});28app.listen(3000);29var express = require('express');30var app = express();31app.options('/subdir', function(req, res) {32 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');33 res.send(200);34});35app.listen(3000);36var express = require('express');37var app = express();38app.options('/subdir', function(req, res) {39 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');40 res.send(200);41});42app.listen(3000);43var express = require('express');44var app = express();45app.options('/subdir', function(req, res) {46 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');47 res.send(200);48});49app.listen(3000);50var express = require('express');51var app = express();52app.options('/subdir', function(req, res) {53 res.set('Allow', 'GET, POST, PUT, DELETE, OPTIONS');54 res.send(200);55});56app.listen(300

Full Screen

Using AI Code Generation

copy

Full Screen

1app.get('/', function(req, res) {2 res.send('Hello World');3});4app.listen(3000, function() {5 console.log('Example app listening on port 3000!');6});7app.options('/', function(req, res) {8 res.send('Hello World');9});10app.listen(3000, function() {11 console.log('Example app listening on port 3000!');12});13app.options('/', function(req, res) {14 res.send('Hello World');15});16app.listen(3000, function() {17 console.log('Example app listening on port 3000!');18});19app.options('/', function(req, res) {20 res.send('Hello World');21});22app.listen(3000, function() {23 console.log('Example app listening on port 3000!');24});25app.options('/', function(req, res) {26 res.send('Hello World');27});28app.listen(3000, function() {29 console.log('Example app listening on port 3000!');30});31app.options('/', function(req, res) {32 res.send('Hello World');33});34app.listen(3000, function() {35 console.log('Example app listening on port 3000!');36});37app.options('/', function(req, res) {38 res.send('Hello World');39});40app.listen(3000, function() {41 console.log('Example app listening on port 3000!');42});43app.options('/', function(req, res) {44 res.send('Hello World');45});46app.listen(3000, function() {47 console.log('Example app listening on port 3000!');48});49app.options('/', function(req, res) {50 res.send('Hello World');51});52app.listen(3000, function() {53 console.log('Example app listening on port 3000!');54});55app.options('/', function(req, res) {56 res.send('Hello World');57});58app.listen(3000, function() {59 console.log('Example app listening on port 3000!');60});

Full Screen

Using AI Code Generation

copy

Full Screen

1var express = require('express');2var app = express();3app.options('/', function(req, res){4 res.send(200);5});6app.listen(3000);7var express = require('express');8var app = express();9app.options('/', function(req, res){10 res.send(200);11});12app.listen(3000);13var express = require('express');14var app = express();15app.options('/', function(req, res){16 res.send(200);17});18app.listen(3000);19var express = require('express');20var app = express();21app.options('/', function(req, res){22 res.send(200);23});24app.listen(3000);25var express = require('express');26var app = express();27app.options('/', function(req, res){28 res.send(200);29});30app.listen(3000);31var express = require('express');32var app = express();33app.options('/', function(req, res){34 res.send(200);35});36app.listen(3000);37var express = require('express');38var app = express();39app.options('/', function(req, res){40 res.send(200);41});42app.listen(3000);43var express = require('express');44var app = express();45app.options('/', function(req, res){46 res.send(200);47});48app.listen(3000);49var express = require('express');50var app = express();51app.options('/', function(req, res){52 res.send(200);53});54app.listen(3000);55var express = require('express');56var app = express();57app.options('/', function(req, res){58 res.send(200);59});60app.listen(3000);61var express = require('express');

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('root');2root.options(function (req, res) {3 res.send('This is the root');4});5var user = require('user');6user.options(function (req, res) {7 res.send('This is the user');8});9var admin = require('admin');10admin.options(function (req, res) {11 res.send('This is the admin');12});13var test = require('test');14test.options(function (req, res) {15 res.send('This is the test');16});17var test1 = require('test1');18test1.options(function (req, res) {19 res.send('This is the test1');20});21var user = require('root');22user.options(function (req, res) {23 res.send('This is the user');24});25var admin = require('root');26admin.options(function (req, res) {27 res.send('This is the admin');28});29var test = require('root');30test.options(function (req, res) {31 res.send('This is the test');32});33var test1 = require('root');34test1.options(function (req, res) {35 res.send('This is the test1');36});37I am using node js and express js for backend. I have a requirement where I need to create a middleware function which will validate the user's access token. The problem is that I need to use the same middleware function in all the routes. I have tried using app.use() but it is not working. Can anyone please help me with this?38I am trying to use the "app.use" function in order to create a middleware function that will validate the user's access token. I have tried using app.use() but it is not working. Can anyone please help me with this?39I have a route that I want to be used by a user with a specific role. I want to use "app.use" function to create a middleware function that will validate the user's access token. I have tried using app.use() but it is not working. Can anyone please help me with this?

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful