text:
=pod

=head1 NAME

X509_VERIFY_PARAM_set_flags, X509_VERIFY_PARAM_clear_flags,
X509_VERIFY_PARAM_get_flags, X509_VERIFY_PARAM_set_purpose,
X509_VERIFY_PARAM_get_inh_flags, X509_VERIFY_PARAM_set_inh_flags,
X509_VERIFY_PARAM_set_trust, X509_VERIFY_PARAM_set_depth,
X509_VERIFY_PARAM_get_depth, X509_VERIFY_PARAM_set_auth_level,
X509_VERIFY_PARAM_get_auth_level, X509_VERIFY_PARAM_set_time,
X509_VERIFY_PARAM_get_time,
X509_VERIFY_PARAM_add0_policy, X509_VERIFY_PARAM_set1_policies,
X509_VERIFY_PARAM_set1_host, X509_VERIFY_PARAM_add1_host,
X509_VERIFY_PARAM_set_hostflags,
X509_VERIFY_PARAM_get_hostflags,
X509_VERIFY_PARAM_get0_peername,
X509_VERIFY_PARAM_set1_email, X509_VERIFY_PARAM_set1_ip,
X509_VERIFY_PARAM_set1_ip_asc
- X509 verification parameters

=head1 SYNOPSIS

 #include <openssl/x509_vfy.h>

 int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param,
                                 unsigned long flags);
 int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param,
                                   unsigned long flags);
 unsigned long X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param);

 int X509_VERIFY_PARAM_set_inh_flags(X509_VERIFY_PARAM *param,
                                     uint32_t flags);
 uint32_t X509_VERIFY_PARAM_get_inh_flags(const X509_VERIFY_PARAM *param);

 int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose);
 int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust);

 void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t);
 time_t X509_VERIFY_PARAM_get_time(const X509_VERIFY_PARAM *param);

 int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param,
                                   ASN1_OBJECT *policy);
 int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
                                     STACK_OF(ASN1_OBJECT) *policies);

 void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth);
 int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param);

 void X509_VERIFY_PARAM_set_auth_level(X509_VERIFY_PARAM *param,
                                       int auth_level);
 int X509_VERIFY_PARAM_get_auth_level(const X509_VERIFY_PARAM *param);

 int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
                                 const char *name, size_t namelen);
 int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
                                 const char *name, size_t namelen);
 void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,
                                      unsigned int flags);
 unsigned int X509_VERIFY_PARAM_get_hostflags(const X509_VERIFY_PARAM *param);
 char *X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *param);
 int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param,
                                  const char *email, size_t emaillen);
 int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param,
                               const unsigned char *ip, size_t iplen);
 int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc);

=head1 DESCRIPTION

These functions manipulate the B<X509_VERIFY_PARAM> structure associated with
a certificate verification operation.

The X509_VERIFY_PARAM_set_flags() function sets the flags in B<param> by oring
it with B<flags>. See the B<VERIFICATION FLAGS> section for a complete
description of values the B<flags> parameter can take.

X509_VERIFY_PARAM_get_flags() returns the flags in B<param>.

X509_VERIFY_PARAM_get_inh_flags() returns the inheritance flags in B<param>
which specifies how verification flags are copied from one structure to
another. X509_VERIFY_PARAM_set_inh_flags() sets the inheritance flags.
See the B<INHERITANCE FLAGS> section for a description of these bits.

X509_VERIFY_PARAM_clear_flags() clears the flags B<flags> in B<param>.

X509_VERIFY_PARAM_set_purpose() sets the verification purpose in B<param>
to B<purpose>. This determines the acceptable purpose of the certificate
chain, for example SSL client or SSL server.

X509_VERIFY_PARAM_set_trust() sets the trust setting in B<param> to
B<trust>.

X509_VERIFY_PARAM_set_time() sets the verification time in B<param> to
B<t>. Normally the current time is used.

X509_VERIFY_PARAM_add0_policy() enables policy checking (it is disabled
by default) and adds B<policy> to the acceptable policy set.

X509_VERIFY_PARAM_set1_policies() enables policy checking (it is disabled
by default) and sets the acceptable policy set to B<policies>. Any existing
policy set is cleared. The B<policies> parameter can be B<NULL> to clear
an existing policy set.

X509_VERIFY_PARAM_set_depth() sets the maximum verification depth to B<depth>.
That is the maximum number of intermediate CA certificates that can appear in a
chain.
A maximal depth chain contains 2 more certificates than the limit, since
neither the end-entity certificate nor the trust-anchor count against this
limit.
Thus a B<depth> limit of 0 only allows the end-entity certificate to be signed
directly by the trust-anchor, while with a B<depth> limit of 1 there can be one
intermediate CA certificate between the trust-anchor and the end-entity
certificate.

X509_VERIFY_PARAM_set_auth_level() sets the authentication security level to
B<auth_level>.
The authentication security level determines the acceptable signature and public
key strength when verifying certificate chains.
For a certificate chain to validate, the public keys of all the certificates
must meet the specified security level.
The signature algorithm security level is not enforced for the chain's I<trust
anchor> certificate, which is either directly trusted or validated by means other
than its signature.
See L<SSL_CTX_set_security_level(3)> for the definitions of the available
levels.
The default security level is -1, or "not set".
At security level 0 or lower all algorithms are acceptable.
Security level 1 requires at least 80-bit-equivalent security and is broadly
interoperable, though it will, for example, reject MD5 signatures or RSA keys
shorter than 1024 bits.

X509_VERIFY_PARAM_set1_host() sets the expected DNS hostname to
B<name> clearing any previously specified host name or names.  If
B<name> is NULL, or empty the list of hostnames is cleared, and
name checks are not performed on the peer certificate.  If B<name>
is NUL-terminated, B<namelen> may be zero, otherwise B<namelen>
must be set to the length of B<name>.

When a hostname is specified,
certificate verification automatically invokes L<X509_check_host(3)>
with flags equal to the B<flags> argument given to
X509_VERIFY_PARAM_set_hostflags() (default zero).  Applications
are strongly advised to use this interface in preference to explicitly
calling L<X509_check_host(3)>, hostname checks may be out of scope
with the DANE-EE(3) certificate usage, and the internal check will
be suppressed as appropriate when DANE verification is enabled.

When the subject CommonName will not be ignored, whether as a result of the
B<X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT> host flag, or because no DNS subject
alternative names are present in the certificate, any DNS name constraints in
issuer certificates apply to the subject CommonName as well as the subject
alternative name extension.

When the subject CommonName will be ignored, whether as a result of the
B<X509_CHECK_FLAG_NEVER_CHECK_SUBJECT> host flag, or because some DNS subject
alternative names are present in the certificate, DNS name constraints in
issuer certificates will not be applied to the subject DN.
As described in X509_check_host(3) the B<X509_CHECK_FLAG_NEVER_CHECK_SUBJECT>
flag takes precedence over the B<X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT> flag.

X509_VERIFY_PARAM_get_hostflags() returns any host flags previously set via a
call to X509_VERIFY_PARAM_set_hostflags().

X509_VERIFY_PARAM_add1_host() adds B<name> as an additional reference
identifier that can match the peer's certificate.  Any previous names
set via X509_VERIFY_PARAM_set1_host() or X509_VERIFY_PARAM_add1_host()
are retained, no change is made if B<name> is NULL or empty.  When
multiple names are configured, the peer is considered verified when
any name matches.

X509_VERIFY_PARAM_get0_peername() returns the DNS hostname or subject
CommonName from the peer certificate that matched one of the reference
identifiers.  When wildcard matching is not disabled, or when a
reference identifier specifies a parent domain (starts with ".")
rather than a hostname, the peer name may be a wildcard name or a
sub-domain of the reference identifier respectively.  The return
string is allocated by the library and is no longer valid once the
associated B<param> argument is freed.  Applications must not free
the return value.

X509_VERIFY_PARAM_set1_email() sets the expected RFC822 email address to
B<email>.  If B<email> is NUL-terminated, B<emaillen> may be zero, otherwise
B<emaillen> must be set to the length of B<email>.  When an email address
is specified, certificate verification automatically invokes
L<X509_check_email(3)>.

X509_VERIFY_PARAM_set1_ip() sets the expected IP address to B<ip>.
The B<ip> argument is in binary format, in network byte-order and
B<iplen> must be set to 4 for IPv4 and 16 for IPv6.  When an IP
address is specified, certificate verification automatically invokes
L<X509_check_ip(3)>.

X509_VERIFY_PARAM_set1_ip_asc() sets the expected IP address to
B<ipasc>.  The B<ipasc> argument is a NUL-terminal ASCII string:
dotted decimal quad for IPv4 and colon-separated hexadecimal for
IPv6.  The condensed "::" notation is supported for IPv6 addresses.

=head1 RETURN VALUES

X509_VERIFY_PARAM_set_flags(), X509_VERIFY_PARAM_clear_flags(),
X509_VERIFY_PARAM_set_inh_flags(),
X509_VERIFY_PARAM_set_purpose(), X509_VERIFY_PARAM_set_trust(),
X509_VERIFY_PARAM_add0_policy() X509_VERIFY_PARAM_set1_policies(),
X509_VERIFY_PARAM_set1_host(), X509_VERIFY_PARAM_add1_host(),
X509_VERIFY_PARAM_set1_email(), X509_VERIFY_PARAM_set1_ip() and
X509_VERIFY_PARAM_set1_ip_asc() return 1 for success and 0 for
failure.

X509_VERIFY_PARAM_get_flags() returns the current verification flags.

X509_VERIFY_PARAM_get_hostflags() returns any current host flags.

X509_VERIFY_PARAM_get_inh_flags() returns the current inheritance flags.

X509_VERIFY_PARAM_set_time() and X509_VERIFY_PARAM_set_depth() do not return
values.

X509_VERIFY_PARAM_get_depth() returns the current verification depth.

X509_VERIFY_PARAM_get_auth_level() returns the current authentication security
level.

=head1 VERIFICATION FLAGS

The verification flags consists of zero or more of the following flags
ored together.

B<X509_V_FLAG_CRL_CHECK> enables CRL checking for the certificate chain leaf
certificate. An error occurs if a suitable CRL cannot be found.

B<X509_V_FLAG_CRL_CHECK_ALL> enables CRL checking for the entire certificate
chain.

B<X509_V_FLAG_IGNORE_CRITICAL> disabled critical extension checking. By default
any unhandled critical extensions in certificates or (if checked) CRLs results
in a fatal error. If this flag is set unhandled critical extensions are
ignored. B<WARNING> setting this option for anything other than debugging
purposes can be a security risk. Finer control over which extensions are
supported can be performed in the verification callback.

The B<X509_V_FLAG_X509_STRICT> flag disables workarounds for some broken
certificates and makes the verification strictly apply B<X509> rules.

B<X509_V_FLAG_ALLOW_PROXY_CERTS> enables proxy certificate verification.

B<X509_V_FLAG_POLICY_CHECK> enables certificate policy checking, by default
no policy checking is performed. Additional information is sent to the
verification callback relating to policy checking.

B<X509_V_FLAG_EXPLICIT_POLICY>, B<X509_V_FLAG_INHIBIT_ANY> and
B<X509_V_FLAG_INHIBIT_MAP> set the B<require explicit policy>, B<inhibit any
policy> and B<inhibit policy mapping> flags respectively as defined in
B<RFC3280>. Policy checking is automatically enabled if any of these flags
are set.

If B<X509_V_FLAG_NOTIFY_POLICY> is set and the policy checking is successful
a special status code is set to the verification callback. This permits it
to examine the valid policy tree and perform additional checks or simply
log it for debugging purposes.

By default some additional features such as indirect CRLs and CRLs signed by
different keys are disabled. If B<X509_V_FLAG_EXTENDED_CRL_SUPPORT> is set
they are enabled.

If B<X509_V_FLAG_USE_DELTAS> is set delta CRLs (if present) are used to
determine certificate status. If not set deltas are ignored.

B<X509_V_FLAG_CHECK_SS_SIGNATURE> enables checking of the root CA self signed
certificate signature. By default this check is disabled because it doesn't
add any additional security but in some cases applications might want to
check the signature anyway. A side effect of not checking the root CA
signature is that disabled or unsupported message digests on the root CA
are not treated as fatal errors.

When B<X509_V_FLAG_TRUSTED_FIRST> is set, construction of the certificate chain
in L<X509_verify_cert(3)> will search the trust store for issuer certificates
before searching the provided untrusted certificates.
Local issuer certificates are often more likely to satisfy local security
requirements and lead to a locally trusted root.
This is especially important when some certificates in the trust store have
explicit trust settings (see "TRUST SETTINGS" in L<x509(1)>).
As of OpenSSL 1.1.0 this option is on by default.

The B<X509_V_FLAG_NO_ALT_CHAINS> flag suppresses checking for alternative
chains.
By default, unless B<X509_V_FLAG_TRUSTED_FIRST> is set, when building a
certificate chain, if the first certificate chain found is not trusted, then
OpenSSL will attempt to replace untrusted certificates supplied by the peer
with certificates from the trust store to see if an alternative chain can be
found that is trusted.
As of OpenSSL 1.1.0, with B<X509_V_FLAG_TRUSTED_FIRST> always set, this option
has no effect.

The B<X509_V_FLAG_PARTIAL_CHAIN> flag causes intermediate certificates in the
trust store to be treated as trust-anchors, in the same way as the self-signed
root CA certificates.
This makes it possible to trust certificates issued by an intermediate CA
without having to trust its ancestor root CA.
With OpenSSL 1.1.0 and later and <X509_V_FLAG_PARTIAL_CHAIN> set, chain
construction stops as soon as the first certificate from the trust store is
added to the chain, whether that certificate is a self-signed "root"
certificate or a not self-signed intermediate certificate.
Thus, when an intermediate certificate is found in the trust store, the
verified chain passed to callbacks may be shorter than it otherwise would
be without the B<X509_V_FLAG_PARTIAL_CHAIN> flag.

The B<X509_V_FLAG_NO_CHECK_TIME> flag suppresses checking the validity period
of certificates and CRLs against the current time. If X509_VERIFY_PARAM_set_time()
is used to specify a verification time, the check is not suppressed.

=head1 INHERITANCE FLAGS

These flags specify how parameters are "inherited" from one structure to
another.

If B<X509_VP_FLAG_ONCE> is set then the current setting is zeroed
after the next call.

If B<X509_VP_FLAG_LOCKED> is set then no values are copied.  This overrides
all of the following flags.

If B<X509_VP_FLAG_DEFAULT> is set then anything set in the source is copied
to the destination. Effectively the values in "to" become default values
which will be used only if nothing new is set in "from".  This is the
default.

If B<X509_VP_FLAG_OVERWRITE> is set then all value are copied across whether
they are set or not. Flags is still Ored though.

If B<X509_VP_FLAG_RESET_FLAGS> is set then the flags value is copied instead
of ORed.

=head1 NOTES

The above functions should be used to manipulate verification parameters
instead of functions which work in specific structures such as
X509_STORE_CTX_set_flags() which are likely to be deprecated in a future
release.

=head1 BUGS

Delta CRL checking is currently primitive. Only a single delta can be used and
(partly due to limitations of B<X509_STORE>) constructed CRLs are not
maintained.

If CRLs checking is enable CRLs are expected to be available in the
corresponding B<X509_STORE> structure. No attempt is made to download
CRLs from the CRL distribution points extension.

=head1 EXAMPLE

Enable CRL checking when performing certificate verification during SSL
connections associated with an B<SSL_CTX> structure B<ctx>:

 X509_VERIFY_PARAM *param;

 param = X509_VERIFY_PARAM_new();
 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
 SSL_CTX_set1_param(ctx, param);
 X509_VERIFY_PARAM_free(param);

=head1 SEE ALSO

L<X509_verify_cert(3)>,
L<X509_check_host(3)>,
L<X509_check_email(3)>,
L<X509_check_ip(3)>,
L<x509(1)>

=head1 HISTORY

The B<X509_V_FLAG_NO_ALT_CHAINS> flag was added in OpenSSL 1.1.0
The flag B<X509_V_FLAG_CB_ISSUER_CHECK> was deprecated in
OpenSSL 1.1.0, and has no effect.

X509_VERIFY_PARAM_get_hostflags() was added in OpenSSL 1.1.0i.

=head1 COPYRIGHT

Copyright 2009-2018 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the OpenSSL license (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
import Ember from 'ember';
import layout from '../templates/components/paper-column';
const { Component } = Ember;

export default Component.extend({
  layout,

  tagName: 'md-data-table-column',
  classNameBindings: ['icon:icon-column']
});

redpajama_set_name: RedPajamaGithub


text:
import axios from 'axios';
import randomId from 'random-id';

import storage from './storage';
import ext from './ext';
import { appConfig } from '../appConfig';
import moment from 'moment';
import { getConfig } from '../config';

export function getCrawlerOption() {
  return new Promise((resolve, reject) => {
    storage.get('option', function(result) {
      if (ext.runtime.lastError) {
        console.log('Runtime error.');
        return resolve('auto');
      }

      const crawlerOption = result.option !== undefined ? result.option : 'auto';
      return resolve(crawlerOption);
    });
  });
}

export function setCrawlerOption(option) {
  storage.set({ option }, function() {
    console.log('option saved');
  });
}

export function getOverlaySetting() {
  return new Promise((resolve, reject) => {
    storage.get('overlayVisible', function(result) {
      if (ext.runtime.lastError) {
        console.log('Runtime error.');
        return resolve(true);
      }
      const overlayVisible = result.overlayVisible !== undefined ? result.overlayVisible : true;
      return resolve(overlayVisible);
    });
  });
}

export function setOverlaySetting(option) {
  storage.set({'overlayVisible': option}, () => {
    console.log('overlay Setting saved');
  });
}

export function getDate() {
  return new Promise((resolve, reject) => {
    storage.get('date', function(result) {
      if (ext.runtime.lastError) {
        console.log('Runtime error.');
        return resolve('later');
      }
      return resolve(result.date || 0);
    });
  });
}

export function getTimeStamp() {
  const unixDate = moment.utc().unix();

  return unixDate;
}

export function postToServer(err, res) {
  getConfig()
    .then(config => {
      axios.post(appConfig.resultUrl, res, {'timeout': config.timeoutForRequests * 1000 || 10000})
        .then(function (response) {
          console.log('posting result successful',  response);
        })
        .catch(function (error) {
          console.log('error with posting result', error);
        });
    })
    .catch(console.log('error while loading config'));
}

export function makeId() {
  return randomId(32, "a0");
}


text:
import tempfile
import time

import os
import os.path

import mycroft
from .file_utils import ensure_directory_exists, create_file

def get_ipc_directory(domain=None):
    """Get the directory used for Inter Process Communication

    Files in this folder can be accessed by different processes on the
    machine.  Useful for communication.  This is often a small RAM disk.

    Args:
        domain (str): The IPC domain.  Basically a subdirectory to prevent
            overlapping signal filenames.

    Returns:
        str: a path to the IPC directory
    """
    config = mycroft.configuration.Configuration.get()
    dir = config.get("ipc_path")
    if not dir:
        # If not defined, use /tmp/mycroft/ipc
        dir = os.path.join(tempfile.gettempdir(), "mycroft", "ipc")
    return ensure_directory_exists(dir, domain)

def create_signal(signal_name):
    """Create a named signal

    Args:
        signal_name (str): The signal's name.  Must only contain characters
            valid in filenames.
    """
    try:
        path = os.path.join(get_ipc_directory(), "signal", signal_name)
        create_file(path)
        return os.path.isfile(path)
    except IOError:
        return False

def check_for_signal(signal_name, sec_lifetime=0):
    """See if a named signal exists

    Args:
        signal_name (str): The signal's name.  Must only contain characters
            valid in filenames.
        sec_lifetime (int, optional): How many seconds the signal should
            remain valid.  If 0 or not specified, it is a single-use signal.
            If -1, it never expires.

    Returns:
        bool: True if the signal is defined, False otherwise
    """
    path = os.path.join(get_ipc_directory(), "signal", signal_name)
    if os.path.isfile(path):
        if sec_lifetime == 0:
            # consume this single-use signal
            os.remove(path)
        elif sec_lifetime == -1:
            return True
        elif int(os.path.getctime(path) + sec_lifetime) < int(time.time()):
            # remove once expired
            os.remove(path)
            return False
        return True

    # No such signal exists
    return False


text:
<!doctype html>

    <title>Switchboard Admin</title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

Switchboard Admin

Rewrites

404's

                    <colgroup>
                      <col class="rule-type"/>
                      <col class="rule-from"/>
                      <col class="rule-to"/>
                      <col class="rule-actions"/>
                    </colgroup>

                        Rule Type
                        From
                        To

                        {{rewrite.rule_type}}
                        {{rewrite.from}}
                        {{rewrite.to}}

                  <form class="form-inline" ng-submit="addRewrite()">

                      Rule Type
                      <select id="rewriteRuleTypeSelect" class="form-control" ng-model="rewriteMethod">
                        <option value="r301">301 (Moved Permanently)</option>
                        <option value="r302">302 (Found)</option>
                        <option value="r303">303 (See Other)</option>
                        <option value="r307">307 (Temporary Redirect)</option>
                      </select>

                      From
                      <input type="text" class="form-control" id="rewriteFromField" ng-model="rewriteFrom" placeholder="From">

                      To
                      <input type="text" class="form-control" id="rewriteToField" ng-model="rewriteTo" placeholder="To">

                    <input class="btn btn-default" type="submit" value="Add Rule">
                  </form>

                    <colgroup>
                      <col class="not-found-path"/>
                      <col class="not-found-hits"/>
                      <col class="not-found-actions"/>
                    </colgroup>

                        Path
                        Hit Count

                        {{not_found.path}}
                        {{not_found.hit_count}}


text:
@interface WQSelectOptionsCell : UITableViewCell

@end


text:
package org.wso2.am.integration.tests.other;

import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.bean.*;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.am.integration.test.utils.generic.APIMTestCaseUtils;
import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
import org.xml.sax.SAXException;

import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class APIApplicationLifeCycleTestCase extends APIMIntegrationBaseTest {
    private APIPublisherRestClient apiPublisher;
    private APIStoreRestClient apiStore;
    private UserManagementClient userManagementClient;
    private TenantManagementServiceClient tenantManagementServiceClient;
    //move to base class
    private String publisherURLHttp;
    private String storeURLHttp;
    private String gatewaySessionCookie;

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws APIManagerIntegrationTestException, IOException,
            XPathExpressionException, URISyntaxException, SAXException, XMLStreamException,
            LoginAuthenticationExceptionException {
        super.init();
        gatewaySessionCookie = createSession(gatewayContext);
        publisherURLHttp = publisherUrls.getWebAppURLHttp();
        storeURLHttp = storeUrls.getWebAppURLHttp();
        apiPublisher = new APIPublisherRestClient(publisherURLHttp);
        apiStore = new APIStoreRestClient(storeURLHttp);

        userManagementClient = new UserManagementClient(
                gatewayContext.getContextUrls().getBackEndUrl(), gatewaySessionCookie);

        tenantManagementServiceClient = new TenantManagementServiceClient(
                gatewayContext.getContextUrls().getBackEndUrl(), gatewaySessionCookie);
    }

    @Test(groups = {"wso2.am"}, description = "API Life cycle test case")
    public void testAPIApplicationLifeCycleITestCase() throws Exception {

        String apiData = "";
        String APIName = "APILifeCycleTestAPI";
        String APIContext = "testAPI";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersion = "1.0.0";
        // This is because with the new context version strategy, if the context does not have the {version} param ,
        // then we add the {version} param to the end of the context.
        String apiContextAddedValue = APIContext + "/" + APIVersion;

        //add all option methods
        apiPublisher.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());
        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setVisibility("restricted");
        apiRequest.setRoles("admin");
        apiPublisher.addAPI(apiRequest);
        apiPublisher.deleteAPI(APIName, APIVersion, providerName);
        //add assertion
        apiPublisher.addAPI(apiRequest);
        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisher.getAPI(
                APIName, providerName));
        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.PUBLISHED);
        apiPublisher.changeAPILifeCycleStatus(updateRequest);
        //Test API properties
        assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch");
        assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1),
                     apiContextAddedValue, "API context mismatch");
        assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch");
        assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch");
        for (String tag : apiBean.getTags()) {
           assertTrue(tags.contains(tag), "API tag data mismatched");
        }
        assertEquals(apiBean.getDescription(), description, "API description mismatch");
        apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());
        apiStore.addApplication("APILifeCycleTestAPI-application", "Gold", "", "this-is-test");
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName,
                storeContext.getContextTenant().getContextUser().getUserName());
        subscriptionRequest.setApplicationName("APILifeCycleTestAPI-application");
        apiStore.subscribe(subscriptionRequest);

        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("APILifeCycleTestAPI-application");
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject response = new JSONObject(responseString);
        String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
        Map<String, String> requestHeaders = new HashMap<String, String>();
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        //Here add API tags and check same have in response.
        //Here check same tags are there
        //Add some comment to API
        //check comment is there
        //Add rating
        //check rating
        Thread.sleep(60000);
        //  for (int i = 0; i < 19; i++) {

        HttpResponse youTubeResponse = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp()+"testAPI/1.0.0/most_popular", requestHeaders);
        assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched");
        assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<category"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<entry>"), "Response data mismatched");

        // }
        //Do get,post,put,delete all here
        //HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), requestHeaders);
        //Assert.assertEquals(youTubeResponse.getResponseCode(), 503, "Response code mismatched");
        //Thread.sleep(60000);
        HttpResponse youTubeResponse1 = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp()+"testAPI/1.0.0/most_popular", null);
        assertEquals(youTubeResponse1.getResponseCode(), 401, "Response code mismatched");
        requestHeaders.clear();
        requestHeaders.put("Authorization", "Bearer " + "-wrong-tokent-text-");
        HttpResponse youTubeResponseError = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp()+"testAPI/1.0.0/most_popular", null);
        assertEquals(youTubeResponseError.getResponseCode(), 401, "Response code mismatched");

        apiStore.getAllPublishedAPIs();
        apiStore.getAllApplications();
        apiStore.getPublishedAPIsByApplication("APILifeCycleTestAPI-application");
        apiStore.isRatingActivated();
        apiStore.addRatingToAPI(APIName, APIVersion, providerName, "4");
        apiStore.addRatingToAPI(APIName, APIVersion, providerName, "2");
        apiStore.addRatingToAPI(APIName, APIVersion, providerName, "1");
        apiStore.removeRatingFromAPI(APIName, APIVersion, providerName);
        apiStore.getAllDocumentationOfAPI(APIName, APIVersion, providerName);
        //apiStore.getAllPaginatedPublishedAPIs("carbon.super","0","10");
        //Negative cases
        apiStore.getPublishedAPIsByApplication("APILifeCycleTestAPI-application-wrong");
        apiStore.isRatingActivated();
        apiStore.addRatingToAPI("NoAPI", APIVersion, providerName, "4");
        apiStore.removeRatingFromAPI("NoAPI", APIVersion, providerName);
        apiStore.getAllDocumentationOfAPI("NoAPI", APIVersion, providerName);
        apiRequest.setTags("updated");
        apiRequest.setProvider("admin");
        Thread.sleep(1000);
        apiPublisher.updateAPI(apiRequest);
        //TODO need to reformat this code after we finalize new APIs
        apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", "In-line",
                "url-no-need", "summary", "");
        apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name1", "How To", "URL",
                "http://www.businesstoday.lk/article.php?article=3549", "summary", "");
        apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name2", "How To", " File",
                "url-no-need", "summary",
                getAMResourceLocation() + File.separator + "configFiles/tokenTest/" + "api-manager.xml");
        apiPublisher.removeDocumentation(APIName, APIVersion, providerName, "Doc Name", "How To");
        //create application
        apiStore.addApplication("test-application", "Gold", "", "this-is-test");
        apiStore.addApplication("test-application2", "Gold", "", "this-is-test");
        apiStore.getAllApplications();

        //Test case to create new application and make subscriptions to that application
        SubscriptionRequest subscriptionRequest1 = new SubscriptionRequest(APIName,
                storeContext.getContextTenant().getContextUser().getUserName());
        subscriptionRequest1.setApplicationName("test-application");
        apiStore.subscribe(subscriptionRequest1);
        APPKeyRequestGenerator generateAppKeyRequest1 = new APPKeyRequestGenerator("test-application");
        String responseString1 = apiStore.generateApplicationKey(generateAppKeyRequest1).getData();
        JSONObject response1 = new JSONObject(responseString1);
        String accessToken1 = response1.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
        Map<String, String> requestHeaders1 = new HashMap<String, String>();
        requestHeaders1.put("Authorization", "Bearer " + accessToken1);
        HttpResponse youTubeResponseTestApp = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp()+"testAPI/1.0.0/most_popular", requestHeaders1);
        for (int i = 0; i < 40; i++) {
            youTubeResponseTestApp = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp()+"testAPI/1.0.0/most_popular", requestHeaders1);
        }
        assertEquals(youTubeResponseTestApp.getResponseCode(), 503, "Response code mismatched");

        //Add comment
        apiStore.isCommentActivated();
        apiStore.addComment(APIName, APIVersion, providerName, "this-is-comment");
        apiStore.getRecentlyAddedAPIs("carbon.super", "5");

        apiStore.updateApplication("test-application", "test-updated-application", "test-url", "this-is-updated", "bronze");
        apiStore.getAllApplications();
        apiData = apiStore.removeApplication("test-updated-application").getData();
        assertTrue(apiData.contains("false"), "Error while removing applications");

        apiStore.getAllApplications();
        apiData = apiStore.getAllSubscriptions().getData();
        assertTrue(apiData.contains("test-application"), "Error while getting all the subscriptions");

        apiStore.getAllTags();

        //Update role permissions
        HttpResponse updateTierPermissionResponse = apiPublisher.updatePermissions("Gold", "Deny", "admin");
        JSONObject jsonObject = new JSONObject(updateTierPermissionResponse.getData());
        assertTrue(!(Boolean) jsonObject.get("error"), "Error while updating tier permission");

        apiData = apiStore.removeAPISubscription(APIName, APIVersion, providerName, "1").getData();
        assertTrue(apiData.contains("{\"error\" : false}"), "Error while unsubscribe from API");

        apiPublisher.logout();
        apiStore.removeApplication("APILifeCycleTestAPI-application");

    }

    @Test(groups = {"wso2.am"}, description = "API Life cycle test invalid scenario", dependsOnMethods = "testAPIApplicationLifeCycleITestCase")
    public void testInvalidLoginAsPublisherTestCase() {

        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        //Try invalid login to publisher
        try {
            apiPublisherRestClient.login(publisherContext.getContextTenant().getContextUser().getUserName()
                    + "invalid",
                    publisherContext.getContextTenant().getContextUser().getPassword());
        } catch (Exception e) {
            assertTrue(e.getMessage().toString().contains(
                    "Please recheck the username and password and try again"),
                    "Invalid user can login to the API publisher");
        }

    }

    @Test(groups = {"wso2.am"}, description = "API Life cycle test subscriber login", enabled = false)
    public void testInvalidLoginAsSubscriberTestCase()
            throws Exception {

        //Try login to publisher with subscriber user
        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        boolean loginFailed = false;
        String error = "";

        if ((userManagementClient != null) &&
                !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser")) {
            userManagementClient.addUser("subscriberUser", "password@123",
                    new String[]{"Internal/subscriber"}, null);
        }

        try {
            apiPublisherRestClient.login("subscriberUser",
                    "password@123");
        } catch (Exception e) {
            loginFailed = true;
            error = e.getMessage().toString();
        }

        Assert.assertTrue(loginFailed && error.contains("Login failed.Insufficient privileges"),
                "Invalid subscriber can login to the API publisher");
    }

    @Test(groups = {"wso2.am"}, description = "API Life cycle test subscriber login", enabled = false)
    public void testInvalidLoginAsTenantSubscriberTestCase()
            throws Exception {

        //Try login to publisher with tenant subscriber user

        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        boolean loginFailed = false;
        String error = "";

        tenantManagementServiceClient.addTenant("wso2.com", "wso2@123", "wso2", "Gold");

        if ((userManagementClient != null) &&
                !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser@wso2.com")) {
            userManagementClient.addUser("subscriberUser@wso2.com", "password@123",
                    new String[]{"Internal/subscriber"}, null);
        }

        try {
            apiPublisherRestClient.login("subscriberUser@wso2.com",
                    "password@123");
        } catch (Exception e) {
            loginFailed = true;
            error = e.getMessage().toString();
        }

        Assert.assertTrue(error.contains("Operation not successful: " +
                "Login failed.Please recheck the username and password and try again"),
                "Invalid tenant subscriber can login to the API publisher");

    }

    @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false)
    public void testAPIVisibilityTestCase()
            throws Exception {

        userManagementClient.addUser("subscriberUser1", "password@123",
                new String[]{"Internal/everyone"}, null);

        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        apiPublisherRestClient.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());

        addPublicAPI(apiPublisherRestClient);
        addVisibleToDomainOnlyAPI(apiPublisherRestClient);
        addVisibleToRolesAPI(apiPublisherRestClient);
        //apiPublisherRestClient.logout();
        boolean bPublishedAPI = false;
        String publishedAPIs;
        /* publishedAPIs = apiStore.getAllPublishedAPIsAsAnonUser().getData();

  if (publishedAPIs.contains("APILifeCycleTestAPIPublic") &&
          !publishedAPIs.contains("APILifeCycleTestAPIDomainOnly") &&
          !publishedAPIs.contains("APILifeCycleTestAPIRoles")) {
      bPublishedAPI = true;
  }

  Assert.assertTrue(bPublishedAPI, "Anonymous user can view other API's");*/

        APIStoreRestClient apiStore1 = new APIStoreRestClient(storeURLHttp);
        apiStore1.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());
        publishedAPIs = apiStore1.getAllPublishedAPIs().getData();
        bPublishedAPI = false;

        if (publishedAPIs.contains("APILifeCycleTestAPIPublic") &&
                publishedAPIs.contains("APILifeCycleTestAPIDomainOnly") &&
                publishedAPIs.contains("APILifeCycleTestAPIRoles")) {
            bPublishedAPI = true;
        }

        Assert.assertTrue(bPublishedAPI, "Admin user can not view all API's");

        if ((userManagementClient != null) &&
                !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser")) {
            userManagementClient.addUser("subscriberUser", "password@123",
                    new String[]{"Internal/subscriber"}, null);
        }

        APIStoreRestClient apiStore2 = new APIStoreRestClient(storeURLHttp);
        apiStore2.login("subscriberUser", "password@123");
        publishedAPIs = apiStore2.getAllPublishedAPIs().getData();
        bPublishedAPI = false;

        if (publishedAPIs.contains("APILifeCycleTestAPIPublic") &&
                publishedAPIs.contains("APILifeCycleTestAPIDomainOnly") &&
                !publishedAPIs.contains("APILifeCycleTestAPIRoles")) {
            bPublishedAPI = true;
        }

    }

    @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false)
    public void copyAPILifeCycleTestCase() throws Exception {

        String APIName = "APILifeCycleTestAPI";
        String APIContext = "testAPI";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersionOld = "1.0.0";
        String APIVersionNew = "2.0.0";
        String defaultVersion = "default_version";

        //add all option methods
        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        apiPublisherRestClient.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());

        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersionOld);
        apiRequest.setVisibility("restricted");
        apiRequest.setRoles("admin");
        apiPublisherRestClient.addAPI(apiRequest);

        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(
                APIName, providerName));
        APILifeCycleStateRequest updateRequest1 = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.PUBLISHED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest1);

        apiPublisherRestClient.copyAPI(providerName, APIName, APIVersionOld, APIVersionNew, "");
        //add assertion
        apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(APIName,
                providerName));
        APILifeCycleStateRequest updateRequest2 = new APILifeCycleStateRequest(APIName,
                providerName, APILifeCycleState.PUBLISHED);
        updateRequest2.setVersion(APIVersionNew);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest2);

        APIStoreRestClient apiStore = new APIStoreRestClient(storeURLHttp);
        apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());

        String apiData = apiStore.getAllPublishedAPIs().getData();

        Assert.assertTrue(!apiData.contains(APIVersionOld),
                "Old version available in the store");

        Assert.assertTrue(apiData.contains(APIVersionNew),
                "New version not available in the store");

        //subscribe to the old API version
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName,
                storeContext.getContextTenant().getContextUser().getUserName());
        apiData = apiStore.subscribe(subscriptionRequest).getData();

        Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"),
                "Can subscribe to the old API version");

        //subscribe to the new API version
        subscriptionRequest.setVersion(APIVersionNew);
        apiData = apiStore.subscribe(subscriptionRequest).getData();

        Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"),
                "Can not subscribe to the old API version");

        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("DefaultApplication");
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject response = new JSONObject(responseString);
        String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
        Map<String, String> requestHeaders = new HashMap<String, String>();
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        //Here add API tags and check same have in response.
        //Here check same tags are there
        //Add some comment to API
        //check comment is there
        //Add rating
        //check rating
        Thread.sleep(60000);

        HttpResponse youTubeResponse = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp() + "testAPI/1.0.0/most_popular", requestHeaders);
        Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<category"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<entry>"), "Response data mismatched");

        youTubeResponse = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp() + "testAPI/2.0.0/most_popular", requestHeaders);
        Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<category"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<entry>"), "Response data mismatched");

    }

    @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false)
    public void otherAPILifeCycleStatesTestCase() throws Exception {

        String APIName = "APILifeCycleTestAPI";
        String APIContext = "testAPI";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersionOld = "1.0.0";
        String APIVersionNew = "2.0.0";
        String defaultVersion = "default_version";

        //add all option methods
        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        apiPublisherRestClient.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());

        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersionOld);
        apiRequest.setVisibility("restricted");
        apiRequest.setRoles("admin");
        apiPublisherRestClient.addAPI(apiRequest);

        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(
                APIName, providerName));
        APILifeCycleStateRequest updateRequest1 = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.PUBLISHED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest1);

        APIStoreRestClient apiStore = new APIStoreRestClient(storeURLHttp);
        apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());

        String apiData = apiStore.getAllPublishedAPIs().getData();

        Assert.assertTrue(apiData.contains(APIName),
                "Added API not available in store");

        APILifeCycleStateRequest updateRequest2 = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.RETIRED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest2);

        apiData = apiStore.getAllPublishedAPIs().getData();

        Assert.assertTrue(!apiData.contains(APIName),
                "Retired API available in store");

        APILifeCycleStateRequest updateRequest3 = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.BLOCKED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest3);

        apiData = apiStore.getAllPublishedAPIs().getData();

        Assert.assertTrue(!apiData.contains(APIName),
                "Blocked API available in store");

    }

    @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false)
    public void copyAndDepricateAPILifeCycleTestCase() throws Exception {

        String APIName = "APILifeCycleTestAPI";
        String APIContext = "testAPI";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersionOld = "1.0.0";
        String APIVersionNew = "2.0.0";
        String defaultVersion = "default_version";

        //add all option methods
        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        apiPublisherRestClient.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());

        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersionOld);
        apiRequest.setVisibility("restricted");
        apiRequest.setRoles("admin");
        apiPublisherRestClient.addAPI(apiRequest);

        //publish initial version
        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(
                APIName, providerName));
        APILifeCycleStateRequest updateRequest1 = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.PUBLISHED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest1);

        //publish new version
        apiPublisherRestClient.copyAPI(providerName, APIName, APIVersionOld, APIVersionNew, "");
        //add assertion
        apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(APIName,
                providerName));
        APILifeCycleStateRequest updateRequest2 = new APILifeCycleStateRequest(APIName,
                providerName, APILifeCycleState.PUBLISHED);
        updateRequest2.setVersion(APIVersionNew);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest2);

        //deprecate old version
        apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(APIName,
                providerName));
        APILifeCycleStateRequest updateRequest3 = new APILifeCycleStateRequest(APIName,
                providerName, APILifeCycleState.DEPRECATED);
        updateRequest3.setVersion(APIVersionOld);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest3);

        APIStoreRestClient apiStore = new APIStoreRestClient(storeURLHttp);
        apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());

        String apiData = apiStore.getAllPublishedAPIs().getData();

        Assert.assertTrue(!apiData.contains(APIVersionOld),
                "Old version available in the store");

        Assert.assertTrue(apiData.contains(APIVersionNew),
                "New version not available in the store");

        //subscribe to the old API version
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName,
                storeContext.getContextTenant().getContextUser().getUserName());
        apiData = apiStore.subscribe(subscriptionRequest).getData();

        Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"),
                "Can subscribe to the old API version");

        //subscribe to the new API version
        subscriptionRequest.setVersion(APIVersionNew);
        apiData = apiStore.subscribe(subscriptionRequest).getData();

        Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"),
                "Can not subscribe to the old API version");

        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("DefaultApplication");
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject response = new JSONObject(responseString);
        String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
        Map<String, String> requestHeaders = new HashMap<String, String>();
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        //Here add API tags and check same have in response.
        //Here check same tags are there
        //Add some comment to API
        //check comment is there
        //Add rating
        //check rating
        Thread.sleep(60000);

        HttpResponse youTubeResponse = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp() + "testAPI/1.0.0/most_popular", requestHeaders);
        Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<category"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<entry>"), "Response data mismatched");

        youTubeResponse = HttpRequestUtil.doGet(gatewayUrls.getWebAppURLNhttp() + "testAPI/2.0.0/most_popular", requestHeaders);
        Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<category"), "Response data mismatched");
        Assert.assertTrue(youTubeResponse.getData().contains("<entry>"), "Response data mismatched");

    }

    public void addPublicAPI(APIPublisherRestClient apiPublisherRestClient) throws Exception {

        String APIName = "APILifeCycleTestAPIPublic";
        String APIContext = "testAPIPublic";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersion = "1.0.0";
        //add all option methods

        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setVisibility("public");
        apiPublisherRestClient.addAPI(apiRequest);
        //add assertion
        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(APIName, providerName));
        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest);

    }

    public void addVisibleToDomainOnlyAPI(APIPublisherRestClient apiPublisherRestClient) throws Exception {

        String APIName = "APILifeCycleTestAPIDomainOnly";
        String APIContext = "testAPIDomainOnly";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersion = "1.0.0";
        //add all option methods
        //apiPublisher.login(userInfo.getUserName(), userInfo.getPassword());
        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setVisibility("private");
        apiPublisherRestClient.addAPI(apiRequest);
        //add assertion;
        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(
                APIName, providerName));
        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName,
                APILifeCycleState.PUBLISHED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest);
    }

    public void addVisibleToRolesAPI(APIPublisherRestClient apiPublisherRestClient) throws Exception {

        String APIName = "APILifeCycleTestAPIRoles";
        String APIContext = "testAPIRoles";
        String tags = "youtube, video, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersion = "1.0.0";
        //add all option methods
        //apiPublisher.login(userInfo.getUserName(), userInfo.getPassword());
        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setVisibility("restricted");
        apiRequest.setRoles("admin");
        apiPublisherRestClient.addAPI(apiRequest);
        //add assertion
        APIBean apiBean = APIMTestCaseUtils.getAPIBeanFromHttpResponse(apiPublisherRestClient.getAPI(
                APIName, providerName));
        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(
                APIName, providerName, APILifeCycleState.PUBLISHED);
        apiPublisherRestClient.changeAPILifeCycleStatus(updateRequest);
    }

    @Test(groups = {"wso2.am"}, description = "API Life cycle application related tests in store", enabled = false)
    public void testApplicationsInStoreTestCase()
            throws Exception {

        //Try login to publisher with tenant subscriber user

        APIStoreRestClient apiStoreRestClient1 = new APIStoreRestClient(storeURLHttp);

        apiStoreRestClient1.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());

        tenantManagementServiceClient.addTenant("wso2.com", "wso2@123", "wso2", "Gold");

        if ((userManagementClient != null) &&
                !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser@wso2.com")) {
            userManagementClient.addUser("subscriberUser@wso2.com", "password@123",
                    new String[]{"Internal/subscriber"}, null);
        }

        apiStoreRestClient1.addApplication("carbonSuperApp", "Gold", "", "super tenant app");
        String apiData = apiStoreRestClient1.addApplication("carbonSuperApp", "Gold", "",
                "super tenant app").getData();
        Assert.assertTrue(apiData.contains("A duplicate application already exists"),
                "application with duplicate name addition allowed");

        APIStoreRestClient apiStoreRestClient2 = new APIStoreRestClient(storeURLHttp);

        apiStoreRestClient2.login("admin@wso2.com",
                "wso2@123");
        apiData = apiStoreRestClient2.addApplication(
                "carbonSuperApp", "Gold", "", "super tenant app").getData();
        Assert.assertTrue(apiData.contains("{\"error\" : false}"),
                "application with same name addition not allowed in other tenant");

        apiStoreRestClient1.addApplication("carbonSuperApp", "Gold", "", "super tenant app");
        apiData = apiStoreRestClient1.removeApplication("carbonSuperApp").getData();
        Assert.assertTrue(apiData.contains("{\"error\" : false}"),
                "application deletion failed");

    }

    @Test(groups = {"wso2.am"}, description = "API Life cycle login to store")
    public void testLoginToStoreTestCase()
            throws Exception {

        //Try login to publisher with tenant subscriber user
        String APICreatorRole = "APICreatorRole";
        String APIPublisherRole = "APIPublisherRole";
        String APIPublisherUser = "APIPublisherUser";
        String APICreatorUser = "APICreatorUser";
        String password = "password@123";
        boolean loginFailed = false;
        String errorString = "";

        APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp);

        String[] createPermissions = {
                "/permission/admin/login",
                "/permission/admin/manage/api/create"};

        if (!userManagementClient.roleNameExists(APICreatorRole)) {
            userManagementClient.addRole(APICreatorRole, null, createPermissions);
        }

        if ((userManagementClient != null) &&
                !userManagementClient.userNameExists(APICreatorRole, APICreatorUser)) {
            userManagementClient.addUser(APICreatorUser, password,
                    new String[]{APICreatorRole}, null);
        }

        String[] publishPermissions = {
                "/permission/admin/login",
                "/permission/admin/manage/api/publish"};

        if (!userManagementClient.roleNameExists(APIPublisherRole)) {
            userManagementClient.addRole(APIPublisherRole, null, publishPermissions);
        }

        if ((userManagementClient != null) &&
                !userManagementClient.userNameExists(APIPublisherRole, APIPublisherUser)) {
            userManagementClient.addUser(APIPublisherUser, password,
                    new String[]{APIPublisherRole}, null);
        }

        try {
            apiStoreRestClient.login("invaliduser", "invaliduser@123");
        } catch (Exception e) {
            loginFailed = true;
            errorString = e.getMessage().toString();
        }

        Assert.assertTrue(loginFailed && errorString.contains("Operation not successful: " +
                "Login failed.Please recheck the username and password and try again"),
                "Invalid user can login to the API store");
        loginFailed = false;

        try {
            apiStoreRestClient.login(APICreatorUser, password);
        } catch (Exception e) {
            loginFailed = true;
            errorString = e.getMessage().toString();
        }

        Assert.assertTrue(loginFailed && errorString.contains("Login failed.Insufficient Privileges"),
                "API creator can login to the API store");
        loginFailed = false;

        try {
            apiStoreRestClient.login(APIPublisherUser, password);
        } catch (Exception e) {
            loginFailed = true;
            errorString = e.getMessage().toString();
        }

        Assert.assertTrue(loginFailed && errorString.contains("Login failed.Insufficient Privileges"),
                "API publisher can login to the API store");

    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {

        APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp);
        apiPublisherRestClient.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());

        /*apiPublisherRestClient.deleteAPI("APILifeCycleTestAPIPublic", "1.0.0", "admin");
        apiPublisherRestClient.deleteAPI("APILifeCycleTestAPIDomainOnly", "1.0.0", "admin");
        apiPublisherRestClient.deleteAPI("APILifeCycleTestAPIRoles", "1.0.0", "admin");*/

        Thread.sleep(5000);
        super.cleanup();
    }
}


text:
#include <burger.h>

/********************************

	Fade the palette to a color set

********************************/

void FadeTo(Word PaletteNum)
{
	FadeToPtr(LoadAResource(PaletteNum));   /* Load in the resource file */
	ReleaseAResource(PaletteNum);   /* Release the resource data */
}


text:
from codecs import open
from setuptools import setup

from libmt94x import __version__

def read_file(filepath):
    with open(filepath, 'rb+', 'utf-8') as f:
        content = f.read()

    return content.strip()

CLASSIFIERS = [
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Libraries :: Python Modules',
    'Development Status :: 5 - Production/Stable',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2.7',
]

setup(
    name='python-libmt94x',
    version=__version__,
    author='Ginger Payments',
    author_email='dev@gingerpayments.com',
    description='This library generates bank statements in MT940/MT942 format',
    long_description=(
        '%s\n\n%s' % (
            read_file('README.rst'),
            read_file('HISTORY.rst'),
        )
    ),
    url='https://github.com/gingerpayments/python-libmt94x',
    license='MIT',
    platforms=['OS Independent'],
    classifiers=CLASSIFIERS,
    packages=['libmt94x'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'Unidecode<0.5',  # translates unicode characters to ascii
        'pycountry<2.0',  # provides currency codes
    ],
)


text:
apetools.devices.adbdevice.AdbDevice.noise
==========================================

.. currentmodule:: apetools.devices.adbdevice

.. autoattribute:: AdbDevice.noise


text:
package org.apache.lucene.benchmark.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Split the Reuters SGML documents into Simple Text files containing: Title, Date, Dateline, Body
 */
public class ExtractReuters {
  private File reutersDir;
  private File outputDir;
  private static final String LINE_SEPARATOR = System.getProperty("line.separator");

  public ExtractReuters(File reutersDir, File outputDir) {
    this.reutersDir = reutersDir;
    this.outputDir = outputDir;
    System.out.println("Deleting all files in " + outputDir);
    for (File f : outputDir.listFiles()) {
      f.delete();
    }
  }

  public void extract() {
    File[] sgmFiles = reutersDir.listFiles(new FileFilter() {
      @Override
      public boolean accept(File file) {
        return file.getName().endsWith(".sgm");
      }
    });
    if (sgmFiles != null && sgmFiles.length > 0) {
      for (File sgmFile : sgmFiles) {
        extractFile(sgmFile);
      }
    } else {
      System.err.println("No .sgm files in " + reutersDir);
    }
  }

  Pattern EXTRACTION_PATTERN = Pattern
      .compile("<TITLE>(.*?)</TITLE>|<DATE>(.*?)</DATE>|<BODY>(.*?)</BODY>");

  private static String[] META_CHARS = { "&", "<", ">", "\"", "'" };

  private static String[] META_CHARS_SERIALIZATIONS = { "&", "<",
      ">", """, "'" };

  /**
   * Override if you wish to change what is extracted
   */
  protected void extractFile(File sgmFile) {
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sgmFile), StandardCharsets.UTF_8));

      StringBuilder buffer = new StringBuilder(1024);
      StringBuilder outBuffer = new StringBuilder(1024);

      String line = null;
      int docNumber = 0;
      while ((line = reader.readLine()) != null) {
        // when we see a closing reuters tag, flush the file

        if (line.indexOf("</REUTERS") == -1) {
          // Replace the SGM escape sequences

          buffer.append(line).append(' ');// accumulate the strings for now,
                                          // then apply regular expression to
                                          // get the pieces,
        } else {
          // Extract the relevant pieces and write to a file in the output dir
          Matcher matcher = EXTRACTION_PATTERN.matcher(buffer);
          while (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
              if (matcher.group(i) != null) {
                outBuffer.append(matcher.group(i));
              }
            }
            outBuffer.append(LINE_SEPARATOR).append(LINE_SEPARATOR);
          }
          String out = outBuffer.toString();
          for (int i = 0; i < META_CHARS_SERIALIZATIONS.length; i++) {
            out = out.replaceAll(META_CHARS_SERIALIZATIONS[i], META_CHARS[i]);
          }
          File outFile = new File(outputDir, sgmFile.getName() + "-"
              + (docNumber++) + ".txt");
          // System.out.println("Writing " + outFile);
          OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8);
          writer.write(out);
          writer.close();
          outBuffer.setLength(0);
          buffer.setLength(0);
        }
      }
      reader.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) {
    if (args.length != 2) {
      usage("Wrong number of arguments ("+args.length+")");
      return;
    }
    File reutersDir = new File(args[0]);
    if (!reutersDir.exists()) {
      usage("Cannot find Path to Reuters SGM files ("+reutersDir+")");
      return;
    }

    // First, extract to a tmp directory and only if everything succeeds, rename
    // to output directory.
    File outputDir = new File(args[1]);
    outputDir = new File(outputDir.getAbsolutePath() + "-tmp");
    outputDir.mkdirs();
    ExtractReuters extractor = new ExtractReuters(reutersDir, outputDir);
    extractor.extract();
    // Now rename to requested output dir
    outputDir.renameTo(new File(args[1]));
  }

  private static void usage(String msg) {
    System.err.println("Usage: "+msg+" :: java -cp <...> org.apache.lucene.benchmark.utils.ExtractReuters <Path to Reuters SGM files> <Output Path>");
  }

}


text: sed -i '' '/const dom = window.shared.ReactHelpers.dom;/d' "$TARGET"


text:
extern int MPCLApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);

// Forward declaration.
@protocol MPCLApplicationDelegate;

/// \brief The \c MPCLApplication class provides a centralized point of control and coordination
/// for command line applications.
///
/// Every application must have exactly one instance of \c MPCLApplication (or a subclass). When an
/// application is launched, the \c MPCLApplicationMain function is called; among its other tasks,
/// this function creates a singleton \c MPCLApplication object. Thereafter you can access this
/// object by invoking the \c sharedApplication class method.
///
/// The application object is typically assigned a delegate, an object that the application informs
/// of significant runtime events—for example, application launch and application termination—giving
/// it an opportunity to respond appropriately.
@interface MPCLApplication : NSObject

/// \brief Returns the singleton application instance.
/// \returns The application instance is created in the \c MPCLApplicationMain function.
+ (instancetype)sharedApplication;

/// The delegate of the application object.
@property (nonatomic, assign) id <MPCLApplicationDelegate> delegate;

/// \brief The binary path of an application.
/// This path points to the binary file that is currently running. It is usually part of \c argv and
/// extracted by \c MPCLApplicationMain.
@property (nonatomic, copy, readonly) NSString *binaryPath;

/// \brief Starts the main event loop.
- (void)run;

/// \brief Terminates the application.
/// When invoked, this method performs several steps to process the termination request. First, it
/// calls the delegate's \c applicationShouldTerminate: method. If \c applicationShouldTerminate:
/// returns \c NO, termination process is aborted and control is handed back to the main event loop.
/// If the method returns \c YES, the application calls the delegate's \c applicationWillTerminate:
/// method and terminates the application.
- (void)terminate;

@end

/// The \c MPCLApplicationDelegate protocol declares methods that are implemented by the delegate of
/// the singleton \c MPCLApplication object. These methods provide you with information about key
/// events in an application's execution such as when it finished launching and when it terminates.
/// Implementing these methods gives you a chance to respond to these system events and respond
/// appropriately.
@protocol MPCLApplicationDelegate <NSObject>

/// \brief Tells the delegate that the launch process is almost done and the app is almost ready to run.
/// You should use this method to complete your app's initialization, to retrieve the launch arguments
/// and to make any final tweaks.
/// \param application The delegating application object.
/// \param arguments The launch arguments represented as an array containing \c NSString elements.
/// The usual path to the binary is not part of this array but can be accessed via the \c binaryPath
/// property.
/// \returns \c NO if the application cannot handle the launch arguments, otherwise return YES.
- (BOOL)application:(MPCLApplication *)application didFinishLaunchingWithArguments:(NSArray *)arguments;

@optional

/// \brief Sent to notify the delegate that the application is about to terminate.
/// This method is called after the \c terminate method has been called. Generally, you should return
/// \c YES to allow the termination to complete, but you can cancel the termination as needed.
/// \param application The delegating application object.
/// \returns \c YES to terminate the application, \c NO to cancel the termination process.
- (BOOL)applicationShouldTerminate:(MPCLApplication *)application;

/// \brief Tells the delegate when the application is about to terminate.
/// \param application The delegating application object.
- (void)applicationWillTerminate:(MPCLApplication *)application;

@end


text:
CKEDITOR.plugins.setLang( 'docprops', 'de', {
	bgColor: 'Hintergrundfarbe',
	bgFixed: 'Nichtrollender (feststehender) Hintergrund',
	bgImage: 'Hintergrundbild-URL',
	charset: 'Zeichensatzkodierung',
	charsetASCII: 'ASCII',
	charsetCE: 'Zentraleuropäisch',
	charsetCR: 'Kyrillisch',
	charsetCT: 'Traditionelles Chinesisch (Big5)',
	charsetGR: 'Griechisch',
	charsetJP: 'Japanisch',
	charsetKR: 'Koreanisch',
	charsetOther: 'Andere Zeichensatzkodierung',
	charsetTR: 'Türkisch',
	charsetUN: 'Unicode (UTF-8)',
	charsetWE: 'Westeuropäisch',
	chooseColor: 'Auswählen',
	design: 'Design',
	docTitle: 'Seitentitel',
	docType: 'Dokumententypüberschrift',
	docTypeOther: 'Andere Dokumententypüberschrift',
	label: 'Dokumenteigenschaften',
	margin: 'Seitenränder',
	marginBottom: 'Unten',
	marginLeft: 'Links',
	marginRight: 'Rechts',
	marginTop: 'Oben',
	meta: 'Metadaten',
	metaAuthor: 'Autor',
	metaCopyright: 'Copyright',
	metaDescription: 'Dokumentbeschreibung',
	metaKeywords: 'Schlüsselwörter (durch Komma getrennt)',
	other: 'Andere...',
	previewHtml: '
Das ist ein Beispieltext. Du schreibst in CKEditor.
',
	title: 'Dokumenteigenschaften',
	txtColor: 'Textfarbe',
	xhtmlDec: 'Beziehe XHTML Deklarationen ein'
} );


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/lv_sensor"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAllCaps="false"
        android:text="light sensor"/>

</LinearLayout>


text:
package com.aishang.app.ui.HotelDetail;

import com.aishang.app.data.model.JHotelRoomCatListByhotelIDResult;
import java.util.List;

/**
 * Created by song on 2016/3/11.
 */
public class RoomCat {
  private JHotelRoomCatListByhotelIDResult.GRoomTypeListEntity roomTypeListEntity;
  private List<JHotelRoomCatListByhotelIDResult.HotelRoomCatListEntity> catListEntities;

  public RoomCat(JHotelRoomCatListByhotelIDResult.GRoomTypeListEntity roomTypeListEntity,
      List<JHotelRoomCatListByhotelIDResult.HotelRoomCatListEntity> catListEntities) {
    this.roomTypeListEntity = roomTypeListEntity;
    this.catListEntities = catListEntities;
  }

  public JHotelRoomCatListByhotelIDResult.GRoomTypeListEntity getRoomTypeListEntity() {
    return roomTypeListEntity;
  }

  public void setRoomTypeListEntity(
      JHotelRoomCatListByhotelIDResult.GRoomTypeListEntity roomTypeListEntity) {
    this.roomTypeListEntity = roomTypeListEntity;
  }

  public List<JHotelRoomCatListByhotelIDResult.HotelRoomCatListEntity> getCatListEntities() {
    return catListEntities;
  }

  public void setCatListEntities(
      List<JHotelRoomCatListByhotelIDResult.HotelRoomCatListEntity> catListEntities) {
    this.catListEntities = catListEntities;
  }

  public void addCatEntity(JHotelRoomCatListByhotelIDResult.HotelRoomCatListEntity entity) {
    catListEntities.add(entity);
  }
}


text:
class SettingsController < ApplicationController
  before_action :authenticate_user!
  before_action :authorize_user
  before_action :set_setting, only: [:edit, :update]

  def edit
  end

  def update
    respond_to do |format|
      if @setting.update(setting_params)
        format.html { redirect_to edit_setting_url(@setting), notice: 'Setting was successfully updated.' }
        format.json { render :edit, status: :ok, location: @setting }
      else
        format.html { render :edit }
        format.json { render json: @setting.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def set_setting
    @setting = Setting.friendly.find(params[:id])
  end

  def setting_params
    params.require(:setting).permit(config: [:site_title, :site_description, :site_keywords, :site_footer, :google_analytics_tracking_id, :email, :whatsup, network: [github: [:handle, :url], facebook: [:handle, :url], twitter: [:handle, :url]]])
  end

  def authorize_user
    authorize Setting
  end
end


text:
'use strict';

const metasync = require('..');
const metatests = require('metatests');

metatests.test('successful some', (test) => {
  const arr = [1, 2, 3];

  const predicate = (x, callback) => callback(null, x % 2 === 0);
  metasync.some(arr, predicate, (err, accepted) => {
    test.error(err);
    test.strictSame(accepted, true);
    test.end();
  });
});

metatests.test('failing some', (test) => {
  const arr = [1, 2, 3];

  const predicate = (x, callback) => callback(null, x > 3);
  metasync.some(arr, predicate, (err, accepted) => {
    test.error(err);
    test.strictSame(accepted, false);
    test.end();
  });
});

metatests.test('erroneous some', (test) => {
  const arr = [1, 2, 3];
  const someError = new Error('Some error');

  const predicate = (x, callback) =>
    x % 2 === 0 ? callback(someError) : callback(null, false);
  metasync.some(arr, predicate, (err, accepted) => {
    test.strictSame(err, someError);
    test.strictSame(accepted, undefined);
    test.end();
  });
});

metatests.test('some with empty array', (test) => {
  const arr = [];

  const predicate = (x, callback) => callback(null, x > 3);
  metasync.some(arr, predicate, (err, accepted) => {
    test.error(err);
    test.strictSame(accepted, false);
    test.end();
  });
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

		    <link rel="stylesheet" type="text/css" href="Styles/branding.css"/>
		    		<title>How to use the SPSF?</title>
				<meta name="Description" content="" />

How to use the SPSF?

How to use the SharePoint Software Factory?

        To unleash the power of the SharePoint Software Factory, the SharePoint application project has to fulfill some requirements like solution/project structure and existing configuration files. Creating such a project with SPSF does NOT leave you stuck with it forever. At any time you wish to continue development without SPSF, you can uninstall it and your projects will still be compilable and deployable. After successful installation of SPSF SharePoint SoftwareFactory you get started in Visual Studio.

Create a new project in Visual Studio

		Start Visual Studio 2012 and click "File -> New -> Project" to create a new Visual Studio project.

		In the project template dialog under the section "Guidance Packages -> SharePoint SoftwareFactory" choose an appropriate project template e.g. "SharePoint 2013 - Application".

		Click "OK" and and the SharePoint Project Wizard will open.

Run SPSF recipes to create SharePoint code

		Most SPSF recipes are displayed in context menus depending on the current selection.
		For instance the recipe "Create new Content Type" is only displayed on projects which will create a .wsp solution and on existing features in that project.

		Alternatively you can use the "Add -> New Item..." (Ctrl+Shift+A) dialog to run the SPSF recipes.

        The recipe will open a wizard, which allows you to specify the required information and choose dependcies from existing artefacts in your project or in out of the box SharePoint.

        When you finish the wizard the necessary code will be generated by SPSF following best practices in naming the files, classes and structuring of the solution. If you enabled resource managment upon project creation all language resources will be automatically stored in a .resx file.

        All your settings in the wizard are reflected in the generated files.

Build a deployment package

        Whenever you require a deployment package which contains all WSP files or if the solution should be deployed to a different farm, you can build the "Deployment" project which collects all solutions, deployment configurations and the necessary PowerShell scripts.

						Disclaimer: The views and opinions expressed in this documentation and in SPSF are those of the authors and do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. All trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.

						SharePoint Software Factory, Version 4.1.3.2705, GPLv2, see http://spsf.codeplex.com for more information


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Core Plot (Mac OS): Source/NSDecimalNumberExtensions.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="customdoxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>

Core Plot (Mac OS)

Cocoa plotting framework for Mac OS X and iOS

Main Page

Animation & Constants

Classes

Files

File List

File Members

NSDecimalNumberExtensions.h

Go to the documentation of this file.

    1 #import <Foundation/Foundation.h>

    2 #import <QuartzCore/QuartzCore.h>

    3

    7 @interface NSDecimalNumber(CPTExtensions)

    8

    9 @end

Generated by


text:
/*
 * FlushableOutgoingEntryReceiver.h
 *
 *  Created on: Sep 22, 2012
 *      Author: Mitchell Wills
 */

#ifndef FLUSHABLEOUTGOINGENTRYRECEIVER_H_
#define FLUSHABLEOUTGOINGENTRYRECEIVER_H_

class FlushableOutgoingEntryReceiver;

#include "networktables2/OutgoingEntryReceiver.h"

class FlushableOutgoingEntryReceiver : public OutgoingEntryReceiver
{
public:
	virtual ~FlushableOutgoingEntryReceiver()
	{
	}
	virtual void flush() = 0;
	virtual void ensureAlive() = 0;
};

#endif /* FLUSHABLEOUTGOINGENTRYRECEIVER_H_ */


text:
package theinternet.pages;

import com.frameworkium.core.ui.annotations.Visible;
import com.frameworkium.core.ui.pages.BasePage;
import io.qameta.allure.Step;
import org.openqa.selenium.support.FindBy;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.CheckBox;

import java.util.List;
import java.util.stream.Stream;

public class CheckboxesPage extends BasePage<CheckboxesPage> {

    @Visible
    @Name("All checkboxes")
    @FindBy(css = "form input[type='checkbox']")
    private List<CheckBox> allCheckboxes;

    @Step("Set all the checkboxes to true")
    public CheckboxesPage checkAllCheckboxes() {
        allCheckboxes.forEach(CheckBox::select);
        return this;
    }

    @Step("Return the checked status of all the checkboxes")
    public Stream<Boolean> getAllCheckboxCheckedStatus() {
        return allCheckboxes.stream()
                .map(CheckBox::isSelected);
    }

}


text:
"""
Module contains task classes used by balancer.
"""
import abc

from dnrm.openstack.common import excutils
from dnrm.openstack.common import log
from dnrm.resources import base

LOG = log.getLogger(__name__)

class Task(object):
    """Base class for task objects."""

    __metaclass__ = abc.ABCMeta

    def __init__(self, resource):
        self._resource = resource

    @abc.abstractmethod
    def execute(self, driver_factory):
        """Called by task queue workers when they start to work on task."""
        pass

    def get_resource_id(self):
        """Returns resource id that task is working on."""
        return self._resource['id']

class StartTask(Task):
    """Task that puts resource to started state."""

    in_states = (base.STATE_STOPPED,)
    process_state = base.STATE_STARTING
    success_state = base.STATE_STARTED
    fail_state = base.STATE_ERROR

    def execute(self, driver_factory):
        resource = self._resource
        driver = driver_factory.get(resource['type'])
        driver.init(resource)
        return resource

class StopTask(Task):
    """Task that puts resource to stopped state."""

    in_states = (base.STATE_STARTED,)
    process_state = base.STATE_STOPPING
    success_state = base.STATE_STOPPED
    fail_state = base.STATE_ERROR

    def execute(self, driver_factory):
        resource = self._resource
        driver = driver_factory.get(resource['type'])
        driver.stop(resource)
        return resource

class WipeTask(Task):
    """Task that wipes task state."""

    in_states = (base.STATE_STARTED,)
    process_state = base.STATE_WIPING
    success_state = base.STATE_STARTED
    fail_state = base.STATE_ERROR

    def execute(self, driver_factory):
        resource = self._resource
        driver = driver_factory.get(resource['type'])
        driver.wipe(resource)
        return resource

class DeleteTask(Task):
    """Task that marks resource as deleted."""

    in_states = (base.STATE_ERROR, base.STATE_STOPPED)
    process_state = base.STATE_DELETING
    success_state = base.STATE_DELETED
    fail_state = base.STATE_ERROR

    def __init__(self, resource, force=False):
        super(DeleteTask, self).__init__(resource)
        self._force = force

    def execute(self, driver_factory):
        resource = self._resource
        driver = driver_factory.get(resource['type'])
        try:
            driver.stop(resource)
        except Exception:
            with excutils.save_and_reraise_exception() as exc_reraiser:
                LOG.exception(_('Failed to delete resource'))
                exc_reraiser.reraise = not self._force
        return resource


text:
API="${API_ORIGIN:-http://localhost:4741}"
URL_PATH="/examples"
curl "${API}${URL_PATH}" \
  --include \
  --request GET \
  --header "Authorization: Token token=$TOKEN"

echo


text:
<?php

declare(strict_types=1);

namespace Picodexter\ParameterEncryptionBundle\Configuration\Key;

use Picodexter\ParameterEncryptionBundle\Exception\Configuration\UnknownKeyTypeException;

/**
 * KeyConfigurationFactoryInterface.
 */
interface KeyConfigurationFactoryInterface
{
    /**
     * Create key configuration.
     *
     * @param array $keyConfig
     *
     * @throws UnknownKeyTypeException
     */
    public function createKeyConfiguration(array $keyConfig);
}


text:
module Types where

import qualified GHC

type Token = GHC.Located GHC.Token


text:
package types

import "github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/noderole"

// NodeInfo type.
//
// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/nodes/info/types.ts#L30-L66
type NodeInfo struct {
	Aggregations map[string]NodeInfoAggregation `json:"aggregations,omitempty"`
	Attributes   map[string]string              `json:"attributes"`
	BuildFlavor  string                         `json:"build_flavor"`
	// BuildHash Short hash of the last git commit in this release.
	BuildHash string `json:"build_hash"`
	BuildType string `json:"build_type"`
	// Host The node's host name.
	Host   string          `json:"host"`
	Http   *NodeInfoHttp   `json:"http,omitempty"`
	Ingest *NodeInfoIngest `json:"ingest,omitempty"`
	// Ip The node's IP address.
	Ip      string        `json:"ip"`
	Jvm     *NodeJvmInfo  `json:"jvm,omitempty"`
	Modules []PluginStats `json:"modules,omitempty"`
	// Name The node's name
	Name       string                        `json:"name"`
	Network    *NodeInfoNetwork              `json:"network,omitempty"`
	Os         *NodeOperatingSystemInfo      `json:"os,omitempty"`
	Plugins    []PluginStats                 `json:"plugins,omitempty"`
	Process    *NodeProcessInfo              `json:"process,omitempty"`
	Roles      []noderole.NodeRole           `json:"roles"`
	Settings   *NodeInfoSettings             `json:"settings,omitempty"`
	ThreadPool map[string]NodeThreadPoolInfo `json:"thread_pool,omitempty"`
	// TotalIndexingBuffer Total heap allowed to be used to hold recently indexed documents before they
	// must be written to disk. This size is a shared pool across all shards on this
	// node, and is controlled by Indexing Buffer settings.
	TotalIndexingBuffer *int64 `json:"total_indexing_buffer,omitempty"`
	// TotalIndexingBufferInBytes Same as total_indexing_buffer, but expressed in bytes.
	TotalIndexingBufferInBytes *ByteSize          `json:"total_indexing_buffer_in_bytes,omitempty"`
	Transport                  *NodeInfoTransport `json:"transport,omitempty"`
	// TransportAddress Host and port where transport HTTP connections are accepted.
	TransportAddress string `json:"transport_address"`
	// Version Elasticsearch version running on this node.
	Version string `json:"version"`
}

// NewNodeInfo returns a NodeInfo.
func NewNodeInfo() *NodeInfo {
	r := &NodeInfo{
		Aggregations: make(map[string]NodeInfoAggregation, 0),
		Attributes:   make(map[string]string, 0),
		ThreadPool:   make(map[string]NodeThreadPoolInfo, 0),
	}

	return r
}


text:
package erjang.driver.js;

import java.util.concurrent.locks.ReentrantLock;

import erjang.EString;
import erjang.driver.EDriver;
import erjang.driver.EDriverControl;

public class EJSDriver implements EDriver {

	private kilim.ReentrantLock lock;

	@Override
	public String driverName() {
		return "erlang_js_drv";
	}

	@Override
	public void finish() {
	}

	@Override
	public ReentrantLock getLock() {
		if (lock == null) {
			lock = new kilim.ReentrantLock();
		}
		return lock;
	}

	@Override
	public EDriverControl start(EString command) {
		return new EJSDriverInstance(this);
	}

	@Override
	public boolean useDriverLevelLocking() {
		return false;
	}

}


text:
package com.reactnativenavigation.utils;

public interface Task<T> {
    void run(T param);
}


text:
package edu.jsykora.sql2stream.integration;

import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import edu.jsykora.sql2stream.InputContainer;
import edu.jsykora.sql2stream.SQL2Stream;
import edu.jsykora.sql2stream.SQL2StreamException;
import edu.jsykora.sql2stream.element.BaseElement;
import edu.jsykora.sql2stream.iterator.ResultIterator;
import edu.jsykora.sql2stream.models.TestingModel;

public class WhereIntegrationTest {
    private List<TestingModel> list1;
    private List<TestingModel> list2;

    @Before
    public void setUp() throws Exception {
        list1 = new ArrayList<>();
        list1.add(new TestingModel("test", 1));
        list1.add(new TestingModel("testing", 1));
        list1.add(new TestingModel("test", 2));
        list1.add(new TestingModel("testing", 2));

        list2 = new ArrayList<>();
        list2.add(new TestingModel("testing", 1));
        list2.add(new TestingModel("testing", 2));
        list2.add(new TestingModel("test", 1));
        list2.add(new TestingModel("test", 2));
    }

    @Test
    public void OneConditionTest() throws SQL2StreamException {
        String sql = "SELECT * FROM list1 t WHERE t.number=1";
        SQL2Stream<TestingModel> test = new SQL2Stream<>(sql, new InputContainer<>(list1, TestingModel.class));
        ResultIterator<BaseElement<TestingModel>> result = test.interpret();
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        if (count != 2) {
            fail();
        }
    }

    @Test
    public void TwoConditionsANDTest() throws SQL2StreamException {
        String sql = "SELECT * FROM list1 t WHERE t.number=1 AND t.name='test'";
        SQL2Stream<TestingModel> test = new SQL2Stream<>(sql, new InputContainer<>(list1, TestingModel.class));
        ResultIterator<BaseElement<TestingModel>> result = test.interpret();
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        if (count != 1) {
            fail();
        }
    }

    @Test
    public void TwoConditionsORTest() throws SQL2StreamException {
        String sql = "SELECT * FROM list1 t WHERE t.number=1 OR t.name='test'";
        SQL2Stream<TestingModel> test = new SQL2Stream<>(sql, new InputContainer<>(list1, TestingModel.class));
        ResultIterator<BaseElement<TestingModel>> result = test.interpret();
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        if (count != 3) {
            fail();
        }
    }

    @Test
    public void TwoConditionsANDNOTTest() throws SQL2StreamException {
        String sql = "SELECT * FROM list1 t WHERE t.number=1 AND NOT t.name='test'";
        SQL2Stream<TestingModel> test = new SQL2Stream<>(sql, new InputContainer<>(list1, TestingModel.class));
        ResultIterator<BaseElement<TestingModel>> result = test.interpret();
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        if (count != 1) {
            fail();
        }
    }

    @Test
    public void OneConditionAndJoinTest() throws SQL2StreamException {
        String sql = "SELECT * FROM list1 t JOIN list2 u ON t.number=u.number WHERE t.number=1";
        SQL2Stream<TestingModel> test = new SQL2Stream<>(sql, new InputContainer<>(list1, TestingModel.class), new InputContainer<>(list2, TestingModel.class));
        ResultIterator<BaseElement<TestingModel>> result = test.interpret();
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        if (count != 4) {
            fail();
        }
    }

    @Test
    public void TwoConditionsANDAndJoinTest() throws SQL2StreamException {
        String sql = "SELECT * FROM list1 t JOIN list2 u ON t.number=u.number WHERE t.number=1 AND u.number=0";
        SQL2Stream<TestingModel> test = new SQL2Stream<>(sql, new InputContainer<>(list1, TestingModel.class), new InputContainer<>(list2, TestingModel.class));
        ResultIterator<BaseElement<TestingModel>> result = test.interpret();
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        if (count != 0) {
            fail();
        }
    }
}


text:
require "md2pdf/version"
require "md2pdf/converter"
require "md2pdf/template"
require "md2pdf/cli"