text:
% launch brainstorm, with no gui (but only if is not already running)
if ~brainstorm('status')
    brainstorm %nogui
end

%% SET EXPORT FOLDER FOR REPORTS
export_folder='/Users/giorgioarcara/Documents/Lavori San Camillo/MEGHEM analisi marzo 2016/MEGHEM_analysis_reports/Scout_run_average_ERSERD';

%% SET PROTOCOL
ProtocolName = 'Meghem_analisi_3';

% get the protocol index, knowing the name
iProtocol = bst_get('Protocol', ProtocolName);

% set the current protocol
gui_brainstorm('SetCurrentProtocol', iProtocol);

% check info
ProtocolInfo=bst_get('ProtocolInfo')

% get the subject list
my_subjects = bst_get('ProtocolSubjects')

% IMPORTANT: I want to confine my analysis on Group analysis (the project
% on default data).

%% SELECT  TRIALS
%
initial_files=[];

my_sFiles_string={'First_Corr'}

    % make the first selection with bst process

% Process: Select results files in: Group_analysis/*/Second_Corr
my_sel_sFiles_ini = bst_process('CallProcess', 'process_select_files_timefreq', initial_files, [], ...
    'subjectname',   'All', ...
    'condition',     '', ...
    'tag',           my_sFiles_string{1}, ...
    'includebad',    0, ...
    'includeintra',  1, ...
    'includecommon', 0);

my_sel_sFiles={ my_sel_sFiles_ini(:).FileName };

%% SEPARATE FILES FOR SUBJECT
SubjectNames={my_subjects.Subject(2:end).Name}; % NOTE! the 2-end, to exclude the intra trials

Subj_grouped=group_by_str_bst(my_sel_sFiles, SubjectNames);

%% SEPARATE FILES BY CONDITION (BY SUBJECT)
Conditions={'Fast18','Slow18'}
Subj_run_Condition={}

for iSubj=1:length(Subj_grouped)
    Subj_Condition{iSubj}=group_by_str_bst(Subj_grouped{iSubj}, Conditions); % IMPORTANT: notice I enter in the cell {}
end;

%% SEPARATE FILES BY RUN (BY SUBJECT, BY CONDITION)
runs={'_01_First','_02_First', '_03_First'}
Subj_Condition_run={};

for iSubj=1:length(Subj_grouped)
    for iCond=1:length(Conditions)
    Subj_Condition_run{iSubj}{iCond}=group_by_str_bst(Subj_Condition{iSubj}{iCond}, runs); % IMPORTANT: notice I enter in the cell {}
    end;
end;

%% SEPARATE FILES ONLY BY CONDITION
Conditions={'Fast18','Slow18'}
Condition_grouped={}

Condition_grouped=group_by_str_bst(my_sel_sFiles, Conditions);

%%% CORRECTION FOR SUBJECT MH005
% is not necessary because it has been already done in the script time freq
% on scout centroids

% Start a new report
bst_report('Start', Condition_grouped);

for iCond=1:length(Conditions)

    %% STEP 1) RUN AVERAGE
    % Process: Average: Everything
    Res = bst_process('CallProcess', 'process_average', Condition_grouped{iCond}, [], ...
        'avgtype',   2, ...  % By subject
        'avg_func',  1, ...  % Arithmetic average:  mean(x)
        'weighted',  0, ...
        'matchrows', 1, ...
        'iszerobad', 1);
    % Process: Add tag to comment.
    Res = bst_process('CallProcess', 'process_add_tag', Res, [], ...
        'tag',  ['| scout | ', Conditions{iCond}]  , ...
        'output', 1);  % Add to comment

    % Process: Add tag to name.
    Res = bst_process('CallProcess', 'process_add_tag', Res, [], ...
        'tag',  ['_scout_', Conditions{iCond}]   , ...
        'output', 2);  % Add to name

    %% STEP 2) ERS/ERD
    % Process: Event-related perturbation (ERS/ERD): [-500ms,-300ms]
    Res = bst_process('CallProcess', 'process_baseline_norm', Res, [], ...
    'baseline',  [-0.5, -0.3], ...
    'method',    'ersd', ...  % Event-related perturbation (ERS/ERD):    x_std = (x - μ) / μ * 100
    'overwrite', 0);

    % Save and display report
    ReportFile = bst_report('Save', Res);
    %bst_report('Open', ReportFile);
    bst_report('Export', ReportFile,  export_folder);
end;


text:
<?php

namespace Dwl\Lcdd\SearchBundle\EventListener;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Dwl\Lcdd\SearchBundle\Entity\Question;

class QuestionListener implements EventSubscriber
{

    public function getSubscribedEvents()
    {
        return array(
          'prePersist',
          'preUpdate',
          'postPersist',
          'postUpdate',
        );
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        if ($entity instanceof \Dwl\Lcdd\SearchBundle\Entity\Question) {

            if(count($entity->getUnqualifiedQuestions()) > 0) {

                foreach ($entity->getUnqualifiedQuestions() as $key => $unqualifiedQuestion) {
                    $unqualifiedQuestion->setQualifiedQuestion($entity);
                }

                $entity->setQualified(true);
                $entity->removeQualifiedQuestion();

            }

        }
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        if ($entity instanceof \Dwl\Lcdd\SearchBundle\Entity\Question) {

            if(count($entity->getUnqualifiedQuestions()) > 0) {

                foreach ($entity->getUnqualifiedQuestions() as $key => $unqualifiedQuestion) {
                    $unqualifiedQuestion->setQualifiedQuestion($entity);
                }

                $entity->setQualified(true);
                $entity->removeQualifiedQuestion();

            }

        }
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $this->postUpdate($args);
    }

    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        if ($entity instanceof \Dwl\Lcdd\SearchBundle\Entity\Question) {

        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
published: false
layout: post
title:  "Accessify Wiki: Proposal"
x-orig-title:  Proposal
date:   2016-01-06 17:30:00
x-created:  16:32, 3 June 2013
x-wiki-last-edit: 13:07, 15 July 2013
categories:
tags:   accessibility  WAI-ARIA  javascript
x-wiki-urls:
  - http://accessify.wikia.com/wiki/Proposal?veaction=edit
  - http://accessify.wikia.com/wiki/Proposal?action=history
  - http://accessify.wikia.com/wiki/Special:Export?action=submit
x-source-format: mediawiki
---

Tag line:

* Working together to fix accessibility on the Web, one site at a time. Working with those of all abilities.

In a nutshell - various versions:

* What is Accessify Wiki? Accessify Wiki is a way of authoring
  **[[Wikipedia:Web accessibility| accessibility]] fixes** for a site, without having
  control of that site, then delivering the fixes to a user during their normal browsing experience.
  This is not intended as a long-term accessibility solution for a site.

* Using Accessify Wiki, person A who has no affiliation to or control over site B,
  can independently (co-)author **[[Wikipedia:Web accessibility| accessibility]] and usability fixes**
  for site B, so that they are delivered to person C during their normal browsing
  experience -- via a [[Wikipedia:Browser extension]], [[Wikipedia:Greasemonkey| user Javascript]] or similar.

* Using Accessify Wiki, person A can during their normal browsing experience experience
  site B with **[[Wikipedia:Web accessibility| accessibility]] and usability fixes**
  -- via a [[Wikipedia:Browser extension]], [[Wikipedia:Greasemonkey| user Javascript]]
  or similar. The fixes can be (co-)authored by person C, even though that
  person has no affiliation to or control over site B.

* So, for example it allows anyone to author accessibility fixes for popular
  and busy sites like Facebook, Google and Baidu.

* Accessify Wiki is also a way of describing accessibility fixes to a
  non-specialist human (eg. a Web developer or designer) in a clear,
  un-ambiguous format, so that they can fix their web site themselves.

## Components

1. End-user browser extensions/addons, user Javascripts (bookmarklets) and similar --
  to deliver fixes in-browser (and to allow users to give feedback on sites and fixes);
2. A repository/database and [Wikipedia:API](query API) to allow the end-user extension to request fixes;
3. Authoring/ development tools -- which may include a Wiki for collaborative authoring,
  a fix-checker/validation service, bookmarklet Javascripts, fix-submission form and so on;
4. Site-owner tools to allow owner-developers to understand and package up/ integrate the accessibility fixes;
5. A standardized way to author and store the fixes for editing, validation and re-use (proposal: [[Wikipedia:YAML]] + [JSON-Schema][def-jsonschema]).

## Notes

* Components 2 and 3 may be combined - different views of the same repository/ Wiki.
* It is hoped that through careful choice/ development of tools and documentation,
  the author of fixes need not be a skilled Web developer, but can instead be someone
  with a passion for accessibility, a willingness to explore and learn, and the desire to help.
* [https://github.com/nfreear/accessify-wiki All code to be open-source];
  **accessibility fixes** to be open-source/open-data/[open content][def-opencontent],
  eg. GPL, MIT, Creative Commons [CC-by/CC-by-sa] (are fixes data or code?)
* To date (April 2013), we have [prototyped][pr-accessify] components 1, 2, 3 and 5.

## How are fixes created?
The idea is:

* To design usable authoring tools,
* To create a low barrier of entry to authoring accessibility fixes,
* And, to use [crowd-sourcing][def-crowd],
* You/ we/ the community as a whole authors and maintains the fixes. So, this
  project follows in the footsteps of Wikipedia, [Project Gutenberg][pg],
  [Fix the Web][fixtheweb], [Scripting Enabled][scriptingenabled] and others.

## How are fixes used?

It is envisioned that accessibility fixes will be used in at least three ways -- a typical **life-cycle** for fixes might be:

1. Immediately after the fixes are authored they are applied by the user Javascripts
  or browser extensions. This is considered a short term, stop-gap solution;
2. Later the fixes are packaged up as Javascript to be included in the site by the site-owner-developer. This can be considered a medium term solution;
3. Eventually, when the site is undergoing maintenance or a re-design, most accessibility fixes are hard-coded in HTML templates or 'view' files.
The developer uses the human-readable YAML file as a precise specification or recipe.
Note, in between the steps the fixes are likely to need editing as they are broken by small or large changes to the site in question.

## Limitations

There are naturally limitations to the accessibility fixes that a system like
*Accessify Wiki* can apply. For example:

* It cannot be used for the whole-sale simplification or clarification of the language of textual content,
* It cannot re-order content to make pages more usable -- it may be possible to
  pre-pend or append text/HTML to parts of a page (proposal),
* Currently it can't make widespread fixes to CSS stylesheets -- this may change (proposal),
* Fixes will tend to break over time as third-party sites are edited and re-designed,
* ...? Notwithstanding these and other limitations, I suggest that **Accessify Wiki**
  will be a useful tool to improve the Web for all.

## Legal and author guidelines

We don't have any terms of service or formal guidelines yet. So for now:

* Remember that the fixes that you write can directly affect an end-users' online experience,
* Respect the end-users' privacy and security,
* Specifically, don't write fixes for the secure areas of online banking services,
  online shops or other areas where private and credit card details are entered
  or displayed (guidance for the moment, may be relaxed),
* No bad/ inappropriate/ offensive language or harassment please.
  We do not approve user submissions, but reserve the right to take down unsuitable content,
* Accessify Wiki and AccessifyHTML5.js are designed to limit what accessibility fixes can do.
  Technically, they use a white-list of allowed HTML5 attributes, so that arbitrary Javascript etc. cannot be injected. However...
* ...DISCLAIMER: "There is no warranty for the program, to the extent permitted by applicable law.
  Except when otherwise stated in writing the copyright holders and/or other parties provide the program "as is" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose." (Source: GPL)
* You keep your copyright and right of attribution for any accessibility fixes or software code you contribute -- specific free/open source/open-content licenses to be decided.

## Is it a Wiki?

Ah, you noticed! At present you can only submit fixes via a form, that you author elsewhere. This functionality will be added - soon hopefully.
Likely candidates are [MoinMoin], [MediaWiki] or [DokuWiki].

## ScraperWiki

What is ScraperWiki? [http://scraperwiki.com ScraperWiki] is a set of online tools for data manipulation and analysis.
We're using it to prototype the _Accessify Wiki_ idea. It may not be the long-term home for the project.
Thank you to the team at ScraperWiki for creating a great set of tools. Check out the [ScraperWiki Beta][scraperwiki-beta].

## Next steps

* Get feedback from the community,
* Choose a domain-name, * DONE. Develop a Greasemonkey/user Javascript,
* Author more fixes * ...?

## How can you help?

* Provide moral support, be a critical friend, leave comments, show some love
  ♥ ...
* Install and use the end-user [user-Javascript and bookmarklet](/run/accessify-user/). Give feedback,
* Try authoring some fixes -- and pester Nick to provide examples and write a tutorial when you get stuck,
* Help write tutorials(!)
* Help with specifications including the JSON Schema,
* Help write code -- server-side and/or Greasemonkey/ user-Javascript,
* Provide web-hosting
* ...?

## Contact
Contact Nick Freear via [mailto:nfreear-@-yahoo.co.uk email] or [http://twitter.com/nfreear Twitter].

[[Category:Development]]


text:
({
	"findLabel": "Sök:",
	"findTooltip": "Ange den text du vill söka efter",
	"replaceLabel": "Ersätt med:",
	"replaceTooltip": "Ange den text du vill ersätta med",
	"findReplace": "Sök och ersätt",
	"matchCase": "Matcha skiftläge",
	"matchCaseTooltip": "Matcha skiftläge",
	"backwards": "Bakåt",
	"backwardsTooltip": "Sök bakåt efter text",
	"replaceAll": "Alla förekomster",
	"replaceAllButton": "Ersätt alla",
	"replaceAllButtonTooltip": "Ersätt all text",
	"findButton": "Sök",
	"findButtonTooltip": "Sök efter texten",
	"replaceButton": "Ersätt",
	"replaceButtonTooltip": "Ersätt texten",
	"replaceDialogText": "${0} förekomster ersattes.",
	"eofDialogText": "Senaste förekomst${0}",
	"eofDialogTextFind": "hittades",
	"eofDialogTextReplace": "ersattes"
})


text:
import React from 'react';
import Blog from '../../../components/Blog';

export const BlogItemsPage = React.createClass({

	componentWillMount () {
		const category = 7;
		if (!this.props.children) {
			this.props.fetchBlogItems(category);
		}
	},

	render () {
		const posts = this.props.posts || {};
		if (this.props.children) {
			return (

					{this.props.children}

			);
		}
		return (

				<Blog posts={posts} isLoading={this.props.isLoading}  />

		);
	}
});

export default BlogItemsPage;


text: The virtual keyboard is from: https://github.com/Mottie/Keyboard


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.database.ContactTest">

    <Button
        android:id="@+id/send_notice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send notice"/>
    <ListView
        android:id="@+id/contact_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

</LinearLayout>


text:
    <title>.:: INEI | Asistencia ::.</title>
    <link rel="stylesheet" href="<?= base_url()?>assets/bower_components/angular-material/angular-material.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic">
    <meta name="viewport" content="initial-scale=1" />
    <link rel="stylesheet" href="<?= base_url()?>assets/custom.css">
    <link href="<?= base_url()?>assets/images/favicon.ico" rel="shortcut icon" type="image/x-icon">

        <md-toolbar>

Iniciar sesión

        </md-toolbar>
        <form name="loginForm" novalidate ng-submit="login(user)">
          <md-content layout="column" class="md-padding">
            <md-input-container class="md-icon-float">
              Usuario
              <md-icon md-svg-src="<?= base_url()?>assets/images/icons/svg/0114-user.svg" class="name"></md-icon>
              <input type="text" name="username" ng-model="user.username" autofocus ng-required="true" />
            </md-input-container>
            <md-input-container class="md-icon-float">
              Contraseña
              <md-icon md-svg-src="<?= base_url()?>assets/images/icons/svg/0143-key2.svg" class="password"></md-icon>
              <input type="password" ng-model="user.password" ng-required="true" />
            </md-input-container>

              <md-button class="md-raised md-primary" ng-disabled="loginForm.$invalid">Ingresar</md-button>

              <md-button  md-no-ink="md-no-ink">¿ Olvidaste contraseña ?</md-button>

          </md-content>
        </form>


text:
@interface UISearchBar (SIABlocks)

- (void)sia_setPositionForBarUsingBlock:(UIBarPosition (^)(id <UIBarPositioning> bar))block;

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>cancel-spot-instance-requests — AWS CLI 1.0.0 documentation</title>
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap.min.css" />

    <link rel="stylesheet" href="../../_static/guzzle.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="AWS CLI 1.0.0 documentation" href="../../index.html" />
    <link rel="up" title="ec2" href="index.html" />
    <link rel="next" title="confirm-product-instance" href="confirm-product-instance.html" />
    <link rel="prev" title="cancel-reserved-instances-listing" href="cancel-reserved-instances-listing.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap-responsive.min.css" />

        AWS CLI

Home

Documentation

Forum

GitHub

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

ec2 »

          ← cancel-reserved-instances-listing
          /

confirm-product-instance →

Table Of Contents

cancel-spot-instance-requests

Description

Synopsis

Options

Quick search

    <form class="form-search margin-top-1em" action="../../search.html" method="get">
        <input type="text" name="q" style="width: 105px" class="input-small search-query" />
        <button type="submit" class="btn btn-small">Search</button>
        <input type="hidden" name="check_keywords" value="yes" />
        <input type="hidden" name="area" value="default" />
    </form>

Feedback

Did you find this page useful? Do you have a suggestion? Give us feedback or
  send us a pull request on GitHub.

[ aws . ec2 ]

cancel-spot-instance-requests¶

Description¶

Cancels one or more Spot Instance requests.

Spot Instances are instances that Amazon EC2 starts on your behalf when the maximum price that you specify exceeds the current Spot Price. Amazon EC2 periodically sets the Spot Price based on available Spot Instance capacity and current spot instance requests.

For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide  or Amazon Elastic Compute Cloud User Guide  .

Synopsis¶

  cancel-spot-instance-requests
[--dry-run | --no-dry-run]
--spot-instance-request-ids <value>

Options¶

<tt class="docutils literal">--dry-run</tt> | <tt class="docutils literal">--no-dry-run</tt> (boolean)

Checks whether you have the required permissions for the action, without actually making the request. Using this option will result in one of two possible errorresponses. If you have the required permissions, the error response will be <tt class="docutils literal">DryRunOperation</tt>  . Otherwise it will be <tt class="docutils literal">UnauthorizedOperation</tt>  .

<tt class="docutils literal">--spot-instance-request-ids</tt> (list)

Specifies the ID of the Spot Instance request.

Syntax:

"string" "string" ...

          ← cancel-reserved-instances-listing
          /

confirm-product-instance →

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

ec2 »

    © Copyright 2013, Amazon Web Services. Created using Sphinx.


text:
Rails.application.routes.draw do
<<<<<<< HEAD
<<<<<<< HEAD
  get 'sightings/index'
  resources :articles do
    resources :comments
  end
  root 'sightings#index'
=======
  get 'sightings' => 'pages#home'
>>>>>>> parent of a4bd459... Made Rails Work
=======
  get 'sightings' => 'pages#home'
>>>>>>> parent of a4bd459... Made Rails Work
end


text:
module ApplicationAnnouncementsConcern
  extend ActiveSupport::Concern

  def global_announcements
    GenericAnnouncement.for_instance(current_tenant).currently_active
  end
end


text:
/**
 *
 */
package uk.co.jemos.podam.test.integration;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.test.dto.SimplePojoToTestSetters;

/**
 * @author mtedone
 *
 */
@ContextConfiguration(locations = {"classpath:podam-test-appContext.xml"})
public class PodamFactoryInjectionIntegrationTest
		extends
			AbstractJUnit4SpringContextTests {

	// ------------------->> Constants

	// ------------------->> Instance / Static variables

	/** The Podam Factory */
	@Resource
	private PodamFactory factory;

	// ------------------->> Constructors

	// ------------------->> Public methods

	@Before
	public void init() {
		Assert.assertNotNull("The PODAM factory cannot be null!", factory);
		Assert.assertNotNull("The factory strategy cannot be null!",
				factory.getStrategy());
	}

	@Test
	public void testSimplePojo() {

		SimplePojoToTestSetters pojo = factory
				.manufacturePojo(SimplePojoToTestSetters.class);
		Assert.assertNotNull("The pojo cannot be null!", pojo);

		int intField = pojo.getIntField();
		Assert.assertTrue("The int field cannot be zero!", intField != 0);

		String stringField = pojo.getStringField();
		Assert.assertNotNull("The string field cannot be null!", stringField);
	}

	// ------------------->> Getters / Setters

	// ------------------->> Private methods

	// ------------------->> equals() / hashcode() / toString()

	// ------------------->> Inner classes

}


text:
Wiki links are the internal links that connect the files in your knowledge base.

To create a wiki link use `[[` and type the name of another file in your repo, for example [[graph-visualization]]

You can also create a [[placeholder]].
A placeholder is a wiki link that doesn't have a target file and a link to a placeholder is styled differently so you can easily tell them apart.
They can still be helpful to highlight connections.

Open the graph with `Foam: Show Graph` command, and look at the placeholder node.

Remember, with `CTRL/CMD+click` on a wikilink you can navigate to the note, or create it (if the link is a placeholder).


text:
'use strict';

require('../../helper');

var server = require('../../../lib/server')();
var assert = require('../../support/assert');
var querystring = require('querystring');
var shapefile = require('shapefile');
const AdmZip = require('adm-zip');
var fs = require('fs');

function assertZipfileContent (content, filename = 'cartodb-query') {
    const tmpfile = '/tmp/myshape.zip';
    const err = fs.writeFileSync(tmpfile, content, 'binary');

    assert.ifError(err);

    const names = new AdmZip(tmpfile).getEntries().map(entry => entry.name);
    assert.ok(names.includes(`${filename}.shp`), `SHP zipfile does not contain .shp: ${names}`);
    assert.ok(names.includes(`${filename}.shx`), `SHP zipfile does not contain .shx: ${names}`);
    assert.ok(names.includes(`${filename}.dbf`), `SHP zipfile does not contain .dbf: ${names}`);
    assert.ok(names.includes(`${filename}.prj`), `SHP zipfile does not contain .prj: ${names}`);

    fs.unlinkSync(tmpfile);
}

describe('export.shapefile', function () {
    it('SHP format, unauthenticated', function (done) {
        assert.response(server, {
            url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp',
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
            assert.strictEqual(true, /filename=cartodb-query.zip/gi.test(cd));
            assertZipfileContent(res.body);
            done();
        });
    });

    it('SHP format, unauthenticated, POST', function (done) {
        assert.response(server, {
            url: '/api/v1/sql',
            data: 'q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp',
            headers: { host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
            method: 'POST'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
            assert.strictEqual(true, /filename=cartodb-query.zip/gi.test(cd), 'Unexpected SHP filename: ' + cd);
            done();
        });
    });

    it('SHP format, big size, POST', function (done) {
        assert.response(server, {
            url: '/api/v1/sql',
            data: querystring.stringify({
                q: 'SELECT 0 as fname, st_makepoint(i,i) FROM generate_series(0,81920) i',
                format: 'shp'
            }),
            headers: { host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
            method: 'POST'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
            assert.strictEqual(true, /filename=cartodb-query.zip/gi.test(cd), 'Unexpected SHP filename: ' + cd);
            assert.ok(res.body.length > 81920, 'SHP smaller than expected: ' + res.body.length);
            done();
        });
    });

    it('SHP format, unauthenticated, with custom filename', function (done) {
        assert.response(server, {
            url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp&filename=myshape',
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
            assert.strictEqual(true, /filename=myshape.zip/gi.test(cd));
            assertZipfileContent(res.body, 'myshape');
            done();
        });
    });

    it('SHP format, unauthenticated, with custom, dangerous filename', function (done) {
        assert.response(server, {
            url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp&filename=b;"%20()[]a',
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var fname = 'b_______a';
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
            assert.strictEqual(true, /filename=b_______a.zip/gi.test(cd), 'Unexpected SHP filename: ' + cd);
            var tmpfile = '/tmp/myshape.zip';
            var writeErr = fs.writeFileSync(tmpfile, res.body, 'binary');
            if (writeErr) {
                return done(writeErr);
            }
            const names = new AdmZip(tmpfile).getEntries().map(entry => entry.name);
            assert.ok(names.includes(`${fname}.shp`), `SHP zipfile does not contain .shp: ${names}`);
            assert.ok(names.includes(`${fname}.shx`), `SHP zipfile does not contain .shx: ${names}`);
            assert.ok(names.includes(`${fname}.dbf`), `SHP zipfile does not contain .dbf: ${names}`);
            assert.ok(names.includes(`${fname}.prj`), `SHP zipfile does not contain .prj: ${names}`);
            fs.unlinkSync(tmpfile);
            done();
        });
    });

    it('SHP format, authenticated', function (done) {
        assert.response(server, {
            url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp&api_key=1234',
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /filename=cartodb-query.zip/gi.test(cd));
            assertZipfileContent(res.body);
            done();
        });
    });

    // See https://github.com/Vizzuality/CartoDB-SQL-API/issues/66
    it('SHP format, unauthenticated, with utf8 data', function (done) {
        var query = querystring.stringify({
            q: "SELECT '♥♦♣♠' as f, st_makepoint(0,0,4326) as the_geom",
            format: 'shp',
            filename: 'myshape'
        });
        assert.response(server, {
            url: '/api/v1/sql?' + query,
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var tmpfile = '/tmp/myshape.zip';
            var writeErr = fs.writeFileSync(tmpfile, res.body, 'binary');
            if (writeErr) {
                return done(writeErr);
            }
            const buffer = new AdmZip(tmpfile).getEntry('myshape.dbf').getData();
            fs.unlinkSync(tmpfile);
            var strings = buffer.toString();
            assert.ok(/♥♦♣♠/.exec(strings), "Cannot find '♥♦♣♠' in here:\n" + strings);
            done();
        });
    });

    // See https://github.com/Vizzuality/CartoDB-SQL-API/issues/66
    it('mixed type geometry', function (done) {
        var query = querystring.stringify({
            q: "SELECT 'POINT(0 0)'::geometry as g UNION ALL SELECT 'LINESTRING(0 0, 1 0)'::geometry",
            format: 'shp'
        });
        assert.response(server, {
            url: '/api/v1/sql?' + query,
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.deepStrictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
            assert.deepStrictEqual(res.headers['content-disposition'], 'inline');
            assert.strictEqual(res.statusCode, 400, res.statusCode + ': ' + res.body);
            var parsedBody = JSON.parse(res.body);
            var error = parsedBody.error[0];
            var expectedError = /Attempt to write non-point \(LINESTRING\) geometry to point shapefile/g;
            assert.ok(expectedError.test(error), error);
            done();
        });
    });

    // See https://github.com/Vizzuality/CartoDB-SQL-API/issues/87
    it('errors are not confused with warnings', function (done) {
        var query = querystring.stringify({
            q: [
                "SELECT 'POINT(0 0)'::geometry as g, 1 as a_very_very_very_long_field_name",
                "SELECT 'LINESTRING(0 0, 1 0)'::geometry, 2"
            ].join(' UNION ALL '),
            format: 'shp'
        });
        assert.response(server, {
            url: '/api/v1/sql?' + query,
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.deepStrictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
            assert.deepStrictEqual(res.headers['content-disposition'], 'inline');
            assert.strictEqual(res.statusCode, 400, res.statusCode + ': ' + res.body);
            var parsedBody = JSON.parse(res.body);
            var error = parsedBody.error[0];
            var expectedError = /Attempt to write non-point \(LINESTRING\) geometry to point shapefile/g;
            assert.ok(expectedError.test(error), error);
            done();
        });
    });

    it('skipfields controls fields included in SHP output', function (done) {
        var query = querystring.stringify({
            q: "SELECT 111 as skipme, 222 as keepme, 'POINT(0 0)'::geometry as g",
            format: 'shp',
            skipfields: 'skipme',
            filename: 'myshape'
        });
        assert.response(server, {
            url: '/api/v1/sql?' + query,
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var tmpfile = '/tmp/myshape.zip';
            var writeErr = fs.writeFileSync(tmpfile, res.body, 'binary');
            if (writeErr) {
                return done(writeErr);
            }
            const buffer = new AdmZip(tmpfile).getEntry('myshape.dbf').getData();
            fs.unlinkSync(tmpfile);
            var strings = buffer.toString();
            assert.ok(!/skipme/.exec(strings), "Could not skip 'skipme' field:\n" + strings);
            done();
        });
    });

    it('SHP format, concurrently', function (done) {
        var concurrency = 1;
        var waiting = concurrency;
        function validate (err, res) {
            assert.ifError(err);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
            assert.strictEqual(true, /filename=cartodb-query.zip/gi.test(cd));
            assertZipfileContent(res.body);
            if (!--waiting) {
                done();
            }
        }
        for (var i = 0; i < concurrency; ++i) {
            assert.response(
                server,
                {
                    url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp',
                    headers: { host: 'vizzuality.cartodb.com' },
                    encoding: 'binary',
                    method: 'GET'
                },
                {
                    status: 200
                },
                validate
            );
        }
    });

    // See https://github.com/CartoDB/CartoDB-SQL-API/issues/111
    it('point with null first', function (done) {
        var query = querystring.stringify({
            q: "SELECT null::geometry as g UNION ALL SELECT 'SRID=4326;POINT(0 0)'::geometry",
            format: 'shp'
        });
        assert.response(server, {
            url: '/api/v1/sql?' + query,
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 200, res.body);
            var cd = res.headers['content-disposition'];
            assert.strictEqual(true, /filename=cartodb-query.zip/gi.test(cd));
            assertZipfileContent(res.body);
            done();
        });
    });

    var limit = 1200;

    it('expects ' + limit + ' rows in public table', function (done) {
        var filename = 'test_1200';

        assert.response(server, {
            url: '/api/v1/sql?' + querystring.stringify({
                q: 'SELECT * from populated_places_simple_reduced limit ' + limit,
                format: 'shp',
                filename: filename
            }),
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        },
        {
            status: 200
        },
        function (err, res) {
            if (err) {
                return done(err);
            }

            var tmpShpPath = '/tmp/' + filename + '.zip';
            err = fs.writeFileSync(tmpShpPath, res.body, 'binary');
            if (err) {
                return done(err);
            }

            const zf = new AdmZip(tmpShpPath);
            zf.getEntries().forEach(entry => {
                const buffer = entry.getData();
                const tmpDbfPath = `/tmp/${entry.name}`;
                const err = fs.writeFileSync(tmpDbfPath, buffer);
                assert.ifError(err);
            });
            shapefile.read('/tmp/' + filename, function (err, collection) {
                if (err) {
                    return done(err);
                }
                assert.strictEqual(collection.features.length, limit);
                done();
            });
        }
        );
    });

    it('SHP zip, wrong path for zip command should return error', function (done) {
        global.settings.zipCommand = '/wrong/path';
        var query = querystring.stringify({
            q: 'SELECT st_makepoint(0,0,4326) as the_geom',
            format: 'shp',
            filename: 'myshape'
        });
        assert.response(server, {
            url: '/api/v1/sql?' + query,
            headers: { host: 'vizzuality.cartodb.com' },
            encoding: 'binary',
            method: 'GET'
        }, { }, function (err, res) {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 400, res.body);
            var parsedBody = JSON.parse(res.body);
            var respBodyPattern = new RegExp('Error executing zip command, {2}Error: spawn(.*)ENOENT', 'i');
            assert.strictEqual(respBodyPattern.test(parsedBody.error[0]), true);
            done();
        });
    });
});


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */
package org.modeshape.web.client.contents;

import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

/**
 * Two columns layout.
 *
 * Left column contains children nodes and binary editor, right column contains
 * details of the node such as properties and permissions.
 *
 *
 * @author kulikov
 */
public class ContentsLayout extends HLayout {
    private ChildrenEditor children;
    private DetailsLayout details;
    private boolean showDetails = false;

    /**
     * Creates layout.
     *
     * @param children children nodes area.
     * @param binary binary content area.
     * @param details node details area.
     */
    public ContentsLayout(ChildrenEditor children, BinaryEditor binary, DetailsLayout details) {
        this.children = children;
        this.details = details;

        //left column
        VLayout panel = new VLayout();

        HLayout hstrut = new HLayout();
        hstrut.setHeight(30);

        //put children and binary editors separated by stut.
        panel.addMember(children);
        panel.addMember(hstrut);
        panel.addMember(binary);

        VLayout strut = new VLayout();
        strut.setWidth(10);

        addMember(panel);
        addMember(strut);
        addMember(details);
    }

    /**
     * Gets status of the details area.
     *
     * @return true if details are visible on the screen.
     */
    public boolean showDetails() {
        return showDetails;
    }

    /**
     * Modifies status of the details area on the screen.
     *
     * @param showDetails true enables details on the screen.
     */
    public void setShowDetails( boolean showDetails ) {
        this.showDetails = showDetails;
        details.setVisible(showDetails);
    }

    @Override
    public void setVisible(boolean visible) {
        children.setVisible(visible);
        if (showDetails) {
            details.setVisible(visible);
        } else {
            details.setVisible(false);
        }
    }

}


text:
<?php
global $nm_theme_options;

$show_static_page = ( $nm_theme_options['blog_static_page'] ) ? true : false;

if ( $show_static_page ) {
	if ( function_exists( 'nm_blog_index_vc_styles' ) ) {
		// Custom vcomp styles - Must be included before "get_header()"
		add_action( 'wp_head', 'nm_blog_index_vc_styles', 1000 );
	}
}

$show_categories = ( $nm_theme_options['blog_categories'] ) ? true : false;
$categories_class = ( $show_categories ) ? '' : ' nm-blog-categories-disabled';

get_header(); ?>

<div class="nm-blog<?php echo esc_attr( $categories_class ); ?>">
    <?php
		// Note: Keep below "get_header()" (page not loading properly in some cases otherwise)
		$blog_page = ( $show_static_page ) ? get_page( $nm_theme_options['blog_static_page_id'] ) : false;

		if ( $blog_page ) :
	?>

            <?php echo do_shortcode( $blog_page->post_content ); ?>

	<?php endif; ?>

    <?php if ( $show_categories ) : ?>

                <?php echo nm_blog_category_menu(); ?>

	<?php endif; ?>

    <?php get_template_part( 'content' ); ?>

<?php get_footer(); ?>


text:
package boundary.Score;

import entity.Question;
import entity.Score;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.CacheStoreMode;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ScoreResource {

    @PersistenceContext
    EntityManager entityManager;

    /**
     * Method to find a Score by id
     * @param id
     * @return Score
     */
    public Score findById(String id) {
        return entityManager.find(Score.class, id);
    }

    /**
     * Method to get all the scores by value decreasing order
     * @return List of Score
     */
    public List<Score> findAll() {
        return entityManager.createNamedQuery("Score.findAll", Score.class)
                .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
                .getResultList();
    }

    /**
     * Method to get all the scores from a Question
     * @param question
     * @return List of Score
     */
    public List<Score> findByQuestion(Question question) {
        return entityManager.createQuery("SELECT s FROM Score s WHERE s.question =: question")
                            .setParameter("question", question)
                            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
                            .getResultList();
    }

    /**
     * Method that returns the scores with pagination and limit method
     *
     * @param offset start at the nth position
     * @param limit number max of result
     * @return List of Score
     */
    public List<Score> offsetLimit(int offset, int limit) {
        return entityManager.createNamedQuery("Score.findAll", Score.class)
                .setFirstResult(offset)
                .setMaxResults(limit)
                .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
                .getResultList();
    }

    /**
     * Method to count Score rows in the database
     * countAll bugs as fuck so let's use this ugly way :(
     * @return int
     */
    public Long countAll() {
       return (long) entityManager.createNamedQuery("Score.findAll", Score.class)
               .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
               .getResultList()
               .size();
    }

    /**
     * Method that inserts a score into the database
     * @param score to add
     * @return the score added
     */
    public Score insert(Score score) {
        score.generateId();
        return entityManager.merge(score);
    }

    /**
     * Method to delete a score
     * @param score the Score to delete
     */
    public void delete(Score score) {
         entityManager.remove(score);
    }

    /**
     * Method to update a score
     * @param score
     * @return the updated score
     */
    public Score update(Score score) {
        return entityManager.merge(score);
    }
}


text:
import {List, fromJS} from 'immutable';
import {A} from '../../constants';

const EMPTY_LIST = List();

export function messages(state = EMPTY_LIST, action = null) {
  switch (action.type) {
  case A.INIT:
    return fromJS(action.payload.messages);
  case A.ADD_MESSAGE:
    return state.push(action.message);
  case A.UPDATE_MESSAGE:
    const i = state.findIndex(item => item.get('id') === action.payload.get('id'));
    if (i > -1) {
      return state.set(i, action.payload);
    }
    return state;
  case A.LOG_OUT:
    return EMPTY_LIST;
  case A.LOAD_CHANNEL_HISTORY:
    const newMessages = fromJS(action.payload.messages)
      .filter(message => !state.find(m => m.get('id') === message.get('id')));
    return state.concat(newMessages);
  default:
    return state;
  }
}


text:
START_ATF_NAMESPACE
    namespace Register
    {
        class _world_account_ping_wracRegister : public IRegister
        {
            public:
                void Register() override
                {
                    auto& hook_core = CATFCore::get_instance();
                    for (auto& r : Detail::_world_account_ping_wrac_functions)
                        hook_core.reg_wrapper(r.pBind, r);
                }
        };
    }; // end namespace Register
END_ATF_NAMESPACE


text:
package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

type SvnVCS struct{}

// If you can help clean this up or improve it, please submit patches!

// svnGet implements the getting logic for svn.
func (s *SvnVCS) Get(dep *Dependency) error {
	dest := fmt.Sprintf("%s/src/%s", os.Getenv("GOPATH"), dep.Name)
	//Info("Cloning %s into %s\n", dep.Repository, dest)
	fmt.Print("[INFO] svn: ")
	out, err := exec.Command("svn", "checkout", dep.Repository, dest).CombinedOutput()
	fmt.Print(string(out))
	return err
}

func (s *SvnVCS) Update(dep *Dependency) error {
	dest := fmt.Sprintf("%s/src/%s", os.Getenv("GOPATH"), dep.Name)

	if _, err := os.Stat(dest); err != nil {
		// Assume a new package?
		Info("Looks like %s is a new package. Cloning.", dep.Name)
		return exec.Command("svn", "checkout", dep.Repository, dest).Run()
	}

	oldDir, err := os.Getwd()
	if err != nil {
		return err
	}
	os.Chdir(dest)
	defer os.Chdir(oldDir)

	out, err := exec.Command("svn", "update").CombinedOutput()
	fmt.Print(string(out))
	return err
}

func (s *SvnVCS) Version(dep *Dependency) error {
	dest := fmt.Sprintf("%s/src/%s", os.Getenv("GOPATH"), dep.Name)

	oldDir, err := os.Getwd()
	if err != nil {
		return err
	}
	os.Chdir(dest)
	defer os.Chdir(oldDir)

	if len(dep.Reference) > 0 {
		if out, err := exec.Command("svn", "update", "-r", dep.Reference).CombinedOutput(); err != nil {
			fmt.Println(string(out))
			return err
		}
	}
	return nil
}

func (s *SvnVCS) LastCommit(dep *Dependency) (string, error) {
	dest := fmt.Sprintf("%s/src/%s", os.Getenv("GOPATH"), dep.Name)

	oldDir, err := os.Getwd()
	if err != nil {
		return "", err
	}
	os.Chdir(dest)
	defer os.Chdir(oldDir)
	out, err := exec.Command("svnversion", ".").CombinedOutput()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}


text:
"""
Static Web Middleware for OpenStack Swift
"""

__all__ = ['version_info', 'version']

#: Version information ``(major, minor, revision)``.
version_info = (0, 0, 1)
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace ServiceHelpers
{
    public static class VisionServiceHelper
    {
        public static int RetryCountOnQuotaLimitError = 6;
        public static int RetryDelayOnQuotaLimitError = 500;

        private static VisionServiceClient visionClient { get; set; }

        static VisionServiceHelper()
        {
            InitializeVisionService();
        }

        public static Action Throttled;

        private static string apiKey;
        public static string ApiKey
        {
            get
            {
                return apiKey;
            }

            set
            {
                var changed = apiKey != value;
                apiKey = value;
                if (changed)
                {
                    InitializeVisionService();
                }
            }
        }

        private static string apiKeyRegion;
        public static string ApiKeyRegion
        {
            get { return apiKeyRegion; }
            set
            {
                var changed = apiKeyRegion != value;
                apiKeyRegion = value;
                if (changed)
                {
                    InitializeVisionService();
                }
            }
        }

        private static void InitializeVisionService()
        {
            visionClient = ApiKeyRegion != null ?
                new VisionServiceClient(ApiKey, string.Format("https://{0}.api.cognitive.microsoft.com/vision/v1.0", ApiKeyRegion)) :
                new VisionServiceClient(ApiKey);
        }

        private static async Task<TResponse> RunTaskWithAutoRetryOnQuotaLimitExceededError<TResponse>(Func<Task<TResponse>> action)
        {
            int retriesLeft = FaceServiceHelper.RetryCountOnQuotaLimitError;
            int delay = FaceServiceHelper.RetryDelayOnQuotaLimitError;

            TResponse response = default(TResponse);

            while (true)
            {
                try
                {
                    response = await action();
                    break;
                }
                catch (Microsoft.ProjectOxford.Vision.ClientException exception) when (exception.HttpStatus == (System.Net.HttpStatusCode)429 && retriesLeft > 0)
                {
                    if (retriesLeft == 1 && Throttled != null)
                    {
                        Throttled();
                    }

                    await Task.Delay(delay);
                    retriesLeft--;
                    delay *= 2;
                    continue;
                }
            }

            return response;
        }

        private static async Task RunTaskWithAutoRetryOnQuotaLimitExceededError(Func<Task> action)
        {
            await RunTaskWithAutoRetryOnQuotaLimitExceededError<object>(async () => { await action(); return null; } );
        }

        public static async Task<AnalysisResult> DescribeAsync(Func<Task<Stream>> imageStreamCallback)
        {
            return await RunTaskWithAutoRetryOnQuotaLimitExceededError<AnalysisResult>(async () => await visionClient.DescribeAsync(await imageStreamCallback()));
        }

        public static async Task<AnalysisResult> AnalyzeImageAsync(string imageUrl, IEnumerable<VisualFeature> visualFeatures = null, IEnumerable<string> details = null)
        {
            return await RunTaskWithAutoRetryOnQuotaLimitExceededError<AnalysisResult>(() => visionClient.AnalyzeImageAsync(imageUrl, visualFeatures, details));
        }

        public static async Task<AnalysisResult> AnalyzeImageAsync(Func<Task<Stream>> imageStreamCallback, IEnumerable<VisualFeature> visualFeatures = null, IEnumerable<string> details = null)
        {
            return await RunTaskWithAutoRetryOnQuotaLimitExceededError<AnalysisResult>(async () => await visionClient.AnalyzeImageAsync(await imageStreamCallback(), visualFeatures, details ));
        }

        public static async Task<AnalysisResult> DescribeAsync(string imageUrl)
        {
            return await RunTaskWithAutoRetryOnQuotaLimitExceededError<AnalysisResult>(() => visionClient.DescribeAsync(imageUrl));
        }
    }
}


text:
package org.wso2.carbon.inbound.endpoint.protocol;

public class PollingConstants {

   public static final String INBOUND_ENDPOINT_INTERVAL ="interval";

}


text:
package org.springframework.core;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Iterator;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * Provides methods to support various naming and other conventions used
 * throughout the framework. Mainly for internal use within the framework.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @author Rossen Stoyanchev
 * @since 2.0
 */
public final class Conventions {

	/**
	 * Suffix added to names when using arrays.
	 */
	private static final String PLURAL_SUFFIX = "List";

	private Conventions() {
	}

	/**
	 * Determine the conventional variable name for the supplied {@code Object}
	 * based on its concrete type. The convention used is to return the
	 * un-capitalized short name of the {@code Class}, according to JavaBeans
	 * property naming rules.
	 *
For example:

	 * {@code com.myapp.Product} becomes {@code "product"}

	 * {@code com.myapp.MyProduct} becomes {@code "myProduct"}

	 * {@code com.myapp.UKProduct} becomes {@code "UKProduct"}

	 *
For arrays the pluralized version of the array component type is used.
	 * For {@code Collection}s an attempt is made to 'peek ahead' to determine
	 * the component type and return its pluralized version.
	 * @param value the value to generate a variable name for
	 * @return the generated variable name
	 */
	public static String getVariableName(Object value) {
		Assert.notNull(value, "Value must not be null");
		Class<?> valueClass;
		boolean pluralize = false;

		if (value.getClass().isArray()) {
			valueClass = value.getClass().getComponentType();
			pluralize = true;
		}
		else if (value instanceof Collection<?> collection) {
			if (collection.isEmpty()) {
				throw new IllegalArgumentException(
						"Cannot generate variable name for an empty Collection");
			}
			Object valueToCheck = peekAhead(collection);
			valueClass = getClassForValue(valueToCheck);
			pluralize = true;
		}
		else {
			valueClass = getClassForValue(value);
		}

		String name = ClassUtils.getShortNameAsProperty(valueClass);
		return (pluralize ? pluralize(name) : name);
	}

	/**
	 * Determine the conventional variable name for the given parameter taking
	 * the generic collection type, if any, into account.
	 *
As of 5.0 this method supports reactive types:

	 * {@code Mono<com.myapp.Product>} becomes {@code "productMono"}

	 * {@code Flux<com.myapp.MyProduct>} becomes {@code "myProductFlux"}

	 * {@code Observable<com.myapp.MyProduct>} becomes {@code "myProductObservable"}

	 * @param parameter the method or constructor parameter
	 * @return the generated variable name
	 */
	public static String getVariableNameForParameter(MethodParameter parameter) {
		Assert.notNull(parameter, "MethodParameter must not be null");
		Class<?> valueClass;
		boolean pluralize = false;
		String reactiveSuffix = "";

		if (parameter.getParameterType().isArray()) {
			valueClass = parameter.getParameterType().getComponentType();
			pluralize = true;
		}
		else if (Collection.class.isAssignableFrom(parameter.getParameterType())) {
			valueClass = ResolvableType.forMethodParameter(parameter).asCollection().resolveGeneric();
			if (valueClass == null) {
				throw new IllegalArgumentException(
						"Cannot generate variable name for non-typed Collection parameter type");
			}
			pluralize = true;
		}
		else {
			valueClass = parameter.getParameterType();
			ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(valueClass);
			if (adapter != null && !adapter.getDescriptor().isNoValue()) {
				reactiveSuffix = ClassUtils.getShortName(valueClass);
				valueClass = parameter.nested().getNestedParameterType();
			}
		}

		String name = ClassUtils.getShortNameAsProperty(valueClass);
		return (pluralize ? pluralize(name) : name + reactiveSuffix);
	}

	/**
	 * Determine the conventional variable name for the return type of the
	 * given method, taking the generic collection type, if any, into account.
	 * @param method the method to generate a variable name for
	 * @return the generated variable name
	 */
	public static String getVariableNameForReturnType(Method method) {
		return getVariableNameForReturnType(method, method.getReturnType(), null);
	}

	/**
	 * Determine the conventional variable name for the return type of the given
	 * method, taking the generic collection type, if any, into account, falling
	 * back on the given actual return value if the method declaration is not
	 * specific enough, e.g. {@code Object} return type or untyped collection.
	 * @param method the method to generate a variable name for
	 * @param value the return value (may be {@code null} if not available)
	 * @return the generated variable name
	 */
	public static String getVariableNameForReturnType(Method method, @Nullable Object value) {
		return getVariableNameForReturnType(method, method.getReturnType(), value);
	}

	/**
	 * Determine the conventional variable name for the return type of the given
	 * method, taking the generic collection type, if any, into account, falling
	 * back on the given return value if the method declaration is not specific
	 * enough, e.g. {@code Object} return type or untyped collection.
	 *
As of 5.0 this method supports reactive types:

	 * {@code Mono<com.myapp.Product>} becomes {@code "productMono"}

	 * {@code Flux<com.myapp.MyProduct>} becomes {@code "myProductFlux"}

	 * {@code Observable<com.myapp.MyProduct>} becomes {@code "myProductObservable"}

	 * @param method the method to generate a variable name for
	 * @param resolvedType the resolved return type of the method
	 * @param value the return value (may be {@code null} if not available)
	 * @return the generated variable name
	 */
	public static String getVariableNameForReturnType(Method method, Class<?> resolvedType, @Nullable Object value) {
		Assert.notNull(method, "Method must not be null");

		if (Object.class == resolvedType) {
			Assert.notNull(value, "Cannot generate variable name for an Object return type with null value");
			return getVariableName(value);
		}

		Class<?> valueClass;
		boolean pluralize = false;
		String reactiveSuffix = "";

		if (resolvedType.isArray()) {
			valueClass = resolvedType.getComponentType();
			pluralize = true;
		}
		else if (Collection.class.isAssignableFrom(resolvedType)) {
			valueClass = ResolvableType.forMethodReturnType(method).asCollection().resolveGeneric();
			if (valueClass == null) {
				if (!(value instanceof Collection<?> collection)) {
					throw new IllegalArgumentException("Cannot generate variable name " +
							"for non-typed Collection return type and a non-Collection value");
				}
				if (collection.isEmpty()) {
					throw new IllegalArgumentException("Cannot generate variable name " +
							"for non-typed Collection return type and an empty Collection value");
				}
				Object valueToCheck = peekAhead(collection);
				valueClass = getClassForValue(valueToCheck);
			}
			pluralize = true;
		}
		else {
			valueClass = resolvedType;
			ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(valueClass);
			if (adapter != null && !adapter.getDescriptor().isNoValue()) {
				reactiveSuffix = ClassUtils.getShortName(valueClass);
				valueClass = ResolvableType.forMethodReturnType(method).getGeneric().toClass();
			}
		}

		String name = ClassUtils.getShortNameAsProperty(valueClass);
		return (pluralize ? pluralize(name) : name + reactiveSuffix);
	}

	/**
	 * Convert {@code String}s in attribute name format (e.g. lowercase, hyphens
	 * separating words) into property name format (camel-case). For example
	 * {@code transaction-manager} becomes {@code "transactionManager"}.
	 */
	public static String attributeNameToPropertyName(String attributeName) {
		Assert.notNull(attributeName, "'attributeName' must not be null");
		if (!attributeName.contains("-")) {
			return attributeName;
		}
		char[] result = new char[attributeName.length() -1]; // not completely accurate but good guess
		int currPos = 0;
		boolean upperCaseNext = false;
		for (int i = 0; i < attributeName.length(); i++ ) {
			char c = attributeName.charAt(i);
			if (c == '-') {
				upperCaseNext = true;
			}
			else if (upperCaseNext) {
				result[currPos++] = Character.toUpperCase(c);
				upperCaseNext = false;
			}
			else {
				result[currPos++] = c;
			}
		}
		return new String(result, 0, currPos);
	}

	/**
	 * Return an attribute name qualified by the given enclosing {@link Class}.
	 * For example the attribute name '{@code foo}' qualified by {@link Class}
	 * '{@code com.myapp.SomeClass}' would be '{@code com.myapp.SomeClass.foo}'
	 */
	public static String getQualifiedAttributeName(Class<?> enclosingClass, String attributeName) {
		Assert.notNull(enclosingClass, "'enclosingClass' must not be null");
		Assert.notNull(attributeName, "'attributeName' must not be null");
		return enclosingClass.getName() + '.' + attributeName;
	}

	/**
	 * Determine the class to use for naming a variable containing the given value.
	 *
Will return the class of the given value, except when encountering a
	 * JDK proxy, in which case it will determine the 'primary' interface
	 * implemented by that proxy.
	 * @param value the value to check
	 * @return the class to use for naming a variable
	 */
	private static Class<?> getClassForValue(Object value) {
		Class<?> valueClass = value.getClass();
		if (Proxy.isProxyClass(valueClass)) {
			Class<?>[] ifcs = valueClass.getInterfaces();
			for (Class<?> ifc : ifcs) {
				if (!ClassUtils.isJavaLanguageInterface(ifc)) {
					return ifc;
				}
			}
		}
		else if (valueClass.getName().lastIndexOf('$') != -1 && valueClass.getDeclaringClass() == null) {
			// '$' in the class name but no inner class -
			// assuming it's a special subclass (e.g. by OpenJPA)
			valueClass = valueClass.getSuperclass();
		}
		return valueClass;
	}

	/**
	 * Pluralize the given name.
	 */
	private static String pluralize(String name) {
		return name + PLURAL_SUFFIX;
	}

	/**
	 * Retrieve the {@code Class} of an element in the {@code Collection}.
	 * The exact element for which the {@code Class} is retrieved will depend
	 * on the concrete {@code Collection} implementation.
	 */
	private static <E> E peekAhead(Collection<E> collection) {
		Iterator<E> it = collection.iterator();
		if (!it.hasNext()) {
			throw new IllegalStateException(
					"Unable to peek ahead in non-empty collection - no element found");
		}
		E value = it.next();
		if (value == null) {
			throw new IllegalStateException(
					"Unable to peek ahead in non-empty collection - only null element found");
		}
		return value;
	}

}


text:
/**
 * @namespace Phaser.GameObjects
 */

var GameObjects = {

    Events: require('./events'),

    DisplayList: require('./DisplayList'),
    GameObjectCreator: require('./GameObjectCreator'),
    GameObjectFactory: require('./GameObjectFactory'),
    UpdateList: require('./UpdateList'),

    Components: require('./components'),

    BuildGameObject: require('./BuildGameObject'),
    BuildGameObjectAnimation: require('./BuildGameObjectAnimation'),
    GameObject: require('./GameObject'),
    BitmapText: require('./bitmaptext/static/BitmapText'),
    Blitter: require('./blitter/Blitter'),
    Container: require('./container/Container'),
    DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapText'),
    Extern: require('./extern/Extern.js'),
    Graphics: require('./graphics/Graphics.js'),
    Group: require('./group/Group'),
    Image: require('./image/Image'),
    Particles: require('./particles'),
    PathFollower: require('./pathfollower/PathFollower'),
    RenderTexture: require('./rendertexture/RenderTexture'),
    RetroFont: require('./bitmaptext/RetroFont'),
    Sprite: require('./sprite/Sprite'),
    Text: require('./text/static/Text'),
    TileSprite: require('./tilesprite/TileSprite'),
    Zone: require('./zone/Zone'),

    //  Shapes

    Shape: require('./shape/Shape'),
    Arc: require('./shape/arc/Arc'),
    Curve: require('./shape/curve/Curve'),
    Ellipse: require('./shape/ellipse/Ellipse'),
    Grid: require('./shape/grid/Grid'),
    IsoBox: require('./shape/isobox/IsoBox'),
    IsoTriangle: require('./shape/isotriangle/IsoTriangle'),
    Line: require('./shape/line/Line'),
    Polygon: require('./shape/polygon/Polygon'),
    Rectangle: require('./shape/rectangle/Rectangle'),
    Star: require('./shape/star/Star'),
    Triangle: require('./shape/triangle/Triangle'),

    //  Game Object Factories

    Factories: {
        Blitter: require('./blitter/BlitterFactory'),
        Container: require('./container/ContainerFactory'),
        DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapTextFactory'),
        Extern: require('./extern/ExternFactory'),
        Graphics: require('./graphics/GraphicsFactory'),
        Group: require('./group/GroupFactory'),
        Image: require('./image/ImageFactory'),
        Particles: require('./particles/ParticleManagerFactory'),
        PathFollower: require('./pathfollower/PathFollowerFactory'),
        RenderTexture: require('./rendertexture/RenderTextureFactory'),
        Sprite: require('./sprite/SpriteFactory'),
        StaticBitmapText: require('./bitmaptext/static/BitmapTextFactory'),
        Text: require('./text/static/TextFactory'),
        TileSprite: require('./tilesprite/TileSpriteFactory'),
        Zone: require('./zone/ZoneFactory'),

        //  Shapes
        Arc: require('./shape/arc/ArcFactory'),
        Curve: require('./shape/curve/CurveFactory'),
        Ellipse: require('./shape/ellipse/EllipseFactory'),
        Grid: require('./shape/grid/GridFactory'),
        IsoBox: require('./shape/isobox/IsoBoxFactory'),
        IsoTriangle: require('./shape/isotriangle/IsoTriangleFactory'),
        Line: require('./shape/line/LineFactory'),
        Polygon: require('./shape/polygon/PolygonFactory'),
        Rectangle: require('./shape/rectangle/RectangleFactory'),
        Star: require('./shape/star/StarFactory'),
        Triangle: require('./shape/triangle/TriangleFactory')
    },

    Creators: {
        Blitter: require('./blitter/BlitterCreator'),
        Container: require('./container/ContainerCreator'),
        DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapTextCreator'),
        Graphics: require('./graphics/GraphicsCreator'),
        Group: require('./group/GroupCreator'),
        Image: require('./image/ImageCreator'),
        Particles: require('./particles/ParticleManagerCreator'),
        RenderTexture: require('./rendertexture/RenderTextureCreator'),
        Sprite: require('./sprite/SpriteCreator'),
        StaticBitmapText: require('./bitmaptext/static/BitmapTextCreator'),
        Text: require('./text/static/TextCreator'),
        TileSprite: require('./tilesprite/TileSpriteCreator'),
        Zone: require('./zone/ZoneCreator')
    }

};

if (typeof EXPERIMENTAL)
{
    GameObjects.DOMElement = require('./domelement/DOMElement');
    GameObjects.Factories.DOMElement = require('./domelement/DOMElementFactory');
}

if (typeof WEBGL_RENDERER)
{
    //  WebGL only Game Objects
    GameObjects.Mesh = require('./mesh/Mesh');
    GameObjects.Quad = require('./quad/Quad');

    GameObjects.Factories.Mesh = require('./mesh/MeshFactory');
    GameObjects.Factories.Quad = require('./quad/QuadFactory');

    GameObjects.Creators.Mesh = require('./mesh/MeshCreator');
    GameObjects.Creators.Quad = require('./quad/QuadCreator');

    GameObjects.Light = require('./lights/Light');

    require('./lights/LightsManager');
    require('./lights/LightsPlugin');
}

module.exports = GameObjects;


text:
@implementation UITextField (PlaceholderLabel)

- (void)setPlaceholderLabelTextColor:(UIColor *)placeholderTextColor {
    if (@available(iOS 13, *)) {
        [self setValue:placeholderTextColor forKeyPath:@"placeholderLabel.textColor"];
    } else {
        [self setValue:placeholderTextColor forKeyPath:@"_placeholderLabel.textColor"];
    }
}
- (UIColor *)placeholderLabelTextColor {
    if (@available(iOS 13, *)) {
        return [self valueForKeyPath:@"placeholderLabel.textColor"];
    } else {
        return [self valueForKeyPath:@"_placeholderLabel.textColor"];
    }
    return nil;
}

- (void)setPlaceholderLabelTextFont:(UIFont *)placeholderTextFont {
    if (@available(iOS 13, *)) {
        [self setValue:placeholderTextFont forKeyPath:@"placeholderLabel.font"];
    } else {
        [self setValue:placeholderTextFont forKeyPath:@"_placeholderLabel.font"];
    }
}
- (UIFont *)placeholderLabelTextFont {
    if (@available(iOS 13, *)) {
        return [self valueForKeyPath:@"placeholderLabel.font"];
    } else {
        return [self valueForKeyPath:@"_placeholderLabel.font"];
    }
    return nil;
}

- (void)setPlaceholderLabelAlpha:(NSNumber *)placeholderLabelAlpha {
    if (@available(iOS 13, *)) {
        [self setValue:placeholderLabelAlpha forKeyPath:@"placeholderLabel.alpha"];
    } else {
        [self setValue:placeholderLabelAlpha forKeyPath:@"_placeholderLabel.alpha"];
    }
}
- (NSNumber *)placeholderLabelAlpha {
    if (@available(iOS 13, *)) {
        return [self valueForKeyPath:@"placeholderLabel.alpha"];
    } else {
        return [self valueForKeyPath:@"_placeholderLabel.alpha"];
    }
    return nil;
}
@end


text:
package org.osc.core.broker.service.mc;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import javax.net.ssl.SSLException;
import javax.persistence.EntityManager;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.osc.core.broker.job.Job;
import org.osc.core.broker.job.lock.LockRequest.LockType;
import org.osc.core.broker.model.entities.management.ApplianceManagerConnector;
import org.osc.core.broker.model.plugin.ApiFactoryService;
import org.osc.core.broker.service.ConformService;
import org.osc.core.broker.service.LockUtil;
import org.osc.core.broker.service.ServiceDispatcher;
import org.osc.core.broker.service.api.AddApplianceManagerConnectorServiceApi;
import org.osc.core.broker.service.api.server.EncryptionApi;
import org.osc.core.broker.service.dto.SslCertificateAttrDto;
import org.osc.core.broker.service.exceptions.VmidcBrokerValidationException;
import org.osc.core.broker.service.persistence.ApplianceManagerConnectorEntityMgr;
import org.osc.core.broker.service.persistence.OSCEntityManager;
import org.osc.core.broker.service.persistence.SslCertificateAttrEntityMgr;
import org.osc.core.broker.service.request.ApplianceManagerConnectorRequest;
import org.osc.core.broker.service.request.DryRunRequest;
import org.osc.core.broker.service.request.ErrorTypeException;
import org.osc.core.broker.service.request.ErrorTypeException.ErrorType;
import org.osc.core.broker.service.response.BaseJobResponse;
import org.osc.core.broker.service.ssl.CertificateResolverModel;
import org.osc.core.broker.service.ssl.SslCertificatesExtendedException;
import org.osc.core.broker.service.tasks.conformance.UnlockObjectTask;
import org.osc.core.broker.service.validator.ApplianceManagerConnectorDtoValidator;
import org.osc.core.broker.util.ValidateUtil;
import org.osc.core.broker.util.crypto.X509TrustManagerFactory;
import org.slf4j.LoggerFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;

/**
 * This component exposes both the API and the implementation so that the
 * {@link AddApplianceManagerConnectorService} and {@link UpdateApplianceManagerConnectorService}
 * can call the {@link #checkManagerConnection(DryRunRequest, ApplianceManagerConnector)}
 * method.
 */
@Component(service={AddApplianceManagerConnectorService.class, AddApplianceManagerConnectorServiceApi.class})
public class AddApplianceManagerConnectorService
extends ServiceDispatcher<DryRunRequest<ApplianceManagerConnectorRequest>, BaseJobResponse>
implements AddApplianceManagerConnectorServiceApi {

    private static final Logger LOG = LoggerFactory.getLogger(AddApplianceManagerConnectorService.class);

    @Reference
    private ApiFactoryService apiFactoryService;

    @Reference
    private ConformService conformService;

    @Reference
    private EncryptionApi encryption;

    @Override
    public BaseJobResponse exec(DryRunRequest<ApplianceManagerConnectorRequest> request, EntityManager em)
            throws Exception {
        OSCEntityManager<ApplianceManagerConnector> appMgrEntityMgr = new OSCEntityManager<>(ApplianceManagerConnector.class, em, this.txBroadcastUtil);

        try {
            validate(request, appMgrEntityMgr);
        } catch (Exception e) {
            if (e instanceof SslCertificatesExtendedException && request.getDto().isForceAddSSLCertificates()) {
                request = internalSSLCertificatesFetch(request, (SslCertificatesExtendedException) e);
                validate(request, appMgrEntityMgr);
            } else {
                throw e;
            }
        }

        String serviceName = this.apiFactoryService.getServiceName(request.getDto().getManagerType());
        ApplianceManagerConnector mc = ApplianceManagerConnectorEntityMgr.createEntity(request.getDto(), this.encryption, serviceName);
        appMgrEntityMgr.create(mc);

        SslCertificateAttrEntityMgr certificateAttrEntityMgr = new SslCertificateAttrEntityMgr(em, this.txBroadcastUtil);
        mc.setSslCertificateAttrSet(certificateAttrEntityMgr.storeSSLEntries(mc.getSslCertificateAttrSet(), mc.getId()));

        appMgrEntityMgr.update(mc);

        // Commit the changes early so that the entity is available for the job engine
        chain(() -> {
            UnlockObjectTask mcUnlock = LockUtil.tryLockMC(mc, LockType.WRITE_LOCK);
            Job job = this.conformService.startMCConformJob(mc, mcUnlock, em);
            return new BaseJobResponse(mc.getId(), job.getId());
        });

        return null;
    }

    private DryRunRequest<ApplianceManagerConnectorRequest> internalSSLCertificatesFetch(
            DryRunRequest<ApplianceManagerConnectorRequest> request, SslCertificatesExtendedException sslCertificatesException) throws Exception {
        X509TrustManagerFactory trustManagerFactory = X509TrustManagerFactory.getInstance();
        for (CertificateResolverModel certObj : sslCertificatesException.getCertificateResolverModels()) {
            trustManagerFactory.addEntry(certObj.getCertificate(), certObj.getAlias());
            request.getDto().getSslCertificateAttrSet().add(new SslCertificateAttrDto(certObj.getAlias(), certObj.getSha1()));
        }
        return request;
    }

    private void validate(DryRunRequest<ApplianceManagerConnectorRequest> request,
            OSCEntityManager<ApplianceManagerConnector> emgr) throws Exception {

        String managerType = request.getDto().getManagerType();
        boolean basicAuth = this.apiFactoryService.isBasicAuth(managerType);
        ApplianceManagerConnectorDtoValidator.checkForNullFields(request.getDto(), false, basicAuth);
        ApplianceManagerConnectorDtoValidator.checkFieldLength(request.getDto(), basicAuth);

        // check for uniqueness of mc name
        if (emgr.isExisting("name", request.getDto().getName())) {
            throw new VmidcBrokerValidationException("Appliance Manager Connector Name: " + request.getDto().getName() + " already exists.");
        }

        // check for valid IP address format
        ValidateUtil.checkForValidIpAddressFormat(request.getDto().getIpAddress());

        // check for uniqueness of mc IP
        if (emgr.isExisting("ipAddress", request.getDto().getIpAddress())) {
            throw new VmidcBrokerValidationException("Appliance Manager IP Address: " + request.getDto().getIpAddress() + " already exists.");
        }

        String serviceName = this.apiFactoryService.getServiceName(request.getDto().getManagerType());
        checkManagerConnection(request, ApplianceManagerConnectorEntityMgr.createEntity(request.getDto(), this.encryption, serviceName));
    }

    void checkManagerConnection(DryRunRequest<ApplianceManagerConnectorRequest> request,
            ApplianceManagerConnector mc) throws ErrorTypeException {
        if (!request.isSkipAllDryRun() && !request.isIgnoreErrorsAndCommit(ErrorType.MANAGER_CONNECTOR_EXCEPTION)) {

            ArrayList<CertificateResolverModel> resolverModels = new ArrayList<>();

            X509TrustManagerFactory managerFactory = X509TrustManagerFactory.getInstance();
            managerFactory.setListener(model -> {
                model.setAlias("manager_" + model.getAlias());
                resolverModels.add(model);
                managerFactory.clearListener();
            });

            try {
                this.apiFactoryService.checkConnection(mc);
            } catch (Exception e) {

                Throwable rootCause = ExceptionUtils.getRootCause(e);
                Throwable cause = e;

                if (rootCause instanceof SocketException
                        || rootCause instanceof SSLException
                        || rootCause instanceof SocketTimeoutException) {
                    cause = rootCause;
                }

                ErrorTypeException errorTypeException = new ErrorTypeException(cause, ErrorType.MANAGER_CONNECTOR_EXCEPTION);
                LOG.warn("Exception encountered when trying to add Manager Connector, allowing user to either ignore or correct issue");
                if (!resolverModels.isEmpty()) {
                    throw new SslCertificatesExtendedException(errorTypeException, resolverModels);
                }
                throw errorTypeException;
            }
        }
    }
}