collect info and output to console

    :param awsclient:
    :param config:
    :param json: True / False to use json format as output
    :return:
510552
def info(awsclient, config, format=None):
    
    if format is None:
        format = 'tabular'
    stack_name = _get_stack_name(config)
    client_cfn = awsclient.get_client('cloudformation')

    resources = all_pages(
        client_cfn.list_stack_resources,
        {'StackName': stack_name},
        lambda x: [(r['ResourceType'], r['LogicalResourceId'], r['ResourceStatus'])
            for r in x['StackResourceSummaries']]
    )

    infos = {
        'stack_output': _get_stack_outputs(client_cfn, stack_name),
        'stack_state': _get_stack_state(client_cfn, stack_name),
        'resources': resources
    }
    if format == 'json':
        print(json.dumps(infos))
    elif format == 'tabular':
        print('stack output:')
        print(tabulate(infos['stack_output'], tablefmt='fancy_grid'))
        print('\nstack_state: %s' % infos['stack_state'])
        print('\nresources:')
        print(tabulate(infos['resources'], tablefmt='fancy_grid'))
269836
def to_json(cls, config, compact=False, indent=2, level=0):
        
        lines = ""
        if isinstance(config, ConfigTree):
            if len(config) == 0:
                lines += '{}'
            else:
                lines += '{\n'
                bet_lines = []
                for key, item in config.items():
                    bet_lines.append('{indent}"{key}": {value}'.format(
                        indent=''.rjust((level + 1) * indent, ' '),
                        key=key.strip('"'),  # for dotted keys enclosed with "" to not be interpreted as nested key
                        value=cls.to_json(item, compact, indent, level + 1))
                    )
                lines += ',\n'.join(bet_lines)
                lines += '\n{indent}}}'.format(indent=''.rjust(level * indent, ' '))
        elif isinstance(config, list):
            if len(config) == 0:
                lines += '[]'
            else:
                lines += '[\n'
                bet_lines = []
                for item in config:
                    bet_lines.append('{indent}{value}'.format(
                        indent=''.rjust((level + 1) * indent, ' '),
                        value=cls.to_json(item, compact, indent, level + 1))
                    )
                lines += ',\n'.join(bet_lines)
                lines += '\n{indent}]'.format(indent=''.rjust(level * indent, ' '))
        elif isinstance(config, basestring):
            lines = json.dumps(config)
        elif config is None or isinstance(config, NoneValue):
            lines = 'null'
        elif config is True:
            lines = 'true'
        elif config is False:
            lines = 'false'
        else:
            lines = str(config)
        return lines
855129
function JSONReporter(dir, config) {
    this._config = config;

    var fileName = config.file || DEFAULT_FILE_NAME;
    this._filePath = path.join(dir, fileName);
}
434744
def json(self, **kwargs):
        
        try:
            return super(ScraperResponse, self).json(**kwargs)
        except ValueError as ve:
            raise ParseException(ve)
409033
def export_json(data, status, headers):
    
    dumped = json.dumps(data, ensure_ascii=False)
    resp = current_app.response_class(
        dumped, status=status, headers=headers,
        content_type='application/json; charset=utf-8')
    return resp
571004
def dump_json(token_dict, dump_path):
    
    if sys.version > '3':
        with open(dump_path, 'w', encoding='utf-8') as output_file:
            json.dump(token_dict, output_file, indent=4)
    else:
        with open(dump_path, 'w') as output_file:
            json.dump(token_dict, output_file, indent=4)
1215686
def is_json_file(filename, show_warnings = False):
    
    try:
        config_dict = load_config(filename, file_type = "json")
        is_json = True
    except:
        is_json = False
    return(is_json)
1088710
def parse():
    
    parser = argparse.ArgumentParser(
        description='Dynamic DynamoDB - Auto provisioning AWS DynamoDB')
    parser.add_argument(
        '-c', '--config',
        help='Read configuration from a configuration file')
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Run without making any changes to your DynamoDB table')
    parser.add_argument(
        '--run-once',
        action='store_true',
        help='Run once and then exit Dynamic DynamoDB, instead of looping')
    parser.add_argument(
        '--show-config',
        action='store_true',
        help='Parse config files, print parsed data and then exit Dynamic DynamoDB')
    parser.add_argument(
        '--check-interval',
        type=int,
        help="""How many seconds should we wait between
                the checks (default: 300)""")
    parser.add_argument(
        '--log-file',
        help='Send output to the given log file')
    parser.add_argument(
        '--log-level',
        choices=['debug', 'info', 'warning', 'error'],
        help='Log level to use (default: info)')
    parser.add_argument(
        '--log-config-file',
        help=(
            'Use a custom Python logging configuration file. Overrides both '
            '--log-level and --log-file.'
        ))
    parser.add_argument(
        '--version',
        action='store_true',
        help='Print current version number')
    parser.add_argument(
        '--aws-access-key-id',
        help="Override Boto configuration with the following AWS access key")
    parser.add_argument(
        '--aws-secret-access-key',
        help="Override Boto configuration with the following AWS secret key")
    daemon_ag = parser.add_argument_group('Daemon options')
    daemon_ag.add_argument(
        '--daemon',
        help=(
            'Run Dynamic DynamoDB in daemon mode. Valid modes are '
            '[start|stop|restart|foreground]'))
    daemon_ag.add_argument(
        '--instance',
        default='default',
        help=(
            'Name of the Dynamic DynamoDB instance. '
            'Used to run multiple instances of Dynamic DynamoDB. '
            'Give each instance a unique name and control them separately '
            'with the --daemon flag. (default: default)'))
    daemon_ag.add_argument(
        '--pid-file-dir',
        default='/tmp',
        help='Directory where pid file is located in. Defaults to /tmp')
    dynamodb_ag = parser.add_argument_group('DynamoDB options')
    dynamodb_ag.add_argument(
        '-r', '--region',
        help='AWS region to operate in (default: us-east-1')
    dynamodb_ag.add_argument(
        '-t', '--table-name',
        help=(
            'Table(s) to target. '
            'The name is treated as a regular expression. '
            'E.g. "^my_table.*$" or "my_table"'))
    r_scaling_ag = parser.add_argument_group('Read units scaling properties')
    r_scaling_ag.add_argument(
        '--reads-upper-threshold',
        type=int,
        help="""Scale up the reads with --increase-reads-with if
                the currently consumed read units reaches this many
                percent (default: 90)""")
    r_scaling_ag.add_argument(
        '--throttled-reads-upper-threshold',
        type=int,
        help="""Scale up the reads with --increase-reads-with if
                the count of throttled read events exceeds this
                count (default: 0)""")
    r_scaling_ag.add_argument(
        '--reads-lower-threshold',
        type=int,
        help="""Scale down the reads with --decrease-reads-with if the
                currently consumed read units is as low as this
                percentage (default: 30)""")
    r_scaling_ag.add_argument(
        '--increase-reads-with',
        type=int,
        help="""How much should we increase the read units with?
                (default: 50, max: 100 if --increase-reads-unit = percent)""")
    r_scaling_ag.add_argument(
        '--decrease-reads-with',
        type=int,
        help="""How much should we decrease the read units with?
                (default: 50)""")
    r_scaling_ag.add_argument(
        '--increase-reads-unit',
        type=str,
        help='Do you want to scale in percent or units? (default: percent)')
    r_scaling_ag.add_argument(
        '--decrease-reads-unit',
        type=str,
        help='Do you want to scale in percent or units? (default: percent)')
    r_scaling_ag.add_argument(
        '--min-provisioned-reads',
        type=int,
        help="""Minimum number of provisioned reads""")
    r_scaling_ag.add_argument(
        '--max-provisioned-reads',
        type=int,
        help="""Maximum number of provisioned reads""")
    r_scaling_ag.add_argument(
        '--num-read-checks-before-scale-down',
        type=int,
        help="""Number of consecutive checks that must meet criteria
            before a scale down event occurs""")
    r_scaling_ag.add_argument(
        '--num-read-checks-reset-percent',
        type=int,
        help="""Percentage Value that will cause the num_read_checks_before
            scale_down var to reset back to 0""")
    w_scaling_ag = parser.add_argument_group('Write units scaling properties')
    w_scaling_ag.add_argument(
        '--writes-upper-threshold',
        type=int,
        help="""Scale up the writes with --increase-writes-with
                if the currently consumed write units reaches this
                many percent (default: 90)""")
    w_scaling_ag.add_argument(
        '--throttled-writes-upper-threshold',
        type=int,
        help="""Scale up the reads with --increase-writes-with if
                the count of throttled write events exceeds this
                count (default: 0)""")
    w_scaling_ag.add_argument(
        '--writes-lower-threshold',
        type=int,
        help="""Scale down the writes with --decrease-writes-with
                if the currently consumed write units is as low as this
                percentage (default: 30)""")
    w_scaling_ag.add_argument(
        '--increase-writes-with',
        type=int,
        help="""How much should we increase the write units with?
                (default: 50,
                max: 100 if --increase-writes-unit = 'percent')""")
    w_scaling_ag.add_argument(
        '--decrease-writes-with',
        type=int,
        help="""How much should we decrease the write units with?
                (default: 50)""")
    w_scaling_ag.add_argument(
        '--increase-writes-unit',
        type=str,
        help='Do you want to scale in percent or units? (default: percent)')
    w_scaling_ag.add_argument(
        '--decrease-writes-unit',
        type=str,
        help='Do you want to scale in percent or units? (default: percent)')
    w_scaling_ag.add_argument(
        '--min-provisioned-writes',
        type=int,
        help="""Minimum number of provisioned writes""")
    w_scaling_ag.add_argument(
        '--max-provisioned-writes',
        type=int,
        help="""Maximum number of provisioned writes""")
    w_scaling_ag.add_argument(
        '--num-write-checks-before-scale-down',
        type=int,
        help="""Number of consecutive checks that must meet criteria
            before a scale down event occurs""")
    w_scaling_ag.add_argument(
        '--num-write-checks-reset-percent',
        type=int,
        help="""Percentage Value that will cause the num_write_checks_before
            scale_down var to reset back to 0""")
    args = parser.parse_args()

    # Print the version and quit
    if args.version:
        # Read the dynamic-dynamodb.conf configuration file
        internal_config_file = ConfigParser.RawConfigParser()
        internal_config_file.optionxform = lambda option: option
        internal_config_file.read(
            os.path.abspath(
                os.path.join(
                    os.path.dirname(__file__), '../dynamic-dynamodb.conf')))

        print 'Dynamic DynamoDB version: {0}'.format(
            internal_config_file.get('general', 'version'))
        sys.exit(0)

    # Replace any new values in the configuration
    configuration = {}
    for arg in args.__dict__:
        if args.__dict__.get(arg) is not None:
            configuration[arg] = args.__dict__.get(arg)

    return configuration
1298
def export_jwks_as_json(self, private=False, issuer=""):
        
        return json.dumps(self.export_jwks(private, issuer))
170003
def get_json(self, timeout):
        
        (action, msg, kwargs) = yield from self.get(timeout)
        if hasattr(msg, "__json__"):
            msg = {"action": action, "event": msg.__json__()}
        else:
            msg = {"action": action, "event": msg}
        msg.update(kwargs)
        return json.dumps(msg, sort_keys=True)
1010381
function json (opts) {
  return {
    ...opts,
    headers: {
      ...opts.headers,
      'content-type': 'application/json'
    },
    body: JSON.stringify(opts.body)
  }
}
1163014
def do_json(self):
        """"""
        # Default to listing probes.
        if (self._args.probes, self._args.targets, self._args.boards) == (False, False, False):
            self._args.probes = True
        
        # Create a session with no device so we load any config.
        session = Session(None,
                            project_dir=self._args.project_dir,
                            config_file=self._args.config,
                            no_config=self._args.no_config,
                            pack=self._args.pack,
                            **convert_session_options(self._args.options)
                            )
        
        if self._args.probes:
            obj = ListGenerator.list_probes()
            print(json.dumps(obj, indent=4))
        elif self._args.targets:
            # Create targets from provided CMSIS pack.
            if ('pack' in session.options) and (session.options['pack'] is not None):
                pack_target.PackTargets.populate_targets_from_pack(session.options['pack'])

            obj = ListGenerator.list_targets()
            print(json.dumps(obj, indent=4))
        elif self._args.boards:
            obj = ListGenerator.list_boards()
            print(json.dumps(obj, indent=4))
1054085
def writer(self, outputs, stdout, stderr=sys.stderr):
        
        for output in outputs:
            try:
                output = flatten(output)
                if self.data_interchange_format == "json":
                    # Only dump one json string, and skip another one, maybe key or value.
                    output = filter(lambda x: x, output)
                else:
                    # JSON is already serialized, so we put `self.serialize` in a else statement.
                    output = map(self.serialize, output)
                print("\t".join(output), file=stdout)
            except BaseException:
                print(output, file=stderr)
                raise
263544
def json(self):
        
        if self._json_adapter is None:
            self._json_adapter = ConfigPersistenceAdapter(
                config=self,
                reader_writer=JsonReaderWriter(),
            )
        return self._json_adapter
816833
def configure_attributes(self, json_data):
        
        env = boto3.session.Session(profile_name=self.env, region_name=self.region)
        elbclient = env.client('elb')

        elb_settings = self.properties['elb']
        LOG.debug('Block ELB Settings Pre Configure Load Balancer Attributes:\n%s', pformat(elb_settings))

        # FIXME: Determine why 'job' is not being used
        # pylint: disable=unused-variable
        for job in json.loads(json_data)['job']:
            load_balancer_attributes = {
                'CrossZoneLoadBalancing': {
                    'Enabled': True
                },
                'AccessLog': {
                    'Enabled': False,
                },
                'ConnectionDraining': {
                    'Enabled': False,
                },
                'ConnectionSettings': {
                    'IdleTimeout': 60
                }
            }
            if elb_settings.get('connection_draining_timeout'):
                connection_draining_timeout = int(elb_settings['connection_draining_timeout'])
                LOG.info('Applying Custom Load Balancer Connection Draining Timeout: %d', connection_draining_timeout)
                load_balancer_attributes['ConnectionDraining'] = {
                    'Enabled': True,
                    'Timeout': connection_draining_timeout
                }
            if elb_settings.get('idle_timeout'):
                idle_timeout = int(elb_settings['idle_timeout'])
                LOG.info('Applying Custom Load Balancer Idle Timeout: %d', idle_timeout)
                load_balancer_attributes['ConnectionSettings'] = {'IdleTimeout': idle_timeout}
            if elb_settings.get('access_log'):
                access_log_bucket_name = elb_settings['access_log']['bucket_name']
                access_log_bucket_prefix = elb_settings['access_log']['bucket_prefix']
                access_log_emit_interval = int(elb_settings['access_log']['emit_interval'])
                LOG.info('Applying Custom Load Balancer Access Log: %s/%s every %d minutes', access_log_bucket_name,
                         access_log_bucket_prefix, access_log_emit_interval)
                load_balancer_attributes['AccessLog'] = {
                    'Enabled': True,
                    'S3BucketName': access_log_bucket_name,
                    'EmitInterval': access_log_emit_interval,
                    'S3BucketPrefix': access_log_bucket_prefix
                }

            LOG.info('Applying Load Balancer Attributes')
            LOG.debug('Load Balancer Attributes:\n%s', pformat(load_balancer_attributes))
            elbclient.modify_load_balancer_attributes(
                LoadBalancerName=self.app, LoadBalancerAttributes=load_balancer_attributes)
532133
def write_json(self, path, contents, message):
        
        log.debug(message.format(path=path))
        makedirs(os.path.dirname(path))
        with open(path, "w") as fh:
            json.dump(contents, fh, indent=2, sort_keys=True)
690995
def get_lambdas(awsclient, config, add_arn=False):
    
    if 'lambda' in config:
        client_lambda = awsclient.get_client('lambda')
        lambda_entries = config['lambda'].get('entries', [])
        lmbdas = []
        for lambda_entry in lambda_entries:
            lmbda = {
                'name': lambda_entry.get('name', None),
                'alias': lambda_entry.get('alias', None),
                'swagger_ref': lambda_entry.get('swaggerRef', None)
            }
            if add_arn:
                _sleep()
                response_lambda = client_lambda.get_function(
                    FunctionName=lmbda['name'])
                lmbda['arn'] = response_lambda['Configuration']['FunctionArn']
            lmbdas.append(lmbda)
        return lmbdas
    else:
        return []