text:
require_relative 'pieces'
require_relative '../chess_utils/chess_utils'

class Board
  include ChessUtils
  include ChessUtils::Renderable

  def initialize
    @rows = Array.new(SIZE) { Array.new(SIZE) }
  end

  def [](pos)
    row, col = pos
    rows[row][col]
  end

  def []=(pos, piece)
    row, col = pos
    rows[row][col] = piece
  end

  def move_piece(piece, pos)
    self[pos] = piece
    self[piece.pos] = nil
    piece.pos = pos
  end

  def in_range?(pos)
    pos.all? { |coord| coord.between?(0, SIZE - 1) }
  end

  def in_check?(color)
    king = pieces.find do |piece|
      piece.is_a?(King) && piece.color == color
    end

    opposing_pieces = pieces.reject { |piece| piece.color == color }

    opposing_pieces.any? do |piece|
      piece.moves.any? { |move| move == king.pos }
    end
  end

  def pieces
    rows.flatten.compact
  end

  def dup
    duped_board = self.class.new

    pieces.each do |piece|
      piece.class.new(duped_board, piece.color, piece.pos)
    end

    duped_board
  end

  def empty?(pos)
    self[pos].nil?
  end

  def piece?(pos)
    self[pos].is_a?(Piece)
  end

  def checkmate?(color)
    pieces = self.pieces.select { |piece| piece.color == color }

    in_check?(color) && pieces.all? { |piece| piece.valid_moves.empty? }
  end

  def fill_rows
    positions.map do |coord, piece|
      piece.new(self, :black, [0, coord])
      piece.new(self, :white, [(SIZE - 1), coord])
    end

    (0...SIZE).each do |coord|
      Pawn.new(self, :black, [1, coord])
      Pawn.new(self, :white, [(SIZE - 2), coord])
    end
  end

  def add_piece(piece, pos)
    raise 'space not empty' unless empty?(pos)

    self[pos] = piece
  end

  protected
  attr_reader :rows

  private

  def positions
    STARTING_POSITIONS.inject({}) do |positions, (coord, piece)|
      positions.merge(coord => constantize(piece))
    end
  end

  def constantize(piece)
    Object.const_get(piece.to_s.capitalize)
  end
end


text:
<?php

namespace app\models;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model {

	/**
	 * Making sure, that our model-class is
	 * referring to the correct table !?
	 */
	protected $table = 'payments';

	/**
	 * Specifying which columns, we want to write to...
	 */
    protected $fillable = [

        'failed',
        'transaction_id',
    ];
}

redpajama_set_name: RedPajamaGithub


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

package com.microsoft.live;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.http.client.HttpClient;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

/**
 * AuthorizationRequest performs an Authorization Request by launching a WebView Dialog that
 * displays the login and consent page and then, on a successful login and consent, performs an
 * async AccessToken request.
 */
class AuthorizationRequest implements ObservableOAuthRequest, OAuthRequestObserver {

    /**
     * OAuthDialog is a Dialog that contains a WebView. The WebView loads the passed in Uri, and
     * loads the passed in WebViewClient that allows the WebView to be observed (i.e., when a page
     * loads the WebViewClient will be notified).
     */
    private class OAuthDialog extends Dialog implements OnCancelListener {

        /**
         * AuthorizationWebViewClient is a static (i.e., does not have access to the instance that
         * created it) class that checks for when the end_uri is loaded in to the WebView and calls
         * the AuthorizationRequest's onEndUri method.
         */
        private class AuthorizationWebViewClient extends WebViewClient {

            private final CookieManager cookieManager;
            private final Set<String> cookieKeys;

            public AuthorizationWebViewClient() {
                // I believe I need to create a syncManager before I can use a cookie manager.
                CookieSyncManager.createInstance(getContext());
                this.cookieManager = CookieManager.getInstance();
                this.cookieKeys = new HashSet<String>();
            }

            /**
             * Call back used when a page is being started.
             *
             * This will check to see if the given URL is one of the end_uris/redirect_uris and
             * based on the query parameters the method will either return an error, or proceed with
             * an AccessTokenRequest.
             *
             * @param view {@link WebView} that this is attached to.
             * @param url of the page being started
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                Uri uri = Uri.parse(url);

                // only clear cookies that are on the logout domain.
                if (uri.getHost() != null && uri.getHost().equals(Config.INSTANCE.getOAuthLogoutUri().getHost())) {
                    this.saveCookiesInMemory(this.cookieManager.getCookie(url));
                }

                Uri endUri = Config.INSTANCE.getOAuthDesktopUri();
                boolean isEndUri = UriComparator.INSTANCE.compare(uri, endUri) == 0;
                if (!isEndUri) {
                    return;
                }

                this.saveCookiesToPreferences();

                AuthorizationRequest.this.onEndUri(uri);
                OAuthDialog.this.dismiss();
            }

            /**
             * Callback when the WebView received an Error.
             *
             * This method will notify the listener about the error and dismiss the WebView dialog.
             *
             * @param view the WebView that received the error
             * @param errorCode the error code corresponding to a WebViewClient.ERROR_* value
             * @param description the String containing the description of the error
             * @param failingUrl the url that encountered an error
             */
            @Override
            public void onReceivedError(WebView view,
                                        int errorCode,
                                        String description,
                                        String failingUrl) {
                AuthorizationRequest.this.onError("", description, failingUrl);
                OAuthDialog.this.dismiss();
            }

//            @Override
//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                // TODO: Android does not like the SSL certificate we use, because it has '*' in
//                // it. Proceed with the errors.
//                handler.proceed();
//            }

            private void saveCookiesInMemory(String cookie) {
                // Not all URLs will have cookies
                if (TextUtils.isEmpty(cookie)) {
                    return;
                }

                String[] pairs = TextUtils.split(cookie, "; ");
                for (String pair : pairs) {
                    int index = pair.indexOf(EQUALS);
                    String key = pair.substring(0, index);
                    this.cookieKeys.add(key);
                }
            }

            private void saveCookiesToPreferences() {
                SharedPreferences preferences =
                        getContext().getSharedPreferences(PreferencesConstants.FILE_NAME,
                                                          Context.MODE_PRIVATE);

                // If the application tries to login twice, before calling logout, there could
                // be a cookie that was sent on the first login, that was not sent in the second
                // login. So, read the cookies in that was saved before, and perform a union
                // with the new cookies.
                String value = preferences.getString(PreferencesConstants.COOKIES_KEY, "");
                String[] valueSplit = TextUtils.split(value, PreferencesConstants.COOKIE_DELIMITER);

                this.cookieKeys.addAll(Arrays.asList(valueSplit));

                Editor editor = preferences.edit();
                value = TextUtils.join(PreferencesConstants.COOKIE_DELIMITER, this.cookieKeys);
                editor.putString(PreferencesConstants.COOKIES_KEY, value);
                editor.commit();

                // we do not need to hold on to the cookieKeys in memory anymore.
                // It could be garbage collected when this object does, but let's clear it now,
                // since it will not be used again in the future.
                this.cookieKeys.clear();
            }
        }

        /** Uri to load */
        private final Uri requestUri;

        /**
         * Constructs a new OAuthDialog.
         *
         * @param context to construct the Dialog in
         * @param requestUri to load in the WebView
         * @param webViewClient to be placed in the WebView
         */
        public OAuthDialog(Uri requestUri) {
            super(AuthorizationRequest.this.activity, android.R.style.Theme_Translucent_NoTitleBar);
            this.setOwnerActivity(AuthorizationRequest.this.activity);

            assert requestUri != null;
            this.requestUri = requestUri;
        }

        /** Called when the user hits the back button on the dialog. */
        @Override
        public void onCancel(DialogInterface dialog) {
            LiveAuthException exception = new LiveAuthException(ErrorMessages.SIGNIN_CANCEL);
            AuthorizationRequest.this.onException(exception);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            this.setOnCancelListener(this);

            FrameLayout content = new FrameLayout(this.getContext());
            LinearLayout webViewContainer = new LinearLayout(this.getContext());
            WebView webView = new WebView(this.getContext());

            webView.setWebViewClient(new AuthorizationWebViewClient());

            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);

            webView.loadUrl(this.requestUri.toString());
            webView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                                     LayoutParams.FILL_PARENT));
            webView.setVisibility(View.VISIBLE);

            webViewContainer.addView(webView);
            webViewContainer.setVisibility(View.VISIBLE);

            content.addView(webViewContainer);
            content.setVisibility(View.VISIBLE);

            content.forceLayout();
            webViewContainer.forceLayout();

            this.addContentView(content,
                                new LayoutParams(LayoutParams.FILL_PARENT,
                                                 LayoutParams.FILL_PARENT));
        }
    }

    /**
     * Compares just the scheme, authority, and path. It does not compare the query parameters or
     * the fragment.
     */
    private enum UriComparator implements Comparator<Uri> {
        INSTANCE;

        @Override
        public int compare(Uri lhs, Uri rhs) {
            String[] lhsParts = { lhs.getScheme(), lhs.getAuthority(), lhs.getPath() };
            String[] rhsParts = { rhs.getScheme(), rhs.getAuthority(), rhs.getPath() };

            assert lhsParts.length == rhsParts.length;
            for (int i = 0; i < lhsParts.length; i++) {
                int compare = lhsParts[i].compareTo(rhsParts[i]);
                if (compare != 0) {
                    return compare;
                }
            }

            return 0;
        }
    }

    private static final String AMPERSAND = "&";
    private static final String EQUALS = "=";

    /**
     * Turns the fragment parameters of the uri into a map.
     *
     * @param uri to get fragment parameters from
     * @return a map containing the fragment parameters
     */
    private static Map<String, String> getFragmentParametersMap(Uri uri) {
        String fragment = uri.getFragment();
        String[] keyValuePairs = TextUtils.split(fragment, AMPERSAND);
        Map<String, String> fragementParameters = new HashMap<String, String>();

        for (String keyValuePair : keyValuePairs) {
            int index = keyValuePair.indexOf(EQUALS);
            String key = keyValuePair.substring(0, index);
            String value = keyValuePair.substring(index + 1);
            fragementParameters.put(key, value);
        }

        return fragementParameters;
    }

    private final Activity activity;
    private final HttpClient client;
    private final String clientId;
    private final DefaultObservableOAuthRequest observable;
    private final String redirectUri;
    private final String scope;

    public AuthorizationRequest(Activity activity,
                                HttpClient client,
                                String clientId,
                                String redirectUri,
                                String scope) {
        assert activity != null;
        assert client != null;
        assert !TextUtils.isEmpty(clientId);
        assert !TextUtils.isEmpty(redirectUri);
        assert !TextUtils.isEmpty(scope);

        this.activity = activity;
        this.client = client;
        this.clientId = clientId;
        this.redirectUri = redirectUri;
        this.observable = new DefaultObservableOAuthRequest();
        this.scope = scope;
    }

    @Override
    public void addObserver(OAuthRequestObserver observer) {
        this.observable.addObserver(observer);
    }

    /**
     * Launches the login/consent page inside of a Dialog that contains a WebView and then performs
     * a AccessTokenRequest on successful login and consent. This method is async and will call the
     * passed in listener when it is completed.
     */
    public void execute() {
        String displayType = this.getDisplayParameter();
        String responseType = OAuth.ResponseType.CODE.toString().toLowerCase(Locale.US);
        String locale = Locale.getDefault().toString();
        Uri requestUri = Config.INSTANCE.getOAuthAuthorizeUri()
                                        .buildUpon()
                                        .appendQueryParameter(OAuth.CLIENT_ID, this.clientId)
                                        .appendQueryParameter(OAuth.SCOPE, this.scope)
                                        .appendQueryParameter(OAuth.DISPLAY, displayType)
                                        .appendQueryParameter(OAuth.RESPONSE_TYPE, responseType)
                                        .appendQueryParameter(OAuth.LOCALE, locale)
                                        .appendQueryParameter(OAuth.REDIRECT_URI, this.redirectUri)
                                        .build();

        OAuthDialog oAuthDialog = new OAuthDialog(requestUri);
        oAuthDialog.show();
    }

    @Override
    public void onException(LiveAuthException exception) {
        this.observable.notifyObservers(exception);
    }

    @Override
    public void onResponse(OAuthResponse response) {
        this.observable.notifyObservers(response);
    }

    @Override
    public boolean removeObserver(OAuthRequestObserver observer) {
        return this.observable.removeObserver(observer);
    }

    /**
     * Gets the display parameter by looking at the screen size of the activity.
     * @return "android_phone" for phones and "android_tablet" for tablets.
     */
    private String getDisplayParameter() {
        ScreenSize screenSize = ScreenSize.determineScreenSize(this.activity);
        DeviceType deviceType = screenSize.getDeviceType();

        return deviceType.getDisplayParameter().toString().toLowerCase(Locale.US);
    }

    /**
     * Called when the response uri contains an access_token in the fragment.
     *
     * This method reads the response and calls back the LiveOAuthListener on the UI/main thread,
     * and then dismisses the dialog window.
     *
     * See Section
     * 1.3.1 of the OAuth 2.0 spec.
     *
     * @param fragmentParameters in the uri
     */
    private void onAccessTokenResponse(Map<String, String> fragmentParameters) {
        assert fragmentParameters != null;

        OAuthSuccessfulResponse response;
        try {
            response = OAuthSuccessfulResponse.createFromFragment(fragmentParameters);
        } catch (LiveAuthException e) {
            this.onException(e);
            return;
        }

        this.onResponse(response);
    }

    /**
     * Called when the response uri contains an authorization code.
     *
     * This method launches an async AccessTokenRequest and dismisses the dialog window.
     *
     * See Section
     * 4.1.2 of the OAuth 2.0 spec for more information.
     *
     * @param code is the authorization code from the uri
     */
    private void onAuthorizationResponse(String code) {
        assert !TextUtils.isEmpty(code);

        // Since we DO have an authorization code, launch an AccessTokenRequest.
        // We do this asynchronously to prevent the HTTP IO from occupying the
        // UI/main thread (which we are on right now).
        AccessTokenRequest request = new AccessTokenRequest(this.client,
                                                            this.clientId,
                                                            this.redirectUri,
                                                            code);

        TokenRequestAsync requestAsync = new TokenRequestAsync(request);
        // We want to know when this request finishes, because we need to notify our
        // observers.
        requestAsync.addObserver(this);
        requestAsync.execute();
    }

    /**
     * Called when the end uri is loaded.
     *
     * This method will read the uri's query parameters and fragment, and respond with the
     * appropriate action.
     *
     * @param endUri that was loaded
     */
    private void onEndUri(Uri endUri) {
        // If we are on an end uri, the response could either be in
        // the fragment or the query parameters. The response could
        // either be successful or it could contain an error.
        // Check all situations and call the listener's appropriate callback.
        // Callback the listener on the UI/main thread. We could call it right away since
        // we are on the UI/main thread, but it is probably better that we finish up with
        // the WebView code before we callback on the listener.
        boolean hasFragment = endUri.getFragment() != null;
        boolean hasQueryParameters = endUri.getQuery() != null;
        boolean invalidUri = !hasFragment && !hasQueryParameters;

        // check for an invalid uri, and leave early
        if (invalidUri) {
            this.onInvalidUri();
            return;
        }

        if (hasFragment) {
            Map<String, String> fragmentParameters =
                    AuthorizationRequest.getFragmentParametersMap(endUri);

            boolean isSuccessfulResponse =
                    fragmentParameters.containsKey(OAuth.ACCESS_TOKEN) &&
                    fragmentParameters.containsKey(OAuth.TOKEN_TYPE);
            if (isSuccessfulResponse) {
                this.onAccessTokenResponse(fragmentParameters);
                return;
            }

            String error = fragmentParameters.get(OAuth.ERROR);
            if (error != null) {
                String errorDescription = fragmentParameters.get(OAuth.ERROR_DESCRIPTION);
                String errorUri = fragmentParameters.get(OAuth.ERROR_URI);
                this.onError(error, errorDescription, errorUri);
                return;
            }
        }

        if (hasQueryParameters) {
            String code = endUri.getQueryParameter(OAuth.CODE);
            if (code != null) {
                this.onAuthorizationResponse(code);
                return;
            }

            String error = endUri.getQueryParameter(OAuth.ERROR);
            if (error != null) {
                String errorDescription = endUri.getQueryParameter(OAuth.ERROR_DESCRIPTION);
                String errorUri = endUri.getQueryParameter(OAuth.ERROR_URI);
                this.onError(error, errorDescription, errorUri);
                return;
            }
        }

        // if the code reaches this point, the uri was invalid
        // because it did not contain either a successful response
        // or an error in either the queryParameter or the fragment
        this.onInvalidUri();
    }

    /**
     * Called when end uri had an error in either the fragment or the query parameter.
     *
     * This method constructs the proper exception, calls the listener's appropriate callback method
     * on the main/UI thread, and then dismisses the dialog window.
     *
     * @param error containing an error code
     * @param errorDescription optional text with additional information
     * @param errorUri optional uri that is associated with the error.
     */
    private void onError(String error, String errorDescription, String errorUri) {
        LiveAuthException exception = new LiveAuthException(error,
                                                            errorDescription,
                                                            errorUri);
        this.onException(exception);
    }

    /**
     * Called when an invalid uri (i.e., a uri that does not contain an error or a successful
     * response).
     *
     * This method constructs an exception, calls the listener's appropriate callback on the main/UI
     * thread, and then dismisses the dialog window.
     */
    private void onInvalidUri() {
        LiveAuthException exception = new LiveAuthException(ErrorMessages.SERVER_ERROR);
        this.onException(exception);
    }
}


text:
use std::ascii::AsciiExt;
use std::iter::repeat;
use rand::{Rng, thread_rng};
use super::configuration::{Configuration, WordTransformations, SeperatorTypes, PaddingCharTypes, PaddingTypes};
use super::word_list::WordList;

/// Generates a password with the given configuration and word list.
///
/// ```
/// use xkcd_pass::{generate_password, Configuration, SimpleEnglish};
///
/// let config = Configuration::default();
/// let word_list = SimpleEnglish::new();
/// // Generate 1 password.
/// let password = generate_password(&config, &word_list);
/// println!("Password: {}", password);
/// ```
pub fn generate_password<A: WordList>(config: &Configuration, word_list: &A) -> String {
    // TODO: Accept different random generators
    let mut rgen = thread_rng();

    // Generate the words
    let word_list = word_list.get_words(config.words.min_length, config.words.max_length);
    let num_words = config.words.num_words as usize;
    let mut chosen_words = Vec::with_capacity(num_words);

    for _ in 0..num_words {
        let random_index = rgen.gen_range(0, word_list.len());
        chosen_words.push(word_list[random_index].clone());
    }
    // Lowercase all the words
    for i in 0..chosen_words.len() {
        chosen_words[i] = to_lower_case(&chosen_words[i]);
    }

    // Modify the case of the words
    match config.words.transformations {
        WordTransformations::CapitaliseFirst => {
            for i in 0..chosen_words.len() {
                let final_word: String = {
                    let word = &chosen_words[i];
                    let mut word_iter = word.chars();
                    let mut first_char = word_iter.next().unwrap();
                    first_char = first_char.to_ascii_uppercase();
                    let rest_of_word: String = word_iter.collect();
                    let mut final_str = first_char.to_string();
                    final_str.push_str(&rest_of_word);
                    final_str
                };
                chosen_words[i] = final_word;
            }
        },
        WordTransformations::CapitaliseNonFirst => {
            for i in 0..chosen_words.len() {
                let final_word: String = {
                    let word = &chosen_words[i];
                    let mut word_iter = word.chars();
                    let mut first_char = word_iter.next().unwrap();
                    first_char = first_char.to_ascii_lowercase();
                    let rest_of_word: String = word_iter.map(|a| a.to_ascii_uppercase()).collect();
                    let mut final_str = first_char.to_string();
                    final_str.push_str(&rest_of_word);
                    final_str
                };
                chosen_words[i] = final_word;
            }
        },
        WordTransformations::LowerCase => {
            // Do nothing since all the words are already lower case
        },
        WordTransformations::UpperCase => {
            for i in 0..chosen_words.len() {
                chosen_words[i] = to_upper_case(&chosen_words[i]);
            }
        },
        WordTransformations::AlternatingLowerUpper => {
            for i in 0..chosen_words.len() {
                if i % 2 == 1 {
                    // Make every second word upper case
                    chosen_words[i] = to_upper_case(&chosen_words[i]);
                }
            }
        },
        WordTransformations::RandomLowerUpper => {
            for i in 0..chosen_words.len() {
                if rgen.gen() {
                    // Make every second word upper case
                    chosen_words[i] = to_upper_case(&chosen_words[i]);
                }
            }
        },
    }

    // Determine the seperator character
    let num_seperators = config.seperator.seperators.len();
    assert!(num_seperators > 0);
    let sep_char = match config.seperator.seperator_type {
        SeperatorTypes::SingleCharacter => {
            config.seperator.seperators[0]
        }
        SeperatorTypes::RandomCharacter => {
            let random_index = rgen.gen_range(0, num_seperators);
            config.seperator.seperators[random_index]
        }
    };

    // Determine the padding character
    let num_pad_chars = config.padding_symbols.padding_chars.len();
    let pad_char = match config.padding_symbols.padding_character_type {
        PaddingCharTypes::SingleCharacter => {
            assert!(num_pad_chars > 0);
            config.padding_symbols.padding_chars[0]
        },
        PaddingCharTypes::RandomCharacter => {
            assert!(num_pad_chars > 0);
            let random_index = rgen.gen_range(0, num_pad_chars);
            config.padding_symbols.padding_chars[random_index]
        },
        PaddingCharTypes::SeperatorCharacter => {
            sep_char
        },
    };

    // Determine the digits before and after
    let num_digits_before = config.padding_digits.num_before;
    let num_digits_after = config.padding_digits.num_after;
    let mut digits_before_str = String::new();
    let mut digits_after_str = String::new();
    if num_digits_before > 0 {
        let digits_before = rgen.gen_range(10u64.pow((num_digits_before - 1) as u32), 10u64.pow(num_digits_before as u32));
        digits_before_str = digits_before.to_string();
    }
    if num_digits_after > 0 {
        let digits_after = rgen.gen_range(10u64.pow((num_digits_after - 1) as u32), 10u64.pow(num_digits_after as u32));
        digits_after_str = digits_after.to_string();
    }

    // Build the final password

    // Generate the string without the padding
    let mut pass = String::from("");
    if num_digits_before > 0 {
        let temp_dig = format!("{}{}", digits_before_str, sep_char);
        pass.push_str(&temp_dig);
    }

    for (i, word) in chosen_words.iter().enumerate() {
        if i != 0 {
            pass.push_str(&sep_char.to_string());
        }
        pass.push_str(&word);
    }

    if num_digits_after > 0 {
        let temp_dig = format!("{}{}", sep_char, digits_after_str);
        pass.push_str(&temp_dig);
    }

    // Generate the padding
    match config.padding_symbols.padding_type {
        PaddingTypes::Adaptive(min_length) => {
            let pass_length = pass.len();
            let min_length = min_length as usize; // TODO: Use usize in config ?
            if min_length > pass_length {
                let needed_padding = min_length - pass_length;
                let end_pad: String = repeat(pad_char).take(needed_padding).collect();

                pass = format!("{}{}", pass, end_pad);
            }
        },
        PaddingTypes::Fixed(num_pad_before, num_pad_after) => {
            let begin_pad: String = repeat(pad_char).take(num_pad_before as usize).collect();
            let end_pad: String = repeat(pad_char).take(num_pad_after as usize).collect();

            pass = format!("{}{}{}", begin_pad, pass, end_pad);
        },
    }

    return pass;
}

fn to_lower_case(s: &str) -> String {
    return s.to_ascii_lowercase();
}

fn to_upper_case(s: &str) -> String {
    return s.to_ascii_uppercase();
}


text:
layout: post
title: "Marc Broussard - Weight of the World"
date: 2014-07-16 00:27:18 -0400
external-url: "https://www.youtube.com/watch?v=q8qUbNt7rzY"
---

Marc Broussard is a musical, lyrical, and human genius. His voice is
incredible and this latest song has backup singers. BACKUP SINGERS.
Soulful in every magical sense of the word.

According to [americansongwriter.com](https://americansongwriter.com/video-premiere-marc-broussard-weight-world-acoustic/),
Marc said:

> "This song is all about keeping love simple. Keeping it all between two
> people and not caring about what the world says. My wife and I ran away
> to get married and had very few witnesses, most of whom were almost
> complete strangers. It didn't matter that our friends and family missed
> our altar moment because it wasn't about them."


text:
<!doctype html>

  <meta charset="utf-8">

  <link rel="import" href="../../test-fixture/test-fixture.html">
  <link rel="import" href="common-imports.html">

  <test-fixture id="default">
    <template>
      <vaadin-combo-box item-label-path="name" item-value-path="symbol">
      </vaadin-combo-box>
    </template>
  </test-fixture>

  <test-fixture id="with-template">
    <template>
      <vaadin-combo-box item-label-path="name" item-value-path="symbol">
        <template>

templatizer-content

        </template>
      </vaadin-combo-box>
    </template>
  </test-fixture>


text:
package com.crawljax.forms;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.xpath.XPathExpressionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import com.crawljax.browser.EmbeddedBrowser;
import com.crawljax.condition.eventablecondition.EventableCondition;
import com.crawljax.core.CandidateElement;
import com.crawljax.core.configuration.InputSpecification;
import com.crawljax.core.state.Identification;
import com.crawljax.util.DomUtils;
import com.crawljax.util.XPathHelper;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;

/**
 * Helper class for FormHandler.
 */
public final class FormInputValueHelper {

	private static final Logger LOGGER = LoggerFactory.getLogger(FormInputValueHelper.class
	        .getName());

	private ImmutableMap<String, String> formFields;
	private ImmutableListMultimap<String, String> formFieldNames;
	private ImmutableListMultimap<String, String> fieldValues;

	private boolean randomInput;

	private static final int EMPTY = 0;

	/**
	 * @param inputSpecification
	 *            the input specification.
	 * @param randomInput
	 *            if random data should be used on the input fields.
	 */
	public FormInputValueHelper(InputSpecification inputSpecification, boolean randomInput) {

		this.formFieldNames = inputSpecification.getFormFieldNames();
		this.fieldValues = inputSpecification.getFormFieldValues();

		ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
		for (Entry<String, String> entry : formFieldNames.entries()) {
			builder.put(entry.getValue(), entry.getKey());
		}
		formFields = builder.build();

		this.randomInput = randomInput;
	}

	private Element getBelongingElement(Document dom, String fieldName) {
		List<String> names = getNamesForInputFieldId(fieldName);
		if (names != null) {
			for (String name : names) {
				String xpath = "//*[@name='" + name + "' or @id='" + name + "']";
				try {
					Node node = DomUtils.getElementByXpath(dom, xpath);
					if (node != null) {
						return (Element) node;
					}
				} catch (XPathExpressionException e) {
					LOGGER.debug(e.getLocalizedMessage(), e);
					// just try next
				}
			}
		}
		return null;
	}

	private int getMaxNumberOfValues(List<String> fieldNames) {
		int maxValues = 0;
		// check the maximum number of form inputValues
		for (String fieldName : fieldNames) {
			List<String> values = getValuesForName(fieldName);
			if (values != null && values.size() > maxValues) {
				maxValues = values.size();
			}
		}
		return maxValues;
	}

	/**
	 * @param browser
	 *            the browser instance
	 * @param sourceElement
	 *            the form elements
	 * @param eventableCondition
	 *            the belonging eventable condition for sourceElement
	 * @return a list with Candidate elements for the inputs
	 */
	public List<CandidateElement> getCandidateElementsForInputs(EmbeddedBrowser browser,
	        Element sourceElement, EventableCondition eventableCondition) {
		List<CandidateElement> candidateElements = new ArrayList<CandidateElement>();
		int maxValues = getMaxNumberOfValues(eventableCondition.getLinkedInputFields());

		if (maxValues == EMPTY) {
			LOGGER.warn("No input values found for element: "
			        + DomUtils.getElementString(sourceElement));
			return candidateElements;
		}

		Document dom;
		try {
			dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());
		} catch (IOException e) {
			LOGGER.error("Catched IOException while parsing dom", e);
			return candidateElements;
		}

		// add maxValues Candidate Elements for every input combination
		for (int curValueIndex = 0; curValueIndex < maxValues; curValueIndex++) {
			List<FormInput> formInputsForCurrentIndex = new ArrayList<FormInput>();
			for (String fieldName : eventableCondition.getLinkedInputFields()) {
				Element element = getBelongingElement(dom, fieldName);
				if (element != null) {
					FormInput formInput =
					        getFormInputWithIndexValue(browser, element, curValueIndex);
					formInputsForCurrentIndex.add(formInput);
				} else {
					LOGGER.warn("Could not find input element for: " + fieldName);
				}
			}

			String id = eventableCondition.getId() + "_" + curValueIndex;
			sourceElement.setAttribute("atusa", id);

			// clone node inclusive text content
			Element cloneElement = (Element) sourceElement.cloneNode(false);
			cloneElement.setTextContent(DomUtils.getTextValue(sourceElement));

			CandidateElement candidateElement =
			        new CandidateElement(cloneElement,
			                XPathHelper.getXPathExpression(sourceElement),
			                formInputsForCurrentIndex);
			candidateElements.add(candidateElement);
		}
		return candidateElements;
	}

	/**
	 * @param input
	 *            the form input
	 * @param dom
	 *            the document
	 * @return returns the belonging node to input in dom
	 * @throws XPathExpressionException
	 *             if a failure is occurred.
	 */
	public Node getBelongingNode(FormInput input, Document dom) throws XPathExpressionException {

		Node result = null;

		switch (input.getIdentification().getHow()) {
			case xpath:
				result = DomUtils.getElementByXpath(dom, input.getIdentification().getValue());
				break;

			case id:
			case name:
				String xpath = "";
				String element = "";

				if (input.getType().equalsIgnoreCase("select")
				        || input.getType().equalsIgnoreCase("textarea")) {
					element = input.getType().toUpperCase();
				} else {
					element = "INPUT";
				}
				xpath =
				        "//" + element + "[@name='" + input.getIdentification().getValue()
				                + "' or @id='" + input.getIdentification().getValue() + "']";
				System.out.println("xpath = " + xpath);
				result = DomUtils.getElementByXpath(dom, xpath);
				System.out.println("node = " + result);
				break;

			default:
				LOGGER.info("Identification " + input.getIdentification()
				        + " not supported yet for form inputs.");
				break;

		}

		return result;
	}

	/**
	 * @param element
	 * @return returns the id of the element if set, else the name. If none found, returns null
	 * @throws Exception
	 */
	private Identification getIdentification(Node element) throws Exception {
		NamedNodeMap attributes = element.getAttributes();
		if (attributes.getNamedItem("id") != null) {
			return new Identification(Identification.How.id, attributes.getNamedItem("id")
			        .getNodeValue());
		} else if (attributes.getNamedItem("name") != null) {
			return new Identification(Identification.How.name, attributes.getNamedItem("name")
			        .getNodeValue());
		}

		// try to find the xpath
		String xpathExpr = XPathHelper.getXPathExpression(element);
		if (xpathExpr != null && !xpathExpr.equals("")) {
			return new Identification(Identification.How.xpath, xpathExpr);
		}

		return null;
	}

	/**
	 * @param browser
	 *            the current browser instance
	 * @param element
	 *            the element in the dom
	 * @return the first related formInput belonging to element in the browser
	 */
	public FormInput getFormInputWithDefaultValue(EmbeddedBrowser browser, Node element) {
		return getFormInput(browser, element, 0);
	}

	/**
	 * @param browser
	 *            the current browser instance
	 * @param element
	 *            the element in the dom
	 * @param indexValue
	 *            the i-th specified value. if i>#values, first value is used
	 * @return the specified value with index indexValue for the belonging elements
	 */
	public FormInput getFormInputWithIndexValue(EmbeddedBrowser browser, Node element,
	        int indexValue) {
		return getFormInput(browser, element, indexValue);
	}

	private FormInput getFormInput(EmbeddedBrowser browser, Node element, int indexValue) {
		Identification identification;
		try {
			identification = getIdentification(element);
			if (identification == null) {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		// CHECK
		String id = fieldMatches(identification.getValue());
		FormInput input = new FormInput();
		input.setType(getElementType(element));
		input.setIdentification(identification);
		Set<InputValue> values = new HashSet<InputValue>();

		if (id != null && fieldValues.containsKey(id)) {
			// TODO: make multiple selection for list available
			// add defined value to element
			String value;
			if (indexValue == 0 || fieldValues.get(id).size() == 1
			        || indexValue + 1 > fieldValues.get(id).size()) {
				// default value
				value = fieldValues.get(id).get(0);
			} else if (indexValue > 0) {
				// index value
				value = fieldValues.get(id).get(indexValue);
			} else {
				// random value
				value =
				        fieldValues.get(id).get(
				                new Random().nextInt(fieldValues.get(id).size() - 1));
			}

			if (input.getType().equals("checkbox") || input.getType().equals("radio")) {
				// check element
				values.add(new InputValue(value, value.equals("1")));
			} else {
				// set value of text input field
				values.add(new InputValue(value, true));
			}

			input.setInputValues(values);
		} else {

			if (this.randomInput) {
				return browser.getInputWithRandomValue(input);
			}
			// field is not specified, lets try a random value

		}
		return input;
	}

	private String fieldMatches(String fieldName) {
		for (String field : formFields.keySet()) {
			Pattern p = Pattern.compile(field, Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(fieldName);
			if (m.matches()) {
				return formFields.get(field);
			}
		}
		return null;
	}

	private List<String> getValuesForName(String inputFieldId) {
		if (!fieldValues.containsKey(inputFieldId)) {
			return null;
		}
		return fieldValues.get(inputFieldId);
	}

	private List<String> getNamesForInputFieldId(String inputFieldId) {
		if (!formFieldNames.containsKey(inputFieldId)) {
			return null;
		}
		return formFieldNames.get(inputFieldId);
	}

	private String getElementType(Node node) {
		if (node.getAttributes().getNamedItem("type") != null) {
			return node.getAttributes().getNamedItem("type").getNodeValue().toLowerCase();
		} else if (node.getNodeName().equalsIgnoreCase("input")) {
			return "text";
		} else {
			return node.getNodeName().toLowerCase();
		}
	}

}


text:
'use strict'
const TestRunner = require('test-runner')
const commandLineArgs = require('../')
const a = require('assert')

const runner = new TestRunner()

const optionDefinitions = [
  { name: 'один' },
  { name: '两' },
  { name: 'три', alias: 'т' }
]

runner.test('name-unicode: unicode names and aliases are permitted', function () {
  const argv = [ '--один', '1', '--两', '2', '-т', '3' ]
  const result = commandLineArgs(optionDefinitions, { argv })
  a.strictEqual(result.один, '1')
  a.strictEqual(result.两, '2')
  a.strictEqual(result.три, '3')
})


text:
script_dir=`dirname $0`

$script_dir/createSchema/dropSchema.sh bootstrap/bootstrap@localhost


text:
package com.google.javascript.jscomp;

import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

import java.util.HashSet;
import java.util.Set;

/**
 * Verifies that constants are only assigned a value once.
 * e.g. var XX = 5;
 * XX = 3;    // error!
 * XX++;      // error!
 *
 */
class ConstCheck extends AbstractPostOrderCallback
    implements CompilerPass {

  static final DiagnosticType CONST_REASSIGNED_VALUE_ERROR =
      DiagnosticType.error(
          "JSC_CONSTANT_REASSIGNED_VALUE_ERROR",
          "constant {0} assigned a value more than once.\n" +
          "Original definition at {1}");

  private final AbstractCompiler compiler;
  private final Set<Scope.Var> initializedConstants;

  /**
   * Creates an instance.
   */
  public ConstCheck(AbstractCompiler compiler) {
    this.compiler = compiler;
    this.initializedConstants = new HashSet<>();
  }

  @Override
  public void process(Node externs, Node root) {
    Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
    NodeTraversal.traverseRoots(compiler, this, externs, root);
  }

  @Override
  public void visit(NodeTraversal t, Node n, Node parent) {
    switch (n.getType()) {
      case Token.NAME:
        if (parent != null &&
            parent.isVar()) {
          String name = n.getString();
          Scope.Var var = t.getScope().getVar(name);
          if (isConstant(var)) {
            // If a constant is declared in externs, add it to initializedConstants to indicate
            // that it is initialized externally.
            if (n.isFromExterns()) {
              initializedConstants.add(var);
            } else if (n.hasChildren()) {
              if (initializedConstants.contains(var)) {
                reportError(t, n, var, name);
              } else {
                initializedConstants.add(var);
              }
            }
          }
        }
        break;

      case Token.ASSIGN:
      case Token.ASSIGN_BITOR:
      case Token.ASSIGN_BITXOR:
      case Token.ASSIGN_BITAND:
      case Token.ASSIGN_LSH:
      case Token.ASSIGN_RSH:
      case Token.ASSIGN_URSH:
      case Token.ASSIGN_ADD:
      case Token.ASSIGN_SUB:
      case Token.ASSIGN_MUL:
      case Token.ASSIGN_DIV:
      case Token.ASSIGN_MOD: {
        Node lhs = n.getFirstChild();
        if (lhs.isName()) {
          String name = lhs.getString();
          Scope.Var var = t.getScope().getVar(name);
          if (isConstant(var)) {
            if (initializedConstants.contains(var)) {
              reportError(t, n, var, name);
            } else {
              initializedConstants.add(var);
            }
          }
        }
        break;
      }

      case Token.INC:
      case Token.DEC: {
        Node lhs = n.getFirstChild();
        if (lhs.isName()) {
          String name = lhs.getString();
          Scope.Var var = t.getScope().getVar(name);
          if (isConstant(var)) {
            reportError(t, n, var, name);
          }
        }
        break;
      }
    }
  }

  /**
   * Gets whether a variable is a constant initialized to a literal value at
   * the point where it is declared.
   */
  private static boolean isConstant(Scope.Var var) {
    return var != null && var.isInferredConst();
  }

  /**
   * Reports a reassigned constant error.
   */
  void reportError(NodeTraversal t, Node n, Scope.Var var, String name) {
    JSDocInfo info = NodeUtil.getBestJSDocInfo(n);
    if (info == null || !info.getSuppressions().contains("const")) {
      Node declNode = var.getNode();
      String declaredPosition = declNode.getSourceFileName() + ":" + declNode.getLineno();
      compiler.report(t.makeError(n, CONST_REASSIGNED_VALUE_ERROR, name, declaredPosition));
    }
  }
}


text:
#include "condor_common.h"
#include "condor_config.h"
#include "string_list.h"

#include "gceresource.h"
#include "gridmanager.h"

#define HASH_TABLE_SIZE	13

HashTable <HashKey, GCEResource *>
	GCEResource::ResourcesByName( HASH_TABLE_SIZE, hashFunction );

const char * GCEResource::HashName( const char *resource_name,
									const char *project,
									const char *zone,
									const char *auth_file )
{
	static std::string hash_name;
	formatstr( hash_name, "gce %s %s %s#%s", resource_name, project, zone, auth_file );
	return hash_name.c_str();
}

GCEResource* GCEResource::FindOrCreateResource( const char *resource_name,
												const char *project,
												const char *zone,
												const char *auth_file )
{
	int rc;
	GCEResource *resource = NULL;

	rc = ResourcesByName.lookup( HashKey( HashName( resource_name, project, zone, auth_file ) ), resource );
	if ( rc != 0 ) {
		resource = new GCEResource( resource_name, project, zone, auth_file );
		ASSERT(resource);
		resource->Reconfig();
		ResourcesByName.insert( HashKey( HashName( resource_name, project, zone, auth_file ) ), resource );
	} else {
		ASSERT(resource);
	}

	return resource;
}

GCEResource::GCEResource( const char *resource_name,
						  const char *project,
						  const char *zone,
						  const char *auth_file ) :
		BaseResource( resource_name ),
		jobsByInstanceID( hashFunction ),
		m_hadAuthFailure( false )
{
	// although no one will use resource_name, we still keep it for base class constructor

	m_auth_file = strdup(auth_file);
	m_project = strdup(project);
	m_zone = strdup(zone);

	gahp = NULL;

	char * gahp_path = param( "GCE_GAHP" );
	if ( gahp_path == NULL ) {
		dprintf(D_ALWAYS, "GCE_GAHP not defined! \n");
		return;
	}

	ArgList args;
	args.AppendArg("-f");

	gahp = new GahpClient( GCE_RESOURCE_NAME, gahp_path, &args );
	gahp->setNotificationTimerId( pingTimerId );
	gahp->setMode( GahpClient::normal );
	gahp->setTimeout( GCEJob::gahpCallTimeout );

	status_gahp = new GahpClient( GCE_RESOURCE_NAME, gahp_path, &args );

	StartBatchStatusTimer();

	status_gahp->setNotificationTimerId( BatchPollTid() );
	status_gahp->setMode( GahpClient::normal );
	status_gahp->setTimeout( GCEJob::gahpCallTimeout );

	free(gahp_path);
}

GCEResource::~GCEResource()
{
	ResourcesByName.remove( HashKey( HashName( resourceName, m_project, m_zone, m_auth_file ) ) );
	delete gahp;
	free( m_auth_file );
	free( m_project );
	free( m_zone );
}

void GCEResource::Reconfig()
{
	BaseResource::Reconfig();
	gahp->setTimeout( GCEJob::gahpCallTimeout );
}

const char *GCEResource::ResourceType()
{
	return "gce";
}

const char *GCEResource::GetHashName()
{
	return HashName( resourceName, m_project, m_zone, m_auth_file );
}

void GCEResource::PublishResourceAd( ClassAd *resource_ad )
{
	BaseResource::PublishResourceAd( resource_ad );

	resource_ad->Assign( ATTR_GCE_AUTH_FILE, m_auth_file );
	resource_ad->Assign( ATTR_GCE_PROJECT, m_project );
	resource_ad->Assign( ATTR_GCE_ZONE, m_zone );
}

void GCEResource::DoPing( unsigned& ping_delay, bool& ping_complete, bool& ping_succeeded )
{
	// Since GCE doesn't use proxy, we should use Startup() to replace isInitialized()
	if ( gahp->isStarted() == false ) {
		dprintf( D_ALWAYS,"gahp server not up yet, delaying ping\n" );
		ping_delay = 5;
		return;
	}

	ping_delay = 0;

	std::string error_code;
	int rc = gahp->gce_ping( resourceName, m_auth_file, m_project, m_zone );

	if ( rc == GAHPCLIENT_COMMAND_PENDING ) {
		ping_complete = false;
	} else if ( rc != 0 ) {
		ping_complete = true;

		// If the service returns an authorization failure, that means
		// the service is up, so return true.  Individual jobs with
		// invalid authentication tokens will then go on hold, which is
		// what we want (rather than saying idle).
		if( error_code != "" ) {
			if( strstr( error_code.c_str(), "(401)" ) != NULL ) {
				ping_succeeded = true;
				m_hadAuthFailure = true;
				formatstr( authFailureMessage, "(%s): '%s'", error_code.c_str(), gahp->getErrorString() );
			}
		} else {
			ping_succeeded = false;
		}
	} else {
		ping_complete = true;
		ping_succeeded = true;
	}

	return;
}

GCEResource::BatchStatusResult GCEResource::StartBatchStatus() {
	ASSERT( status_gahp );

	StringList instance_id_list;
	StringList instance_name_list;
	StringList instance_status_list;
	StringList instance_status_msg_list;
	int rc = status_gahp->gce_instance_list( resourceName, m_auth_file,
											 m_project, m_zone,
											 instance_id_list,
											 instance_name_list,
											 instance_status_list,
											 instance_status_msg_list );

	if( rc == GAHPCLIENT_COMMAND_PENDING ) { return BSR_PENDING; }

	if( rc != 0 ) {
		dprintf( D_ALWAYS, "Error doing batched GCE status query: %s\n",
				 status_gahp->getErrorString() );
		return BSR_ERROR;
	}

	//
	// We have to let a job know if we can't find a status report for it.
	//
	List<GCEJob> myJobs;
	GCEJob * nextJob = NULL;
	BaseJob *nextBaseJob = NULL;
	registeredJobs.Rewind();
	while ( (nextBaseJob = registeredJobs.Next()) ) {
		nextJob = dynamic_cast< GCEJob * >( nextBaseJob );
		ASSERT( nextJob );
		if ( !nextJob->m_instanceName.empty() ) {
			myJobs.Append( nextJob );
		}
	}

	int job_cnt = instance_id_list.number();
	instance_id_list.rewind();
	instance_name_list.rewind();
	instance_status_list.rewind();
	instance_status_msg_list.rewind();
	ASSERT( instance_name_list.number() == job_cnt );
	ASSERT( instance_status_list.number() == job_cnt );
	ASSERT( instance_status_msg_list.number() == job_cnt );
	for( int i = 0; i < job_cnt; i++ ) {
		std::string instance_id = instance_id_list.next();
		std::string instance_name = instance_name_list.next();
		std::string instance_status = instance_status_list.next();
		std::string instance_status_msg = instance_status_msg_list.next();

		// First, lookup the job using both instace_id and instance_name
		std::string remote_job_id;
		formatstr( remote_job_id, "gce %s %s %s", resourceName,
				   instance_name.c_str(), instance_id.c_str() );

		BaseJob * tmp = NULL;
		rc = BaseJob::JobsByRemoteId.lookup( HashKey( remote_job_id.c_str() ), tmp );

		if( rc == 0 ) {
			ASSERT( tmp );
			GCEJob * job = dynamic_cast< GCEJob * >( tmp );
			if( job == NULL ) {
				EXCEPT( "Found non-GCEJob identified by '%s'.",
						remote_job_id.c_str() );
			}

			dprintf( D_FULLDEBUG, "Found job object via instance id for '%s', updating status ('%s').\n", instance_id.c_str(), instance_status.c_str() );
			// TODO Can we get public DNS name?
			job->StatusUpdate( instance_id.c_str(), instance_status.c_str(),
							   instance_status_msg.c_str(), NULL );
			myJobs.Delete( job );
			continue;
		}

		// We may not know the job's instance_id. Look it up using just the
		// instance_name
		formatstr( remote_job_id, "gce %s %s", resourceName,
				   instance_name.c_str() );

		tmp = NULL;
		rc = BaseJob::JobsByRemoteId.lookup( HashKey( remote_job_id.c_str() ), tmp );

		if( rc == 0 ) {
			ASSERT( tmp );
			GCEJob * job = dynamic_cast< GCEJob * >( tmp );
			if( job == NULL ) {
				EXCEPT( "Found non-GCEJob identified by '%s'.",
						remote_job_id.c_str() );
			}

			dprintf( D_FULLDEBUG, "Found job object via instance name for '%s', updating status ('%s').\n", instance_name.c_str(), instance_status.c_str() );
			// TODO Can we get public DNS name?
			job->StatusUpdate( instance_id.c_str(), instance_status.c_str(),
							   instance_status_msg.c_str(), NULL );
			myJobs.Delete( job );
			continue;
		}

		dprintf( D_FULLDEBUG, "Found unknown instance id='%s' name='%s'; skipping.\n",
				 instance_id.c_str(), instance_name.c_str() );
		continue;
	}

	myJobs.Rewind();
	while( ( nextJob = myJobs.Next() ) ) {
		dprintf( D_FULLDEBUG, "Informing job %p it got no status.\n", nextJob );
		nextJob->StatusUpdate( NULL, NULL, NULL, NULL );
	}

	return BSR_DONE;

	// This should never happen (but the compiler hates you).
	return BSR_ERROR;
}

GCEResource::BatchStatusResult GCEResource::FinishBatchStatus() {
	return StartBatchStatus();
}


text:
#ifndef NODEAUDIOHANDLER_H
#define NODEAUDIOHANDLER_H

#include "AudioHandler.h"

#include <nan.h>
#include <uv.h>

#include <node_version.h>

/**
 * @brief The NodeAudioHandler class
 * Handles audio data by calling a user provided Javascript callback with it.
 */
class NodeAudioHandler : public AudioHandler {
public:
  NodeAudioHandler(v8::Local<v8::Function> musicDeliveryCallback);
  ~NodeAudioHandler();
  void setStopped(bool stopped);
  static NAN_METHOD(setNeedMoreData);
protected:
  void afterMusicDelivery(const sp_audioformat* format);
  bool dataNeeded();
private:
  Nan::Callback musicDeliveryCallback;
  uv_timer_t musicTimer;
  bool needMoreData;
  bool stopped;
  int musicTimerRepeat;
#if NODE_VERSION_AT_LEAST(0, 11, 0) // TODO 11 or 12?
  static void musicTimeout(uv_timer_t* timer);
#else
  static void musicTimeout(uv_timer_t* timer, int status);
#endif
  bool callMusicDeliveryCallback(audio_fifo_data_t* audioData);
};

#endif // NODEAUDIOHANDLER_H


text:
package msLsh

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.mllib.linalg.{Vector, Vectors}

object Main {
  def main(args: Array[String]): Unit = {

	val sc = new SparkContext(new SparkConf)

	val meanShift = msLsh.MsLsh

	val data = sc.textFile(args(0)).map(_.split(",").map(_.toDouble))
					.zipWithIndex
					.map{ case(data, id) => (id, Vectors.dense(data))}.cache

	val model = meanShift.train(sc, data, k=15, epsilon1=args(1).toDouble, epsilon2=args(2).toDouble, epsilon3=args(3).toDouble, ratioToStop=1.0, yStarIter=args(4).toInt, cmin=args(5).toInt, normalisation=args(6).toBoolean, w=1, nbseg=100, nbblocs1=args(7).toInt, nbblocs2=args(8).toInt, nbLabelIter=args(9).toInt)

	val nbd = data.count
	val nbd2 = model.head.clustersCardinalities.values.reduce(_+_)

	println("nbd : " + nbd + "\nnbd2 : " + nbd)

	model.head.clustersCardinalities.foreach(println)
	//meanShift.savelabeling(model(0),"/myPath/label")
	//meanShift.saveClusterInfo(model(0),"/myPath/clusterInfo")

	}
}


text:
@extends('layouts.dashboard')

@section('title')
    Création d'une faction
@endsection

@section('content')

Création d'une nouvelle faction

            Veuillez simplement renseigner le nom de la faction que vous désirez créer.

            <form action="{{ url('faction/create') }}" method="post">

                    Nom
                    <input type="text" class="form-control" name="name" value="{{ old('name') }}">

                <button type="submit" class="btn btn-success">Créer la faction</button>
            </form>

@endsection


text:
#region license
// Copyright (c) 2007-2010 Mauricio Scheffer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using SolrNetLight.Utils;
using SolrNetLight;
using System.Reflection;
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace SolrNetLight.Commands {
	/// <summary>
	/// Adds / updates documents to solr
	/// </summary>
	/// <typeparam name="T">Document type</typeparam>
	public class AddCommand<T> : ISolrCommand {
	    private readonly IEnumerable<KeyValuePair<T, double?>> documents = new List<KeyValuePair<T, double?>>();
	    private readonly AddParameters parameters;

        /// <summary>
        /// Adds / updates documents to solr
        /// </summary>
        /// <param name="documents"></param>
        /// <param name="serializer"></param>
        /// <param name="parameters"></param>
	    public AddCommand(IEnumerable<KeyValuePair<T, double?>> documents, AddParameters parameters) {
            this.documents = documents;
            this.parameters = parameters;
        }

        /// <summary>
        /// Executes this command
        /// </summary>
        /// <param name="connection">The Solr connection</param>
        /// <returns></returns>
	    public async Task<string> Execute(ISolrConnection connection) {
            string flux = string.Empty;
            JObject json = new JObject();
            foreach (var item in this.documents)
            {
                var cmd = new SolrAddRootCommandObject<T>(item.Key);

                flux = JsonConvert.SerializeObject(cmd);

                PropertyInfo[] myPropertyInfo;
                Dictionary<string, object> dictionnaryProperties = new Dictionary<string, object>();

                myPropertyInfo = Type.GetType(typeof(T).AssemblyQualifiedName).GetProperties();
                for (int i = 0; i < myPropertyInfo.Length; i++)
                {
                    dictionnaryProperties = myPropertyInfo[i].GetPropertyAttributes(dictionnaryProperties);
                }

                json = JObject.Parse(flux);

                var fieldDictionaryList = new List<string>();

                foreach (var dictionaryItem in dictionnaryProperties)
                {
                    fieldDictionaryList.Add(dictionaryItem.Key);
                }

                string formattedFlux = RemoveFields(json.SelectToken("add.doc"), fieldDictionaryList).ToString();
            }

            return await connection.Post("/update", json.ToString());
		}

        private JContainer RemoveFields(JToken token, List<string> fields)
        {
            JContainer container = token as JContainer;
            if (container == null) return null;

            List<JToken> removeList = new List<JToken>();

            List<JProperty> propertiesToAdd = new List<JProperty>();

            foreach (JToken el in container.Children())
            {
                JProperty p = el as JProperty;
                if (p != null && fields.Contains(p.Name))
                {
                    foreach (var item in p.Value.ToString().Split(','))
                    {
                        string[] keyValue = item.Split(':');
                        string propertySufix = Regex.Replace(keyValue[0],"[^0-9a-zA-Z]+","");
                        string propertyValue = Regex.Replace(keyValue[1], "[^0-9a-zA-Z]+", "");
                        propertiesToAdd.Add(new JProperty(string.Concat(p.Name, propertySufix), propertyValue));
                    }

                    removeList.Add(el);
                }
                RemoveFields(el, fields);
            }

            foreach (JToken el in removeList)
            {
                el.Remove();
            }

            foreach (JToken item in propertiesToAdd)
            {
                container.Add(item);
            }

            return container;
        }

    }
}


text:
package com.linkedin.pinot.core.realtime.stream;

import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Fetches the partition offset for a stream given the offset criteria, using the {@link StreamMetadataProvider}
 */
public class PartitionOffsetFetcher implements Callable<Boolean> {

  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionOffsetFetcher.class);
  private static final int STREAM_PARTITION_OFFSET_FETCH_TIMEOUT_MILLIS = 10000;

  private final String _topicName;
  private final OffsetCriteria _offsetCriteria;
  private final int _partitionId;

  private Exception _exception = null;
  private long _offset = -1;
  private StreamConsumerFactory _streamConsumerFactory;
  StreamConfig _streamConfig;

  public PartitionOffsetFetcher(final OffsetCriteria offsetCriteria, int partitionId, StreamConfig streamConfig) {
    _offsetCriteria = offsetCriteria;
    _partitionId = partitionId;
    _streamConfig = streamConfig;
    _streamConsumerFactory = StreamConsumerFactoryProvider.create(streamConfig);
    _topicName = streamConfig.getTopicName();
  }

  public long getOffset() {
    return _offset;
  }

  public Exception getException() {
    return _exception;
  }

  /**
   * Callable to fetch the offset of the partition given the stream metadata and offset criteria
   * @return
   * @throws Exception
   */
  @Override
  public Boolean call() throws Exception {
    String clientId = PartitionOffsetFetcher.class.getSimpleName() + "-" + _topicName + "-" + _partitionId;
    try (
        StreamMetadataProvider streamMetadataProvider = _streamConsumerFactory.createPartitionMetadataProvider(clientId,
            _partitionId)) {
      _offset =
          streamMetadataProvider.fetchPartitionOffset(_offsetCriteria, STREAM_PARTITION_OFFSET_FETCH_TIMEOUT_MILLIS);
      if (_exception != null) {
        LOGGER.info("Successfully retrieved offset({}) for stream topic {} partition {}", _offset, _topicName,
            _partitionId);
      }
      return Boolean.TRUE;
    } catch (TransientConsumerException e) {
      LOGGER.warn("Temporary exception when fetching offset for topic {} partition {}:{}", _topicName, _partitionId,
          e.getMessage());
      _exception = e;
      return Boolean.FALSE;
    } catch (Exception e) {
      _exception = e;
      throw e;
    }
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: antiprovn
 * Date: 10/1/14
 * Time: 6:17 AM
 */

namespace User\Entity;

use Doctrine\ORM\Mapping as ORM;

use Common\Entity;
use Common\Func;

/** @ORM\Entity */
class Freelancer extends Entity{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="Resource")
     */
    protected $Resources = null;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="CatTool")
     * @ORM\JoinTable(name="UserDesktopCatTools")
     */
    protected $DesktopCatTools = null;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="OperatingSystem")
     * @ORM\JoinTable(name="UserOperatingSystem")
     */
    protected $DesktopOperatingSystems = null;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="Specialism")
     * @ORM\JoinTable(name="UserInterpretingSpecialisms")
     */
    protected $InterpretingSpecialisms = null;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="CatTool")
     * @ORM\JoinTable(name="UserTranslationCatTools")
     */
    protected $TranslationCatTools = null;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="Specialism")
     * @ORM\JoinTable(name="UserTranslationSpecialisms")
     */
    protected $TranslationSpecialisms = null;

    public function getData(){
        return array(
            'id' => $this->id,
            'DesktopCatTools' => Func::getReferenceIds($this->DesktopCatTools),
            'DesktopOperatingSystems' => Func::getReferenceIds($this->DesktopOperatingSystems),
            'InterpretingSpecialisms' => Func::getReferenceIds($this->InterpretingSpecialisms),
            'Resources' => Func::getReferenceIds($this->Resources),
            'TranslationCatTools' => Func::getReferenceIds($this->TranslationCatTools),
            'TranslationSpecialisms' => Func::getReferenceIds($this->TranslationSpecialisms),
        );
    }

    /**
     * @param array $data
     * @param \Doctrine\ORM\EntityManager $entityManager
     */
    public function updateData($data, $entityManager){
        $keys = array(
            'DesktopCatTools',
            'DesktopOperatingSystems',
            'InterpretingSpecialisms',
            'Resources',
            'TranslationCatTools',
            'TranslationSpecialisms');
        return $this->updateManyToOne($data, $keys, $entityManager);
    }

}


text:
<?php

namespace Zephir\Definition;

/**
 * @author Nikita Gusakov <dev@nkt.me>
 */
class FunctionDefinition extends Definition
{
    /**
     * @var VariableDefinition[]
     */
    private $arguments = [];
    /**
     * @var string
     */
    private $returnTypes = [];
    /**
     * @var string
     */
    private $code;

    public function addArgument(VariableDefinition $argument)
    {
        $this->arguments[] = $argument;
    }

    public function getArguments()
    {
        return $this->arguments;
    }

    public function addReturnType($type)
    {
        $this->returnTypes[] = $type;
    }

    public function getReturnTypes()
    {
        return $this->returnTypes;
    }

    public function hasReturnType($type)
    {
        return in_array($type, $this->returnTypes);
    }

    public function setCode($code)
    {
        $this->code = $code;
    }

    public function getCode()
    {
        return $this->code;
    }
}


text:
require 'singleton'
class PauseState < GameState
  include Singleton
  attr_accessor :play_state

  def initialize
    @message = Gosu::Image.from_text(
      $window, "Game Paused",
      Utils.title_font, 60)
  end

  def enter
    music.play(true)
    music.volume = 1
    @score_display = ScoreDisplay.new(@play_state.object_pool)
    @mouse_coords = [$window.mouse_x, $window.mouse_y]
  end

  def leave
    music.volume = 0
    music.stop
    $window.mouse_x, $window.mouse_y = @mouse_coords
  end

  def music
    @@music ||= Gosu::Song.new(
      $window, Utils.media_path('menu_music.mp3'))
  end

  def draw
    @play_state.draw
    @message.draw(
      $window.width / 2 - @message.width / 2,
      $window.height / 4 - @message.height - 50,
      1000)
    info.draw(
      $window.width / 2 - info.width / 2,
      $window.height / 4 - info.height,
      1000)
    @score_display.draw
  end

  def info
    @info ||= Gosu::Image.from_text(
      $window, 'Q: Quit to Main Menu',
      Utils.main_font, 30)
  end

  def button_down(id)
    if id == Gosu::KbQ
      MenuState.instance.play_state = @play_state
      GameState.switch(MenuState.instance)
    end
    if id == Gosu::KbC && @play_state
      GameState.switch(@play_state)
    end
    if id == Gosu::KbEscape
      GameState.switch(@play_state)
    end
  end
end


text:
package com.cezarykluczynski.stapi.etl.template.common.processor;

import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class RecordingTimeProcessor implements ItemProcessor<String, Integer> {

	private static final String COLON = ":";

	@Override
	public Integer process(String item) throws Exception {
		if (!StringUtils.contains(item, COLON)) {
			return null;
		}

		List<String> parts = Lists.newArrayList(StringUtils.split(item, COLON));

		final int partsSize = parts.size();

		String minutesCandiate;
		String hoursCandidate;

		Integer seconds = Ints.tryParse(parts.get(partsSize - 1));

		if (seconds == null) {
			return null;
		}

		if (parts.size() > 1) {
			minutesCandiate = parts.get(partsSize - 2);
			Integer minutes = Ints.tryParse(minutesCandiate);
			if (minutes == null) {
				return null;
			}

			seconds += minutes * 60;
		}

		if (parts.size() > 2) {
			hoursCandidate = parts.get(partsSize - 3);
			Integer hours = Ints.tryParse(hoursCandidate);
			if (hours == null) {
				return null;
			}

			seconds += hours * 3600;
		}

		return seconds;
	}

}


text:
members = ["Andres", "Juan", "Frank", "Nilda", "Edgardo"]

members.each do |name|
  puts "Hello, #{name}"
end


text:
loop@index.android.bundle:394:13289
topCall@index.android.bundle:394:14134
run@index.android.bundle:394:15126
executeCode@index.android.bundle:394:117
value@index.android.bundle:380:1115
value@index.android.bundle:380:1343
index.android.bundle:400:622
emit@index.android.bundle:435:1024
onevent@index.android.bundle:446:2305
onpacket@index.android.bundle:446:1991
index.android.bundle:449:219
emit@index.android.bundle:435:1024
ondecoded@index.android.bundle:416:3756
index.android.bundle:449:219
emit@index.android.bundle:412:1034
add@index.android.bundle:407:1938
ondata@index.android.bundle:416:3708
index.android.bundle:449:219
emit@index.android.bundle:435:1024
onPacket@index.android.bundle:419:6195
index.android.bundle:419:3820
emit@index.android.bundle:435:1024
onPacket@index.android.bundle:425:1331
onData@index.android.bundle:425:1284
onmessage@index.android.bundle:442:1381
value@index.android.bundle:95:1491
index.android.bundle:106:1777
value@index.android.bundle:58:1364
value@index.android.bundle:43:2897
index.android.bundle:43:1013
index.android.bundle:43:106
value@index.android.bundle:43:985
[native code]


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PowerArgs.EasterEggs
{
    internal class MatrixWriter : TextWriter
    {
        TextWriter wrapped;
        Queue<char> chars = new Queue<char>();
        bool cancelled;

        public MatrixWriter()
        {
            wrapped = Console.Out;
        }

        public override Encoding Encoding
        {
            get { return Encoding.Default; }
        }

        public override void Write(char value)
        {
            Write("" + value);
        }

        public override void Write(string value)
        {
            lock (chars)
            {
                foreach (char c in value) chars.Enqueue(c);
            }
        }

        public override void WriteLine()
        {
            WriteLine("");
        }

        public override void WriteLine(string value)
        {
            Write(value + "\n");
        }

        public void Cancel()
        {
            cancelled = true;
        }

        public void Loop()
        {
            Console.SetOut(this);
            Random r = new Random();
            Console.CursorVisible = false;
            Stopwatch sw = new Stopwatch();
            double sleep = 30;
            sw.Start();

            ConsoleColor resetFG = Console.ForegroundColor, resetBG = Console.BackgroundColor;
            try
            {
                char last = ' ';
                while (true)
                {
                    if (Console.CursorLeft < Console.BufferWidth - 1)
                    {
                        Console.BackgroundColor = ConsoleColor.Green;
                        wrapped.Write(' ');
                        if (Console.CursorLeft > 0) Console.CursorLeft--;
                    }
                    Console.BackgroundColor = resetBG;

                    while (sw.ElapsedMilliseconds < sleep) ;
                    sleep = sleep * .97;

                    lock (chars)
                    {
                        if (chars.Count > 0)
                        {
                            var c = chars.Dequeue();
                            if (c == '\r') continue;
                            if (sleep < 6)
                            {
                                Thread.Sleep(r.Next(20, 100));
                                sleep = 30;
                            }

                            Console.ForegroundColor = ConsoleColor.DarkGreen;
                            if (Console.CursorLeft < Console.BufferWidth - 1)
                            {
                                wrapped.Write(' ');
                                Console.CursorLeft--;
                            }
                            wrapped.Write(c);
                            last = c;
                        }
                        else if (cancelled)
                        {
                            break;
                        }
                    }

                    sw.Restart();
                }
            }
            finally
            {
                Console.ForegroundColor = resetFG;
                Console.BackgroundColor = resetBG;
            }
        }
    }

    /// <summary>
    /// An easter egg that makes all command line output get written in a green themed, futuristic fasion.  Don't use in a real program :).
    /// Breaking changes are allowed in the PowerArgs.EasterEggs namespace.
    /// </summary>
    public static class MatrixMode
    {
        /// <summary>
        /// Starts MatrixMode.
        /// </summary>
        /// <returns>An action that when invoked stops MatrixMode.</returns>
        public static Action Start()
        {
            var writer = new MatrixWriter();

            Task t = new Task(() =>
            {
                Thread.CurrentThread.IsBackground = false;
                writer.Loop();
            });
            t.Start();
            Thread.Sleep(100);
            return () =>
            {
                writer.Cancel();
            };
        }
    }
}


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.cpd;

import java.io.FilenameFilter;

public interface Language {

    Tokenizer getTokenizer();

    FilenameFilter getFileFilter();
}


text:
'use strict';

const _ = require('yyf-core');

const defaultOptions = {
    encoding: 'utf8',
    escape: '"',
    quote: '"',
    delimiter: ',',
    newLine: '\r\n'
};

class CsvSettings {
    constructor(options) {
        _.merge(this, defaultOptions, options || {});
        this.escapedQuote = this.escape + this.quote;
        this.regexpEscapedQuote = new RegExp(this.escapedQuote, 'g');
        this.lengthEscapedQuote = (this.escape + this.quote).length;
        this.regexpDelimiter = new RegExp(this.delimiter, 'g');
        this.lengthDelimiter = this.delimiter.length;
        this.regexpQuote = new RegExp(this.quote, 'g');
        this.lengthQuote = this.quote.length;
        this.regexpNewLine = new RegExp(this.newLine, 'g');
    }
}

module.exports = CsvSettings;


text:
//
//  StarIoExtManager.h
//  StarIO_Extension
//
//  Created by Yuji on 2015/**/**.
//  Copyright (c) 2015年 Star Micronics. All rights reserved.
//

#import <Foundation/Foundation.h>

#import <StarIO/SMPort.h>

typedef NS_ENUM(NSInteger, StarIoExtManagerType) {
    StarIoExtManagerTypeStandard = 0,
    StarIoExtManagerTypeWithBarcodeReader,
    StarIoExtManagerTypeOnlyBarcodeReader,
};

typedef NS_ENUM(NSInteger, StarIoExtManagerStatus) {
    StarIoExtManagerStatusInvalid                 __attribute__((unavailable("Not available. Please change to StarIoExtManager...StatusInvalid."))) = 0,
    StarIoExtManagerStatusImpossible              __attribute__((unavailable("Not available. Please change to StarIoExtManager...StatusImpossible."))),
    StarIoExtManagerStatusPrinterOnline           __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterStatusOnline."))),
    StarIoExtManagerStatusPrinterOffline          __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterStatusOffline."))),
    StarIoExtManagerStatusPrinterPaperReady       __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterPaperStatusReady."))),
    StarIoExtManagerStatusPrinterPaperNearEmpty   __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterPaperStatusNearEmpty."))),
    StarIoExtManagerStatusPrinterPaperEmpty       __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterPaperStatusEmpty."))),
    StarIoExtManagerStatusPrinterCoverOpen        __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterCoverStatusOpen."))),
    StarIoExtManagerStatusPrinterCoverClose       __attribute__((unavailable("Not available. Please change to StarIoExtManagerPrinterCoverStatusClose."))),
    StarIoExtManagerStatusCashDrawerOpen          __attribute__((unavailable("Not available. Please change to StarIoExtManagerCashDrawerStatusOpen."))),
    StarIoExtManagerStatusCashDrawerClose         __attribute__((unavailable("Not available. Please change to StarIoExtManagerCashDrawerStatusClose."))),
    StarIoExtManagerStatusBarcodeReaderConnect    __attribute__((unavailable("Not available. Please change to StarIoExtManagerBarcodeReaderStatusConnect."))),
    StarIoExtManagerStatusBarcodeReaderDisconnect __attribute__((unavailable("Not available. Please change to StarIoExtManagerBarcodeReaderStatusDisconnect.")))
};

typedef NS_ENUM(NSInteger, StarIoExtManagerPrinterStatus) {
    StarIoExtManagerPrinterStatusInvalid = 0,
    StarIoExtManagerPrinterStatusImpossible,
    StarIoExtManagerPrinterStatusOnline,
    StarIoExtManagerPrinterStatusOffline
};

typedef NS_ENUM(NSInteger, StarIoExtManagerPrinterPaperStatus) {
    StarIoExtManagerPrinterPaperStatusInvalid = 0,
    StarIoExtManagerPrinterPaperStatusImpossible,
    StarIoExtManagerPrinterPaperStatusReady,
    StarIoExtManagerPrinterPaperStatusNearEmpty,
    StarIoExtManagerPrinterPaperStatusEmpty
};

typedef NS_ENUM(NSInteger, StarIoExtManagerPrinterCoverStatus) {
    StarIoExtManagerPrinterCoverStatusInvalid = 0,
    StarIoExtManagerPrinterCoverStatusImpossible,
    StarIoExtManagerPrinterCoverStatusOpen,
    StarIoExtManagerPrinterCoverStatusClose
};

typedef NS_ENUM(NSInteger, StarIoExtManagerCashDrawerStatus) {
    StarIoExtManagerCashDrawerStatusInvalid = 0,
    StarIoExtManagerCashDrawerStatusImpossible,
    StarIoExtManagerCashDrawerStatusOpen,
    StarIoExtManagerCashDrawerStatusClose
};

typedef NS_ENUM(NSInteger, StarIoExtManagerBarcodeReaderStatus) {
    StarIoExtManagerBarcodeReaderStatusInvalid = 0,
    StarIoExtManagerBarcodeReaderStatusImpossible,
    StarIoExtManagerBarcodeReaderStatusConnect,
    StarIoExtManagerBarcodeReaderStatusDisconnect
};

@class StarIoExtManager;

@protocol StarIoExtManagerDelegate <NSObject>

@optional

- (void)didPrinterImpossible;
- (void)didPrinterImpossible:(StarIoExtManager *)manager;

- (void)didPrinterOnline;
- (void)didPrinterOnline:(StarIoExtManager *)manager;
- (void)didPrinterOffline;
- (void)didPrinterOffline:(StarIoExtManager *)manager;

- (void)didPrinterPaperReady;
- (void)didPrinterPaperReady:(StarIoExtManager *)manager;
- (void)didPrinterPaperNearEmpty;
- (void)didPrinterPaperNearEmpty:(StarIoExtManager *)manager;
- (void)didPrinterPaperEmpty;
- (void)didPrinterPaperEmpty:(StarIoExtManager *)manager;

- (void)didPrinterCoverOpen;
- (void)didPrinterCoverOpen:(StarIoExtManager *)manager;
- (void)didPrinterCoverClose;
- (void)didPrinterCoverClose:(StarIoExtManager *)manager;

- (void)didCashDrawerOpen;
- (void)didCashDrawerOpen:(StarIoExtManager *)manager;
- (void)didCashDrawerClose;
- (void)didCashDrawerClose:(StarIoExtManager *)manager;

- (void)didBarcodeReaderImpossible;
- (void)didBarcodeReaderImpossible:(StarIoExtManager *)manager;

- (void)didBarcodeReaderConnect;
- (void)didBarcodeReaderConnect:(StarIoExtManager *)manager;
- (void)didBarcodeReaderDisconnect;
- (void)didBarcodeReaderDisconnect:(StarIoExtManager *)manager;

- (void)didBarcodeDataReceive:(NSData *)data;
- (void)didBarcodeDataReceive:(StarIoExtManager *)manager data:(NSData *)data;

- (void)didAccessoryConnectSuccess;
- (void)didAccessoryConnectSuccess:(StarIoExtManager *)manager;
- (void)didAccessoryConnectFailure;
- (void)didAccessoryConnectFailure:(StarIoExtManager *)manager;
- (void)didAccessoryDisconnect;
- (void)didAccessoryDisconnect:(StarIoExtManager *)manager;

- (void)didStatusUpdate:(NSString *)status;
- (void)didStatusUpdate:(StarIoExtManager *)manager status:(NSString *)status;

@end

@interface StarIoExtManager : NSObject

@property (readonly, nonatomic) SMPort *port;

@property (readonly, nonatomic) StarIoExtManagerStatus              printerOnlineStatus        __attribute__((unavailable("Not available. Please change to printerStatus.")));
@property (readonly, nonatomic) StarIoExtManagerPrinterStatus       printerStatus;
@property (readonly, nonatomic) StarIoExtManagerStatus              printerPaperReadyStatus    __attribute__((unavailable("Not available. Please change to printerPaperStatus")));
@property (readonly, nonatomic) StarIoExtManagerPrinterPaperStatus  printerPaperStatus;
@property (readonly, nonatomic) StarIoExtManagerStatus              printerCoverOpenStatus     __attribute__((unavailable("Not available. Please change to printerCoverStatus.")));
@property (readonly, nonatomic) StarIoExtManagerPrinterCoverStatus  printerCoverStatus;
@property (readonly, nonatomic) StarIoExtManagerStatus              cashDrawerOpenStatus       __attribute__((unavailable("Not available. Please change to cashDrawerStatus.")));
@property (readonly, nonatomic) StarIoExtManagerCashDrawerStatus    cashDrawerStatus;
@property (readonly, nonatomic) StarIoExtManagerStatus              barcodeReaderConnectStatus __attribute__((unavailable("Not available. Please change to barcodeReaderStatus.")));
@property (readonly, nonatomic) StarIoExtManagerBarcodeReaderStatus barcodeReaderStatus;

@property (nonatomic) BOOL cashDrawerOpenActiveHigh;

@property (weak, nonatomic) id<StarIoExtManagerDelegate> delegate;

@property (readonly, nonatomic) NSRecursiveLock *lock;

- (id)initWithType:(StarIoExtManagerType)type portName:(NSString *)portName portSettings:(NSString *)portSettings ioTimeoutMillis:(NSUInteger)ioTimeoutMillis;

- (BOOL)connect;

- (BOOL)disconnect;

@end


text:
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from entity.signal_handlers import turn_on_syncing, turn_off_syncing
from entity.models import Entity, EntityKind

class EntityTestCase(TestCase):
    """
    The base class for entity tests. Provides helpers for creating entities.
    """
    def setUp(self):
        """
        Ensure entity syncing is in default state when tests start.
        """
        super(EntityTestCase, self).setUp()
        turn_off_syncing()
        turn_on_syncing()

    def tearDown(self):
        """
        Make sure syncing is turned back to its original state.
        """
        super(EntityTestCase, self).tearDown()
        turn_off_syncing()
        turn_on_syncing()

    def create_entity(self, model_obj):
        """
        Given a model object, create an entity.
        """
        entity_type = ContentType.objects.get_for_model(model_obj)
        return Entity.objects.create(
            entity_type=entity_type, entity_id=model_obj.id,
            entity_kind=EntityKind.objects.get_or_create(
                name='{0}__{1}'.format(entity_type.app_label, entity_type.model),
                defaults={'display_name': u'{0}'.format(entity_type)}
            )[0])


text:
void register_ImageDetails_class();

#endif//ImageDetails_hpp__pyplusplus_wrapper


text:
import {
  Inject,
  Injectable,
  NgModuleFactoryLoader,
  NgModuleRef,
} from '@angular/core';
import { ELEMENT_MODULE_PATHS_TOKEN } from './element-registry';
import { from, Observable, of } from 'rxjs';
import { createCustomElement } from '@angular/elements';

@Injectable()
export class ElementsLoader {
  /** Map of unregistered custom elements and their respective module paths to load. */
  private elementsToLoad: Map<string, string>;
  /** Map of custom elements that are in the process of being loaded and registered. */
  private elementsLoading = new Map<string, Promise<void>>();

  constructor(private moduleFactoryLoader: NgModuleFactoryLoader,
              private moduleRef: NgModuleRef<any>,
              @Inject(ELEMENT_MODULE_PATHS_TOKEN) elementModulePaths: Map<string, string>) {
    this.elementsToLoad = new Map(elementModulePaths);
  }

  /**
   * Queries the provided element for any custom elements that have not yet been registered with
   * the browser. Custom elements that are registered will be removed from the list of unregistered
   * elements so that they will not be queried in subsequent calls.
   */
  loadContainedCustomElements(element: HTMLElement): Observable<void> {
    const unregisteredSelectors = Array.from(this.elementsToLoad.keys())
        .filter(s => element.querySelector(s));

    if (!unregisteredSelectors.length) { return of(undefined); }

    // Returns observable that completes when all discovered elements have been registered.
    const allRegistered = Promise.all(unregisteredSelectors.map(s => this.loadCustomElement(s)));
    return from(allRegistered.then(() => undefined));
  }

  /** Loads and registers the custom element defined on the `WithCustomElement` module factory. */
  loadCustomElement(selector: string): Promise<void> {
    if (this.elementsLoading.has(selector)) {
      // The custom element is in the process of being loaded and registered.
      return this.elementsLoading.get(selector)!;
    }

    if (this.elementsToLoad.has(selector)) {
      // Load and register the custom element (for the first time).
      const modulePath = this.elementsToLoad.get(selector)!;
      const loadedAndRegistered = this.moduleFactoryLoader
          .load(modulePath)
          .then(elementModuleFactory => {
            const elementModuleRef = elementModuleFactory.create(this.moduleRef.injector);
            const injector = elementModuleRef.injector;
            const CustomElementComponent = elementModuleRef.instance.customElementComponent;
            const CustomElement = createCustomElement(CustomElementComponent, {injector});

            customElements!.define(selector, CustomElement);
            return customElements.whenDefined(selector);
          })
          .then(() => {
            // The custom element has been successfully loaded and registered.
            // Remove from `elementsLoading` and `elementsToLoad`.
            this.elementsLoading.delete(selector);
            this.elementsToLoad.delete(selector);
          })
          .catch(err => {
            // The custom element has failed to load and register.
            // Remove from `elementsLoading`.
            // (Do not remove from `elementsToLoad` in case it was a temporary error.)
            this.elementsLoading.delete(selector);
            return Promise.reject(err);
          });

      this.elementsLoading.set(selector, loadedAndRegistered);
      return loadedAndRegistered;
    }

    // The custom element has already been loaded and registered.
    return Promise.resolve();
  }
}