text:
package io.realm;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.Nullable;

import io.realm.internal.RealmNotifier;
import io.realm.internal.Util;
import io.realm.internal.android.AndroidCapabilities;
import io.realm.internal.android.AndroidRealmNotifier;
import io.realm.internal.async.RealmAsyncTaskImpl;
import io.realm.internal.network.AuthenticateResponse;
import io.realm.internal.network.AuthenticationServer;
import io.realm.internal.network.ChangePasswordResponse;
import io.realm.internal.network.ExponentialBackoffTask;
import io.realm.internal.network.LogoutResponse;
import io.realm.internal.network.LookupUserIdResponse;
import io.realm.internal.objectserver.Token;
import io.realm.log.RealmLog;

/**
 * This class represents a user on the Realm Object Server. The credentials are provided by various 3rd party
 * providers (Facebook, Google, etc.).
 *

 * A user can log in to the Realm Object Server, and if access is granted, it is possible to synchronize the local
 * and the remote Realm. Moreover, synchronization is halted when the user is logged out.
 *

 * It is possible to persist a user. By retrieving a user, there is no need to log in to the 3rd party provider again.
 * Persisting a user between sessions, the user's credentials are stored locally on the device, and should be treated
 * as sensitive data.
 */
public class SyncUser {
    private final String identity;
    private Token refreshToken;
    private final URL authenticationUrl;
    // maps all RealmConfiguration and accessToken, using this SyncUser.
    private final Map<SyncConfiguration, Token> realms = new HashMap<SyncConfiguration, Token>();

    SyncUser(Token refreshToken, URL authenticationUrl) {
        this.identity = refreshToken.identity();
        this.authenticationUrl = authenticationUrl;
        this.refreshToken = refreshToken;
    }

    /**
     * Returns the current user that is logged in and still valid.
     * A user is invalidated when he/she logs out or the user's access token expires.
     *
     * @return current {@link SyncUser} that has logged in and is still valid. {@code null} if no user is logged in or the user has
     * expired.
     * @throws IllegalStateException if multiple users are logged in.
     */
    public static SyncUser currentUser() {
        SyncUser user = SyncManager.getUserStore().getCurrent();
        if (user != null && user.isValid()) {
            return user;
        }
        return null;
    }

    /**
     * Returns all valid users known by this device.
     * A user is invalidated when he/she logs out or the user's access token expires.
     *
     * @return a map from user identifier to user. It includes all known valid users.
     */
    public static Map<String, SyncUser> all() {
        UserStore userStore = SyncManager.getUserStore();
        Collection<SyncUser> storedUsers = userStore.allUsers();
        Map<String, SyncUser> map = new HashMap<>();
        for (SyncUser user : storedUsers) {
            if (user.isValid()) {
                map.put(user.getIdentity(), user);
            }
        }
        return Collections.unmodifiableMap(map);
    }

    /**
     * Loads a user that has previously been serialized using {@link #toJson()}.
     *
     * @param user JSON string representing the user.
     * @return the user object.
     * @throws IllegalArgumentException if the JSON couldn't be converted to a valid {@link SyncUser} object.
     */
    public static SyncUser fromJson(String user) {
        try {
            JSONObject obj = new JSONObject(user);
            URL authUrl = new URL(obj.getString("authUrl"));
            Token userToken = Token.from(obj.getJSONObject("userToken"));//TODO rename to refresh_token
            return new SyncUser(userToken, authUrl);
        } catch (JSONException e) {
            throw new IllegalArgumentException("Could not parse user json: " + user, e);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("URL in JSON not valid: " + user, e);
        }
    }

    /**
     * Logs in the user to the Realm Object Server. This is done synchronously, so calling this method on the Android
     * UI thread will always crash. A logged in user is required to be able to create a {@link SyncConfiguration}.
     *
     * @param credentials credentials to use.
     * @param authenticationUrl server that can authenticate against.
     * @throws ObjectServerError if the login failed.
     * @throws IllegalArgumentException if the URL is malformed.
     */
    public static SyncUser login(final SyncCredentials credentials, final String authenticationUrl) throws ObjectServerError {
        URL authUrl;
        try {
            authUrl = new URL(authenticationUrl);
            // If no path segment is provided append `/auth` which is the standard location.
            if (authUrl.getPath().equals("")) {
                authUrl = new URL(authUrl.toString() + "/auth");
            }
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Invalid URL " + authenticationUrl + ".", e);
        }

        ObjectServerError error;
        try {
            AuthenticateResponse result;
            if (credentials.getIdentityProvider().equals(SyncCredentials.IdentityProvider.ACCESS_TOKEN)) {
                // Credentials using ACCESS_TOKEN as IdentityProvider are optimistically assumed to be valid already.
                // So log them in directly without contacting the authentication server. This is done by mirroring
                // the JSON response expected from the server.
                String userIdentifier = credentials.getUserIdentifier();
                String token = (String) credentials.getUserInfo().get("_token");
                boolean isAdmin = (Boolean) credentials.getUserInfo().get("_isAdmin");
                result = AuthenticateResponse.createValidResponseWithUser(userIdentifier, token, isAdmin);
            } else {
                final AuthenticationServer server = SyncManager.getAuthServer();
                result = server.loginUser(credentials, authUrl);
            }
            if (result.isValid()) {
                SyncUser user = new SyncUser(result.getRefreshToken(), authUrl);
                RealmLog.info("Succeeded authenticating user.\n%s", user);
                SyncManager.getUserStore().put(user);
                SyncManager.notifyUserLoggedIn(user);
                return user;
            } else {
                RealmLog.info("Failed authenticating user.\n%s", result.getError());
                error = result.getError();
            }
        } catch (Throwable e) {
            throw new ObjectServerError(ErrorCode.UNKNOWN, e);
        }
        throw error;
    }

    /**
     * Logs in the user to the Realm Object Server. A logged in user is required to be able to create a
     * {@link SyncConfiguration}.
     *
     * @param credentials credentials to use.
     * @param authenticationUrl server that the user is authenticated against.
     * @param callback callback when login has completed or failed. The callback will always happen on the same thread
     * as this this method is called on.
     * @return representation of the async task that can be used to cancel it if needed.
     * @throws IllegalArgumentException if not on a Looper thread.
     */
    public static RealmAsyncTask loginAsync(final SyncCredentials credentials, final String authenticationUrl, final Callback<SyncUser> callback) {
        checkLooperThread("Asynchronous login is only possible from looper threads.");
        return new Request<SyncUser>(SyncManager.NETWORK_POOL_EXECUTOR, callback) {
            @Override
            public SyncUser run() throws ObjectServerError {
                return login(credentials, authenticationUrl);
            }
        }.start();
    }

    /**
     * Log a user out, destroying their server state, unregistering them from the SDK, and removing
     * any synced Realms associated with them, from on-disk storage on next app launch (or directly
     * if all instances are closed).
     * If the user is already logged out or in an error state, this method does nothing.
     *
     * This method should be called whenever the application is committed to not using a user again
     * unless they are recreated. Failing to call this method may result in unused files and metadata
     * needlessly taking up space.
     *
     * Once the Object Server has confirmed the logout any registered {@link AuthenticationListener}
     * will be notified and user credentials will be deleted from this device.
     */
//    /* FIXME: Add this back to the javadoc when enable SyncConfiguration.Builder#deleteRealmOnLogout()
//

//     Any Realms owned by the user will be deleted, when the application restart.
//     */
    // this is a fire and forget, end user should not worry about the state of the async query
    @SuppressWarnings("FutureReturnValueIgnored")
    public void logout() {
        // Acquire lock to prevent users creating new instances
        synchronized (Realm.class) {
            if (!SyncManager.getUserStore().isActive(identity, authenticationUrl.toString())) {
                return; // Already logged out status
            }

            // Mark the user as logged out in the ObjectStore
            SyncManager.getUserStore().remove(identity, authenticationUrl.toString());

            // invalidate all pending refresh_token queries
            for (SyncConfiguration syncConfiguration : realms.keySet()) {
                SyncSession session = SyncManager.getSession(syncConfiguration);
                if (session != null) {
                    session.clearScheduledAccessTokenRefresh();
                }
            }

            // Remove all local tokens, preventing further connections.
            // don't remove identity as this SyncUser might be re-activated and we need
            // to avoid throwing a mismatch SyncConfiguration in RealmCache if we have
            // the similar SyncConfiguration using the same identity, but with different (new)
            // refresh-token.
            realms.clear();

            // Finally revoke server token. The local user is logged out in any case.
            final AuthenticationServer server = SyncManager.getAuthServer();
            // don't reference directly the refreshToken inside the revoke request
            // as it may revoke the newly acquired refresh_token
            final Token refreshTokenToBeRevoked = refreshToken;

            ThreadPoolExecutor networkPoolExecutor = SyncManager.NETWORK_POOL_EXECUTOR;
            networkPoolExecutor.submit(new ExponentialBackoffTask<LogoutResponse>(3) {

                @Override
                protected LogoutResponse execute() {
                    return server.logout(refreshTokenToBeRevoked, getAuthenticationUrl());
                }

                @Override
                protected void onSuccess(LogoutResponse response) {
                    SyncManager.notifyUserLoggedOut(SyncUser.this);
                }

                @Override
                protected void onError(LogoutResponse response) {
                    RealmLog.error("Failed to log user out.\n" + response.getError().toString());
                }
            });
        }
    }

    /**
     * Changes this user's password. This is done synchronously and involves the network, so calling this method on the
     * Android UI thread will always crash.
     *

     * WARNING: Changing a user's password through an authentication server that doesn't use HTTPS is a major
     * security flaw, and should only be done while testing.
     *
     * @param newPassword the user's new password.
     * @throws ObjectServerError if the password could not be changed.
     */
    public void changePassword(final String newPassword) throws ObjectServerError {
        //noinspection ConstantConditions
        if (newPassword == null) {
            throw new IllegalArgumentException("Not-null 'newPassword' required.");
        }
        AuthenticationServer authServer = SyncManager.getAuthServer();
        ChangePasswordResponse response = authServer.changePassword(refreshToken, newPassword, getAuthenticationUrl());
        if (!response.isValid()) {
            throw response.getError();
        }
    }

    /**
     * Changes another user's password. This is done synchronously and involves the network, so calling this method on the
     * Android UI thread will always crash.
     *

     * This user needs admin privilege in order to change someone else's password.
     *

     * WARNING: Changing a user's password through an authentication server that doesn't use HTTPS is a major
     * security flaw, and should only be done while testing.
     *
     * @param userId identity ({@link #getIdentity()}) of the user we want to change the password for.
     * @param newPassword the user's new password.
     * @throws ObjectServerError if the password could not be changed.
     */
    public void changePassword(final String userId, final String newPassword) throws ObjectServerError {
        //noinspection ConstantConditions
        if (newPassword == null) {
            throw new IllegalArgumentException("Not-null 'newPassword' required.");
        }

        if (Util.isEmptyString(userId)) {
            throw new IllegalArgumentException("None empty 'userId' required.");
        }

        if (userId.equals(getIdentity())) { // user want's to change his/her own password
            changePassword(newPassword);

        } else {
            if (!isAdmin()) {
                throw new IllegalStateException("User need to be admin in order to change another user's password.");
            }

            AuthenticationServer authServer = SyncManager.getAuthServer();
            ChangePasswordResponse response = authServer.changePassword(refreshToken, userId, newPassword, getAuthenticationUrl());
            if (!response.isValid()) {
                throw response.getError();
            }
        }
    }

    /**
     * Changes this user's password asynchronously.
     *

     * WARNING: Changing a users password using an authentication server that doesn't use HTTPS is a major
     * security flaw, and should only be done while testing.
     *
     * @param newPassword the user's new password.
     * @param callback callback when login has completed or failed. The callback will always happen on the same thread
     * as this method is called on.
     * @return representation of the async task that can be used to cancel it if needed.
     * @throws IllegalArgumentException if not on a Looper thread.
     */
    public RealmAsyncTask changePasswordAsync(final String newPassword, final Callback<SyncUser> callback) {
        checkLooperThread("Asynchronous changing password is only possible from looper threads.");
        //noinspection ConstantConditions
        if (callback == null) {
            throw new IllegalArgumentException("Non-null 'callback' required.");
        }
        return new Request<SyncUser>(SyncManager.NETWORK_POOL_EXECUTOR, callback) {
            @Override
            public SyncUser run() {
                changePassword(newPassword);
                return SyncUser.this;
            }
        }.start();
    }

    /**
     * Changes another user's password asynchronously.
     *

     * This user needs admin privilege in order to change someone else's password.
     *
     * WARNING: Changing a users password using an authentication server that doesn't use HTTPS is a major
     * security flaw, and should only be done while testing.
     *
     * @param userId identity ({@link #getIdentity()}) of the user we want to change the password for.
     * @param newPassword the user's new password.
     * @param callback callback when login has completed or failed. The callback will always happen on the same thread
     * as this method is called on.
     * @return representation of the async task that can be used to cancel it if needed.
     * @throws IllegalArgumentException if not on a Looper thread.
     */
    public RealmAsyncTask changePasswordAsync(final String userId, final String newPassword, final Callback<SyncUser> callback) {
        checkLooperThread("Asynchronous changing password is only possible from looper threads.");
        //noinspection ConstantConditions
        if (callback == null) {
            throw new IllegalArgumentException("Non-null 'callback' required.");
        }

        return new Request<SyncUser>(SyncManager.NETWORK_POOL_EXECUTOR, callback) {
            @Override
            public SyncUser run() {
                changePassword(userId, newPassword);
                return SyncUser.this;
            }
        }.start();
    }

    /**
     * Given a Realm Object Server authentication provider and a provider identifier for a user (for example, a username), look up and return user information for that user.
     *
     * @param providerUserIdentity The username or identity of the user as issued by the authentication provider.
     *                             In most cases this is different from the Realm Object Server-issued identity.
     * @param provider The authentication provider {@link io.realm.SyncCredentials.IdentityProvider} that manages the user whose information is desired.
     *
     * @return {@code SyncUser} associated with the given identity provider and providerId, or {@code null} in case
     * of an {@code invalid} provider or {@code providerId}.
     * @throws ObjectServerError in case of an error.
     */
    public SyncUserInfo retrieveInfoForUser(final String providerUserIdentity, final String provider) throws ObjectServerError {
        if (Util.isEmptyString(providerUserIdentity)) {
            throw new IllegalArgumentException("'providerUserIdentity' cannot be empty.");
        }

        if (Util.isEmptyString(provider)) {
            throw new IllegalArgumentException("'provider' cannot be empty.");
        }

        if (!isAdmin()) {
            throw new IllegalArgumentException("SyncUser needs to be admin in order to lookup other users ID.");
        }

        AuthenticationServer authServer = SyncManager.getAuthServer();
        LookupUserIdResponse response = authServer.retrieveUser(refreshToken, provider, providerUserIdentity, getAuthenticationUrl());
        if (!response.isValid()) {
            if (response.getError().getErrorCode() == ErrorCode.UNKNOWN_ACCOUNT) {
                return null;
            } else {
                throw response.getError();
            }
        } else {
            return SyncUserInfo.fromLookupUserIdResponse(response);
        }
    }

    /**
     * Given a Realm Object Server authentication provider and a provider identifier for a user (for example, a username), asynchronously look up and return user information for that user.
     *
     * @param providerUserIdentity The username or identity of the user as issued by the authentication provider.
     *                             In most cases this is different from the Realm Object Server-issued identity.
     * @param provider The authentication provider {@link io.realm.SyncCredentials.IdentityProvider} that manages the user whose information is desired.
     *
     * @return {@code SyncUser} associated with the given identity provider and providerId, or {@code null} in case
     * of an {@code invalid} provider or {@code providerId}.
     * @param callback callback when the lookup has completed or failed. The callback will always happen on the same thread
     * as this method is called on.
     * @return representation of the async task that can be used to cancel it if needed.
     */
    public RealmAsyncTask retrieveInfoForUserAsync(final String providerUserIdentity, final String provider, final Callback<SyncUserInfo> callback) {
        checkLooperThread("Asynchronously retrieving user is only possible from looper threads.");
        //noinspection ConstantConditions
        if (callback == null) {
            throw new IllegalArgumentException("Non-null 'callback' required.");
        }

        return new Request<SyncUserInfo>(SyncManager.NETWORK_POOL_EXECUTOR, callback) {
            @Override
            public SyncUserInfo run() throws ObjectServerError {
                return retrieveInfoForUser(providerUserIdentity, provider);
            }
        }.start();
    }

    private static void checkLooperThread(String errorMessage) {
        AndroidCapabilities capabilities = new AndroidCapabilities();
        capabilities.checkCanDeliverNotification(errorMessage);
    }

    /**
     * Returns a JSON token representing this user.
     *

     * Possession of this JSON token can potentially grant access to data stored on the Realm Object Server, so it
     * should be treated as sensitive data.
     *
     * @return JSON string representing this user. It can be converted back into a real user object using
     * {@link #fromJson(String)}.
     * @see #fromJson(String)
     */
    public String toJson() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("authUrl", authenticationUrl);
            obj.put("userToken", refreshToken.toJson());
            return obj.toString();
        } catch (JSONException e) {
            throw new RuntimeException("Could not convert SyncUser to JSON", e);
        }
    }

    /**
     * Returns {@code true} if the user is logged into the Realm Object Server. If this method returns {@code true} it
     * implies that the user has valid credentials that have not expired.
     *

     * The user might still have been logged out by the Realm Object Server which will not be detected before the
     * user tries to actively synchronize a Realm. If a logged out user tries to synchronize a Realm, an error will be
     * reported to the {@link SyncSession.ErrorHandler} defined by
     * {@link SyncConfiguration.Builder#errorHandler(SyncSession.ErrorHandler)}.
     *
     * @return {@code true} if the User is logged into the Realm Object Server, {@code false} otherwise.
     */
    public boolean isValid() {
        return refreshToken != null && refreshToken.expiresMs() > System.currentTimeMillis() && SyncManager.getUserStore().isActive(identity, authenticationUrl.toString());
    }

    /**
     * Returns {@code true} if this user is an administrator on the Realm Object Server, {@code false} otherwise.
     *

     * Administrators can access all Realms on the server as well as change the permissions of the Realms.
     *
     * @return {@code true} if the user is an administrator on the Realm Object Server, {@code false} otherwise.
     */
    public boolean isAdmin() {
        return refreshToken.isAdmin();
    }

    /**
     * Returns the identity of this user on the Realm Object Server. The identity is a guaranteed to be unique
     * among all users on the Realm Object Server.
     *
     * @return identity of the user on the Realm Object Server. If the user has logged out or the login has expired
     * {@code null} is returned.
     */
    public String getIdentity() {
        return identity;
    }

    /**
     * Returns this user's refresh token. This is the users credential for accessing the Realm Object Server and should
     * be treated as sensitive data.
     *
     * @return the user's refresh token. If this user has logged out or the login has expired {@code null} is returned.
     */
    Token getRefreshToken() {
        return refreshToken;
    }

    void setRefreshToken(Token refreshToken) {
        this.refreshToken = refreshToken;
    }

    /**
     * Returns all the valid sessions belonging to the user.
     *
     * @return the all valid sessions belong to the user.
     */
    public List<SyncSession> allSessions() {
        return SyncManager.getAllSessions(this);
    }

    /**
     * Checks if the user has access to the given Realm. Being authenticated means that the
     * user is known by the Realm Object Server and have been granted access to the given Realm.
     *
     * Authenticating will happen automatically as part of opening a Realm.
     */
    boolean isRealmAuthenticated(SyncConfiguration configuration) {
        Token token = realms.get(configuration);
        return token != null && token.expiresMs() > System.currentTimeMillis();
    }

    Token getAccessToken(SyncConfiguration configuration) {
        return realms.get(configuration);
    }

    void addRealm(SyncConfiguration syncConfiguration, Token accessToken) {
        realms.put(syncConfiguration, accessToken);
    }
    /**
     * Returns the {@link URL} where this user was authenticated.
     *
     * @return {@link URL} where the user was authenticated.
     */
    public URL getAuthenticationUrl() {
        return authenticationUrl;
    }

    // Creates the URL to the permission Realm based on the authentication URL.
    private static String getManagementRealmUrl(URL authUrl) {
        String scheme = "realm";
        if (authUrl.getProtocol().equalsIgnoreCase("https")) {
            scheme = "realms";
        }
        try {
            return new URI(scheme, authUrl.getUserInfo(), authUrl.getHost(), authUrl.getPort(),
                    "/~/__management", null, null).toString();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Could not create URL to the management Realm", e);
        }
    }

    /**
     * Returns an instance of the {@link PermissionManager} for this user that makes it possible to see, modify and create
     * permissions related to this users Realms.
     *

     * Every instance returned by this method must be closed by calling {@link PermissionManager#close()} when it
     * no longer is needed.
     *

     * The {@link PermissionManager} can only be opened from the main tread, calling this method from any other thread
     * will throw an {@link IllegalStateException}.
     *
     * @throws IllegalStateException if this method is not called from the UI thread.
     * @return an instance of the PermissionManager.
     */
    public PermissionManager getPermissionManager() {
        if (!new AndroidCapabilities().isMainThread()) {
            throw new IllegalStateException("The PermissionManager can only be opened from the main thread.");
        }
        return PermissionManager.getInstance(this);
    }

    // what defines a user is it's identity(Token) and authURL (as required by the constructor)
    //
    // not the list of Realms it's managing, furthermore, trying to include the `realms` in the `hashCode` will
    // end in a StackOverFlow, since we need to calculate the `hashCode` of the SyncConfiguration which itself
    // contains a reference to the SyncUser.
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        SyncUser syncUser = (SyncUser) o;

        if (!identity.equals(syncUser.identity)) return false;
        return authenticationUrl.toExternalForm().equals(syncUser.authenticationUrl.toExternalForm());
    }

    @Override
    public int hashCode() {
        int result = identity.hashCode();
        result = 31 * result + authenticationUrl.toExternalForm().hashCode();
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{");
        sb.append("UserId: ").append(identity);
        sb.append(", AuthUrl: ").append(getAuthenticationUrl());
        sb.append("}");
        return sb.toString();
    }

    // Class wrapping requests made against the auth server. Is also responsible for calling with success/error on the
    // correct thread.
    private static abstract class Request<T> {
        @Nullable
        private final Callback<T> callback;
        private final RealmNotifier handler;
        private final ThreadPoolExecutor networkPoolExecutor;

        Request(ThreadPoolExecutor networkPoolExecutor, @Nullable Callback<T> callback) {
            this.callback = callback;
            this.handler = new AndroidRealmNotifier(null, new AndroidCapabilities());
            this.networkPoolExecutor = networkPoolExecutor;
        }

        // Implements the request. Return the current sync user if the request succeeded. Otherwise throw an error.
        public abstract T run() throws ObjectServerError;

        // Start the request
        public RealmAsyncTask start() {
            Future<?> authenticateRequest = networkPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        postSuccess(Request.this.run());
                    } catch (ObjectServerError e) {
                        postError(e);
                    } catch (Throwable e) {
                        postError(new ObjectServerError(ErrorCode.UNKNOWN, "Unexpected error", e));
                    }
                }
            });
            return new RealmAsyncTaskImpl(authenticateRequest, networkPoolExecutor);
        }

        private void postError(final ObjectServerError error) {
            boolean errorHandled = false;
            if (callback != null) {
                Runnable action = new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(error);
                    }
                };
                errorHandled = handler.post(action);
            }

            if (!errorHandled) {
                RealmLog.error(error, "An error was thrown, but could not be handled.");
            }
        }

        private void postSuccess(final T result) {
            if (callback != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(result);
                    }
                });
            }
        }
    }

    public interface Callback<T> {
        void onSuccess(T result);

        void onError(ObjectServerError error);
    }
}


text:
package com.wepay.exception;

import com.wepay.net.WePayResource;

public class WePayException extends Exception {

	private String error;
	private String errorDescription;
	private Integer errorCode;

	public WePayException(String message) {
		super(message);
	}

	public WePayException(String message, Throwable throwable) {
		super(message, throwable);
	}

	public String getError() {
		return error;
	}

	public String getErrorDescription() {
		return errorDescription;
	}

	public Integer getErrorCode() {
		return errorCode;
	}

	public String getMessage() {
		return WePayResource.gson.toJson(this);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<profilesXml />


text:
package com.noelios.restlet.authentication;

import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.restlet.data.ChallengeRequest;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.Method;
import org.restlet.data.Parameter;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.util.DateUtils;
import org.restlet.util.Series;

import com.noelios.restlet.Engine;
import com.noelios.restlet.http.HttpConstants;
import com.noelios.restlet.util.Base64;
import com.noelios.restlet.util.SecurityUtils;

/**
 * Implements the HTTP authentication for the Amazon S3 service.
 *
 * @author Jerome Louvel
 */
public class HttpAmazonS3Helper extends AuthenticationHelper {

    /**
     * Returns the canonicalized AMZ headers.
     *
     * @param requestHeaders
     *            The list of request headers.
     * @return The canonicalized AMZ headers.
     */
    private static String getCanonicalizedAmzHeaders(
            Series<Parameter> requestHeaders) {
        // Filter out all the AMZ headers required for AWS authentication
        final SortedMap<String, String> amzHeaders = new TreeMap<String, String>();
        String headerName;
        for (final Parameter param : requestHeaders) {
            headerName = param.getName().toLowerCase();
            if (headerName.startsWith("x-amz-")) {
                if (!amzHeaders.containsKey(headerName)) {
                    amzHeaders.put(headerName, requestHeaders
                            .getValues(headerName));
                }
            }
        }

        // Concatenate all AMZ headers
        final StringBuilder sb = new StringBuilder();
        for (final Entry<String, String> entry : amzHeaders.entrySet()) {
            sb.append(entry.getKey()).append(':').append(entry.getValue())
                    .append("\n");
        }

        return sb.toString();
    }

    /**
     * Returns the canonicalized resource name.
     *
     * @param resourceRef
     *            The resource reference.
     * @return The canonicalized resource name.
     */
    private static String getCanonicalizedResourceName(Reference resourceRef) {
        final StringBuilder sb = new StringBuilder();

        String hostName = resourceRef.getHostDomain();
        if (hostName.endsWith(".s3.amazonaws.com")) {
            // The bucket name needs to be extracted
            String bucketName = hostName.substring(0, hostName.length() - 17);
            sb.append("/" + bucketName);
        }

        sb.append(resourceRef.getPath());

        final Form query = resourceRef.getQueryAsForm();
        if (query.getFirst("acl", true) != null) {
            sb.append("?acl");
        } else if (query.getFirst("torrent", true) != null) {
            sb.append("?torrent");
        } else if (query.getFirst("location", true) != null) {
            sb.append("?location");
        }

        return sb.toString();
    }

    /**
     * Constructor.
     */
    public HttpAmazonS3Helper() {
        super(ChallengeScheme.HTTP_AWS_S3, true, false);
    }

    @Override
    public String format(ChallengeRequest request) {
        return null;
    }

    @Override
    public void formatCredentials(StringBuilder sb,
            ChallengeResponse challenge, Request request,
            Series<Parameter> httpHeaders) {

        // Setup the method name
        final String methodName = request.getMethod().getName();

        // Setup the Date header
        String date = "";

        if (httpHeaders.getFirstValue("X-Amz-Date", true) == null) {
            // X-Amz-Date header didn't override the standard Date header
            date = httpHeaders.getFirstValue(HttpConstants.HEADER_DATE, true);
            if (date == null) {
                // Add a fresh Date header
                date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123
                        .get(0));
                httpHeaders.add(HttpConstants.HEADER_DATE, date);
            }
        }

        // Setup the ContentType header
        String contentMd5 = httpHeaders.getFirstValue(
                HttpConstants.HEADER_CONTENT_MD5, true);
        if (contentMd5 == null) {
            contentMd5 = "";
        }

        // Setup the ContentType header
        String contentType = httpHeaders.getFirstValue(
                HttpConstants.HEADER_CONTENT_TYPE, true);
        if (contentType == null) {
            boolean applyPatch = false;

            // This patch seems to apply to Sun JVM only.
            final String jvmVendor = System.getProperty("java.vm.vendor");
            if ((jvmVendor != null)
                    && (jvmVendor.toLowerCase()).startsWith("sun")) {
                final int majorVersionNumber = Engine.getJavaMajorVersion();
                final int minorVersionNumber = Engine.getJavaMinorVersion();

                if (majorVersionNumber == 1) {
                    if (minorVersionNumber < 5) {
                        applyPatch = true;
                    } else if (minorVersionNumber == 5) {
                        // Sun fixed the bug in update 10
                        applyPatch = (Engine.getJavaUpdateVersion() < 10);
                    }
                }
            }

            if (applyPatch && !request.getMethod().equals(Method.PUT)) {
                contentType = "application/x-www-form-urlencoded";
            } else {
                contentType = "";
            }
        }

        // Setup the canonicalized AmzHeaders
        final String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(httpHeaders);

        // Setup the canonicalized resource name
        final String canonicalizedResource = getCanonicalizedResourceName(request
                .getResourceRef());

        // Setup the message part
        final StringBuilder rest = new StringBuilder();
        rest.append(methodName).append('\n').append(contentMd5).append('\n')
                .append(contentType).append('\n').append(date).append('\n')
                .append(canonicalizedAmzHeaders).append(canonicalizedResource);

        // Append the AWS credentials
        sb.append(challenge.getIdentifier()).append(':').append(
                Base64.encode(SecurityUtils.toHMac(rest.toString(), new String(
                        challenge.getSecret())), false));

    }

}


text:
estdlib
=======

My personal C++ library. It contains replacements for many of the the Standard Template Library containers, as well as some data structures and algorithms of my own design (though I doubt any of them are truly original). I place a strong emphasis on well-written and well-documented code, though the oldest classes now date back nearly a decade and deserve a modern touch-up.

Many classes require C++11 features to build. The included Makefile should be sufficient, provided you have gcc >= 4.7 installed (and the g++ command is on your path).


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "vaapidecoder_base.h"
#include "common/log.h"
#include "vaapi/vaapisurfaceallocator.h"
#include "vaapi/vaapicontext.h"
#include "vaapi/vaapidisplay.h"
#include "vaapi/VaapiUtils.h"
#include "vaapidecsurfacepool.h"
#include <string.h>
#include <stdlib.h> // for setenv
#include <va/va_backend.h>
#include <unistd.h>

namespace YamiMediaCodec{
typedef VaapiDecoderBase::PicturePtr PicturePtr;

inline void unrefAllocator(SurfaceAllocator* allocator)
{
    allocator->unref(allocator);
}

VaapiDecoderBase::VaapiDecoderBase()
    : m_VAStarted(false)
    , m_currentPTS(INVALID_PTS)
{
    INFO("base: construct()");
    m_externalDisplay.handle = 0,
    m_externalDisplay.type = NATIVE_DISPLAY_AUTO,
    memset(&m_videoFormatInfo, 0, sizeof(VideoFormatInfo));
    memset(&m_configBuffer, 0, sizeof(m_configBuffer));
    m_configBuffer.fourcc = YAMI_FOURCC_NV12;
}

VaapiDecoderBase::~VaapiDecoderBase()
{
    INFO("base: deconstruct()");
    stop();
}

PicturePtr VaapiDecoderBase::createPicture(int64_t timeStamp /* , VaapiPictureStructure structure = VAAPI_PICTURE_STRUCTURE_FRAME */)
{
    PicturePtr picture;
    /*accquire one surface from m_surfacePool in base decoder  */
    SurfacePtr surface = createSurface();
    if (!surface) {
        DEBUG("create surface failed");
        return picture;
    }

    picture.reset(new VaapiDecPicture(m_context, surface, timeStamp));
    return picture;
}

YamiStatus VaapiDecoderBase::start(VideoConfigBuffer* buffer)
{
    YamiStatus status;

    INFO("base: start()");

    if (buffer == NULL) {
        return YAMI_DECODE_INVALID_DATA;
    }

    m_configBuffer = *buffer;
    m_configBuffer.data = NULL;
    m_configBuffer.size = 0;

    m_videoFormatInfo.width = buffer->width;
    m_videoFormatInfo.height = buffer->height;
    m_videoFormatInfo.surfaceWidth = buffer->surfaceWidth;
    m_videoFormatInfo.surfaceHeight = buffer->surfaceHeight;
    m_videoFormatInfo.surfaceNumber = buffer->surfaceNumber;
    if (!m_configBuffer.fourcc) {
        /* This just a workaround, user usually memset the VideoConfigBuffer to zero, and we will copy it to m_configBuffer.
           We need remove fields only for internal user from VideoConfigBuffer
           i.e., following thing should removed:
            int32_t surfaceWidth;
            int32_t surfaceHeight;
            int32_t frameRate;
            int32_t surfaceNumber;
            VAProfile profile;
            uint32_t flag;
            uint32_t fourcc;
        */
        m_videoFormatInfo.fourcc = m_configBuffer.fourcc = YAMI_FOURCC_NV12;
    }
    else {
        m_videoFormatInfo.fourcc = m_configBuffer.fourcc;
    }

    status = setupVA(buffer->surfaceNumber, buffer->profile);
    if (status != YAMI_SUCCESS)
        return status;

    DEBUG
        ("m_videoFormatInfo video size: %d x %d, m_videoFormatInfo surface size: %d x %d",
         m_videoFormatInfo.width, m_videoFormatInfo.height,
         m_videoFormatInfo.surfaceWidth, m_videoFormatInfo.surfaceHeight);

#ifdef __ENABLE_DEBUG__
    renderPictureCount = 0;
    if (access("/tmp/yami", F_OK) == 0) {
        m_dumpSurface = true;
    }
    else {
        m_dumpSurface = false;
    }
    DEBUG("m_dumpSurface: %d", m_dumpSurface);
#endif
    return YAMI_SUCCESS;
}

YamiStatus VaapiDecoderBase::reset(VideoConfigBuffer* buffer)
{
    YamiStatus status;

    INFO("base: reset()");
    if (buffer == NULL) {
        return YAMI_DECODE_INVALID_DATA;
    }

    flush();

    status = terminateVA();
    if (status != YAMI_SUCCESS)
        return status;

    status = start(buffer);
    if (status != YAMI_SUCCESS)
        return status;

    return YAMI_SUCCESS;
}

void VaapiDecoderBase::stop(void)
{
    INFO("base: stop()");
    terminateVA();

    m_currentPTS = INVALID_PTS;

    m_videoFormatInfo.valid = false;
}

void VaapiDecoderBase::flush(void)
{

    INFO("base: flush()");
    if (m_surfacePool) {
        m_surfacePool->flush();
    }

    m_currentPTS = INVALID_PTS;
}

struct BufferRecycler
{
    BufferRecycler(const DecSurfacePoolPtr&  pool, VideoRenderBuffer* buffer)
        :m_pool(pool), m_buffer(buffer)
    {
    }
    void operator()(VideoFrame* frame)
    {
        m_pool->recycle(m_buffer);
        delete frame;
    }

private:
    DecSurfacePoolPtr  m_pool;
    VideoRenderBuffer* m_buffer;
};

SharedPtr<VideoFrame> VaapiDecoderBase::getOutput()
{
    SharedPtr<VideoFrame> frame;
    DecSurfacePoolPtr pool = m_surfacePool;
    if (!pool)
        return frame;
    VideoRenderBuffer *buffer = pool->getOutput();
    if (buffer) {
        frame.reset(new VideoFrame, BufferRecycler(pool, buffer));
        memset(frame.get(), 0, sizeof(VideoFrame));
        frame->surface = (intptr_t)buffer->surface;
        frame->timeStamp = buffer->timeStamp;
        frame->crop = buffer->crop;
        frame->fourcc = buffer->fourcc;
#ifdef __ENABLE_DEBUG__
        if (m_dumpSurface && access("/tmp/yami/dumpon", F_OK) == 0) {
            DEBUG("dumpSurface display: %p, surface: 0x%x", buffer->display, buffer->surface);
            dumpSurface(buffer->display, buffer->surface);
        }
#endif
    }
    return frame;
}

const VideoFormatInfo *VaapiDecoderBase::getFormatInfo(void)
{
    INFO("base: getFormatInfo()");

    if (!m_VAStarted)
        return NULL;

    return &m_videoFormatInfo;
}

YamiStatus
VaapiDecoderBase::setupVA(uint32_t numSurface, VAProfile profile)
{
    INFO("base: setup VA");

    if (m_VAStarted) {
        return YAMI_SUCCESS;
    }

    if (m_display) {
        WARNING("VA is partially started.");
        return YAMI_FAIL;
    }

    m_display = VaapiDisplay::create(m_externalDisplay);

    if (!m_display) {
        ERROR("failed to create display");
        return YAMI_FAIL;
    }

    VAConfigAttrib attrib;
    attrib.type = VAConfigAttribRTFormat;
    attrib.value = VA_RT_FORMAT_YUV420;

    ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD,&attrib, 1);
    if (!config) {
        ERROR("failed to create config");
        return YAMI_FAIL;
    }

    if (!m_externalAllocator) {
        //use internal allocator
        m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator);
    } else {
        m_allocator = m_externalAllocator;
    }

    m_configBuffer.surfaceNumber = numSurface;
    m_surfacePool = VaapiDecSurfacePool::create(m_display, &m_configBuffer, m_allocator);
    DEBUG("surface pool is created");
    if (!m_surfacePool)
        return YAMI_FAIL;
    std::vector<VASurfaceID> surfaces;
    m_surfacePool->getSurfaceIDs(surfaces);
    if (surfaces.empty())
        return YAMI_FAIL;
    int size = surfaces.size();
    m_context = VaapiContext::create(config,
                                       m_videoFormatInfo.width,
                                       m_videoFormatInfo.height,
                                       0, &surfaces[0], size);

    if (!m_context) {
        ERROR("create context failed");
        return YAMI_FAIL;
    }

    m_videoFormatInfo.surfaceWidth = m_videoFormatInfo.width;
    m_videoFormatInfo.surfaceHeight = m_videoFormatInfo.height;

    m_VAStarted = true;
    return YAMI_SUCCESS;
}

bool VaapiDecoderBase::createAllocator()
{
    if (m_allocator)
        return true;
    m_display = VaapiDisplay::create(m_externalDisplay);
    if (!m_display) {
        ERROR("failed to create display");
        return false;
    }

    if (!m_externalAllocator) {
        //use internal allocator
        m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator);
    }
    else {
        m_allocator = m_externalAllocator;
    }
    if (!m_allocator) {
        m_display.reset();
        ERROR("failed to create allocator");
        return false;
    }
    return true;
}

bool VaapiDecoderBase::isSurfaceGeometryChanged() const
{
    return m_config.width < m_videoFormatInfo.width
        || m_config.height < m_videoFormatInfo.height
        || m_config.surfaceNumber != m_videoFormatInfo.surfaceNumber
        || m_config.fourcc != m_videoFormatInfo.fourcc;
}

YamiStatus VaapiDecoderBase::ensureSurfacePool()
{

    if (!isSurfaceGeometryChanged())
        return YAMI_SUCCESS;
    VideoFormatInfo& info = m_videoFormatInfo;
    m_config.width = info.surfaceWidth;
    m_config.height = info.surfaceHeight;
    m_config.surfaceNumber = info.surfaceNumber;
    m_config.fourcc = info.fourcc;

    if (!createAllocator())
        return YAMI_FAIL;

    m_surfacePool = VaapiDecSurfacePool::create(m_display, &m_config, m_allocator);
    if (!m_surfacePool)
        return YAMI_FAIL;
    DEBUG("surface pool is created");

    return YAMI_SUCCESS;
}

YamiStatus VaapiDecoderBase::ensureProfile(VAProfile profile)
{
    YamiStatus status;
    status = ensureSurfacePool();
    if (status != YAMI_SUCCESS)
        return status;

    if (!m_display || !m_surfacePool) {
        ERROR("bug: no display or surface pool");
        return YAMI_FAIL;
    }
    if (m_config.profile == profile)
        return YAMI_SUCCESS;

    m_config.profile = profile;
    VAConfigAttrib attrib;
    attrib.type = VAConfigAttribRTFormat;
    attrib.value = VA_RT_FORMAT_YUV420;

    ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD, &attrib, 1);
    if (!config) {
        ERROR("failed to create config");
        return YAMI_FAIL;
    }

    std::vector<VASurfaceID> surfaces;
    m_surfacePool->getSurfaceIDs(surfaces);
    if (surfaces.empty())
        return YAMI_FAIL;
    int size = surfaces.size();
    m_context = VaapiContext::create(config,
        m_videoFormatInfo.width,
        m_videoFormatInfo.height,
        0, &surfaces[0], size);

    if (!m_context) {
        ERROR("create context failed");
        return YAMI_FAIL;
    }
    return YAMI_SUCCESS;
}

YamiStatus VaapiDecoderBase::terminateVA(void)
{
    INFO("base: terminate VA");
    m_config.resetConfig();
    m_surfacePool.reset();
    m_allocator.reset();
    DEBUG("surface pool is reset");
    m_context.reset();
    m_display.reset();

    m_VAStarted = false;
    return YAMI_SUCCESS;
}

void VaapiDecoderBase::setNativeDisplay(NativeDisplay * nativeDisplay)
{
    if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO)
        return;

    m_externalDisplay = *nativeDisplay;
}

void VaapiDecoderBase::releaseLock(bool lockable)
{
    if (!m_surfacePool)
        return;

    m_surfacePool->setWaitable(lockable);
}

void VaapiDecoderBase::setAllocator(SurfaceAllocator* allocator)
{
    m_externalAllocator.reset(allocator,unrefAllocator);
}

SurfacePtr VaapiDecoderBase::createSurface()
{
    SurfacePtr surface;
    if (m_surfacePool) {
        surface = m_surfacePool->acquireWithWait();
    }
    return surface;
}

YamiStatus VaapiDecoderBase::outputPicture(const PicturePtr& picture)
{
    //TODO: reorder poc
    return m_surfacePool->output(picture->getSurface(),
               picture->m_timeStamp)
        ? YAMI_SUCCESS
        : YAMI_FAIL;
}

VADisplay VaapiDecoderBase::getDisplayID()
{
    if (!m_display)
        return NULL;
    return m_display->getID();
}

#define CHECK(f)                        \
    do {                                \
        if (m_videoFormatInfo.f != f) { \
            m_videoFormatInfo.f = f;    \
            changed = true;             \
        }                               \
    } while (0)

bool VaapiDecoderBase::setFormat(uint32_t width, uint32_t height, uint32_t surfaceWidth, uint32_t surfaceHeight,
    uint32_t surfaceNumber, uint32_t fourcc)
{
    bool changed = false;
    CHECK(width);
    CHECK(height);
    CHECK(surfaceWidth);
    CHECK(surfaceHeight);
    CHECK(surfaceNumber);
    CHECK(fourcc);
    //this not true, but it's only way to let user get format info
    m_VAStarted = true;
    return changed;
}

} //namespace YamiMediaCodec


text:
Spine.Bone = function(boneData) {
    this.boneData = boneData;
    this.parent = null;
    this.x = boneData.x;
    this.y = boneData.y;
    this.rotation = boneData.rotation;
    this.scaleX = boneData.scaleX;
    this.scaleY = boneData.scaleY;

    this.m00 = 0; // a
    this.m01 = 0; // b
    this.worldX = 0; // x
    this.m10 = 0; // c
    this.m11 = 0; // d
    this.worldY = 0; // y
    this.worldRotation = 0;
    this.worldScaleX = 1;
    this.worldScaleY = 1;

    if(!boneData) throw "boneData cannot be null";

};

Spine.Bone.prototype = {
    destroy: function() {},

    setToBindPose: function() {
        this.x = this.boneData.x;
        this.y = this.boneData.y;
        this.rotation = this.boneData.rotation;
        this.scaleX = this.boneData.scaleX;
        this.scaleY = this.boneData.scaleY;
    },

    updateWorldTransform: function(flipX, flipY) {
        if(this.parent) {
            this.worldX = this.x * this.parent.m00 + this.y * this.parent.m01 + this.parent.worldX;
            this.worldY = this.x * this.parent.m10 + this.y * this.parent.m11 + this.parent.worldY;
            this.worldScaleX = this.parent.worldScaleX * this.scaleX;
            this.worldScaleY = this.parent.worldScaleY * this.scaleY;
            this.worldRotation = this.parent.worldRotation + this.rotation;
        }
        else {
            this.worldX = this.x;
            this.worldY = this.y;
            this.worldScaleX = this.scaleX;
            this.worldScaleY = this.scaleY;
            this.worldRotation = this.rotation;
        }

        var radians = this.worldRotation * Math.PI / 180,
            cos = Math.cos(radians),
            sin = Math.sin(radians);

        this.m00 = cos * this.worldScaleX;
        this.m10 = sin * this.worldScaleX;
        this.m01 = -sin * this.worldScaleY;
        this.m11 = cos * this.worldScaleY;

        if(flipX) {
            this.m00 *= -1;
            this.m01 *= -1;
        }
        if(flipY) {
            this.m10 *= -1;
            this.m11 *= -1;
        }
        if(this.boneData.yDown) {
            this.m10 *= -1;
            this.m11 *= -1;
        }
    }
};


text:
<?php

namespace LaravelDoctrine\ORM\Console;

use Illuminate\Contracts\View\Factory;
use InvalidArgumentException;
use LaravelDoctrine\ORM\ConfigMigrations\MitchellMigrator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class ConvertConfigCommand extends Command
{
    protected $name = 'doctrine:config:convert';

    protected $description = 'Convert the configuration file for another laravel-doctrine implementation into a valid configuration for LaravelDoctrine\ORM.';

    public function fire(Factory $viewFactory)
    {
        //add config templates directory to view locations
        $viewFactory->addLocation(realpath(__DIR__ . '/ConfigMigrations/templates'));

        if (($destPath = $this->option('dest-path')) === null) {
            $destPath = 'config';
        }

        if (($author = $this->argument('author')) === null) {
            throw new InvalidArgumentException('Missing author option');
        }

        if (($sourceFilePath = $this->option('source-file')) === null) {
            $sourceFilePath = 'config/doctrine.php';
        }

        $destPath = realpath($destPath);

        if (!is_dir($destPath)) {
            mkdir($destPath, 0777, true);
        }

        if (!is_writable($destPath)) {
            throw new InvalidArgumentException(
                sprintf("Configuration destination directory '<info>%s</info>' does not have write permissions.",
                    $destPath)
            );
        }

        $destFilePath = $destPath . '/doctrine.generated.php';

        $originalSourceFilePath = $sourceFilePath;
        $sourceFilePath = realPath($sourceFilePath);

        if (!file_exists($sourceFilePath)) {
            throw new InvalidArgumentException(
                sprintf("Source file at path '<info>%s</info>' does not exist.",
                    $originalSourceFilePath)
            );
        }

        $sourceArrayConfig = include $sourceFilePath;

        //TODO make this relative

        switch ($author) {
            case 'atrauzzi':
                //$convertedConfigString = $this->convertAtrauzzi($sourceArrayConfig, $viewFactory);
                break;
            case 'mitchellvanw':
                $convertedConfigString = $this->convertMitchell($sourceArrayConfig, $viewFactory);
                break;
            default:
                throw new InvalidArgumentException('Author provided was not a valid choice.');
        }

        file_put_contents($destFilePath, '<?php ' . $convertedConfigString);
        $this->info('Conversion successful. File generated at ' . $destFilePath);
    }

    /**
     * Convert a configuration file from mitchellvanw/laravel-doctrine to a string representation of a php array configuration for this project
     *
     * @param array $sourceConfig
     * @param Factory $viewFactory
     * @return string
     */
    private function convertMitchell($sourceConfig, $viewFactory)
    {
        $mMigrator = new MitchellMigrator($viewFactory);

        return $mMigrator->convertConfiguration($sourceConfig);
    }

    /**
     * Convert a configuration file from atrauzzi/laravel-doctrine to a string representation of a php array configuration for this project
     *
     * @param array $sourceConfig
     * @param Factory $viewFactory
     * @return string
     *
     */
    private function convertAtrauzzi($sourceConfig, $viewFactory)
    {
        //TODO
    }

    public function getArguments()
    {
        return [
            ['author', InputArgument::REQUIRED, 'The name of the author of the repository being migrated from. Options are "atrauzzi" and "mitchellvanw"'],

        ];
    }

    protected function getOptions()
    {
        return [
            ['dest-path', null, InputOption::VALUE_OPTIONAL, 'Where the generated configuration should be placed. Default is config.', 'config'],
            ['source-file', null, InputOption::VALUE_OPTIONAL, 'Where the source configuration file is located. Default is config/doctrine.php', 'config/doctrine.php']
        ];
    }
}


text:
@interface BBSRunTime : NSObject

@end


text:
"""Updated primary trigger

Revision ID: 3506dcc19f7a
Revises: b332c012c57d
Create Date: 2017-08-23 09:15:59.855718

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '3506dcc19f7a'
down_revision = 'b332c012c57d'
branch_labels = None
depends_on = None

def upgrade():
    op.execute(
        sa.DDL(
            '''
        DROP TRIGGER user_useremail_primary_trigger ON user_useremail_primary;
        DROP FUNCTION user_useremail_primary_validate();
        '''
        )
    )
    op.execute(
        sa.DDL(
            '''
        DROP TRIGGER user_userphone_primary_trigger ON user_userphone_primary;
        DROP FUNCTION user_userphone_primary_validate();
        '''
        )
    )
    op.execute(
        sa.DDL(
            '''
        CREATE FUNCTION user_useremail_primary_validate() RETURNS TRIGGER AS $$
        DECLARE
            target RECORD;
        BEGIN
            IF (NEW.useremail_id IS NOT NULL) THEN
                SELECT user_id INTO target FROM useremail WHERE id = NEW.useremail_id;
                IF (target.user_id != NEW.user_id) THEN
                    RAISE foreign_key_violation USING MESSAGE = 'The target is not affiliated with this parent';
                END IF;
            END IF;
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
        CREATE TRIGGER user_useremail_primary_trigger BEFORE INSERT OR UPDATE
        ON user_useremail_primary
        FOR EACH ROW EXECUTE PROCEDURE user_useremail_primary_validate();
        '''
        )
    )
    op.execute(
        sa.DDL(
            '''
        CREATE FUNCTION user_userphone_primary_validate() RETURNS TRIGGER AS $$
        DECLARE
            target RECORD;
        BEGIN
            IF (NEW.userphone_id IS NOT NULL) THEN
                SELECT user_id INTO target FROM userphone WHERE id = NEW.userphone_id;
                IF (target.user_id != NEW.user_id) THEN
                    RAISE foreign_key_violation USING MESSAGE = 'The target is not affiliated with this parent';
                END IF;
            END IF;
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
        CREATE TRIGGER user_userphone_primary_trigger BEFORE INSERT OR UPDATE
        ON user_userphone_primary
        FOR EACH ROW EXECUTE PROCEDURE user_userphone_primary_validate();
        '''
        )
    )

def downgrade():
    op.execute(
        sa.DDL(
            '''
        DROP TRIGGER user_useremail_primary_trigger ON user_useremail_primary;
        DROP FUNCTION user_useremail_primary_validate();
        '''
        )
    )
    op.execute(
        sa.DDL(
            '''
        DROP TRIGGER user_userphone_primary_trigger ON user_userphone_primary;
        DROP FUNCTION user_userphone_primary_validate();
        '''
        )
    )
    op.execute(
        sa.DDL(
            '''
        CREATE FUNCTION user_useremail_primary_validate() RETURNS TRIGGER AS $$
        DECLARE
            target RECORD;
        BEGIN
            SELECT user_id INTO target FROM useremail WHERE id = NEW.useremail_id;
            IF (target.user_id != NEW.user_id) THEN
                RAISE foreign_key_violation USING MESSAGE = 'The target is not affiliated with this parent';
            END IF;
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
        CREATE TRIGGER user_useremail_primary_trigger BEFORE INSERT OR UPDATE
        ON user_useremail_primary
        FOR EACH ROW EXECUTE PROCEDURE user_useremail_primary_validate();
        '''
        )
    )
    op.execute(
        sa.DDL(
            '''
        CREATE FUNCTION user_userphone_primary_validate() RETURNS TRIGGER AS $$
        DECLARE
            target RECORD;
        BEGIN
            SELECT user_id INTO target FROM userphone WHERE id = NEW.userphone_id;
            IF (target.user_id != NEW.user_id) THEN
                RAISE foreign_key_violation USING MESSAGE = 'The target is not affiliated with this parent';
            END IF;
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
        CREATE TRIGGER user_userphone_primary_trigger BEFORE INSERT OR UPDATE
        ON user_userphone_primary
        FOR EACH ROW EXECUTE PROCEDURE user_userphone_primary_validate();
        '''
        )
    )


text:
#include "constrained_ik/constrained_ik.h"
#include "constrained_ik/enum_types.h"
#include "constrained_ik/constraints/goal_minimize_change.h"
#include "example_utils.h"
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/planning_scene/planning_scene.h>

using namespace constrained_ik;
using namespace constrained_ik::basic_kin;
using namespace Eigen;

/**
 * @brief This is an example showing how to add a GoalMinimizeChange constraint using c++
 * @todo Improve this example to where there is also a position constraint.
 */
int main(int argc, char *argv[])
{
  ros::init(argc, argv, "goal_minimize_change_example");
  Constrained_IK ik;
  BasicKin kin;
  robot_model_loader::RobotModelLoaderPtr loader;

  // Load example robot model
  getExampleRobotData(loader);

  // Initialize kinematic model
  kin.init(loader->getModel()->getJointModelGroup("manipulator"));

  // Create constraint
  constraints::GoalMinimizeChange *constraint = new constraints::GoalMinimizeChange;
  constraint->setDebug(false);
  constraint->setWeight(1.0);

  // Add constraint to solver
  ik.addConstraint(constraint, constraint_types::Primary);

  // Initialize Solver
  ik.init(kin);

  // Calculate IK for sample case
  evaluteExampleIK(kin, ik);

  return 0;
}


text:
namespace {

const char kDisplayDispositionMetric[] = "PasswordBubble.DisplayDisposition";

}  // namespace

typedef ManagePasswordsViewTest ManagePasswordsBubbleViewTest;
namespace metrics_util = password_manager::metrics_util;

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest, BasicOpenAndClose) {
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());
  ManagePasswordsBubbleView::ShowBubble(
      browser()->tab_strip_model()->GetActiveWebContents(),
      ManagePasswordsBubble::USER_ACTION);
  EXPECT_TRUE(ManagePasswordsBubbleView::IsShowing());
  const ManagePasswordsBubbleView* bubble =
      ManagePasswordsBubbleView::manage_password_bubble();
  EXPECT_TRUE(bubble->initially_focused_view());
  EXPECT_EQ(bubble->initially_focused_view(),
            bubble->GetFocusManager()->GetFocusedView());
  EXPECT_FALSE(bubble->IsTimerRunning());
  ManagePasswordsBubbleView::CloseBubble();
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());

  // And, just for grins, ensure that we can re-open the bubble.
  ManagePasswordsBubbleView::ShowBubble(
      browser()->tab_strip_model()->GetActiveWebContents(),
      ManagePasswordsBubble::USER_ACTION);
  EXPECT_TRUE(ManagePasswordsBubbleView::manage_password_bubble()->
      GetFocusManager()->GetFocusedView());
  EXPECT_TRUE(ManagePasswordsBubbleView::IsShowing());
  ManagePasswordsBubbleView::CloseBubble();
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());
}

// Same as 'BasicOpenAndClose', but use the command rather than the static
// method directly.
IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest, CommandControlsBubble) {
  // The command only works if the icon is visible, so get into management mode.
  SetupManagingPasswords();
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());
  ExecuteManagePasswordsCommand();
  EXPECT_TRUE(ManagePasswordsBubbleView::IsShowing());
  const ManagePasswordsBubbleView* bubble =
      ManagePasswordsBubbleView::manage_password_bubble();
  EXPECT_TRUE(bubble->initially_focused_view());
  EXPECT_EQ(bubble->initially_focused_view(),
            bubble->GetFocusManager()->GetFocusedView());
  ManagePasswordsBubbleView::CloseBubble();
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());

  // And, just for grins, ensure that we can re-open the bubble.
  ExecuteManagePasswordsCommand();
  EXPECT_TRUE(ManagePasswordsBubbleView::IsShowing());
  ManagePasswordsBubbleView::CloseBubble();
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());
}

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest,
                       CommandExecutionInManagingState) {
  SetupManagingPasswords();
  ExecuteManagePasswordsCommand();

  scoped_ptr<base::HistogramSamples> samples(
      GetSamples(kDisplayDispositionMetric));
  EXPECT_EQ(
      0,
      samples->GetCount(
          metrics_util::AUTOMATIC_WITH_PASSWORD_PENDING));
  EXPECT_EQ(0,
            samples->GetCount(
                metrics_util::MANUAL_WITH_PASSWORD_PENDING));
  EXPECT_EQ(1,
            samples->GetCount(
                metrics_util::MANUAL_MANAGE_PASSWORDS));
}

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest,
                       CommandExecutionInAutomaticState) {
  // Open with pending password: automagical!
  SetupPendingPassword();

  // Bubble should not be focused by default.
  EXPECT_FALSE(ManagePasswordsBubbleView::manage_password_bubble()->
      GetFocusManager()->GetFocusedView());
  // Bubble can be active if user clicks it.
  EXPECT_TRUE(ManagePasswordsBubbleView::manage_password_bubble()->
      CanActivate());
  EXPECT_TRUE(ManagePasswordsBubbleView::manage_password_bubble()->
      IsTimerRunning());

  scoped_ptr<base::HistogramSamples> samples(
      GetSamples(kDisplayDispositionMetric));
  EXPECT_EQ(
      1,
      samples->GetCount(
          metrics_util::AUTOMATIC_WITH_PASSWORD_PENDING));
  EXPECT_EQ(0,
            samples->GetCount(
                metrics_util::MANUAL_WITH_PASSWORD_PENDING));
  EXPECT_EQ(0,
            samples->GetCount(
                metrics_util::MANUAL_MANAGE_PASSWORDS));
}

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest,
                       CommandExecutionInPendingState) {
  // Open once with pending password: automagical!
  SetupPendingPassword();
  ManagePasswordsBubbleView::CloseBubble();
  // This opening should be measured as manual.
  ExecuteManagePasswordsCommand();

  scoped_ptr<base::HistogramSamples> samples(
      GetSamples(kDisplayDispositionMetric));
  EXPECT_EQ(
      1,
      samples->GetCount(
          metrics_util::AUTOMATIC_WITH_PASSWORD_PENDING));
  EXPECT_EQ(1,
            samples->GetCount(
                metrics_util::MANUAL_WITH_PASSWORD_PENDING));
  EXPECT_EQ(0,
            samples->GetCount(
                metrics_util::MANUAL_MANAGE_PASSWORDS));
}

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest,
                       CommandExecutionInAutomaticSaveState) {
  SetupAutomaticPassword();
  ManagePasswordsBubbleView::CloseBubble();
  // Re-opening should count as manual.
  ExecuteManagePasswordsCommand();

 scoped_ptr<base::HistogramSamples> samples(
      GetSamples(kDisplayDispositionMetric));
  EXPECT_EQ(
      1,
      samples->GetCount(
          metrics_util::AUTOMATIC_GENERATED_PASSWORD_CONFIRMATION));
  EXPECT_EQ(0,
            samples->GetCount(
                metrics_util::MANUAL_WITH_PASSWORD_PENDING));
  EXPECT_EQ(1,
            samples->GetCount(
                metrics_util::MANUAL_MANAGE_PASSWORDS));
}

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest, CloseOnClick) {
  ManagePasswordsBubbleView::ShowBubble(
      browser()->tab_strip_model()->GetActiveWebContents(),
      ManagePasswordsBubble::AUTOMATIC);
  EXPECT_TRUE(ManagePasswordsBubbleView::IsShowing());
  EXPECT_FALSE(ManagePasswordsBubbleView::manage_password_bubble()->
      GetFocusManager()->GetFocusedView());
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());
}

IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleViewTest, CloseOnKey) {
  content::WindowedNotificationObserver focus_observer(
      content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
      content::NotificationService::AllSources());
  ui_test_utils::NavigateToURL(
      browser(),
      GURL("data:text/html;charset=utf-8,<input type=\"text\" autofocus>"));
  focus_observer.Wait();
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ManagePasswordsBubbleView::ShowBubble(web_contents,
                                        ManagePasswordsBubble::AUTOMATIC);
  EXPECT_TRUE(ManagePasswordsBubbleView::IsShowing());
  EXPECT_FALSE(ManagePasswordsBubbleView::manage_password_bubble()->
      GetFocusManager()->GetFocusedView());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
  EXPECT_TRUE(web_contents->GetRenderViewHost()->IsFocusedElementEditable());
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_K,
      false, false, false, false));
  EXPECT_FALSE(ManagePasswordsBubbleView::IsShowing());
}


text:
namespace remoting {
namespace protocol {

// TransportChannelSocketAdapter implements P2PDatagramSocket interface on
// top of cricket::IceTransportInternal. It is used by IceTransport to provide
// P2PDatagramSocket interface for channels.
class TransportChannelSocketAdapter : public P2PDatagramSocket,
                                      public sigslot::has_slots<> {
 public:
  // Doesn't take ownership of the |channel|. The |channel| must outlive
  // this adapter.
  explicit TransportChannelSocketAdapter(
      cricket::IceTransportInternal* ice_transport);

  TransportChannelSocketAdapter(const TransportChannelSocketAdapter&) = delete;
  TransportChannelSocketAdapter& operator=(
      const TransportChannelSocketAdapter&) = delete;

  ~TransportChannelSocketAdapter() override;

  // Sets callback that should be called when the adapter is being
  // destroyed. The callback is not allowed to touch the adapter, but
  // can do anything else, e.g. destroy the TransportChannel.
  void SetOnDestroyedCallback(base::OnceClosure callback);

  // Closes the stream. |error_code| specifies error code that will
  // be returned by Recv() and Send() after the stream is closed.
  // Must be called before the session and the channel are destroyed.
  void Close(int error_code);

  // P2PDatagramSocket interface.
  int Recv(const scoped_refptr<net::IOBuffer>& buf,
           int buf_len,
           const net::CompletionRepeatingCallback& callback) override;
  int Send(const scoped_refptr<net::IOBuffer>& buf,
           int buf_len,
           const net::CompletionRepeatingCallback& callback) override;

 private:
  void OnNewPacket(rtc::PacketTransportInternal* transport,
                   const char* data,
                   size_t data_size,
                   const int64_t& packet_time,
                   int flags);
  void OnWritableState(rtc::PacketTransportInternal* transport);
  void OnChannelDestroyed(cricket::IceTransportInternal* ice_transport);

  base::ThreadChecker thread_checker_;

  raw_ptr<cricket::IceTransportInternal> channel_;

  base::OnceClosure destruction_callback_;

  net::CompletionRepeatingCallback read_callback_;
  scoped_refptr<net::IOBuffer> read_buffer_;
  int read_buffer_size_;

  net::CompletionRepeatingCallback write_callback_;
  scoped_refptr<net::IOBuffer> write_buffer_;
  int write_buffer_size_;

  int closed_error_code_;
};

}  // namespace protocol
}  // namespace remoting

#endif  // REMOTING_PROTOCOL_CHANNEL_SOCKET_ADAPTER_H_


text: <mime-viewer [manifestUri]="manifestUri" [canvasIndex]="canvasIndex" tabindex="0"></mime-viewer>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of tt_random</title>
  <meta name="keywords" content="tt_random">
  <meta name="description" content="Generates a random tensor">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../m2html.css">

Home >  tt2 > core > tt_random.m

tt_random

PURPOSE

Generates a random tensor

SYNOPSIS

function [tt]=tt_random(n,d,r)

DESCRIPTION

Generates a random tensor
   [TT]=TT_RANDOM(N,D,R) Generates a random tensor with dimensions specified
   by (N,D), where N can be a number of an array of dimension D, R is a
   rank or a array of dimension d+1

 TT-Toolbox 2.2, 2009-2012

This is TT Toolbox, written by Ivan Oseledets et al.
Institute of Numerical Mathematics, Moscow, Russia
webpage: http://spring.inm.ras.ru/osel

For all questions, bugs and suggestions please mail
ivan.oseledets@gmail.com
---------------------------

CROSS-REFERENCE INFORMATION

This function calls:

tt_rand	Generates a random tensor

This function is called by:

norm	Matrix norm of the TT-matrix

tt_mvk2	Matrix-by-vector product by DMRG/Krylov method

dmrg_eigb	Find several minimal eigenvalues of a TT-matrix using DMRG method

dmrg_solve2	Solution of linear systems in TT-format via DMRG iteration

SOURCE CODE

0001 function [tt]=tt_random(n,d,r)
0002 %Generates a random tensor
0003 %   [TT]=TT_RANDOM(N,D,R) Generates a random tensor with dimensions specified
0004 %   by (N,D), where N can be a number of an array of dimension D, R is a
0005 %   rank or a array of dimension d+1
0006 %
0007 %
0008 % TT-Toolbox 2.2, 2009-2012
0009 %
0010 %This is TT Toolbox, written by Ivan Oseledets et al.
0011 %Institute of Numerical Mathematics, Moscow, Russia
0012 %webpage: http://spring.inm.ras.ru/osel
0013 %
0014 %For all questions, bugs and suggestions please mail
0015 %ivan.oseledets@gmail.com
0016 %---------------------------
0017 tt=tt_rand(n,d,r);
0018 return
0019 end

<address>Generated on Wed 08-Feb-2012 18:20:24 by m2html © 2005</address>


text:
package com.hazelcast.impl;

import com.hazelcast.logging.ILogger;

import java.util.logging.Level;

public class SplitBrainHandler implements Processable {
    private final Node node;
    private final ILogger logger;
    private volatile boolean inProgress = false;
    private final long firstRunDelayMillis;
    private final long nextRunDelayMillis;

    public SplitBrainHandler(Node node) {
        this.node = node;
        this.logger = node.getLogger(SplitBrainHandler.class.getName());
        firstRunDelayMillis = node.getGroupProperties().MERGE_FIRST_RUN_DELAY_SECONDS.getLong() * 1000L;
        nextRunDelayMillis = node.getGroupProperties().MERGE_NEXT_RUN_DELAY_SECONDS.getLong() * 1000L;
    }

    public void process() {
        if (node.isMaster() && node.joined() && node.isActive()) {
            if (!inProgress && node.clusterManager.shouldTryMerge()) {
                inProgress = true;
                node.executorManager.executeNow(new FallThroughRunnable() {
                    @Override
                    public void doRun() {
                        searchForOtherClusters();
                        inProgress = false;
                    }
                });
            }
        }
    }

    private void searchForOtherClusters() {
        Joiner joiner = node.getJoiner();
        if (joiner != null) {
            logger.log(Level.FINEST, "Searching for other clusters.");
            node.getSystemLogService().logJoin("Searching for other clusters.");
            joiner.searchForOtherClusters(this);
        }
    }

    public void restart() {
        node.factory.restartToMerge();
    }

    public long getFirstRunDelayMillis() {
        return firstRunDelayMillis;
    }

    public long getNextRunDelayMillis() {
        return nextRunDelayMillis;
    }
}


text:
        <? if(!empty($order_items)){
            echo "Order Summary ";
          }else{
            echo "FEED ME I'M HUNGRY";
          } ?>

              <? if(!empty($order_items)){
                  foreach ($order_items as $row) {?>

                        <a href="<?= $row['prod_link']?>" title="<?= $row['prod_name']?>">
                        <img itemprop="image" class="primary-image" data-altimg="" src="<?= $row['image_link']?>" alt="<?= $row['prod_name'];?>">

                          Diesel <?= $row['prod_name']?>

                          <?if(!empty($row['color_name'])):?>

                              Colour:

                              <?=$row['color_name'];?>

                          <?endif;

                          if(!empty($row['size'])):?>

                              Size:

                              <?=$row['size'];?>

                          <?endif;

                          if(!empty($row['length'])):?>

                              Length:

                              <?=$row['length'];?>

                          <?endif;?>

                            Quantity
                            <?=$row['quantity'];?>

                             $<?=number_format($row['total'],2); ?>

              <? } // end of foreach cart_items ?>

              Order Subtotal
              $<?=isset($cart_total) ? number_format($cart_total,2) : '0.00'; ?>

              Shipping

				 <?if(SHIPPING_SET_PRICE =='0'){
					echo "Free";
				  }else{?>
					$<?= SHIPPING_SET_PRICE;
				  }?>

              Have a promotional code?
              <form class="cart-coupon hidden" action="" method="post" name="dwfrm_cart_d0tfijoghkcz" id="apply-coupon">
                <fieldset>

                  Enter Coupon Code
                  <input type="text" class="coupon-code" name="dwfrm_cart_couponCode" id="dwfrm_cart_couponCode">
                  <button type="submit" value="dwfrm_cart_addCoupon" name="dwfrm_cart_addCoupon" id="add-coupon">
                  Apply </button>
                </fieldset>
              </form>

              Order Total
              $<?= number_format($order_total,2);?>

			<?php if(ENVIRONMENT == 'production'):?>

			<?php endif; ?>

          <? }else{ ?>

YOUR SHOPPING BAG IS EMPTY

            <a href="<?= base_url();?>" class="continue button primary-button">
            Back To Shopping

        <? }?>


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IParameter.cs" company="CatenaLogic">
//   Copyright (c) 2014 - 2018 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace ContinuaInit.Models
{
    public interface IParameter
    {
        string Value { get; }
    }
}


text:
namespace GameEngine {
	namespace graphics{
		VertexArray::VertexArray(){
			glGenVertexArrays(1, &m_ArrayID);
		}
		VertexArray::~VertexArray(){
			int n = m_Buffers.size();
			for (int i = 0; i < n ; i++){
				delete m_Buffers[i];
			}
		}

		void VertexArray::addBuffer(Buffer *buffer, GLuint index){
			bind();
			buffer->bind();

			glEnableVertexAttribArray(index);
			glVertexAttribPointer(index, buffer->getComponentCount(), GL_FLOAT, GL_FALSE, 0, 0);

			buffer->unbind();
			unbind();
		}
		void VertexArray::bind() const{ glBindVertexArray(m_ArrayID); }
		void VertexArray::unbind() const{ glBindVertexArray(0); }
	}
}


text:
namespace blink {

class Frame;

// Small helper class to track the set of frames that a Frame has opened.
// Due to layering restrictions, we need to hide the implementation, since
// public/web/ cannot depend on wtf/.
class OpenedFrameTracker {
  DISALLOW_NEW();

 public:
  OpenedFrameTracker();
  OpenedFrameTracker(const OpenedFrameTracker&) = delete;
  OpenedFrameTracker& operator=(const OpenedFrameTracker&) = delete;
  ~OpenedFrameTracker();
  void Trace(Visitor*) const;

  bool IsEmpty() const;
  void Add(Frame*);
  void Remove(Frame*);

  // Helper used when swapping a frame into the frame tree: this updates the
  // opener for opened frames to point to the new frame being swapped in.
  void TransferTo(Frame*) const;

 private:
  HeapHashSet<WeakMember<Frame>> opened_frames_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_OPENED_FRAME_TRACKER_H_


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W31184_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans695.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">HORIZONTAL SECTION PLAT CONTINENTAL RESOURCES INC. SECTION 35, TISSN, R98W WILLIAMS COUNTY, NORTH DAKOTA

ALL CORNERS SHOWN ON THIS PLAT WERE FOUND /N THE FIELD DISTANCES TO ALL OTHERS ARE CALCULATED. ALL BEARINGS SHOWN ARE ASSUMED.'
£15705! dWfi'l/VEIIMVC l/VC
BOX 357 BOWMAN, ND. 58623
PHONE: 70 7 ~523—334O FAX: 70 7 —523—5243
PROJECT NO. 15—10


text:
package org.openestate.io.is24_xml.xml;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class Adapter20
    extends XmlAdapter<String, Long>
{

    public Long unmarshal(String value) {
        return (org.openestate.io.is24_xml.Is24XmlUtils.parseZahl3(value));
    }

    public String marshal(Long value) {
        return (org.openestate.io.is24_xml.Is24XmlUtils.printZahl3Including0(value));
    }

}


text:
class TermsController < ApplicationController
end


text:
* [Added] Upgrade dependencies. See [#11726](https://github.com/DataDog/integrations-core/pull/11726).
* [Added] Add metric_patterns options to filter all metric submission by a list of regexes. See [#11695](https://github.com/DataDog/integrations-core/pull/11695).

## 2.2.0 / 2022-02-19 / Agent 7.35.0

* [Added] Add `pyproject.toml` file. See [#11441](https://github.com/DataDog/integrations-core/pull/11441).
* [Fixed] Fix namespace packaging on Python 2. See [#11532](https://github.com/DataDog/integrations-core/pull/11532).

## 2.1.1 / 2022-01-08 / Agent 7.34.0

* [Fixed] Add comment to autogenerated model files. See [#10945](https://github.com/DataDog/integrations-core/pull/10945).

## 2.1.0 / 2021-10-04 / Agent 7.32.0

* [Added] Disable generic tags. See [#10027](https://github.com/DataDog/integrations-core/pull/10027).

## 2.0.0 / 2021-08-22 / Agent 7.31.0

* [Changed] Remove messages for integrations for OK service checks. See [#9888](https://github.com/DataDog/integrations-core/pull/9888).

## 1.9.1 / 2021-07-22 / Agent 7.30.0

* [Fixed] Properly allow deprecated required config. See [#9750](https://github.com/DataDog/integrations-core/pull/9750).

## 1.9.0 / 2021-07-12

* [Added] Add runtime configuration validation. See [#8991](https://github.com/DataDog/integrations-core/pull/8991).
* [Fixed] Bump base package dependency. See [#9666](https://github.com/DataDog/integrations-core/pull/9666).

## 1.8.0 / 2021-05-28 / Agent 7.29.0

* [Added] Remove unused dependency. See [#9435](https://github.com/DataDog/integrations-core/pull/9435).

## 1.7.1 / 2021-03-07 / Agent 7.27.0

* [Fixed] Bump minimum base package version. See [#8443](https://github.com/DataDog/integrations-core/pull/8443).

## 1.7.0 / 2020-10-31 / Agent 7.24.0

* [Added] [doc] Add encoding in log config sample. See [#7708](https://github.com/DataDog/integrations-core/pull/7708).
* [Added] Add supervisord logs. See [#7636](https://github.com/DataDog/integrations-core/pull/7636).

## 1.6.1 / 2020-09-21 / Agent 7.23.0

* [Fixed] Fix style for the latest release of Black. See [#7438](https://github.com/DataDog/integrations-core/pull/7438).

## 1.6.0 / 2020-05-17 / Agent 7.20.0

* [Added] Allow optional dependency installation for all checks. See [#6589](https://github.com/DataDog/integrations-core/pull/6589).

## 1.5.0 / 2020-04-04 / Agent 7.19.0

* [Added] Make error message more explicit. See [#6211](https://github.com/DataDog/integrations-core/pull/6211).
* [Added] Enable basic authentication for socket option (unix_http_server). See [#6239](https://github.com/DataDog/integrations-core/pull/6239).
* [Fixed] Update deprecated imports. See [#6088](https://github.com/DataDog/integrations-core/pull/6088).

## 1.4.0 / 2020-02-22 / Agent 7.18.0

* [Added] Upgrade supervisor dependency. See [#5627](https://github.com/DataDog/integrations-core/pull/5627).

## 1.3.0 / 2019-12-02 / Agent 7.16.0

* [Added] Add version metadata. See [#4979](https://github.com/DataDog/integrations-core/pull/4979).

## 1.2.0 / 2019-05-14 / Agent 6.12.0

* [Added] Support Python 3. See [#3605](https://github.com/DataDog/integrations-core/pull/3605).
* [Added] Adhere to code style. See [#3571](https://github.com/DataDog/integrations-core/pull/3571).

## 1.1.4 / 2018-10-29 / Agent 6.8.0

* [Fixed] Fix AgentCheck import. See [#2482][1].

## 1.1.3 / 2018-09-04 / Agent 6.5.0

* [Fixed] Add data files to the wheel package. See [#1727][2].

## 1.1.2 / 2018-06-20 / Agent 6.4.0

* [Tooling] Bump check to be in sync with new release tooling

## 1.1.1 / 2018-01-10

* [FEATURE] add support for tags per instance. See [#411][3]. Thanks [@frederikhappel][4].

## 1.1.0 / 2017-09-18

* [SECURITY] bumping supervisor dep to 3.3.3 to address [CVE-2017-11610][5].

## 1.0.0 / 2017-03-22

* [FEATURE] adds supervisord integration.
[1]: https://github.com/DataDog/integrations-core/pull/2482
[2]: https://github.com/DataDog/integrations-core/pull/1727
[3]: https://github.com/DataDog/integrations-core/pull/411
[4]: https://github.com/frederikhappel
[5]: https://nvd.nist.gov/vuln/detail/CVE-2017-11610


text:
<?php
/**
 * Created by PhpStorm.
 * User: dwwang
 * Date: 5/27/15
 * Time: 22:13
 */
class Coupon extends MpController
{

    public function doIndex()
    {
        $html = file_get_html('http://coupon.aliexpress.com/');
        $lis = array();
        $urls = array();
        foreach($html->find('.coupon-list li') as $element){
            $link = $element->children(0);
            $href=$link->href;
            $img=$link->children(0)->children(0)->src;
            $store=$link->children(1)->children(0)->innertext;
            $price=$link->children(1)->children(1)->children(0)->innertext;
            $order=$link->children(1)->children(2)->children(0)->innertext;
            $time=$link->children(1)->children(3)->innertext;
            $li = (object) array('href' => $href, 'img' => $img, 'store' => $store, 'price' => $price, 'order' => $order, 'time' => $time);
            array_push($lis,$li);
            array_push($urls,$href);
        }
        $api_url="http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.getPromotionLinks/85087";
        $http = new WoniuHttp();
        $data['trackingId'] = "aliexprice";
        $data['fields'] = "url,promotionUrl";
        $data['urls'] = join(",",$urls);
        $ref="http://www.aliexprice.com/";
        $result=$http->setReferer($ref)->post($api_url, $data);
//        echo $result;
        $result_object=json_decode($result);
        $hrefs = $result_object->result->promotionUrls;
        for($i=0;$i<count($hrefs);$i++){
            $url = $hrefs[$i];
            $item = $lis[$i];
            $item->href = $url->promotionUrl;
        }
//        var_dump($lis);
        $viewData=array('items'=>$lis,'title'=>"Aliexprice.com - Online Shopping for Electronics, Fashion, Home & Garden, Toys & Sports, Automobiles from China.",
                        'keywords'=>"Aliexprice, Online shopping, Shopping Online, Online Marketing, Automotive, Phones, Accessories, Computers, Electronics, Fashion, Beauty, Health, Home, Garden, Toys , Sports, Weddings, Events",
                        'description'=>"Online Shopping for Cheap Automotive, Phones Accessories, Computers Electronics, Fashion, Beauty Health, Home Garden, Toys Sports, Weddings Events from China; Shopping on Aliexprice |the world's Online Marketing place.");
        $this->view('coupon',$viewData);
    }

}


text:
<?php

namespace Dili\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DiliAdminBundle extends Bundle
{
}


text:
package biz.c24.io.gettingstarted.transaction.transactions;

/**
 *
 * @author C24 Integration Objects;
 **/
public class StatGenTransform extends biz.c24.io.api.transform.Transform
{
    public final biz.c24.io.gettingstarted.transaction.transactions.StatGenTransform.JustScroogeFilter JUSTSCROOGE = new biz.c24.io.gettingstarted.transaction.transactions.StatGenTransform.JustScroogeFilter();
    public final biz.c24.io.gettingstarted.transaction.transactions.StatGenTransform.RecordToStmtLineTransform RECORDTOSTMTLINE = new biz.c24.io.gettingstarted.transaction.transactions.StatGenTransform.RecordToStmtLineTransform();

    {
        register(JUSTSCROOGE);
        register(RECORDTOSTMTLINE);
    }

    public StatGenTransform()
    {
        super(new biz.c24.io.api.data.DataType[] {biz.c24.io.gettingstarted.transaction.TransactionsClass.getInstance()}, new biz.c24.io.api.data.DataType[] {biz.c24.io.training.statements.StatementFileClass.getInstance()});
    }

    public StatGenTransform(biz.c24.io.api.data.Element[] inputElements, biz.c24.io.api.data.Element[] outputElements)
    {
        super(new biz.c24.io.api.data.DataType[] {biz.c24.io.gettingstarted.transaction.TransactionsClass.getInstance()}, new biz.c24.io.api.data.DataType[] {biz.c24.io.training.statements.StatementFileClass.getInstance()}, inputElements, outputElements);
    }

    protected StatGenTransform(biz.c24.io.api.data.DataType[] inputTypes, biz.c24.io.api.data.DataType[] outputTypes)
    {
        super(inputTypes, outputTypes);
    }

    protected StatGenTransform(biz.c24.io.api.data.DataType[] inputTypes, biz.c24.io.api.data.DataType[] outputTypes, biz.c24.io.api.data.Element[] inputElements, biz.c24.io.api.data.Element[] outputElements)
    {
        super(inputTypes, outputTypes, inputElements, outputElements);
    }

    public java.lang.String getName()
    {
        return "StatGen.tfd";
    }

    public static void main(java.lang.String[] args)
    {
        if (args.length == 2)
        {
            org.apache.log4j.Appender appender = new org.apache.log4j.ConsoleAppender(new org.apache.log4j.SimpleLayout());

            java.util.Set loggers = new java.util.HashSet();

            try
            {
                biz.c24.io.api.transform.Transform transform = new StatGenTransform();
                loggers.add(transform.getLog());

                biz.c24.io.api.data.Element inputElement0 = null;
                transform.setInput(0, inputElement0 = transform.getPossibleInputElementDecls(0).length > 0 ? (biz.c24.io.api.data.Element) java.lang.Class.forName(transform.getPossibleInputElementDecls(0)[0]).getMethod("getInstance", null).invoke(null, null) : transform.getInput(0));
                loggers.add(inputElement0.getLog());

                biz.c24.io.api.data.Element outputElement0 = null;
                transform.setOutput(0, outputElement0 = transform.getPossibleOutputElementDecls(0).length > 0 ? (biz.c24.io.api.data.Element) java.lang.Class.forName(transform.getPossibleOutputElementDecls(0)[0]).getMethod("getInstance", null).invoke(null, null) : transform.getOutput(0));
                loggers.add(outputElement0.getLog());

                for (java.util.Iterator it = loggers.iterator(); it.hasNext(); )
                {
                    org.apache.log4j.Logger logger = (org.apache.log4j.Logger) it.next();
                    logger.addAppender(appender);
                    logger.setLevel(org.apache.log4j.Level.OFF); // change this to see console logging
                }

                java.lang.System.out.println("Running...");
                java.util.List inputBeanList = new java.util.LinkedList();
                java.lang.Object[][] inputBeanArray = new java.lang.Object[1][];
                biz.c24.io.api.presentation.Source source0 = transform.getInput(0).getModel().source();
                for (int i=0; ; i++)
                {
                    java.lang.String inputFileName = args[0];
                    java.io.File inputFile = new java.io.File(i == 0 ? inputFileName : (inputFileName.indexOf('.') == -1 ? inputFileName + i : inputFileName.substring(0, inputFileName.lastIndexOf(".")) + i + inputFileName.substring(inputFileName.lastIndexOf("."))));
                    if (!inputFile.canRead())
                        break;
                    java.lang.System.out.println("Reading '"+inputFile.getAbsolutePath()+"' ...");
                    source0.setInputStream(new java.io.FileInputStream(inputFile));
                    inputBeanList.add(source0.readObject(inputElement0));
                    source0.getInputStream().close();
                }
                inputBeanArray[0] = inputBeanList.toArray(new java.lang.Object[inputBeanList.size()]);
                    inputBeanList.clear();

                java.lang.Object[][] outputBeanArray = transform.transform(inputBeanArray);
                biz.c24.io.api.presentation.Sink sink0 = transform.getOutput(0).getModel().sink();
                for (int i=0; i<outputBeanArray[0].length; i++)
                {
                    java.lang.String outputFileName = args[1];
                    java.io.File outputFile = new java.io.File(i == 0 ? outputFileName : (outputFileName.indexOf('.') == -1 ? outputFileName + i : outputFileName.substring(0, outputFileName.lastIndexOf(".")) + i + outputFileName.substring(outputFileName.lastIndexOf("."))));
                    java.lang.System.out.println("Writing '"+outputFile.getAbsolutePath()+"' ...");
                    sink0.setOutputStream(new java.io.FileOutputStream(outputFile));
                    sink0.writeObject((biz.c24.io.api.data.ComplexDataObject) outputBeanArray[0][i]);
                    sink0.getOutputStream().close();
                }

                java.lang.System.out.println("Finished");
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                for (java.util.Iterator it = loggers.iterator(); it.hasNext(); )
                    ((org.apache.log4j.Logger) it.next()).removeAppender(appender);
            }
        }
        else
            java.lang.System.out.println("Usage: java StatGenTransform <input 'Transactions' filename> <output 'StatementFile' filename>");
    }

    public java.lang.Object[][] transform(final java.lang.Object[][] inArr) throws biz.c24.io.api.data.ValidationException
    {
        checkRequiredInputs(inArr);
        java.lang.Object[][] outArr = transform(inArr, init(inArr));
        checkRequiredOutputs(outArr);
        return outArr;
    }

    protected java.lang.Object[][] transform(java.lang.Object[][] inArr, java.lang.Object[][] outArr) throws biz.c24.io.api.data.ValidationException
    {
        initElement(outArr[0], "Statement", "StmtLine", transform(RECORDTOSTMTLINE, new java.lang.Object[] {filter(JUSTSCROOGE, new java.lang.Object[] {}, resolve(inArr[0], "CustomerDetails", false, true))}, 0, null), false, true);
        return outArr;
    }

    public biz.c24.io.training.statements.StatementFile transform(final biz.c24.io.gettingstarted.transaction.Transactions input1) throws biz.c24.io.api.data.ValidationException
    {
        java.lang.Object[][] outArr = transform(new java.lang.Object[][]{{input1}});
        return (biz.c24.io.training.statements.StatementFile) (outArr.length > 0 && outArr[0].length > 0 ? outArr[0][0] : null);
    }

    /**
     *
     * @author C24 Integration Objects;
     **/
    public class JustScroogeFilter extends biz.c24.io.api.transform.Filter
    {

        public java.lang.Object filter(final java.lang.Object arg, final java.lang.Object[] inArr) throws biz.c24.io.api.data.ValidationException
        {
            java.lang.Object obj = EQUALS.f(resolve(arg, "Name", false, true), "Mr Scrooge");
            if (booleanOrValue(obj))
                return resolve(arg, "", false, true);
            else
                return null;
        }

    }

    /**
     *
     * @author C24 Integration Objects;
     **/
    public class RecordToStmtLineTransform extends biz.c24.io.api.transform.Transform
    {

        public RecordToStmtLineTransform()
        {
            super(new biz.c24.io.api.data.DataType[] {biz.c24.io.gettingstarted.transaction.CustomerDetailsClass.getInstance()}, new biz.c24.io.api.data.DataType[] {biz.c24.io.training.statements.StatementLineClass.getInstance()});
        }

        public RecordToStmtLineTransform(biz.c24.io.api.data.Element[] inputElements, biz.c24.io.api.data.Element[] outputElements)
        {
            super(new biz.c24.io.api.data.DataType[] {biz.c24.io.gettingstarted.transaction.CustomerDetailsClass.getInstance()}, new biz.c24.io.api.data.DataType[] {biz.c24.io.training.statements.StatementLineClass.getInstance()}, inputElements, outputElements);
        }

        protected RecordToStmtLineTransform(biz.c24.io.api.data.DataType[] inputTypes, biz.c24.io.api.data.DataType[] outputTypes)
        {
            super(inputTypes, outputTypes);
        }

        protected RecordToStmtLineTransform(biz.c24.io.api.data.DataType[] inputTypes, biz.c24.io.api.data.DataType[] outputTypes, biz.c24.io.api.data.Element[] inputElements, biz.c24.io.api.data.Element[] outputElements)
        {
            super(inputTypes, outputTypes, inputElements, outputElements);
        }

        public java.lang.String getName()
        {
            return "Record to StmtLine";
        }

        public java.lang.Object[][] transform(final java.lang.Object[][] inArr) throws biz.c24.io.api.data.ValidationException
        {
            checkRequiredInputs(inArr);
            java.lang.Object[][] outArr = transform(inArr, init(inArr));
            checkRequiredOutputs(outArr);
            return outArr;
        }

        protected java.lang.Object[][] transform(java.lang.Object[][] inArr, java.lang.Object[][] outArr) throws biz.c24.io.api.data.ValidationException
        {
            initElement(outArr[0], null, "TxAmount", CAST.f(resolve(inArr[0], "Amount", false, true), biz.c24.io.api.data.FloatDataType.getInstance()), false, true);
            initElement(outArr[0], null, "PostingNarrative", resolve(inArr[0], "Name", false, true), false, true);
            return outArr;
        }

    }

}