text:
package de.hub.emffrag.datastore;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import org.eclipse.emf.common.util.URI;

public class DataIndex<KT> {

	private final DataStore store;
	private final byte[] fullPrefix;
	private final byte[] fullPrefixNext;
	private final KeyType<KT> keyType;

	public DataIndex(DataStore store, String prefix, KeyType<KT> keyType) {
		super();
		this.store = store;
		this.fullPrefix = (prefix + "_").getBytes();
		this.fullPrefixNext = (prefix + (char) ('_' + 1)).getBytes();
		this.keyType = keyType;
	}

	public byte[] getStoreKey(KT key) {
		byte[] serialize = keyType.serialize(key);
		return ByteBuffer.allocate(fullPrefix.length + serialize.length).put(fullPrefix).put(serialize).array();
	}

	public URI getURI(KT key) {
		return URI.createURI(store.getURIString()).appendSegment(URIUtils.encode(getStoreKey(key)));
	}

	public KT add() {
		KT last = last();
		KT key = null;
		if (last == null) {
			key = keyType.nullKey();
		} else {
			key = keyType.next(last);
		}
		if (add(key)) {
			return key;
		} else {
			// TODO error handling: retry for a couple of times and then fail?
			throw new RuntimeException("Could not add key " + new String(keyType.serialize(key)));
		}
	}

	public KT first() {
		byte[] lastStoreKeyInIndex = store.ceiling(fullPrefix);
		if (lastStoreKeyInIndex == null) {
			return null;
		}

		if (prefixMatches(lastStoreKeyInIndex)) {
			return keyType.deserialize(lastStoreKeyInIndex, fullPrefix.length);
		} else {
			return null;
		}
	}

	private boolean prefixMatches(byte[] lastStoreKeyInIndex) {
		boolean prefixMatches = true;
		for (int i = 0; i < fullPrefix.length; i++) {
			prefixMatches &= fullPrefix[i] == lastStoreKeyInIndex[i];
		}
		return prefixMatches;
	}

	public KT last() {
		byte[] lastStoreKeyInIndex = store.floor(fullPrefixNext);
		if (lastStoreKeyInIndex == null) {
			return null;
		}

		if (prefixMatches(lastStoreKeyInIndex)) {
			return keyType.deserialize(lastStoreKeyInIndex, fullPrefix.length);
		} else {
			return null;
		}
	}

	public KT exactOrNext(KT key) {
		byte[] ceiling = store.ceiling(getStoreKey(key));
		return ceiling == null ? null : keyType.deserialize(ceiling, fullPrefix.length);
	}

	public boolean exists(KT key) {
		return !store.check(getStoreKey(key));
	}

	public KT next(KT key) {
		byte[] ceiling = store.ceiling(getStoreKey(keyType.next(key)));
		return ceiling == null ? null : keyType.deserialize(ceiling, fullPrefix.length);
	}

	/**
	 * @return True if the key could be added, thus was a new key.
	 */
	public boolean add(KT key) {
		byte[] storeKey = getStoreKey(key);
		return store.ckeckAndCreate(storeKey);
	}

	public void set(KT key, String value) {
		PrintWriter printWriter = new PrintWriter(openOutputStream(key));
		printWriter.print(value);
		printWriter.close();
	}

	public String get(KT key) {
		InputStream openInputStream = openInputStream(key);
		return openInputStream == null ? null : slurp(openInputStream, 1024);
	}

	public String remove(KT key) {
		byte[] storeKey = getStoreKey(key);
		InputStream openInputStream = store.openInputStream(storeKey);
		if (openInputStream == null) {
			return null;
		} else {
			String result = slurp(openInputStream, 1024);
			store.delete(storeKey);
			return result;
		}
	}

	public OutputStream openOutputStream(KT key) {
		return store.openOutputStream(getStoreKey(key));
	}

	public InputStream openInputStream(KT key) {
		return store.openInputStream(getStoreKey(key));
	}

	private static String slurp(final InputStream is, final int bufferSize) {
		final char[] buffer = new char[bufferSize];
		final StringBuilder out = new StringBuilder();
		try {
			final Reader in = new InputStreamReader(is, "UTF-8");
			try {
				for (;;) {
					int rsz = in.read(buffer, 0, buffer.length);
					if (rsz < 0)
						break;
					out.append(buffer, 0, rsz);
				}
			} finally {
				in.close();
			}
		} catch (UnsupportedEncodingException ex) {
			/* ... */
		} catch (IOException ex) {
			/* ... */
		}
		return out.toString();
	}

	public KT getKeyFromURI(URI crossReferenceURI) {
		byte[] key = URIUtils.decode(crossReferenceURI.segment(1));
		return keyType.deserialize(key, fullPrefix.length);
	}
}


text:
    Rows: Default: 5
    <?php echo form_input(array('name' => 'settings[rows]', 'value' => set_value('settings[rows]', ( ! empty($Field->settings['rows'])) ? $Field->settings['rows'] : ''))); ?>

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function () {

    $('#commentButton').click(function(){
        ajaxJson({
            url: '/comment',
            data: $('#comment-form').serializeArray(),
            success: function(ret) {

            }
        });
    });

});


text:
```js
cy.nodes().filterFn(function( ele ){
  return ele.data('weight') > 50;
});
```


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Publções Inst. Micol. Recife 320: 6 (1961)

#### Original name
Aciesia Bat.

### Remarks
null


text:
from __future__ import unicode_literals
import webnotes

@webnotes.whitelist()
def update(ml):
	"""update modules"""
	webnotes.conn.set_global('hidden_modules', ml)
	webnotes.msgprint('Updated')
	webnotes.clear_cache()


text:
#if !defined(BOOST_FUSION_ADAPTED_30122005_1420)
#define BOOST_FUSION_ADAPTED_30122005_1420

#include <boost/fusion/adapted/adt.hpp>
#include <boost/fusion/adapted/array.hpp>
#include <boost/fusion/adapted/boost_array.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
#include <boost/fusion/adapted/mpl.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/fusion/adapted/struct.hpp>

// The std_tuple_iterator adaptor only supports implementations
// using variadic templates
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#include <boost/fusion/adapted/std_tuple.hpp>
#endif

#endif


text:
package com.wordpress.tonytam.mathgetto24;

import android.util.Log;

import com.wordpress.tonytam.model.cards.PlayingCardEasy24;
import com.wordpress.tonytam.model.cards.PlayingCardMedium24;
import com.wordpress.tonytam.model.cards.PlayingCardNoFace;
import com.wordpress.tonytam.model.cards.PlayingDeck;
import com.wordpress.tonytam.model.cards.PlayingCard;
import com.wordpress.tonytam.util.Permute;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author by tonytam on 6/4/14.
 */
public class Math24Game {
    public PlayingDeck deck;

    public PlayingDeck
            _easyDeck,
            _hardDeck,
            _mediumDeck;

    static final public int LEVEL_EASY = 1;
    static final public int LEVEL_MEDIUM = 2;
    static final public int LEVEL_HARD = 3;

    static final public int PLUS_OPERATOR = 0;
    static final public int MINUS_OPERATOR = 1;
    static final public int MULTIPLY_OPERATOR = 2;
    static final public int DIVIDE_OPERATOR = 3;

    static public BigDecimal rightAnswer;

    public PlayingCard hand[];
    public PlayingCard nextHand[];

    AnswerPackage thisAnswer;
    AnswerPackage nextAnswer;

    public int currentGameTime;

    public ArrayList<Integer> playerScores;

    static public Method operators[];

    static public String operatorChars[] = {
            "+",
            "-",
            "×",
            "÷",
    };

    Math24Game () {
        Class bigDecimalClass = BigDecimal.class;
        operators = new Method[4];
        try {
            operators[0] = bigDecimalClass.getMethod("add", BigDecimal.class);
            operators[1] = bigDecimalClass.getMethod("subtract", BigDecimal.class);
            operators[2] = bigDecimalClass.getMethod("multiply", BigDecimal.class);
            operators[3] = bigDecimalClass.getMethod("divide", BigDecimal.class);
        } catch (NoSuchMethodException e) {
            Log.e("Math24Game", e.toString());
        }
    }

    static public BigDecimal getRightAnswer () {
        if (Math24Game.rightAnswer == null) {
            Math24Game.rightAnswer = new BigDecimal(24);
        }
        return rightAnswer;
    }
    static public String operatorString(int op) {
        return operatorChars[op];
    }

    static public Method operatorMethod(int op) {
        return operators[op];
    }

    static public Method methodOf (int op ) {
        return operators[op];
    }

    public PlayingCard [] dealHand() {
        if (nextHand[0] == null) {
            for (int numHands = 0; numHands <= 50; numHands++) {
                for (int i = 0; i <= 3; i++) {
                    this.hand[i] = Math24Game.this.deck.drawRandomCard();
                    Log.d("Math24Game: dealHand ", this.hand[i].description());
                }

                thisAnswer = this.calculateAnswer();
                if (thisAnswer != null) {
                    Log.d("dealHand", "deal next hand");
                    break;
                } else {
                    Log.d("dealHand", "try again for another hand");
                    returnHand();
                }
            }
        } else {
            hand = nextHand.clone();
            thisAnswer = nextAnswer;
            Log.d("dealHand", "Shortcut deal");
        }

        class CalculateAnswer extends Thread {

            public void run() {
                for (int numHands = 0; numHands <= 50; numHands++) {
                    for (int i = 0; i <= 3; i++) {
                        Math24Game.this.nextHand[i] = Math24Game.this.deck.drawRandomCard();
                        Log.d("Math24Game: card ", Math24Game.this.nextHand[i].description());
                    }

                    nextAnswer = Math24Game.this.calculateAnswer(Math24Game.this.nextHand);
                    if (nextAnswer != null) {
                        break;
                    } else {
                        // Next hand should be returned
                        returnHand(Math24Game.this.nextHand);
                    }
                }
                if (nextAnswer == null) {
                    Log.d("dealHand", "No winning hand");
                }
            }
        }
        new CalculateAnswer().start();
        return hand;
    }

    public AnswerPackage calculateAnswer (PlayingCard hand[]) {
        Permute permute = new Permute(hand);
        AnswerPackage answer = null;
        for (Iterator i = permute; i.hasNext(); ) {
            PlayingCard [] a = (PlayingCard[]) i.next();
            Log.d("calculateAnswer", toString(a));
            answer = calculateHand(a);
            if (answer != null) {
                break;
            }
        }
        if (answer != null) {
            Log.d("calculateAnswer", answer.stringAnswer + "=" + answer.answer.toString());
        } else {
            Log.d("calculateAnswer", "NO ANSWER");
        }
        return answer;
    }

    public AnswerPackage calculateAnswer () {

        return calculateAnswer(this.hand);
    }

    public void setLevel (int level) {
        Log.d("setLevel", String.valueOf(level));
        switch (level) {
            case LEVEL_EASY:
                deck = _easyDeck;
                break;
            case LEVEL_MEDIUM:
                deck = _mediumDeck;
                break;
            case LEVEL_HARD:
                deck = _hardDeck;
                break;
            default:
                Log.e("setLevel", "Invalid level " + String.valueOf(level));
                break;
        }
    }
    // Using the cards in the given sequence and operators in the sequence
    // calculate whether there is an answer.  This can be used
    // to verify the human players answer
    //
    // RETURN the answerPackage or nil if 24 is not found
    //
    public AnswerPackage calculateHand (PlayingCard cards[],
                                        Method operators[],
                                        String operatorStrs[]) {
        BigDecimal rightAnswer = getRightAnswer();
        AnswerPackage storeAnswerPackage;

        storeAnswerPackage = calculateSimple (
                cards,
                operators,
                operatorStrs);
        if (storeAnswerPackage != null &&
                storeAnswerPackage.answer.equals(rightAnswer)) {
            return storeAnswerPackage;
        }

        storeAnswerPackage = calculateNested (
                cards,
                operators,
                operatorStrs);
        if (storeAnswerPackage != null &&
                storeAnswerPackage.answer.equals(rightAnswer)) {
            return storeAnswerPackage;
        }

        storeAnswerPackage = calculateGrouping (
                cards,
                operators,
                operatorStrs);
        if (storeAnswerPackage != null &&
                storeAnswerPackage.answer.equals(rightAnswer)) {
            return storeAnswerPackage;
        }

        storeAnswerPackage = calculateGroupingThree (
                cards,
                operators,
                operatorStrs);
        if (storeAnswerPackage != null &&
                storeAnswerPackage.answer.equals(rightAnswer)) {
            return storeAnswerPackage;
        }

        storeAnswerPackage = calculateGroupingOfTwo (
                cards,
                operators,
                operatorStrs);
        if (storeAnswerPackage != null &&
                storeAnswerPackage.answer.equals(rightAnswer)) {
            return storeAnswerPackage;
        }

        storeAnswerPackage = calculateGroupingSecond (
                cards,
                operators,
                operatorStrs);
        if (storeAnswerPackage != null &&
                storeAnswerPackage.answer.equals(rightAnswer)) {
            return storeAnswerPackage;
        }

        if (storeAnswerPackage != null ) {
            Log.d("CalculateHand", storeAnswerPackage.toString());
        }
        return null;
    }
    /*
     * Apply all the possible operators on the 4 cards, keeping them in the same order
     * Solve for these combination
     * ((a op b) op c) op d
     * (a op b) op (c op d)
     * a op (b op c) op d
     */
    public AnswerPackage calculateHand (PlayingCard cards[]) {
        BigDecimal rightAnswer = getRightAnswer();
        AnswerPackage storeAnswerPackage;

        for (int j = 0; j <= 3; ++j) {
            for (int k = 0; k <= 3; ++k) {
                for (int l = 0; l <= 3; ++l) {
                    Method currentOperators[] = {
                            this.operators[j],
                            this.operators[k],
                            this.operators[l]
                    };

                    String currentOperatorChars[] = {
                            this.operatorChars[j],
                            this.operatorChars[k],
                            this.operatorChars[l]
                    };

                    storeAnswerPackage = calculateHand(
                            cards,
                            currentOperators,
                            currentOperatorChars);
                    if (storeAnswerPackage != null &&
                        storeAnswerPackage.answer.equals(rightAnswer)) {
                        return storeAnswerPackage;
                    }
                    /*
                    if ([storeAnswerPackage.answer compare:rightAnswer]==NSOrderedSame){
                        DLog( @ "answer %@", storeAnswerPackage.stringAnswer);

                        found = TRUE;
                        break;
                    }
                    */
                }
            }
        }
        return null;
    }

    // ((a op b) op c) op d
    public AnswerPackage calculateSimple (PlayingCard cards[],
                                          Method operators[],
                                          String operatorStrs[]) {
        BigDecimal subtotal ;
        AnswerPackage answer = new AnswerPackage();
        Method selector0 = operators[0];
        Method selector1 = operators[1];
        Method selector2 = operators[2];

        PlayingCard card0 = cards[0];
        PlayingCard card1 = cards[1];
        PlayingCard card2 = cards[2];
        PlayingCard card3 = cards[3];

        try {
            subtotal = (BigDecimal) selector0.invoke(new BigDecimal(card0.rank), new BigDecimal(card1.rank));

            subtotal = (BigDecimal) selector1.invoke(subtotal, new BigDecimal(card2.rank));

            subtotal = (BigDecimal) selector2.invoke(subtotal, new BigDecimal(card3.rank));
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }

        answer.answer = subtotal;
        answer.stringFormat = "((%d %s %d) %s %d) %s %d";
        answer.stringAnswer = String.format(answer.stringFormat,
                card0.rank, operatorStrs[0],
                card1.rank, operatorStrs[1],
                card2.rank, operatorStrs[2],
                card3.rank);

        //Log.i("calculateSimple", answer.stringAnswer);
        //Log.i("calculateSimple", answer.answer.toString());

        return answer;
    }

    // (a op b) op (c op d)
    public AnswerPackage calculateGrouping(PlayingCard cards[],
                                           Method operators[],
                                           String operatorStrs[]) {
        BigDecimal subtotal, subtotal1;
        AnswerPackage answer = new AnswerPackage();
        Method selector0 = operators[0];
        Method selector1 = operators[1];
        Method selector2 = operators[2];

        PlayingCard card0 = cards[0];
        PlayingCard card1 = cards[1];
        PlayingCard card2 = cards[2];
        PlayingCard card3 = cards[3];

        try {
            subtotal = (BigDecimal) selector0.invoke(new BigDecimal(card0.rank), new BigDecimal(card1.rank));

            subtotal1 = (BigDecimal) selector2.invoke(new BigDecimal(card2.rank), new BigDecimal(card3.rank));

            subtotal = (BigDecimal) selector1.invoke(subtotal, subtotal1);
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }

        answer.answer = subtotal;
        answer.stringFormat = "(%d %s %d) %s (%d %s %d)";
        answer.stringAnswer = String.format(answer.stringFormat,
                card0.rank, operatorStrs[0],
                card1.rank, operatorStrs[1],
                card2.rank, operatorStrs[2],
                card3.rank);

        //Log.i("calculateSimple", answer.stringAnswer);
        //Log.i("calculateSimple", answer.answer.toString());

        return answer;
    }

    // a op (b op (c op d))
    public AnswerPackage calculateGroupingThree(PlayingCard cards[],
                                           Method operators[],
                                           String operatorStrs[]) {
        BigDecimal subtotal;
        AnswerPackage answer = new AnswerPackage();
        Method selector0 = operators[0];
        Method selector1 = operators[1];
        Method selector2 = operators[2];

        PlayingCard card0 = cards[0];
        PlayingCard card1 = cards[1];
        PlayingCard card2 = cards[2];
        PlayingCard card3 = cards[3];

        try {
            subtotal = (BigDecimal) selector2.invoke(new BigDecimal(card2.rank), new BigDecimal(card3.rank));

            subtotal = (BigDecimal) selector1.invoke(new BigDecimal(card1.rank), subtotal);

            subtotal = (BigDecimal) selector0.invoke(new BigDecimal(card0.rank), subtotal);
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }

        answer.answer = subtotal;
        answer.stringFormat = "%d %s ((%d %s (%d %s %d))";
        answer.stringAnswer = String.format(answer.stringFormat,
                card0.rank, operatorStrs[0],
                card1.rank, operatorStrs[1],
                card2.rank, operatorStrs[2],
                card3.rank);

        //Log.i("calculateSimple", answer.stringAnswer);
        //Log.i("calculateSimple", answer.answer.toString());

        return answer;
    }

    // (a op b) op c op d
    public AnswerPackage calculateGroupingOfTwo  (PlayingCard cards[],
                                         Method operators[],
                                         String operatorStrs[]) {
        BigDecimal subtotal;
        AnswerPackage answer = new AnswerPackage();
        Method selector0 = operators[0];
        Method selector1 = operators[1];
        Method selector2 = operators[2];

        PlayingCard card0 = cards[0];
        PlayingCard card1 = cards[1];
        PlayingCard card2 = cards[2];
        PlayingCard card3 = cards[3];

        try {
            subtotal = (BigDecimal) selector0.invoke(new BigDecimal(card0.rank), new BigDecimal(card1.rank));

            subtotal = (BigDecimal) selector1.invoke(subtotal, new BigDecimal(card2.rank));

            subtotal = (BigDecimal) selector2.invoke(subtotal, new BigDecimal(card3.rank));
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }

        answer.answer = subtotal;
        answer.stringFormat = "(%d %s %d) %s %d %s %d";
        answer.stringAnswer = String.format(answer.stringFormat,
                card0.rank, operatorStrs[0],
                card1.rank, operatorStrs[1],
                card2.rank, operatorStrs[2],
                card3.rank);

        //Log.i("calculateSimple", answer.stringAnswer);
        //Log.i("calculateSimple", answer.answer.toString());

        return answer;
    }

    // a op ((b op c) op d)
    public AnswerPackage calculateNested(PlayingCard cards[],
                                         Method operators[],
                                         String operatorStrs[]) {
        BigDecimal subtotal;
        AnswerPackage answer = new AnswerPackage();
        Method selector0 = operators[0];
        Method selector1 = operators[1];
        Method selector2 = operators[2];

        PlayingCard card0 = cards[0];
        PlayingCard card1 = cards[1];
        PlayingCard card2 = cards[2];
        PlayingCard card3 = cards[3];

        try {
            subtotal = (BigDecimal) selector1.invoke(new BigDecimal(card1.rank), new BigDecimal(card2.rank));

            subtotal = (BigDecimal) selector2.invoke(subtotal, new BigDecimal(card3.rank));

            subtotal = (BigDecimal) selector0.invoke(new BigDecimal(card0.rank), subtotal);
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }

        answer.answer = subtotal;
        answer.stringFormat = "%d %s ((%d %s %d) %s %d)";
        answer.stringAnswer = String.format(answer.stringFormat,
                card0.rank, operatorStrs[0],
                card1.rank, operatorStrs[1],
                card2.rank, operatorStrs[2],
                card3.rank);

        //Log.i("calculateSimple", answer.stringAnswer);
        //Log.i("calculateSimple", answer.answer.toString());

        return answer;
    }

    // a op (b op c) op d
    public AnswerPackage calculateGroupingSecond (PlayingCard cards[],
                                         Method operators[],
                                         String operatorStrs[]) {
        BigDecimal subtotal;
        AnswerPackage answer = new AnswerPackage();
        Method selector0 = operators[0];
        Method selector1 = operators[1];
        Method selector2 = operators[2];

        PlayingCard card0 = cards[0];
        PlayingCard card1 = cards[1];
        PlayingCard card2 = cards[2];
        PlayingCard card3 = cards[3];

        try {
            subtotal = (BigDecimal) selector1.invoke(new BigDecimal(card1.rank), new BigDecimal(card2.rank));

            subtotal = (BigDecimal) selector0.invoke(new BigDecimal(card0.rank), subtotal);

            subtotal = (BigDecimal) selector2.invoke(subtotal, new BigDecimal(card3.rank));
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }

        answer.answer = subtotal;
        answer.stringFormat = "%d %s (%d %s %d) %s %d";
        answer.stringAnswer = String.format(answer.stringFormat,
                card0.rank, operatorStrs[0],
                card1.rank, operatorStrs[1],
                card2.rank, operatorStrs[2],
                card3.rank);

        //Log.i("calculateSimple", answer.stringAnswer);
        //Log.i("calculateSimple", answer.answer.toString());

        return answer;
    }

    public Math24Game returnHand () {
        return returnHand(this.hand);
    }

    public Math24Game returnHand (PlayingCard hand[]) {
        for (PlayingCard card : hand) {
            deck.addCard(card);
        }

        for (int i = 0; i < hand.length; i++) {
            hand[i] = null;
        }
        return this;
    }

    public String toString(PlayingCard []ar) {
        final int n = Array.getLength(ar);
        final StringBuffer sb = new StringBuffer("[");
        for (int j = 0; j < n; j++) {
            sb.append(Array.get(ar, j).toString());
            if (j < n - 1) sb.append(",");
        }
        sb.append("]");
        return new String(sb);
    }

    // validate playerNumber to be 0 or 1
    public Integer getPlayerScore(int playerNumber) {
            return playerScores.get(playerNumber);
    }
    public Integer playerRightAnswer(int playerNumber) {
        this.playerScores.set(playerNumber,
                playerScores.get(playerNumber).intValue() + 1);
        return playerScores.get(playerNumber);
    }

    public Integer playerWrongAnswer (int playerNumber) {
        this.playerScores.set(playerNumber,
                playerScores.get(playerNumber).intValue() - 1);
        return playerScores.get(playerNumber);
    }

    public void startGame() {

        this.currentGameTime = 600;
        this.playerScores = new ArrayList<Integer>(2);
        this.playerScores.add(new Integer(0));
        this.playerScores.add(new Integer(0));

        if (this._hardDeck == null) {
            this._hardDeck = new PlayingDeck (new PlayingCardNoFace());
        }

        if (this._easyDeck == null) {
            this._easyDeck = new PlayingDeck (new PlayingCardEasy24());
        }

        if (this._mediumDeck == null) {
            this._mediumDeck = new PlayingDeck (new PlayingCardMedium24());
        }
        this.deck = this._hardDeck;

        this.hand = new PlayingCard[4];
        this.nextHand = new PlayingCard[4];
        nextAnswer = new AnswerPackage();
        thisAnswer = new AnswerPackage();

        this.dealHand();

        /*

        this.answerOperators = malloc(sizeof(SEL) * 3);
        this.operatorStrings = [[NSMutableArray alloc] init];
        this.answerCardArray = [[NSMutableArray alloc] init];
        this.answerArray = [[NSMutableArray alloc] init];

        // just because it's hard to map SEL, we have the string representations

                nil];

        // Keep track of the UIButtons where the operators are
        this.operatorLabels2 = [NSArray arrayWithObjects:
        this.buttonPlus2,
                this.buttonMinus2,
                this.buttonMultiplication2,
                this.buttonDivision2,
                nil
        ];

        // Keep track of the labels used to display the status/answers to both players
        this.labelAnswers = [[NSArray alloc] initWithObjects:this.labelAnswer, this.labelAnswer2, nil];

        // Start off with no answer controllers
        [self showAnswerControllers:FALSE];
        this.labelMiddleInfo.hidden = TRUE;
        */
    }
}


text:
require 'gooddata'
require 'gooddata_datawarehouse'

module GoodData
  module Bricks
    class WarehouseMiddleware < Bricks::Middleware
      def call(params)
        if params.key?('ads_client')
          puts "Setting up ADS connection to #{params['ads_client']['ads_id']}"
          fail "ADS middleware needs username either as part of ads_client spec or as a global 'GDC_USERNAME' parameter" unless params['ads_client']['username'] || params['GDC_USERNAME']
          fail "ADS middleware needs password either as part of ads_client spec or as a global 'GDC_PASSWORD' parameter" unless params['ads_client']['password'] || params['GDC_PASSWORD']

          ads = GoodData::Datawarehouse.new(params['ads_client']['username'] || params['GDC_USERNAME'], params['ads_client']['password'] || params['GDC_PASSWORD'], params['ads_client']['ads_id'])
          @app.call(params.merge('ads_client' => ads))
        else
          @app.call(params)
        end
      end
    end
  end
end


text:
package com.option_u.stolpersteine.activities.description;

import android.app.Activity;
import android.webkit.WebView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class HTMLContentLoader {

    private WebView browser;

    public HTMLContentLoader(WebView browser) {
        this.browser = browser;
    }

    public void loadContent(final Activity activity, final String url, final String cssQuery) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document document = Jsoup.parse(new URL(url).openStream(), "utf-8", url);
                    Elements elements = document.select(cssQuery);
                    if (elements.isEmpty()) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                browser.loadUrl(url);
                            }
                        });
                        return;
                    }
                    String content = elements.toString();
                    content = removeHTMLTagHyperlink(content);
                    DataLoaderRunnable dataLoaderRunnable = new DataLoaderRunnable(browser, content);
                    activity.runOnUiThread(dataLoaderRunnable);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private class DataLoaderRunnable implements Runnable {

        private WebView browser;
        private String data;
        private String mimeType = "text/html; charset=UTF-8";

        public DataLoaderRunnable(WebView browser, String data) {
            this.browser = browser;
            this.data = data;
        }

        @Override
        public void run() {
            browser.loadData(data, mimeType, null);
        }

    }

    private String removeHTMLTagHyperlink(String content) {
        Pattern pattern = Pattern.compile("<a\\s.+?>(.+?)</a>");
        Matcher matcher = pattern.matcher(content);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}


text:
extern NSString *const StripePublishableKey;
extern NSString *const BackendBaseURL;
extern NSString *const AppleMerchantId;


text:
#ifndef KEEPALIVEREQUESTER_H
#define KEEPALIVEREQUESTER_H

#include "TileMapToolkit.h"
#include <cstdio>

class KeepAliveRequester : public TileMapTimerListener,
                           public BufferRequesterListener {
public:
   KeepAliveRequester(TileMapToolkit* toolkit,
                      BufferRequester& req) :
      m_toolkit(toolkit),
      m_bufReq(req)
   {
      m_timer =
         toolkit->createPeriodicTimer( this,
                                       TileMapToolkit::PRIO_STANDARD);
      m_timer->start(2000);
   }

   /**
    *  @see BufferRequesterListener.
    */
   void requestReceived(const MC2SimpleString& descr,
                        BitBuffer* dataBuffer,
                        OriginType origin)
   {
      printf("[KA_REQ]: Recv %p (size %u) / %s and origin %s\n",
             dataBuffer,
             dataBuffer ? dataBuffer->getBufferSize() : 0,
             descr.c_str(),
             OriginType::toString(origin));

      delete dataBuffer;
   }

   virtual void timerExpired(uint32 id) {
      printf("timerExpired()\n");

      m_bufReq.requestBuffer("", this);
   }

private:
   TileMapToolkit* m_toolkit;
   TileMapPeriodicTimer* m_timer;
   BufferRequester& m_bufReq;
};

#endif /* KEEPALIVEREQUESTER_H */


text:
import {Utils, FS} from '../../lib';

export const nameList = new Set<string>(JSON.parse(
	FS('config/chat-plugins/usersearch.json').readIfExistsSync() || "[]"
));

const ONLINE_SYMBOL = ` \u25C9 `;
const OFFLINE_SYMBOL = ` \u25CC `;

class PunishmentHTML extends Chat.JSX.Component<{userid: ID, target: string}> {
	render() {
		const {userid, target} = {...this.props};
		const buf = [];
		for (const cmdName of ['Forcerename', 'Namelock', 'Weeknamelock']) {
			// We have to use dangerouslySetInnerHTML here because otherwise the `value`
			// property of the button tag is auto escaped, making
 into &#10;
			buf.push(<span dangerouslySetInnerHTML={
				{
					__html: `<button class="button" name="send" value="/msgroom staff,/${toID(cmdName)} ${userid}` +
					`
/uspage ${target}">${cmdName}</button>`,
				}
			} />);
		}
		return buf;
	}
}

class SearchUsernames extends Chat.JSX.Component<{target: string, page?: boolean}> {
	render() {
		const {target, page} = {...this.props};
		const results: {offline: string[], online: string[]} = {
			offline: [],
			online: [],
		};
		for (const curUser of Users.users.values()) {
			if (!curUser.id.includes(target) || curUser.id.startsWith('guest')) continue;
			if (Punishments.isGlobalBanned(curUser)) continue;
			if (curUser.connected) {
				results.online.push(`${!page ? ONLINE_SYMBOL : ''} ${curUser.name}`);
			} else {
				results.offline.push(`${!page ? OFFLINE_SYMBOL : ''} ${curUser.name}`);
			}
		}
		for (const k in results) {
			Utils.sortBy(results[k as keyof typeof results], result => toID(result));
		}
		if (!page) {
			return <>
				Users with a name matching '{target}':

				{!results.offline.length && !results.online.length ?
					<>No users found.</> : <>
						{results.online.join('; ')}
						{!!results.offline.length &&
							<>{!!results.online.length && <>

</>}{results.offline.join('; ')}</>}
					</>
				}
			</>;
		}
		return

Usernames containing "{target}"

			{!results.online.length && !results.offline.length ?

No results found.
 :
				<>{!!results.online.length &&

Online users

							Username
							Punish

						{(() => {
							const online = [];
							for (const username of results.online) {
								online.push(

									<username>{username}</username>
									<PunishmentHTML userid={toID(username)} target={target} />

);
							}
							return online;
						})()}

}
				{!!(results.online.length && results.offline.length) &&
}
				{!!results.offline.length &&

Offline users

							Username
							Punish

						{(() => {
							const offline = [];
							for (const username of results.offline) {
								offline.push(

									<username>{username}</username>
									<PunishmentHTML userid={toID(username)} target={target} />

);
							}
							return offline;
						})()}

}</>
			}

;
	}
}

function saveNames() {
	FS('config/chat-plugins/usersearch.json').writeUpdate(() => JSON.stringify([...nameList]));
}

export const commands: Chat.ChatCommands = {
	us: 'usersearch',
	uspage: 'usersearch',
	usersearchpage: 'usersearch',
	usersearch(target, room, user, connection, cmd) {
		this.checkCan('lock');
		target = toID(target);
		if (!target) { // just join directly if it's the page cmd, they're likely looking for the full list
			if (cmd.includes('page')) return this.parse(`/j view-usersearch`);
			return this.parse(`/help usersearch`);
		}
		if (target.length < 3) {
			throw new Chat.ErrorMessage(`That's too short of a term to search for.`);
		}
		const showPage = cmd.includes('page');
		if (showPage) {
			this.parse(`/j view-usersearch-${target}`);
			return;
		}
		return this.sendReplyBox(<SearchUsernames target={target} />);
	},
	usersearchhelp: [
		`/usersearch [pattern]: Looks for all names matching the [pattern]. Requires: % @ &`,
		`Adding "page" to the end of the command, i.e. /usersearchpage OR /uspage will bring up a page.`,
		`See also /usnames for a staff-curated list of the most commonly searched terms.`,
	],
	usnames: 'usersearchnames',
	usersearchnames: {
		'': 'list',
		list() {
			this.parse(`/join view-usersearch`);
		},
		add(target, room, user) {
			this.checkCan('lock');
			const targets = target.split(',').map(toID).filter(Boolean);
			if (!targets.length) {
				return this.errorReply(`Specify at least one term.`);
			}
			for (const [i, arg] of targets.entries()) {
				if (nameList.has(arg)) {
					targets.splice(i, 1);
					this.errorReply(`Term ${arg} is already on the usersearch term list.`);
					continue;
				}
				if (arg.length < 3) {
					targets.splice(i, 1);
					this.errorReply(`Term ${arg} is too short for the usersearch term list. Must be more than 3 characters.`);
					continue;
				}
				nameList.add(arg);
			}
			if (!targets.length) {
				// fuck you too, "mia added 0 term to the usersearch name list"
				return this.errorReply(`No terms could be added.`);
			}
			const count = Chat.count(targets, 'terms');
			Rooms.get('staff')?.addByUser(
				user, `${user.name} added the ${count} "${targets.join(', ')}" to the usersearch name list.`
			);
			this.globalModlog(`USERSEARCH ADD`, null, targets.join(', '));
			if (!room || room.roomid !== 'staff') {
				this.sendReply(`You added the ${count} "${targets.join(', ')}" to the usersearch name list.`);
			}
			saveNames();
		},
		remove(target, room, user) {
			this.checkCan('lock');
			const targets = target.split(',').map(toID).filter(Boolean);
			if (!targets.length) {
				return this.errorReply(`Specify at least one term.`);
			}
			for (const [i, arg] of targets.entries()) {
				if (!nameList.has(arg)) {
					targets.splice(i, 1);
					this.errorReply(`${arg} is not in the usersearch name list, and has been skipped.`);
					continue;
				}
				nameList.delete(arg);
			}
			if (!targets.length) {
				return this.errorReply(`No terms could be removed.`);
			}
			const count = Chat.count(targets, 'terms');
			Rooms.get('staff')?.addByUser(
				user, `${user.name} removed the ${count} "${targets.join(', ')}" from the usersearch name list.`
			);
			this.globalModlog(`USERSEARCH REMOVE`, null, targets.join(', '));
			if (!room || room.roomid !== 'staff') {
				this.sendReply(`You removed the ${count} "${targets.join(', ')}"" from the usersearch name list.`);
			}
			saveNames();
		},
	},
	usnameshelp: [
		`/usnames add [...terms]: Adds the given [terms] to the usersearch name list. Requires: % @ &`,
		`/usnames remove [...terms]: Removes the given [terms] from the usersearch name list. Requires: % @ &`,
		`/usnames OR /usnames list: Shows the usersearch name list.`,
	],
};

export const pages: Chat.PageTable = {
	usersearch(query, user) {
		this.checkCan('lock');
		const target = toID(query.shift());
		if (!target) {
			this.title = `[Usersearch Terms]`;
			const sorted: {[k: string]: number} = {};
			for (const curUser of Users.users.values()) {
				for (const term of nameList) {
					if (curUser.id.includes(term)) {
						if (!(term in sorted)) sorted[term] = 0;
						sorted[term]++;
					}
				}
			}
			return

				Usersearch term list
				<button style={{float: 'right'}} class="button" name="send" value="/uspage">
					 Refresh
				</button>

				{!nameList.size ?

None found.
 :

								Term
								Current Matches

							{(() => {
								const buf = [];
								for (const k of Utils.sortBy(Object.keys(sorted), v => -sorted[v])) {
									buf.push(

										{k}
										{sorted[k]}
										<button class="button" name="send" value={`/uspage ${k}`}>Search</button>

);
								}
								if (!buf.length) return
No names found.
;
								return buf;
							})()}

				}

;
		}
		this.title = `[Usersearch] ${target}`;
		return <SearchUsernames target={target} page />;
	},
};


text:
var gulp = require("gulp")
var fs = require("fs");
var browserify = require("browserify");
var babelify = require("babelify");

gulp.task("babel", function(){
	browserify({
		debug: true,
		standalone: "JSONEdit"
	  })
	  .transform(babelify)
	  .require("./src/index.js", { entry: true })
	  .bundle()
	  .on("error", function (err) { console.log("Error: " + err.message); })
	  .pipe(fs.createWriteStream("JSONEditBundle.js"));
})

gulp.task("watch", function  () {
	gulp.watch("src/**/*.js", ["babel"]);
})

gulp.task("default", ["watch"])


text:
// File:    ProcessQueryPairs.scala
// Author:  Henry Feild
// Date:    20-Nov-2012
// Copyright 2013 Henry Feild
// License: Revised BSD -- see LICENSE in the root directory.

package edu.umass.ciir.tqgraph

import edu.umass.ciir.tqgraph.util.{ScalaFileIO,FileParser,FileIO,CommandLineIO}
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashMap
import java.io.File

/**
 * Takes a set of query reformulation counts and produces three things:
 *

 *
query-id --> query-text mapping
 *
term --> query-ids postings
 *
sparse rewrite adjacency matrix; rows sum to 1
 *

 * Currently these are all written to text files.
 *
 * @author hfeild
 */
class ProcessQueryPairs(rewriteFile:String, queryCountEst:Int=0) {
    import ProcessQueryPairs._

    val queryToIDMap = new HashMap[String,Int]()
    val rewriteMatrix = new HashMap[Int,HashMap[Int,Double]]()
    val termPostings = new HashMap[String, ArrayBuffer[Int]]()

    // If the caller gave a query count estimate, we can use that as a hint
    // to our hash maps.
    if( queryCountEst > 0 ) {
        queryToIDMap.sizeHint(queryCountEst)
        rewriteMatrix.sizeHint(queryCountEst)
        termPostings.sizeHint(queryCountEst)
    }

    /**
     * Adds the given query string to the query id map if it's not already
     * in there. It will be assigned the next available id.
     *
     * @param query The query to add.
     */
    def addToMapIfNeeded(query:String) {
        if( !queryToIDMap.contains(query) )
            queryToIDMap(query) = queryToIDMap.size
    }

    /**
     * Adds a term to the term postings list if it's not already.
     *
     * @param term The term to add.
     */
    def addToTermPostingsIfNeeded(term:String) {
        if( !termPostings.contains(term) )
            termPostings(term) = new ArrayBuffer[Int]()
    }

    /**
     * Process one line from the query reformulation file. It assumes that
     * the file has a header -- if it does not, then initialize seenHeader to
     * true. The reformulation file should consist of three
     * tab-delimited columns:
     *

     *
query 1
     *
query 2
     *
frequency
     *

     *
     * @param line          A line from the reformulation file.
     * @param seenHeader    Whether the header has been skipped. If
     *                      false, then the current line is
     *                      skipped and the return value is true.
     */
    def parseInputLine(line:String, seenHeader:Boolean):Boolean = {
        if( !seenHeader )
            return true

        val cols = line.split("\\t")
        val query1 = cols(Query1Col)
        val query2 = cols(Query2Col)
        val count = cols(FrequencyCol).toDouble

        if( query1 == query2 )
            return seenHeader

        addToMapIfNeeded(query1)
        addToMapIfNeeded(query2)

        if( !rewriteMatrix.contains(queryToIDMap(query1)) )
            rewriteMatrix(queryToIDMap(query1)) = new HashMap[Int,Double]()

        rewriteMatrix(queryToIDMap(query1))(queryToIDMap(query2)) = count

        seenHeader
    }

    /**
     * Normalizes the rows of the rewrite matrix so that the outgoing edges
     * of each query sums to 1.
     */
    def normalizeRows(){
        rewriteMatrix.values.foreach{queries =>
            val sum = queries.values.sum.toDouble
            queries.foreach{case(q,v) =>
                queries(q) = v / sum
            }
        }
    }

    /**
     * Reads in and parses the rewrite file, creating a normalized, sparse
     * re-write matrix,
     */
    def generateSparseRewriteMatrix() {
        FileParser.parseLatinFile(rewriteFile, false, parseInputLine)
        normalizeRows()
    }

    /**
     * Generates a term postings list.
     */
    def generateTermPostings(){
        queryToIDMap.foreach{case(q,id) =>
            val terms = q.toLowerCase.split("\\W+")
            terms.toSet.foreach{t:String =>
                addToTermPostingsIfNeeded(t)
                termPostings(t) += id
            }
        }
    }

    /**
     * Writes the sparse re-write matrix to file. The output format is:
     * [src query id]\t[dest query1 id]\t[prob1]\t[dest query2 id]\t[prob1]...
     * e.g.:
     *

     *     1  2  0.5  3  0.25  4  0.25
     *

     * This represents the query with id 1 being reformulated as the query with
     * id 2 50% of the time, reformulated as the query with id 3 25% of the
     * time, and reformulated as the query with id 4 25% of the time. The
     * probabilities sum to 1 for each row.
     *
     * @param filename  The name of the file to write the sparse matrix to.
     */
    def writeMatrix(filename:String) {
        val file = FileIO.getBufferedLatinWriter(filename)
        rewriteMatrix.foreach{case(qid, queries) =>
            file.write(qid.toString)
            queries.foreach{case(qid2,count) =>
                file.write("\t")
                file.write(qid2.toString)
                file.write("\t")
                file.write(count.toString)
            }
            file.write("\n")
        }
        file.close()
    }

    /**
     * Writes the term postings map to file. The output format is:
     * [term]\t[query1 id]\t[query2 id],...
     * where queryi contains [term]. E.g.
     *

     *     books  1  10  23  55  101
     *

     * Where the query mapping might be: 1 -> "free books", 10 -> "used books",
     * 23 -> "cheap books", 55 -> "books for kindle", and 101 ->
     * "children s books".
     *
     * @param filename  The name of the output file.
     */
    def writeTermPostings(filename:String){
        val file = FileIO.getBufferedLatinWriter(filename)
        termPostings.foreach{case(term,qids) =>
            file.write(term)
            qids.foreach{qid => file.write("\t"); file.write(qid.toString)}
            file.write("\n")
        }
        // Write the uniform vector.
        file.write("::UNIFORM::")
        queryToIDMap.values.foreach(id => file.write("\t"+ id))
        file.write("\n")
        file.close
    }

    /**
     * Writes the query mapping to file. The format is:
     * [query text]\t[query id]
     * E.g.,
     *

     *     free books  1
     *     used books  10
     *     cheap books  23
     *     books for kindle  55
     *     children's books  101
     *

     *
     * @param filename  The name of the output file.
     */
    def writeQueryIDMapping(filename:String){
        val file = FileIO.getBufferedLatinWriter(filename)
        queryToIDMap.foreach{case(q,qid) =>
            file.write(q)
            file.write("\t")
            file.write(qid.toString)
            file.write("\n")
        }
        file.close
    }

    /**
     * Clears the re-write matrix. Useful if you want to free some memory.
     */
    def discardRewriteMatrix() = rewriteMatrix.clear
}

/**
 * Companion for the ProcessQueryPairs class.
 */
object ProcessQueryPairs {

    val Query1Col = 0
    val Query2Col = 1
    val FrequencyCol = 2

    val TermPostingsFilename = "term-postings.tsv.gz"
    val QueryIDMappingFilename = "query-id-map.tsv.gz"
    val QueryReformulationMatrixFilename = "query-rewrite-matrix.tsv.gz"

    val Usage = """
    |Usage: ProcessQueryPairs <query pair file> <out dir> [<query count est>]
    |
    | Produces three files with tab-delimited columns in <out dir>:
    |
    |   term-postings.tsv.gz
    |   query-id-map.tsv.gz
    |   query-rewrite-matrix.tsv.gz
    |
    |""".stripMargin

    /**
     * A command line interface for creating a sparse re-write matrix, a
     * query-to-id mapping, and a term postings list. See Usage for details
     * about how to call.
     *
     * @param args  Command line params. Should consist of a query reformulation
     *              file and an output directory at a minimum.
     */
    def main(args:Array[String]){
        if( args.size < 2 || !ScalaFileIO.fileExists(args(0)))
            CommandLineIO.exitNice(Usage)

        val queryPairFile = args(0)
        val outDir = args(1)
        val queryCountEst = if( args.size > 2 ) args(2).toInt else 0

        if( !ScalaFileIO.fileExists(outDir) )
            new File(outDir).mkdirs()

        val pqp = new ProcessQueryPairs(queryPairFile, queryCountEst)
        pqp.generateSparseRewriteMatrix()
        pqp.writeMatrix(outDir+"/"+QueryReformulationMatrixFilename)
        pqp.writeQueryIDMapping(outDir+"/"+QueryIDMappingFilename)

        // Free up some memory...
        pqp.discardRewriteMatrix()

        pqp.generateTermPostings()
        pqp.writeTermPostings(outDir+"/"+TermPostingsFilename)
    }

}


text:
using System;
using System.Collections.Generic;

public class PriorityQueue<T> : IEnumerable<T> where T : IComparable
{
    private const int InitialSize = 16;

    private T[] data;
    private int count;

    public PriorityQueue(int capacity)
    {
        this.data = new T[capacity];
        this.count = 0;
    }

    public PriorityQueue()
        : this(InitialSize)
    {
    }

    public int Count
    {
        get
        {
            return this.count;
        }
    }

    public void Enqueue(T value)
    {
        if (this.count == this.data.Length)
        {
            this.Resize();
        }

        this.data[this.count] = value;
        int current = this.count;
        while (current >= 0 && this.data[current].CompareTo(this.data[(current - 1) / 2]) > 0)
        {
            this.Swap(current, (current - 1) / 2);
            current = (current - 1) / 2;
        }

        this.count++;
    }

    public T Dequeue()
    {
        T result = this.data[0];
        this.count--;
        this.data[0] = this.data[this.count];
        var current = 0;
        var max = this.MaxChildIndex(current);
        while (max > 0 && current < max)
        {
            this.Swap(current, max);
            current = max;
            max = this.MaxChildIndex(current);
        }

        return result;
    }

    public void Clear()
    {
        this.data = new T[InitialSize];
        this.count = 0;
    }

    public IEnumerator<T> GetEnumerator()
    {
        for (int i = 0; i < this.count; i++)
        {
            yield return this.data[i];
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    private int MaxChildIndex(int parentIndex)
    {
        var leftChildIndex = (parentIndex * 2) + 1;
        var rightChildIndex = (parentIndex * 2) + 2;
        if (rightChildIndex >= this.count)
        {
            if (leftChildIndex >= this.count)
            {
                return -1;
            }
            else
            {
                return leftChildIndex;
            }
        }
        else
        {
            if (this.data[leftChildIndex].CompareTo(this.data[rightChildIndex]) > 0)
            {
                return leftChildIndex;
            }
            else
            {
                return rightChildIndex;
            }
        }
    }

    private void Swap(int firstIndex, int secondIndex)
    {
        T temp = this.data[firstIndex];
        this.data[firstIndex] = this.data[secondIndex];
        this.data[secondIndex] = temp;
    }

    private void Resize()
    {
        T[] resizedArray = new T[this.data.Length * 2];
        Array.Copy(this.data, resizedArray, this.data.Length);
        this.data = resizedArray;
    }
}


text:
"use strict";
const {toPromise, resolve} = require("./promise");
const {registerGlobalInterceptor} = require("./interceptor");
const {createPipeline} = require("./pipeline");
const {createContainer} = require("./container");

module.exports = {
	toPromise,
	resolve,
	registerGlobalInterceptor,
	createPipeline,
	createContainer
};


text: export { Awake32 as default } from "../../";


text:
I use this microservice to maintain my social media.

The application takes a list of RSS/ATOM feeds, provided as an array in the /modules/feeds.js module, picks a random article and posts it to my Facebook page and Twitter account. The specified cron job will run this code every 2 hours.

If you wish to use this application for yourself:

* Clone the repo
* Navigate to the cloned direcotry and run `npm install`
* Supply an array of RSS/ATOM URLs in the /modules/feeds.js file.
* Create a .env file in the root directory and fill in your personal details (see .env.example file)


text:
name: "🙋🏼♂ Support question"
about: 'I need assistance or clarification on usage of this library.'
labels: question

---

### Versions:
- ide-helper Version: #.#.#
- Laravel Version: #.#.# <!-- remove if not applicable -->
- Lumen Version: #.#.# <!-- remove if not applicable -->
- PHP Version: #.#.#

### Question:


text:
<?php

namespace Parse\Test;

use Parse\HttpClients\ParseCurlHttpClient;
use Parse\HttpClients\ParseStreamHttpClient;
use Parse\ParseClient;
use Parse\ParseException;
use Parse\ParseObject;
use Parse\ParseQuery;

class Helper
{
    /**
     * Application Id
     * @var string
     */
    public static $appId      = 'app-id-here';

    /**
     * Rest API Key
     * @var string
     */
    public static $restKey    = 'rest-api-key-here';

    /**
     * Master Key
     * @var string
     */
    public static $masterKey  = 'master-key-here';

    /**
     * Account Key (for parse.com)
     * @var string
     */
    public static $accountKey = 'account-key';

    public static function setUp()
    {
        ini_set('error_reporting', E_ALL);
        ini_set('display_errors', 1);
        date_default_timezone_set('UTC');

        ParseClient::initialize(
            self::$appId,
            self::$restKey,
            self::$masterKey,
            true,
            self::$accountKey
        );
        self::setServerURL();
        self::setHttpClient();
    }

    public static function setHttpClient()
    {
        //
        // Set a curl http client to run primary tests under
        // may be:
        //
        // ParseCurlHttpClient
        // ParseStreamHttpClient
        //

        global $USE_CLIENT_STREAM;

        if (isset($USE_CLIENT_STREAM)) {
            // stream client
            ParseClient::setHttpClient(new ParseStreamHttpClient());
        } else {
            // default client set
            if (function_exists('curl_init')) {
                // cURL client
                ParseClient::setHttpClient(new ParseCurlHttpClient());
            } else {
                // stream client
                ParseClient::setHttpClient(new ParseStreamHttpClient());
            }
        }
    }

    public static function setServerURL()
    {
        ParseClient::setServerURL('http://localhost:1337', 'parse');
    }

    public static function tearDown()
    {
    }

    public static function clearClass($class)
    {
        $query = new ParseQuery($class);
        $query->each(
            function (ParseObject $obj) {
                $obj->destroy(true);
            },
            true
        );
    }

    public static function setUpWithoutCURLExceptions()
    {
        ParseClient::initialize(
            self::$appId,
            self::$restKey,
            self::$masterKey,
            false,
            self::$accountKey
        );
    }
}


text:
import volumedriver.storagerouter.EventMessages_pb2 as EventMessages
from ovs.lib.vdisk import VDiskController
from ovs.lib.vmachine import VMachineController
from ovs.lib.vpool import VPoolController
from ovs.lib.storagedriver import StorageDriverController

class Mapping(object):
    """
    Mapping container
    """
    mapping = {EventMessages.EventMessage.VolumeDelete: [{'property': 'volume_delete',
                                                          'task': VDiskController.delete_from_voldrv,
                                                          'arguments': {'name': 'volumename',
                                                                        '[NODE_ID]': 'storagedriver_id'}}],
               EventMessages.EventMessage.VolumeResize: [{'property': 'volume_resize',
                                                          'task': VDiskController.resize_from_voldrv,
                                                          'arguments': {'name': 'volumename',
                                                                        'size': 'volumesize',
                                                                        'path': 'volumepath',
                                                                        '[NODE_ID]': 'storagedriver_id'}}],
               EventMessages.EventMessage.VolumeRename: [{'property': 'volume_rename',
                                                          'task': VDiskController.rename_from_voldrv,
                                                          'arguments': {'name': 'volumename',
                                                                        'old_path': 'volume_old_path',
                                                                        'new_path': 'volume_new_path',
                                                                        '[NODE_ID]': 'storagedriver_id'}}],
               EventMessages.EventMessage.FileCreate: [{'property': 'file_create',
                                                        'task': VMachineController.update_from_voldrv,
                                                        'arguments': {'path': 'name',
                                                                      '[NODE_ID]': 'storagedriver_id'},
                                                        'options': {'delay': 3,
                                                                    'dedupe': True,
                                                                    'dedupe_key': '[TASK_NAME]_[name]_[storagedriver_id]',
                                                                    'execonstoragerouter': True}}],
               EventMessages.EventMessage.FileWrite: [{'property': 'file_write',
                                                       'task': VMachineController.update_from_voldrv,
                                                       'arguments': {'path': 'name',
                                                                     '[NODE_ID]': 'storagedriver_id'},
                                                       'options': {'delay': 3,
                                                                   'dedupe': True,
                                                                   'dedupe_key': '[TASK_NAME]_[name]_[storagedriver_id]',
                                                                   'execonstoragerouter': True}}],
               EventMessages.EventMessage.FileDelete: [{'property': 'file_delete',
                                                        'task': VMachineController.delete_from_voldrv,
                                                        'arguments': {'path': 'name',
                                                                      '[NODE_ID]': 'storagedriver_id'}}],
               EventMessages.EventMessage.FileRename: [{'property': 'file_rename',
                                                        'task': VMachineController.rename_from_voldrv,
                                                        'arguments': {'old_path': 'old_name',
                                                                      'new_path': 'new_name',
                                                                      '[NODE_ID]': 'storagedriver_id'},
                                                        'options': {'delay': 3,
                                                                    'dedupe': True,
                                                                    'dedupe_key': '[TASK_NAME]_[new_name]_[storagedriver_id]',
                                                                    'execonstoragerouter': True}}],
               EventMessages.EventMessage.UpAndRunning: [{'property': 'up_and_running',
                                                          'task': VPoolController.mountpoint_available_from_voldrv,
                                                          'arguments': {'mountpoint': 'mountpoint',
                                                                        '[NODE_ID]': 'storagedriver_id'},
                                                          'options': {'execonstoragerouter': True}}],
               EventMessages.EventMessage.RedirectTimeoutWhileOnline: [{'property': 'redirect_timeout_while_online',
                                                                        'task': StorageDriverController.update_status,
                                                                        'arguments': {'remote_node_id': 'storagedriver_id'},
                                                                        'options': {'dedupe': True,
                                                                                'dedupe_key': '[TASK_NAME]_[storagedriver_id]'}}]}


text:
using System;
using System.Runtime.Serialization;

namespace Gallio.Framework.Pattern
{
    /// <summary>
    /// The type of exception thrown when a test declaration is malformed or
    /// contains an error.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Implementations of <see cref="IPattern" /> may use this exception to report that a pattern
    /// is malformed or not valid in the context in which it appears.
    /// </para>
    /// <para>
    /// The exception effectively halts the processing of the pattern.  The message
    /// text is then manifested as an error annotation that may be displayed to the user.
    /// </para>
    /// <para>
    /// When you see this error, check to make sure that the syntax of the test
    /// is correct, all required parameters have been provided and they contain
    /// valid values.
    /// </para>
    /// </remarks>
    [Serializable]
    public class PatternUsageErrorException : Exception
    {
        /// <summary>
        /// Creates a usage error exception.
        /// </summary>
        /// <param name="message">A message that describes how the pattern was misused and possibly what should be done to correct it.</param>
        public PatternUsageErrorException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Creates a usage error exception.
        /// </summary>
        /// <param name="message">A message that describes how the pattern was misused and possibly what should be done to correct it.</param>
        /// <param name="innerException">An optional exception that will be used to provide aditional details about the usage error.</param>
        public PatternUsageErrorException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Creates an exception from serialization info.
        /// </summary>
        /// <param name="info">The serialization info.</param>
        /// <param name="context">The streaming context.</param>
        protected PatternUsageErrorException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}


text:
Int64 type: MinValue
--SKIPIF--
<?php if (PHP_INT_SIZE !== 8) { die("skip Can't represent 64-bit ints on a 32-bit platform"); } ?>
--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php

DO NOT EDIT THIS FILE
--FILE--
<?php

require_once __DIR__ . '/../utils/basic.inc';

$canonicalBson = hex2bin('10000000126100000000000000008000');
$canonicalExtJson = '{"a" : {"$numberLong" : "-9223372036854775808"}}';
$relaxedExtJson = '{"a" : -9223372036854775808}';

// Canonical BSON -> Native -> Canonical BSON
echo bin2hex(fromPHP(toPHP($canonicalBson))), "\n";

// Canonical BSON -> Canonical extJSON
echo json_canonicalize(toCanonicalExtendedJSON($canonicalBson)), "\n";

// Canonical BSON -> Relaxed extJSON
echo json_canonicalize(toRelaxedExtendedJSON($canonicalBson)), "\n";

// Canonical extJSON -> Canonical BSON
echo bin2hex(fromJSON($canonicalExtJson)), "\n";

// Relaxed extJSON -> BSON -> Relaxed extJSON
echo json_canonicalize(toRelaxedExtendedJSON(fromJSON($relaxedExtJson))), "\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
10000000126100000000000000008000
{"a":{"$numberLong":"-9223372036854775808"}}
{"a":-9223372036854775808}
10000000126100000000000000008000
{"a":-9223372036854775808}
===DONE===


text:
/**
 *  This source code is licensed in accordance with the terms specified in
 *  the LICENSE file found in the root directory of this source tree.
 */

#include <osquery/core/tables.h>
#include <osquery/logger/logger.h>
#include <osquery/utils/conversions/darwin/iokit.h>

namespace osquery {
namespace tables {

#define kIODeviceEfiPath_ ":/efi/platform"
#define kIODeviceChosenPath_ ":/chosen"
#define kEmbeddedOSClass_ "AppleEmbeddedOSSupportHost"
#define kAppleCoprocessorVersionKey_ "apple-coprocessor-version"

/// as defined in
/// /System/Library/Frameworks/Kernel.framework/Headers/IOKit/IOPlatformExpert.h
static const std::unordered_map<uint32_t, std::string> kCoprocessorVersions = {
    {0x00000000, ""},
    {0x00010000, "Apple T1 Chip"},
    {0x00020000, "Apple T2 Chip"},
};

static inline void genBootUuid(Row& r) {
  auto chosen = IORegistryEntryFromPath(
      kIOMasterPortDefault, kIODeviceTreePlane kIODeviceChosenPath_);
  if (chosen == MACH_PORT_NULL) {
    return;
  }

  CFMutableDictionaryRef properties = nullptr;
  auto kr = IORegistryEntryCreateCFProperties(
      chosen, &properties, kCFAllocatorDefault, kNilOptions);
  IOObjectRelease(chosen);

  if (kr != KERN_SUCCESS) {
    LOG(WARNING) << "Cannot get EFI properties";
    if (properties != nullptr) {
      CFRelease(properties);
    }
    return;
  }

  r["boot_uuid"] = getIOKitProperty(properties, "boot-uuid");
  CFRelease(properties);
}

static inline void genAppleCoprocessorVersion(Row& r) {
  auto asoc = IORegistryEntryFromPath(kIOMasterPortDefault,
                                      kIODeviceTreePlane kIODeviceEfiPath_);
  if (asoc == MACH_PORT_NULL) {
    LOG(WARNING) << "Cannot open EFI Device Tree";
    return;
  }

  CFMutableDictionaryRef properties = nullptr;
  auto kr = IORegistryEntryCreateCFProperties(
      asoc, &properties, kCFAllocatorDefault, kNilOptions);
  IOObjectRelease(asoc);

  if (kr != KERN_SUCCESS) {
    LOG(WARNING) << "Cannot get EFI properties";
    if (properties != nullptr) {
      CFRelease(properties);
    }
    return;
  }

  if (CFDictionaryContainsKey(properties,
                              CFSTR(kAppleCoprocessorVersionKey_))) {
    auto version_data = (CFDataRef)CFDictionaryGetValue(
        properties, CFSTR(kAppleCoprocessorVersionKey_));
    auto range = CFRangeMake(0, CFDataGetLength(version_data));

    auto buffer = std::vector<unsigned char>(range.length + 1, 0);
    CFDataGetBytes(version_data, range, &buffer[0]);

    uint32_t version = 0;
    memcpy(&version, buffer.data(), sizeof(uint32_t));
    r["coprocessor_version"] = (kCoprocessorVersions.count(version) > 0)
                                   ? kCoprocessorVersions.at(version)
                                   : "unknown";
  }
  CFRelease(properties);
}

QueryData genIBridgeInfo(QueryContext& context) {
  QueryData results;
  Row r;

  genAppleCoprocessorVersion(r);
  genBootUuid(r);

  auto eos = IOServiceNameMatching(kEmbeddedOSClass_);
  if (eos == nullptr) {
    LOG(WARNING)
        << "EmbeddedOS class not found. Perhaps this mac doesn't have T* chip";
    return results;
  }

  auto service = IOServiceGetMatchingService(kIOMasterPortDefault, eos);
  CFMutableDictionaryRef properties = nullptr;
  auto kr = IORegistryEntryCreateCFProperties(
      service, &properties, kCFAllocatorDefault, kNilOptions);
  IOObjectRelease(service);

  if (kr != KERN_SUCCESS) {
    LOG(WARNING) << "Cannot get EmbeddedOS properties";
    if (properties != nullptr) {
      CFRelease(properties);
    }
    return results;
  }

  r["unique_chip_id"] = getIOKitProperty(properties, "DeviceUniqueChipID");
  r["firmware_version"] = getIOKitProperty(properties, "DeviceBuildVersion");

  CFRelease(properties);

  results.push_back(std::move(r));
  return results;
}
} // namespace tables
} // namespace osquery


text:
<?php
/**
* MySMS - Simple SMS Component for Joomla
*
* Axel Sauerhoefer < mysms[at]quelloffen.com >
*
* http://www.willcodejoomlaforfood.de
*
* $Author: axel $
* $Rev: 187 $
* $HeadURL: svn://willcodejoomlaforfood.de/mysms/trunk/administrator/components/com_mysms/mysms.backend.php $
*
* $Id: mysms.backend.php 187 2009-12-14 19:14:27Z axel $
*
* All rights reserved.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* MySMS! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
**/
//check if joomla call us
defined( '_JEXEC' ) or die( 'Restricted access' );

if( defined( 'MYSMS_BACKEND_BACKEND_PHP' ) == true )
{
  return;
}

/**
 * Define our class constant to precent multipe definition
 */
define( 'MYSMS_BACKEND_BACKEND_PHP', 1 );

/**
 * MySMS Backend dispatcher class
 *
 * @author Axel Sauerhöfer <axel@willcodejoomlaforfood.de>
 * @version 1.5.3
 * @package MySMS
 * @subpackage Backend
 */
class mySmsBackend
{
  /*
   * task to proccess
   * @var string
   */
  var $task;

  /*
   * task to proccess
   * @var string
   */
  var $action;

  /**
   * parameter array
   * @var array
   */
  var $cid;

  /**
   * global database object
   * @var object mosDatabase
   */
  var $db;

  /**
   * Error handler
   * @var object mySMSError
   */
  var $errorHandler;

  /**
   * html layer
   * @var object mySmsBackendHtml
   */
  var $html;

  /**
   * crypto class
   * @var object mySmsCrypt
   */
  var $crypto;

  /**
   * Constructor
   *
   * @param string $task task to execute
   * @param array  $params array filled wiht parameter and globals like $database, $ItemId, $option
   */
  function mySmsBackend( $act, $task = 'default',  $cid = array() )
  {
    $this->action		= $act;
    $this->task 		= $task;
    $this->html			= new mySmsBackendHtml();
    $this->errorHandler = new mySMSError();
    $this->crypto		= new mySmsCrypt();
    $this->cid			= $cid;
    $this->db			= &JFactory::getDBO();
  }

  /**
   * Execute
   *
   * The Execute method is the only method to call, it is the entry point.
   * It check's if the given task exists, and is callable, if not the default
   * task will be called by call_user_method
   */
  function Execute( )
  {
    $method = 'Do' . ucfirst( strtolower( $this->action ) ) . ucfirst( strtolower( $this->task ) );

    if( !method_exists( $this, $method ) ){
      return $this->DoDefault();
    }

    if( !is_callable( array( $this, $method ) ) ){
      return $this->DoDefault();
    }

   call_user_func( array( $this, $method ) );
  }

  /**
   * Check if we can handle the request
   *
   * This method checks if we can handle the given task.
   *
   * @return bool return true if the task is handable, otherwise false
   */
  function CanHandle()
  {
    $method = 'Do' . ucfirst( strtolower( $this->action ) ) . ucfirst( strtolower( $this->task ) );

    if( !method_exists( $this, $method ) ){
      return false;
    }

    if( !is_callable( array( $this, $method ) ) ){
      return false;
    }

    return true;
  }

  /**
   * Show Configuration Defalut
   *
   * Show the default panel for configuration
   */
  function DoConfigurationDefault()
  {
    $this->html->showCredits();
  }

  function DoDefaultDefault()
  {
    $this->html->showCredits();
  }

  /**
   * DoProviderDefault
   *
   * Show the default select provider panel
   */
	function DoProviderDefault()
  	{
       $dir = _MYSMS_ADMIN_PATH . 'provider/';

       if( !file_exists( $dir ) )
       {
       		$this->errorHandler->Alert( JText::_( 'MYSMS_PROVIDER_NOT_FOUND' ) );
       }

      $factory = new ProviderFactory();
      $factory->registerAllProvider();

       $sql = "SELECT * from #__mysms_provider WHERE name != 'Base SMS Provider'";

       $this->ExecuteSql( $sql );
       $rows = $this->db->loadObjectList();
       $this->html->showProviderSelectPanel( $rows );
  }

  /**
   * Do Edit a specific provider
   *
   * Show the edit panel for a provider
   */
  function DoProviderEdit()
  {
      //only one provider can be edited
      if( is_array( $this->cid ) ){
          $id = (int)$this->cid[0];
      }else{
          $id = (int)$this->cid;
      }

      //set query and execute it, load selected provider
      $sql = "SELECT * FROM #__mysms_provider WHERE id=$id";

	  $this->ExecuteSql( $sql );
      $row = $this->db->loadObject();

      $factory = new ProviderFactory();
      $provider = $factory->getInstance( $row->name );

      if( $provider === false )
      {
      	$this->errorHandler->Alert( JText::_( 'MYSMS_PROVIDERFACTORY_NOT_FOUND' ) );
      }

       $provider->_params = $this->crypto->Decode( $row->params );
       $this->html->editProvider( $row, $provider );
  }

  /**
   * DoProviderSave
   *
   * Save new settings for a provider like username, password etc.
   * Do encryption before store in database
   */
  function DoProviderSave()
  {
      $params = JRequest::getVar( 'providerparams', array() );
      $id 	  = JRequest::getVar( 'id', -1 );

      if( is_string( $params ) )
      {
          $params = explode(",", $params );
      }

      $array = array();

      foreach($params as $key)
      {
          if( !strlen( $key ) )
          {
            continue;
          }

          $tmp 		 = JRequest::getVar( $key );
          $array[$key] = $tmp;
      }

       $str = $this->crypto->Encode( $array );

      $sql = "UPDATE #__mysms_provider SET active='0'";
      $this->ExecuteSql( $sql );

      $sql = "UPDATE #__mysms_provider SET params='$str',active='1' WHERE id=$id";
      $this->ExecuteSql( $sql );

      MySMSRedirect( 'index2.php?option=com_mysms&act=provider', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * DoProviderCancel
   *
   * User Canceld editing a provider, redirect to start page
   */
  function DoProviderCancel()
  {
    MySMSRedirect( 'index2.php?option=com_mysms' );
  }

  /**
   * Default for user panel
   */
  function  DoUser()
  {
  	$this->DoUserDefault();
  }

  /**
   * DoUserDefault
   *
   * Show the user overview panle
   */
  function DoUserDefault()
  {
       global $mainframe, $option;

       $sql = "SELECT COUNT(*) AS COUNTER FROM #__users";
	   $this->ExecuteSql( $sql );

       $total 		= $this->db->loadResult();
       $limit 		= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mainframe->getCfg('list_limit') ) );
       $limitstart	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );

       jimport('joomla.html.pagination');
       $pageNav = new JPagination( $total, $limitstart, $limit );

       $sql = "SELECT id, name, username from #__users";
       $this->ExecuteSql( $sql );

       $rows = $this->db->loadObjectList();

       $sql = "SELECT id, userid, state, credits from #__mysms_joomlauser";
	   $this->ExecuteSql( $sql );
       $mySmsRows = $this->db->loadObjectList();
       $this->html->showUser( $rows, $mySmsRows, $pageNav );
  }

  /**
   * DoUserPublish
   *
   */
  function DoUserPublish()
  {
    if( !is_array( $this->cid ) ){
           $this->cid = array(  $this->cid );
      }

      foreach( $this->cid as $uid ){
     	 $sql = "SELECT COUNT(*) AS COUNT FROM #__mysms_joomlauser WHERE userid=" . $uid;
     	 $this->ExecuteSql( $sql );
     	 $row = $this->db->loadObject();

     	 if( $row->COUNT  > 0 )
     	 {
     		$sql = "UPDATE #__mysms_joomlauser SET state=1 WHERE userid IN( " . implode( ',', $this->cid ) . ")";
     	 }else{
     	 	$sql = "INSERT INTO #__mysms_joomlauser VALUES( 0, $uid, '','',1, 0 )";
     	 }

		$this->ExecuteSql( $sql );
      }

       MySMSRedirect( 'index2.php?option=com_mysms&act=user', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * DoUserUnpublish
   *
   */
  function DoUserUnpublish()
  {
      if( !is_array( $this->cid ) )
      {
           $this->cid = array(  $this->cid );
      }

      $sql = "UPDATE #__mysms_joomlauser SET state=0 WHERE userid IN( " . implode( ',', $this->cid ) . ")";
	  $this->ExecuteSql( $sql );
      MySMSRedirect( 'index2.php?option=com_mysms&act=user', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * Edit a user
   */
  function DoUserEdit()
  {
      if( !is_array( $this->cid ) ){
           $this->cid = array(  $this->cid );
      }

      $userid = $this->cid[0];

      if( !is_numeric( $userid[0] ) )
      {
        $this->errorHandler->Alert( JText::_( 'MYSMS_EDIT_USER_INVALID_DATA' ) );
      }

        $sql = "SELECT * FROM #__users WHERE id=$userid LIMIT 1";
		$this->ExecuteSql( $sql );
        $row = $this->db->loadObject();

        $sql = "SELECT * FROM #__mysms_joomlauser WHERE userid=$userid LIMIT 1";
        $this->ExecuteSql( $sql );
        $mySMSRow = $this->db->loadObject();
        $this->html->editUser($row, $mySMSRow);
  }

  /**
   * Save user settings
   */
  function DoUserSave()
  {
      $number 	= JRequest::getVar( 'number' , ''  );
      $comment 	= JRequest::getVar( 'comment', '' );
      $credits 	= JRequest::getVar( 'credits', -99 );

      if( $credits == -99 || !is_numeric( $credits ) )
      {
        $this->errorHandler->Alert( JText::_( 'MYSMS_INVALID_BALANCE' ) );
      }

      $id      = JRequest::getVar( 'id', -1 );

      if( $id == -1 )
      {
        $this->errorHandler->Alert( JText::_( 'MYSMS_INVALUD_USER_DATA' ) );
      }

      $sql = "UPDATE #__mysms_joomlauser SET number='$number', comment='$comment', credits='$credits' WHERE userid=$id";
	  $this->ExecuteSql( $sql );

	  MySMSRedirect( 'index2.php?option=com_mysms&act=user', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * Cancel user edit
   */
  function DoUserCancel()
  {
  	MySMSRedirect( 'index2.php?option=com_mysms' );
  }

  /**
   * Show the load panel for multiple user
   */
  function DoUserLoadlistpanel()
  {
  	$this->html->showLoadPanel( $this->cid );
  }

  /**
   * Save the new credits for multipe user
   */
  function DoUserLoadlist()
  {
	$credits = JRequest::getVar( 'credits', -1 );
	$sql = "UPDATE #__mysms_joomlauser SET credits=$credits WHERE userid IN (" . implode(',',$this->cid) . ")";
	$this->ExecuteSql( $sql );
	MySMSRedirect( 'index2.php?option=com_mysms&act=user', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * Wrapper to execute sql statments,
   * maybe put later logging etc.
   */
  function ExecuteSql( $sql )
  {
  	$this->db->setQuery($sql);

    if( $this->db->query() === false )
    {
        $this->errorHandler->Alert( JText::_( 'MYSMS_SQLQUERY_ERROR' ) );
    }
  }

  /**
   * Do Advertisment default panel
   */
	function DoAdDefault()
	{
  		$sql = "SELECT value FROM #__mysms_config WHERE name='advertisment'";
  		$this->ExecuteSql( $sql );
 		$row = $this->db->loadObject();
 		$ad = is_null($row)?'':$row->value;
 		$this->html->showAdvertisment( $ad );
   }

  /**
   * Save advertisment
   *
   */
  function DoAdSave()
  {
      $ad = JRequest::getVar( 'ad',null);

      //check if a ad string exists in db
      $sql = "SELECT COUNT(*) AS CNT FROM #__mysms_config WHERE name='advertisment'";
	  $this->ExecuteSql( $sql );
      $row = $this->db->loadObject();

      if( $row->CNT == 0 )
      { // it is a insert
          $sql = "INSERT INTO #__mysms_config VALUES(0, 'advertisment', '$ad')";
      }else{  //update
          $sql = "UPDATE #__mysms_config SET value='$ad' WHERE name='advertisment' LIMIT 1";
      }

      $this->ExecuteSql( $sql );

      MySMSRedirect( 'index2.php?option=com_mysms', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * Cancel edditing advertisment
   */
  function DoAdCancel()
  {
  	MySMSRedirect( 'index2.php?option=com_mysms' );
  }

  /**
   * Default panel for global settings
   */
  function DoGlobalDefault()
  {
	//select all config parameter
	$sql = "SELECT id, name, value FROM #__mysms_config";
	$this->ExecuteSql( $sql );
	$config = $this->db->loadObjectList();

	$defaultConfig = array( 'maxsms' 		=> array( 'type' => 'text'    , 'value' =>  0 ),
						    'mailonerror' 	=> array( 'type' => 'text'    , 'value' =>  0 ),
							'email' 		=> array( 'type' => 'text'    , 'value' =>  'youremail@localhost' ),
							'policy' 		=> array( 'type' => 'textarea', 'value' =>  '' ) );

	foreach($config as $c )
	{
		if( isset( $defaultConfig[$c->name] ) )
		{
			$defaultConfig[$c->name]['value'] = $c->value;
		}
	}

	$this->html->showGlobal( $defaultConfig );
  }

  /**
   * Save global settings
   */
  function DoGlobalSave()
  {

	$config = JRequest::getVar( 'config', array() );

	foreach( $config as $key => $val ){

		$sql = "SELECT COUNT(*) AS C FROM #__mysms_config WHERE name='$key' ";
		$this->ExecuteSql( $sql );

		$result = null;
		$result = $this->db->loadObject();

		if( $result->C < 1 ){
			$sql = "INSERT INTO #__mysms_config VALUES( 0 , '$key', '$val')";
		}else{
			$sql = "UPDATE #__mysms_config SET value='$val' WHERE name='$key' LIMIT 1";
		}

		$this->ExecuteSql( $sql );
	}

	 MySMSRedirect( 'index2.php?option=com_mysms&act=global', JText::_( 'MYSMS_CHANGES_SAVED' ) );
  }

  /**
   * Show some information about com_mysms
   *
   */
  function DoAboutDefault()
  {
  	$this->html->showAbout();
  }

  /**
   * Cancel editting global settings
   */
  function DoGlobalCancel()
  {
	 MySMSRedirect( 'index2.php?option=com_mysms' );
  }

  /**
   * Do perform a Prerequisites check
   */
  function DoPrereqDefault()
  {
		$checker = new MySmsPrerequisite();
		$data = $checker->Check();
		$this->html->showPrerequisite( $data );
  }

}//end class
?>


text:
package com.seventeenkouer.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * Created by phil hong
 * User: wind
 * Date: 2018/6/26
 * Time: 下午12:23
 * To change this template use File | Settings | File Templates.
 */

    public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据bean名称获取Bean
     *
     * @param <T>
     * @param name Spring中定义的BeanID
     * @return BeanID对应的实例化对象(Spring定义的Service)
     * @throws BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(name);
    }

    /**
     * 根据class类名获取Bean
     *
     * @param <T>
     * @param className
     * @return
     */
    public static <T> T getBean(Class<T> className) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(className);
    }

    public static void unRegisterBean(String beanName) {
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        DefaultListableBeanFactory beanfactory = (DefaultListableBeanFactory) context.getBeanFactory();
        beanfactory.removeBeanDefinition(beanName);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pulsar4X.Entities
{
    public enum StarSystemEntityType
    {
        Invalid,
        Body,
        Waypoint,
        JumpPoint,
        TaskGroup,
        Population,
        Missile,
        TypeCount
    }

    public struct SystemPosition
    {
        /// <summary>
        /// System currently in.
        /// </summary>
        public StarSystem System { get; set; }

        /// <summary>
        /// System X coordinante in AU
        /// </summary>
        public double X { get; set; }

        /// <summary>
        /// System Y coordinante in AU
        /// </summary>
        public double Y { get; set; }

        /// <summary>
        /// Initilized constructor.
        /// </summary>
        /// <param name="system">StarSystem value.</param>
        /// <param name="x">X value.</param>
        /// <param name="y">Y value.</param>
        public SystemPosition(StarSystem system, double x, double y) : this()
        {
            System = system;
            X = x;
            Y = y;
        }

        /// <summary>
        /// Static function to find the distance between two positions.
        /// </summary>
        /// <param name="posA"></param>
        /// <param name="posB"></param>
        /// <returns>distance between posA and posB</returns>
        public static float GetDistanceBetween(SystemPosition posA, SystemPosition posB)
        {
            if (posA.System != posB.System)
            {
                throw new InvalidOperationException("Cannont compare distances between positions in different systems.");
            }
            float distX = (float)(posA.X - posB.X);
            float distY = (float)(posA.Y - posB.Y);

            return (float)Math.Sqrt((distX * distX) + (distY * distY));
        }

        /// <summary>
        /// Instance function for those who don't like static functions.
        /// </summary>
        /// <param name="otherPos"></param>
        /// <returns></returns>
        public float GetDistanceTo(SystemPosition otherPos)
        {
            return GetDistanceBetween(this, otherPos);
        }

        /// <summary>
        /// Adds two SystemPositions together.
        /// </summary>
        /// <param name="posA"></param>
        /// <param name="posB"></param>
        /// <returns></returns>
        public static SystemPosition operator +(SystemPosition posA, SystemPosition posB)
        {
            if (posA.System != posB.System)
            {
                throw new InvalidOperationException("Cannot add positions in different systems.");
            }

            posA.X += posB.X;
            posA.Y += posB.Y;
            return posA;
        }
    }

    public abstract class StarSystemEntity : GameEntity
    {
        /// <summary>
        /// Current System and Position of the entity.
        /// </summary>
        public SystemPosition Position;

        /// <summary>
        /// Type of entity that is represented here.
        /// </summary>
        public StarSystemEntityType SSEntity { get; set; }

        public StarSystemEntity()
            : base()
        {

            //default leagal orders.
            _legalOrders = new List<Constants.ShipTN.OrderType>
            {
                (Constants.ShipTN.OrderType.MoveTo),
                (Constants.ShipTN.OrderType.ExtendedOrbit),
                (Constants.ShipTN.OrderType.Picket),
                (Constants.ShipTN.OrderType.SendMessage),
                (Constants.ShipTN.OrderType.EqualizeFuel),
                (Constants.ShipTN.OrderType.EqualizeMSP),
                (Constants.ShipTN.OrderType.ActivateTransponder),
                (Constants.ShipTN.OrderType.DeactivateTransponder),
                (Constants.ShipTN.OrderType.ActivateSensors),
                (Constants.ShipTN.OrderType.DeactivateSensors),
                (Constants.ShipTN.OrderType.ActivateShields),
                (Constants.ShipTN.OrderType.DeactivateShields),
                (Constants.ShipTN.OrderType.DivideFleetToSingleShips),
                (Constants.ShipTN.OrderType.DetachNonGeoSurvey),
                (Constants.ShipTN.OrderType.DetachNonGravSurvey),
                (Constants.ShipTN.OrderType.RefuelFromOwnTankers),
                (Constants.ShipTN.OrderType.DetachTankers),
                (Constants.ShipTN.OrderType.ResupplyFromOwnSupplyShips),
                (Constants.ShipTN.OrderType.DetachSupplyShips),
                (Constants.ShipTN.OrderType.ReloadFromOwnColliers),
                (Constants.ShipTN.OrderType.DetachColliers),
                (Constants.ShipTN.OrderType.ReleaseAt),
            };
        }

        /// <summary>
        /// generic orders a selected tg targeting anything will have all these options if the selecteed tg can do these.
        /// </summary>
        protected List<Constants.ShipTN.OrderType> _legalOrders;

        /// <summary>
        /// list of legal orders a taskgroup or unit can use againsed this entity ie when this entity is the target.
        /// </summary>
        /// <param name="faction"></param>
        /// <returns></returns>
        public virtual List<Constants.ShipTN.OrderType> LegalOrders(Faction faction)
        {
            List<Constants.ShipTN.OrderType> legalOrders = new List<Constants.ShipTN.OrderType>();
            legalOrders.AddRange(_legalOrders);

            return legalOrders;
        }
    }
}


text:
package eu.intent.sdk.model;

import com.google.gson.annotations.SerializedName;

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

/**
 * A list of ITOperation.
 */
public class ITOperationList {
    public List<ITOperation> operations = new ArrayList<>();
    @SerializedName("count")
    public int totalCount = 0;
}


text:
layout: page
title: Mcpherson - Randall Wedding
date: 2016-05-24
author: Vincent Snow
tags: weekly links, java
status: published
summary: Phasellus placerat turpis in nisl.
banner: images/banner/people.jpg
booking:
  startDate: 12/04/2019
  endDate: 12/08/2019
  ctyhocn: YUBCAHX
  groupCode: MRW
published: true
---
Proin sagittis vel justo sit amet feugiat. Sed eu viverra sem. Nullam rutrum nec purus vel pellentesque. In semper felis at lorem rhoncus sodales. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam imperdiet orci in nulla finibus, pulvinar convallis nisl ultricies.

1 Fusce sodales nibh a urna tempor efficitur
1 Praesent a metus ultricies, pellentesque ligula vitae, convallis lectus
1 Vivamus ac leo tristique, porta sem vitae, ullamcorper diam.

Etiam elementum tempus lorem, vitae dapibus metus. Nunc massa felis, accumsan et consectetur sodales, facilisis ut nunc. Suspendisse tempor, elit eu commodo rhoncus, quam metus dignissim tortor, eu porttitor nisl elit vitae leo. Morbi et commodo orci. Duis mollis, est sed tempus blandit, mi velit laoreet odio, et congue metus sapien nec sem. Ut egestas venenatis scelerisque. Sed tempus aliquet varius. Curabitur interdum et nisi congue viverra. Quisque vel elit nibh. Donec in mattis dui.
Vivamus volutpat ante vel elit malesuada tempor. Donec varius nulla sem, eu placerat massa maximus vitae. Phasellus eros velit, luctus in luctus quis, porttitor et odio. Proin fringilla nibh ullamcorper aliquet gravida. Mauris egestas arcu nec libero dapibus scelerisque. Nunc ac elit sapien. Sed ornare enim sed diam varius, sed dictum libero vulputate. Sed a sem sollicitudin, ultricies metus ac, tincidunt arcu. Integer pulvinar nibh sit amet lobortis ultrices.


text:
package com.nutiteq.advancedmap3;

import android.os.Bundle;

import com.nutiteq.advancedmap3.datasource.CartoDBSQLDataSource;
import com.nutiteq.advancedmap3.listener.MyMapEventListener;
import com.nutiteq.core.MapPos;
import com.nutiteq.core.MapRange;
import com.nutiteq.datasources.LocalVectorDataSource;
import com.nutiteq.graphics.Color;
import com.nutiteq.layers.VectorLayer;
import com.nutiteq.styles.PointStyleBuilder;

/**
 * A sample demonstrating how to use CartoDB SQL API to get data
 * and how to create custom VectorDataSource
 */
public class CartoDBSQLActivity extends VectorMapSampleBaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // MapSampleBaseActivity creates and configures mapView
        super.onCreate(savedInstanceState);

        // define style for vector objects. Note that all objects must have same style here, which can be big limitation
        PointStyleBuilder pointStyleBuilder = new PointStyleBuilder();
        pointStyleBuilder.setColor(new Color(0x800000ff)); // blue
        pointStyleBuilder.setSize(10);

        // Initialize a local vector data source
        CartoDBSQLDataSource vectorDataSource1 = new CartoDBSQLDataSource(baseProjection,"https://nutiteq.cartodb.com/api/v2/sql","SELECT cartodb_id,the_geom_webmercator AS the_geom,name,address,bikes,slot,field_7,field_8,field_9,field_16,field_17,field_18 FROM stations_1 WHERE !bbox!",pointStyleBuilder.buildStyle());
        // Initialize a vector layer with the previous data source
        VectorLayer vectorLayer1 = new VectorLayer(vectorDataSource1);
        // Add the previous vector layer to the map
        mapView.getLayers().add(vectorLayer1);
        // Set visible zoom range for the vector layer
        vectorLayer1.setVisibleZoomRange(new MapRange(14, 23));

        // set listener to get point click popups

        // 1. Initialize a local vector data source and layer for click Balloons
        LocalVectorDataSource vectorDataSource = new LocalVectorDataSource(baseProjection);
        // Initialize a vector layer with the previous data source
        VectorLayer vectorLayer = new VectorLayer(vectorDataSource);
        // Add the previous vector layer to the map
        mapView.getLayers().add(vectorLayer);

        mapView.setMapEventListener(new MyMapEventListener(mapView, vectorDataSource));

        // finally animate map to the marker
        mapView.setFocusPos(baseProjection.fromWgs84(new MapPos(-74.0059, 40.7127)), 1);
        mapView.setZoom(15, 1);
    }

    @Override
    protected void onDestroy() {
        mapView.setMapEventListener(null);

        super.onDestroy();
    }
}


text:
module EFA2.Example.LinearOne where

import EFA2.Topology.Topology (makeWithDirEdges, makeNodes)
import EFA2.Topology.TopologyData (NodeType(Source, Sink))
import EFA2.Topology.EfaGraph (mkGraph)

import EFA2.Interpreter.Env
          (Index(Energy, DTime), DTimeMap, EnergyMap)
import EFA2.Solver.Equation (EqTerm, Term(Atom,Const))
import EFA2.Example.SymSig (TheGraph(TheGraph))

import qualified EFA2.Signal.Index as Idx
import qualified EFA2.Signal.Signal as S
import EFA2.Signal.Signal (UTFSig, TC, Scalar, toScalar)
import EFA2.Signal.Typ (Typ, UT)
import EFA2.Signal.Data (Data, Nil)

import qualified Data.Map as M

sec :: Idx.Section
sec = Idx.Section 0

rec0, rec1 :: Idx.Record
rec0 = Idx.Record 0
rec1 = Idx.Record 1

edgeIdx ::
   (Idx.Record -> Idx.SecNode -> Idx.SecNode -> idx) ->
   Idx.Record -> Idx.Section -> Int -> Int -> idx
edgeIdx mkIdx rec s x y =
   mkIdx rec (Idx.SecNode s (Idx.Node x)) (Idx.SecNode s (Idx.Node y))

dtimes0 :: DTimeMap UTFSig
dtimes0 = M.fromList [(Idx.DTime rec0 sec, S.fromList [1.0])]

sigs0 :: EnergyMap UTFSig
sigs0 = M.fromList [ (edgeIdx Idx.Energy rec0 sec 0 1, S.fromList [3]) ]

dtimes1 :: DTimeMap UTFSig
dtimes1 = M.fromList [(Idx.DTime rec1 sec, S.fromList [1.0])]

sigs1 :: EnergyMap UTFSig
sigs1 = M.fromList [ (edgeIdx Idx.Energy rec1 sec 0 1, S.fromList [3.3]) ]

-------------------------

type InTermScalar = TC Scalar (Typ UT UT UT) (Data Nil EqTerm)

dtimes0s :: DTimeMap InTermScalar
dtimes0s = M.fromList [ (Idx.DTime rec0 sec, toScalar (Const 20.0)) ]

sigs0s :: EnergyMap InTermScalar
sigs0s = M.fromList [ (edgeIdx Idx.Energy rec0 sec 0 1, toScalar (Const 3.0)) ]

dtimes1s :: DTimeMap InTermScalar
dtimes1s = M.fromList [ (Idx.DTime rec1 sec, toScalar (Const 20.0)) ]

sigs1s :: EnergyMap InTermScalar
sigs1s = M.fromList [ (edgeIdx Idx.Energy rec1 sec 0 1, toScalar (Const 3.3)) ]

-------------------------

dtimes0ss :: DTimeMap InTermScalar
dtimes0ss = M.fromList [ (Idx.DTime rec0 sec, toScalar $ Atom $ DTime $ Idx.DTime rec0 sec) ]

sigs0ss :: EnergyMap InTermScalar
sigs0ss = M.fromList [ (edgeIdx Idx.Energy rec0 sec 1 0, toScalar $ Atom $ Energy $ edgeIdx Idx.Energy rec0 sec 1 0) ]

dtimes1ss :: DTimeMap InTermScalar
dtimes1ss = M.fromList [ (Idx.DTime rec1 sec, toScalar $ Atom $ DTime $ Idx.DTime rec1 sec) ]

sigs1ss :: EnergyMap InTermScalar
sigs1ss = M.fromList [ (edgeIdx Idx.Energy rec1 sec 0 1, toScalar $ Atom $ Energy $ edgeIdx Idx.Energy rec1 sec 0 1) ]

linearOne :: TheGraph InTermScalar
linearOne = TheGraph g sigs0s
  where g = mkGraph ns es
        ns = makeNodes [(0, Source), (1, Sink)]
        es = makeWithDirEdges [(0, 1)]


text:
<?xml version="1.0" encoding="utf-8"?>

Viewing Event Details (Month View)

How to view the full details of an event when events are displayed in a monthly calendar.

Click the Month View  button and navigate to the required date.

If event titles are not displayed in calendar cells, place your mouse over the date that is displayed in the required date cell and then click on the date.

If event titles are displayed in calendar cells and then click on the linked [Event Title] to view full event details. Event details may be displayed when you position your mouse over the event title as shown in the below image.

Click the Return link to return to the previous page.