text:
package com.pg.creg.expr.character;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Pedro Gandola <pedro.gandola@gmail.com>
 */
public class SubtractionTest {

    /**
     * Test of eval method, of class Subtraction.
     */
    @Test
    public void testEval() throws Exception {
        StringBuilder builder = new StringBuilder();
        Subtraction instance = new Subtraction(new Word(), new Digit());
        instance.eval(builder);
        assertEquals(builder.toString(), "[\\w&&[^\\d]]");
    }

}


text:
package com.armadialogcreator.gui.main.stringtable;

import com.armadialogcreator.core.stringtable.KnownLanguage;
import com.armadialogcreator.core.stringtable.Language;
import com.armadialogcreator.core.stringtable.StringTable;
import com.armadialogcreator.core.stringtable.StringTableKey;
import com.armadialogcreator.data.SimpleStringTableKey;
import com.armadialogcreator.gui.fxcontrol.CheckMenuButton;
import com.armadialogcreator.gui.main.popup.NameTextFieldDialog;
import com.armadialogcreator.lang.Lang;
import com.armadialogcreator.util.MapObserver;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.geometry.Pos;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.ResourceBundle;

/**
 @author Kayler
 @since 12/26/2016 */
class NewStringTableKeyDialog extends NameTextFieldDialog {

	private final StringTableKey key = new SimpleStringTableKey("str_tag_name", new MapObserver<>(new HashMap<>()));
	private final StringTable table;

	private final ResourceBundle bundle = Lang.getBundle("StringTableBundle");

	public NewStringTableKeyDialog(@NotNull StringTable table) {
		super("", "");
		setMessage(bundle.getString("StringTableEditorPopup.Tab.Edit.insert_key_popup_body"));
		setTitle(bundle.getString("StringTableEditorPopup.Tab.Edit.insert_key_tooltip"));

		this.table = table;

		setInputText(key.getId());

		CheckMenuButton<Language> menuButtonLangs = new CheckMenuButton<>(bundle.getString("StringTableEditorPopup.Tab.Edit.insert_key_popup_lang_button_text"), null, KnownLanguage.values());
		menuButtonLangs.setAlignment(Pos.CENTER_LEFT);
		menuButtonLangs.getSelectedItemsReadOnly().addListener(new ListChangeListener<Language>() {
			@Override
			public void onChanged(Change<? extends Language> c) {
				while (c.next()) {
					if (c.wasRemoved()) {
						key.getLanguageTokenMap().remove(c.getRemoved());
					} else if (c.wasAdded()) {
						for (int i = c.getFrom(); i < c.getTo(); i++) {
							key.getLanguageTokenMap().put(c.getList().get(i), "");
						}
					}
				}
			}
		});
		myRootElement.getChildren().add(menuButtonLangs);
		inputTextProperty().addListener(new ChangeListener<String>() {
			boolean added;
			final String badInput = "bad-input-text-field";

			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				newValue = newValue != null ? newValue : "";
				if (!StringTableKey.idIsProper(newValue)) {
					if (!added) {
						added = true;
						myNode.getStyleClass().add(badInput);
						getCanOkProperty().setValue(false);
					}
				} else {
					added = false;
					myNode.getStyleClass().remove(badInput);
					getCanOkProperty().setValue(true);
					key.setId(newValue);
				}
			}
		});

		myNode.requestFocus();
		myNode.positionCaret(myNode.getText().indexOf('_'));
		myNode.selectEnd();

	}

	@Override
	protected void ok() {
		StringTableKey existingKey = table.getKeyById(key.getId());
		if (existingKey != null) {
			new KeyAlreadyExistsDialog(key).show();
			return;
		}
		if (key.idIsProper()) {
			super.ok();
		} else {
			myNode.requestFocus();
			beep();
		}
	}

	/**
	 Get the new key. If the dialog was cancelled, will still return a non-null key

	 @return new key
	 */
	@NotNull
	public StringTableKey getKey() {
		return key;
	}
}

redpajama_set_name: RedPajamaGithub


text:
require "drip/collection"

module Drip
  class Orders < Collection
    def self.collection_name
      "orders"
    end

    def self.resource_name
      "order"
    end
  end
end


text:
package freemarker.core;

import java.io.IOException;

import freemarker.template.TemplateException;

/**
 * An instruction that does multiple assignments, like [#local x=1 x=2].
 * Each assignment is represented by a {@link Assignment} child element.
 * If there's only one assignment, its usually just a {@link Assignment} without parent {@link AssignmentInstruction}.
 */
final class AssignmentInstruction extends TemplateElement {

    private int scope;
    private Expression namespaceExp;

    AssignmentInstruction(int scope) {
        this.scope = scope;
        setRegulatedChildBufferCapacity(1);
    }

    void addAssignment(Assignment assignment) {
        addRegulatedChild(assignment);
    }

    void setNamespaceExp(Expression namespaceExp) {
        this.namespaceExp = namespaceExp;
        int ln = getRegulatedChildCount();
        for (int i = 0; i < ln; i++) {
            ((Assignment) getRegulatedChild(i)).setNamespaceExp(namespaceExp);
        }
    }

    @Override
    void accept(Environment env) throws TemplateException, IOException {
        int ln = getRegulatedChildCount();
        for (int i = 0; i < ln; i++) {
            Assignment assignment = (Assignment) getRegulatedChild(i);
            env.visit(assignment);
        }
    }

    @Override
    protected String dump(boolean canonical) {
        StringBuilder buf = new StringBuilder();
        if (canonical) buf.append('<');
        buf.append(Assignment.getDirectiveName(scope));
        if (canonical) {
            buf.append(' ');
            int ln = getRegulatedChildCount();
            for (int i = 0; i < ln; i++) {
                if (i != 0) {
                    buf.append(", ");
                }
                Assignment assignment = (Assignment) getRegulatedChild(i);
                buf.append(assignment.getCanonicalForm());
            }
        } else {
            buf.append("-container");
        }
        if (namespaceExp != null) {
            buf.append(" in ");
            buf.append(namespaceExp.getCanonicalForm());
        }
        if (canonical) buf.append(">");
        return buf.toString();
    }

    @Override
    int getParameterCount() {
        return 2;
    }

    @Override
    Object getParameterValue(int idx) {
        switch (idx) {
        case 0: return Integer.valueOf(scope);
        case 1: return namespaceExp;
        default: return null;
        }
    }

    @Override
    ParameterRole getParameterRole(int idx) {
        switch (idx) {
        case 0: return ParameterRole.VARIABLE_SCOPE;
        case 1: return ParameterRole.NAMESPACE;
        default: return null;
        }
    }

    @Override
    String getNodeTypeSymbol() {
        return Assignment.getDirectiveName(scope);
    }

    @Override
    public TemplateElement postParseCleanup(boolean stripWhitespace) throws ParseException {
        super.postParseCleanup(stripWhitespace);
        return this;
    }

    @Override
    boolean isNestedBlockRepeater() {
        return false;
    }

}


text:
package com.evolveum.midpoint.testing.story.notorious;

import static org.testng.AssertJUnit.assertEquals;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import javax.xml.namespace.QName;

import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import com.evolveum.midpoint.model.api.context.ModelContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.InternalInspector;
import com.evolveum.midpoint.schema.internals.InternalMonitor;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;

/**
 * Testing bushy roles hierarchy. Especially reuse of the same role
 * in the rich role hierarchy. It looks like this:
 *
 *                    user
 *                     |
 *       +------+------+-----+-----+-....
 *       |      |      |     |     |
 *       v      v      v     v     v
 *      Ra1    Ra2    Ra3   Ra4   Ra5
 *       |      |      |     |     |
 *       +------+------+-----+-----+
 *                     |
 *                     v
 *  +--assignment--> supernotorious org
 *  |                  |
 *  |    +------+------+-----+-----+-....
 *  |    |      |      |     |     |
 *  |    v      v      v     v     v
 *  +-- Rb1    Rb2    Rb3   Rb4   Rb5 ---..
 *
 * Naive mode of evaluation would imply cartesian product of all Rax and Rbx
 * combinations. That's painfully inefficient. Therefore make sure that the
 * notorious roles is evaluated only once and the results of the evaluation
 * are reused.
 *
 * @author Radovan Semancik
 */
@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class })
public class TestSupernotoriousOrg extends TestNotoriousOrg {

	public static final File ORG_SUPERNOTORIOUS_FILE = new File(TEST_DIR, "org-supernotorious.xml");
	public static final String ORG_SUPERNOTORIOUS_OID = "16baebbe-5046-11e7-82a0-eb7b7e3400f6";

	@Override
	protected String getNotoriousOid() {
		return ORG_SUPERNOTORIOUS_OID;
	}

	@Override
	protected File getNotoriousFile() {
		return ORG_SUPERNOTORIOUS_FILE;
	}

	@Override
	protected void fillLevelBRole(RoleType roleType, int i) {
		super.fillLevelBRole(roleType, i);
		roleType
			.beginAssignment()
				.targetRef(getNotoriousOid(), getNotoriousType())
//				.focusType(RoleType.COMPLEX_TYPE)
			.end();
	}

	@Test
    public void test010LevelBRolesSanity() throws Exception {
		final String TEST_NAME = "test010LevelBRolesSanity";
        displayTestTile(TEST_NAME);

        ObjectQuery query = queryFor(RoleType.class).item(RoleType.F_ROLE_TYPE).eq(ROLE_LEVEL_B_ROLETYPE).build();
		searchObjectsIterative(RoleType.class, query,
				role -> {
					assertRoleMembershipRef(role, getNotoriousOid());
				}, NUMBER_OF_LEVEL_B_ROLES);
	}

	@Override
	protected void assertRoleEvaluationCount(int numberOfNotoriousAssignments, int numberOfOtherAssignments) {
		inspector.assertRoleEvaluations(getNotoriousOid(), hackify(numberOfNotoriousAssignments));
	}
}


text:
import React from "react";
import PropTypes from "prop-types";
import { Spin } from "antd";
import styles from "./weather.less";

function Weather({ city, icon, dateTime, temperature, name, loading }) {
    return (
        <Spin spinning={loading}>

                    <div
                        className={styles.icon}
                        style={{
                            backgroundImage: `url(${icon})`,
                        }}
                    />

{name}

{`${temperature}°`}

{city},{dateTime}

        </Spin>);
}

Weather.propTypes = {
    city: PropTypes.string,
    icon: PropTypes.string,
    dateTime: PropTypes.string,
    temperature: PropTypes.string,
    name: PropTypes.string,
    loading: PropTypes.bool,
};

export default Weather;


text:
================================================
How to use python-twitter with Google App Engine
================================================

**********
Background
**********

Google App Engine uses virtual machines to do work and serve your application's content. In order to make a 'regular' external web request, the instance must use the built-in urlfetch library provided by Google in addition to the traditional python requests library. As a result, a few extra steps must be followed to use python-twitter on App Engine.

*************
Prerequisites
*************

Follow the `third party vendor library install instructions <https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#vendoring>`_ to include the two dependency libraries listed in ``requirements.txt``: ``requests`` and ``requests_oauthlib``, as well as this ``python-twitter`` library. Typically you can just place the three module folders into the same place as your app.yaml file; it might look something like this:

| myapp/
| ├── twitter/
| ├── requests_oauthlib/
| ├── requests_toolbelt/
| ├── main.py
| └── app.yaml

********
app.yaml
********

In order to use HTTPS, you'll have to make sure the built-in SSL library is properly imported in your ``app.yaml`` file. Here's what that section of your ``app.yaml`` file might look like:

| libraries:
| - name: jinja2
|  version: latest
| - name: webapp2
|  version: latest
| - name: ssl
|  version: latest

****************************
Limitations & Considerations
****************************

Caching
^^^^^^^
When using twitter-python on App Engine, caching is disabled. You'll have to add and manage App Engine's memcache logic on your own if you require any caching beyond what is probably already setup on App Engine by default.

Datastore
^^^^^^^^^
If you plan to store tweets or other information returned by the API in Datastore, you'll probably want to make your own NDP models to store the desired components of the response rather than shoving the whole response into an entity.

Sockets
^^^^^^^^^
When urllib3 is imported on App Engine it will throw a warning about sockets: ``AppEnginePlatformWarning: urllib3 is using URLFetch on Google App Engine sandbox...`` This is just a warning that you'd have to use the Sockets API if you intend to use the sockets feature of the library, which we don't use in python-twitter so it can be ignored.


text:
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
app = pg.mkQApp()
app.processEvents()

def test_scatterplotitem():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect.
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())

    # test SymbolAtlas accepts custom symbol
    s = pg.ScatterPlotItem()
    symbol = QtGui.QPainterPath()
    symbol.addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1))
    s.addPoints([{'pos': [0,0], 'data': 1, 'symbol': symbol}])

    for i, pxMode in enumerate([True, False]):
        for j, useCache in enumerate([True, False]):
            s = pg.ScatterPlotItem()
            s.opts['useCache'] = useCache
            plot.addItem(s)
            s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
            s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])

            # Test uniform spot updates
            s.setSize(10)
            s.setBrush('r')
            s.setPen('g')
            s.setSymbol('+')
            app.processEvents()

            # Test list spot updates
            s.setSize([10] * 6)
            s.setBrush([pg.mkBrush('r')] * 6)
            s.setPen([pg.mkPen('g')] * 6)
            s.setSymbol(['+'] * 6)
            s.setPointData([s] * 6)
            app.processEvents()

            # Test array spot updates
            s.setSize(np.array([10] * 6))
            s.setBrush(np.array([pg.mkBrush('r')] * 6))
            s.setPen(np.array([pg.mkPen('g')] * 6))
            s.setSymbol(np.array(['+'] * 6))
            s.setPointData(np.array([s] * 6))
            app.processEvents()

            # Test per-spot updates
            spot = s.points()[0]
            spot.setSize(20)
            spot.setBrush('b')
            spot.setPen('g')
            spot.setSymbol('o')
            spot.setData(None)
            app.processEvents()

    plot.clear()

def test_init_spots():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect.
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())
    spots = [
        {'x': 0, 'y': 1},
        {'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'},
    ]
    s = pg.ScatterPlotItem(spots=spots)

    # Check we can display without errors
    plot.addItem(s)
    app.processEvents()
    plot.clear()

    # check data is correct
    spots = s.points()

    defPen = pg.mkPen(pg.getConfigOption('foreground'))

    assert spots[0].pos().x() == 0
    assert spots[0].pos().y() == 1
    assert spots[0].pen() == defPen
    assert spots[0].data() is None

    assert spots[1].pos().x() == 1
    assert spots[1].pos().y() == 2
    assert spots[1].pen() == pg.mkPen(None)
    assert spots[1].brush() == pg.mkBrush(None)
    assert spots[1].data() == 'zzz'

if __name__ == '__main__':
    test_scatterplotitem()


text:
package com.vowovrz.struts2_02.context;

import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

public class AwareContextTest implements ApplicationAware, SessionAware,
		RequestAware, ParameterAware {
	public String execute() {

		application.put("applicationKey", "applicationValue OK");
		System.out.println("applicationMap : " + application.get("date"));

		session.put("sessionKey", "sessionValue OK");
		System.out.println("sessionMap : " + session.get("date"));

		request.put("requestKey", "requestValue OK");
		//request不能通过链接传递参数,得通过转发才行
		//System.out.println("request : " + request.get("date"));

		String[] str = new String[3];
		str[0] = "abc";
		str[1] = "abc222";
		str[2] = "abc555";

		parameters.put("age", str);
		System.out.println("parameters : "
				+ ((String[]) parameters.get("name"))[0]);

		System.out.println();
		return "success";
	}

	private Map<String, Object> application;
	private Map<String, Object> session;
	private Map<String, Object> request;
	private Map<String, String[]> parameters;

	@Override
	public void setParameters(Map<String, String[]> parameters) {
		this.parameters = parameters;
	}

	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setApplication(Map<String, Object> application) {
		this.application = application;
	}
}


text:
import os
import sys
import glob
import numpy as np
import pm_funcs
import argparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

stilts_folder = os.path.dirname(os.path.realpath(__file__))

parser = argparse.ArgumentParser(description='CMD Bins')
parser.add_argument('K', type=int, help='Numero de epoca en Ks')
parser.add_argument('J', type=int, help='Numero de epoca en J')
parser.add_argument('--refstars', '-r', type=str, default=None, help='Destaca las estrellas en el archivo de refstars indicado')
parser.add_argument('--show-plot', '-p', action='store_true', help='Muestra el plot del CMD')

args = parser.parse_args()

cmd_modo, match, col1, col2, mag1, mag2, cmd_pdf = pm_funcs.get_CMD()

#Numero de epocas a usar
k_epoch = args.K
j_epoch = args.J

#Refstars
refst = args.refstars

if match=='RA DEC':
    match   = "RA DEC"
    omodo   = 'RD'

matcher = 'sky params=0.3'
if match == 'ID':
    matcher = 'exact'
    omodo   = 'ID'

output = 'CMD_%03d-%03d-%s.dat' % (k_epoch, j_epoch, omodo)

#Busca los catalogos
k_catalog = glob.glob('*k*%03d.datgc' % k_epoch)[0]
j_catalog = glob.glob('*j*%03d.datgc' % j_epoch)[0]

#Realiza el match usando K como referencia (1 and 2)
print 'Archivos para generar el CMD: %s %s\n' % (k_catalog, j_catalog)

os.system('java -jar %s/stilts.jar tmatch2 \
               in1=%s values1="%s" ifmt1=ascii \
               in2=%s values2="%s" ifmt2=ascii \
               matcher=%s find=best join=all1 \
               out=%s ofmt=ascii' % (stilts_folder,k_catalog,match,j_catalog,match,matcher,output) )

    #idk, rak, dek, xk, yk, magk, magek = np.genfromtxt(k_catalog, unpack=True)
    #idj, raj, dej, xj, yj, magj, magej = np.genfromtxt(j_catalog, unpack=True)

if cmd_pdf:
    ids, K, J = np.genfromtxt(output,unpack=True,usecols=(0,5,12))

    fig, ax = plt.subplots(figsize=[4,6])
    ax.plot(J-K,K,'.k',ms=1, alpha=1, rasterized=False)
    ax.set_xlabel('$J-K$')
    ax.set_ylabel('$K$')
    ax.set_title(k_catalog)

    if cmd_modo=='manual':
        ax.set_xlim(col1,col2)
        ax.set_ylim(mag1,mag2)
    else:
        ax.invert_yaxis()
    if refst is not None:
        idr = np.genfromtxt(refst, unpack=True, usecols=(0,))
        idx = np.in1d(ids, idr)
        ax.plot((J-K)[idx], K[idx], '.r', ms=1, alpha=1, rasterized=False)

    print '\nGuardando PNG...'
    fig.savefig(output.replace('.dat', '.png'), dpi=200, bbox_inches='tight')
    if args.show_plot:
        plt.show()
print '\nDone!'


text:
/**
 * Wrapper for SVGDefsElement native interface
 *
 * It can wrap SVGDefsElement elements
 *
 * If svgDOMNode is wrapped by Vector.Defs's super class then
 * it removes that wrapper and returns a new Vector.Defs wrapper.
 * To get a appropriate wrapper please use Vector.wrap() method.
 *
 * @type {Vector.Defs}
 */
var Defs = Vector.Defs = function Defs(svgDOMNode) {
    var wrappedInstance = Graphics.call(this, svgDOMNode);
    if (wrappedInstance)
        return wrappedInstance;
};

setPrototypeOf(Defs, Graphics);

Defs.prototype = Object.create(Graphics.prototype);

Defs.prototype.constructor = Defs;

Vector.merge(Defs, {

    domInterface: window.SVGDefsElement

});

Vector.merge(Defs.prototype, {

    tag: "defs",

    // Namespace of all the attributes is null
    _defaultAttrValues: Vector.merge(Vector.merge({}, Defs.prototype._defaultAttrValues), {

    })
});

ShapeContainer.makeInheritance(Defs);
StructuralContainer.makeInheritance(Defs);


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.dialogflow.v3.model;

/**
 * Represents the result of annotation for the message.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2MessageAnnotation extends com.google.api.client.json.GenericJson {

  /**
   * Indicates whether the text message contains entities.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean containEntities;

  /**
   * The collection of annotated message parts ordered by their position in the message. You can
   * recover the annotated message by concatenating [AnnotatedMessagePart.text].
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<GoogleCloudDialogflowV2AnnotatedMessagePart> parts;

  static {
    // hack to force ProGuard to consider GoogleCloudDialogflowV2AnnotatedMessagePart used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowV2AnnotatedMessagePart.class);
  }

  /**
   * Indicates whether the text message contains entities.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getContainEntities() {
    return containEntities;
  }

  /**
   * Indicates whether the text message contains entities.
   * @param containEntities containEntities or {@code null} for none
   */
  public GoogleCloudDialogflowV2MessageAnnotation setContainEntities(java.lang.Boolean containEntities) {
    this.containEntities = containEntities;
    return this;
  }

  /**
   * The collection of annotated message parts ordered by their position in the message. You can
   * recover the annotated message by concatenating [AnnotatedMessagePart.text].
   * @return value or {@code null} for none
   */
  public java.util.List<GoogleCloudDialogflowV2AnnotatedMessagePart> getParts() {
    return parts;
  }

  /**
   * The collection of annotated message parts ordered by their position in the message. You can
   * recover the annotated message by concatenating [AnnotatedMessagePart.text].
   * @param parts parts or {@code null} for none
   */
  public GoogleCloudDialogflowV2MessageAnnotation setParts(java.util.List<GoogleCloudDialogflowV2AnnotatedMessagePart> parts) {
    this.parts = parts;
    return this;
  }

  @Override
  public GoogleCloudDialogflowV2MessageAnnotation set(String fieldName, Object value) {
    return (GoogleCloudDialogflowV2MessageAnnotation) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDialogflowV2MessageAnnotation clone() {
    return (GoogleCloudDialogflowV2MessageAnnotation) super.clone();
  }

}


text:
var utils = require("./utils");

function EmitterEvent(source, type, data){
    "use strict";
    this.source = source;
    this.type = type;
    this.data = data;
    this._propagate = true;
    this._default = true;
}

EmitterEvent.prototype = {
    constructor: EmitterEvent,
    isDefaultPrevented: function () {
        "use strict";
        return !this._default;
    },
    isPropagationStopped: function () {
        "use strict";
        return !this._propagate;
    },
    preventDefault: function () {
        "use strict";
        this._default = false;
    },
    stopPropagation: function () {
        "use strict";
        this._propagate = false;
    }
}

var Emitter = {
    on: function(name, callback){
        "use strict";
        var callbacks = this.$handlers;
        if(!callbacks){
            callbacks = this.$handlers = {};
        }
        if(!(name in callbacks)){
            callbacks[name] = [];
        }
        callbacks[name].push(callback);
        return this;
    },
    off: function(name, callback){
        "use strict";
        var argc = arguments.length, listeners = this.$handlers;
        if(!listeners || (name && !(name in listeners))){
            return;
        }
        if(argc === 0){
            this.$handlers = {};
        }else if(argc === 1){
            delete listeners[name];
        }else{
            var ls = this.$handlers[name];
            utils.remove(listeners[name], callback);
        }
        return this;
    },
    trigger: function(name, data, options){
        "use strict";
        options = options || {bubble: false};
        var event = new EmitterEvent(this, name, data),
            component = this,
            defaultHandler = options.defaultHandler;
        while(component && component.$callHandlers){
            component.$callHandlers(event);
            if(!options.bubble || event.isPropagationStopped()){
                break;
            }
            component = component.getParent ? component.getParent() : null;
        }
        if(defaultHandler && !event.isDefaultPrevented()){
            defaultHandler(event);
        }
        return event;
    },
    $callHandlers: function(event){
        "use strict";
        var listeners = this.$handlers,
            name = event.type,
            owner = this.getParent ? this.getParent(): null;
        if(listeners && (name in listeners)){
            var i, items = listeners[name];
            for(i=0;i<items.length;i++){
                items[i].call(owner, event);
            }
        }
    },
    listenTo: function(obj, name, callback){
        "use strict";
        var listeners = this.$monitors, self = this;
        if(utils.isString(callback)){
            callback = this[callback];
        }
        function callbackWrapper(){
            return callback.apply(self, arguments);
        }
        callbackWrapper.originalFunc = callback;
        if(!listeners){
            listeners = this.$monitors = [];
        }
        obj.on(name, callbackWrapper);
        listeners.push([obj, name, callbackWrapper]);
        return this;
    },
    stopListening: function(){
        "use strict";
        var listeners = this.$monitors, i = 0, item;
        if(listeners){
            for(i=0; i< listeners.length; i++){
                item = listeners[i];
                item[0].off(item[1], item[2]);
            }
            delete this.$monitors;
        }
        return this;
    }
};

module.exports = {
    Emitter: Emitter,
    enhance: function(target){
        "use strict";
        utils.assign(target, Emitter);
    }
};


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserNumber extends Model
{
	/**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'aircall_number_id',
    	'aircall_user_id',
    ];
}


text:
title: "Google Chrome Prank Extension"
layout: "post"
permalink: "/2014/12/chrome-extension-prank.html"
uuid: "7364057370260415509"
guid: "tag:blogger.com,1999:blog-2609351362218351940.post-7364057370260415509"
date: "2014-12-16 22:41:00"
description:
blogger:
    siteid: "2609351362218351940"
    postid: "7364057370260415509"
    comments: "0"
categories:
author:
    name: "Mary Briskin"
    url: "https://plus.google.com/107701473444340691919?rel=author"
    image: "//lh3.googleusercontent.com/-a5cam6dPXIY/AAAAAAAAAAI/AAAAAAAAAd4/1vBYBu0Sn2E/s512-c/photo.jpg"
---

  Next Cyber Monday will be a blast.

  Confused Shopper is a Chrome extension that changes all of the prices on your page to appear to be between $0.01 and $0.99. Secretly upload it to a friend's computer and enjoy their reaction when they discover the great new deals of the day.

  This was my first Chrome Extension so to get started, I read through Google's tutorial.

  To capture all of the prices on the page I used a regular expression, to access and change them I used Javascript's String replace() method and innerHTML method.

{% highlight javascript %}

function activate() {
  // captures all of the prices on the page
  var prices = /[$](\.|\,|\d+)+/g;
  //replaces them with randomly generated prices
  document.body.innerHTML = document.body.innerHTML.replace(prices, randomPrice);
}

{% endhighlight %}

  Lessons Learned:

Calling the Javascript String replace() method with a function

Regular Expressions for a repeating patterns

Basic setup of a Chrome extension

  Issues:

Something like '$5 billion' would turn into something like '$0.45 billion', which looks silly.

Since prices are randomly generated, if a page displays the price of a single item twice the two values will likely be different.

  Fixes/additional features to add:

Include conditions for the words 'billion, million, hundred' etc. and change accordingly.

Keep equal prices equal (i.e. $10 and $10 will equal $0.22 and $0.22).

Let users choose the range of prices they want to display.

Add functionality for turning the extension off

Including a safeguard to keep people from actually buying anything when they are unaware of the real price.

  Get the Confused Shopper Extension HERE.


text:
package io.github.mzmine.gui.chartbasics.chartutils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.Arrays;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.LookupPaintScale;
import org.jfree.chart.renderer.PaintScale;
import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRendererState;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.util.Args;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.Range;
import org.jfree.data.general.DatasetUtils;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYZDataset;
import io.github.mzmine.modules.visualization.kendrickmassplot.KendrickMassPlotXYDataset;
import io.github.mzmine.modules.visualization.kendrickmassplot.KendrickMassPlotXYZDataset;

/**
 * A renderer that represents data from an {@link XYZDataset} by drawing a circle at each (x,
 */
public class XYCirclePixelSizeRenderer extends AbstractXYItemRenderer
    implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
  /**
   *
   */
  private static final long serialVersionUID = 1L;

  /**
   * The circle width (defaults to 1.0).
   */
  private double circleWidth = 1.0;

  /**
   * The circle height (defaults to 1.0).
   */
  private double circleHeight = 1.0;

  /**
   * The anchor point used to align each circle to its (x, y) location. The default value is
   * {@code RectangleAnchor.CENTER}.
   */
  private RectangleAnchor circleAnchor = RectangleAnchor.CENTER;

  /** Temporary storage for the x-offset used to align the circle anchor. */
  private double xOffset;

  /** Temporary storage for the y-offset used to align the circle anchor. */
  private double yOffset;

  /** The paint scale. */
  private PaintScale paintScale;

  /**
   * Creates a new {@code XYCircleRenderer} instance with default attributes.
   */
  public XYCirclePixelSizeRenderer() {
    updateOffsets();
    this.paintScale = new LookupPaintScale();
  }

  /**
   * Returns the circle width, in data/axis units.
   *
   * @return The circle width.
   *
   * @see #setCircleWidth(double)
   */
  public double getCircleWidth() {
    return this.circleWidth;
  }

  /**
   * Sets the width of the circles used to represent each data item and sends a
   * {@link RendererChangeEvent} to all registered listeners.
   *
   * @param width the new width, in data/axis units (must be > 0.0).
   *
   * @see #getCircleWidth()
   */
  public void setCircleWidth(double width) {
    if (width <= 0.0) {
      throw new IllegalArgumentException("The 'width' argument must be > 0.0");
    }
    this.circleWidth = width;
    updateOffsets();
    fireChangeEvent();
  }

  /**
   * Returns the circle height, in data/axis units.
   *
   * @return The circle height.
   *
   * @see #setCircleHeight(double)
   */
  public double getCircleHeight() {
    return this.circleHeight;
  }

  /**
   * Sets the height of the circles used to represent each data item and sends a
   * {@link RendererChangeEvent} to all registered listeners.
   *
   * @param height the new height, in data/axis units (must be > 0.0).
   *
   * @see #getCircleHeight()
   */
  public void setCircleHeight(double height) {
    if (height <= 0.0) {
      throw new IllegalArgumentException("The 'height' argument must be > 0.0");
    }
    this.circleHeight = height;
    updateOffsets();
    fireChangeEvent();
  }

  /**
   * Returns the anchor point used to align a circle at its (x, y) location. The default values is
   * {@link RectangleAnchor#CENTER}.
   *
   * @return The anchor point (never {@code null}).
   *
   * @see #setCircleAnchor(RectangleAnchor)
   */
  public RectangleAnchor getCircleAnchor() {
    return this.circleAnchor;
  }

  /**
   * Sets the anchor point used to align a circle at its (x, y) location and sends a
   * {@link RendererChangeEvent} to all registered listeners.
   *
   * @param anchor the anchor.
   *
   * @see #getCircleAnchor()
   */
  public void setCircleAnchor(RectangleAnchor anchor) {
    Args.nullNotPermitted(anchor, "anchor");
    if (this.circleAnchor.equals(anchor)) {
      return; // no change
    }
    this.circleAnchor = anchor;
    updateOffsets();
    fireChangeEvent();
  }

  /**
   * Returns the paint scale used by the renderer.
   *
   * @return The paint scale (never {@code null}).
   *
   * @see #setPaintScale(PaintScale)
   * @since 1.0.4
   */
  public PaintScale getPaintScale() {
    return this.paintScale;
  }

  /**
   * Sets the paint scale used by the renderer and sends a {@link RendererChangeEvent} to all
   * registered listeners.
   *
   * @param scale the scale ({@code null} not permitted).
   *
   * @see #getPaintScale()
   * @since 1.0.4
   */
  public void setPaintScale(PaintScale scale) {
    Args.nullNotPermitted(scale, "scale");
    this.paintScale = scale;
    fireChangeEvent();
  }

  /**
   * Updates the offsets to take into account the circle width, height and anchor.
   */
  private void updateOffsets() {
    if (this.circleAnchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
      this.xOffset = 0.0;
      this.yOffset = 0.0;
    } else if (this.circleAnchor.equals(RectangleAnchor.BOTTOM)) {
      this.xOffset = -this.circleWidth / 2.0;
      this.yOffset = 0.0;
    } else if (this.circleAnchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
      this.xOffset = -this.circleWidth;
      this.yOffset = 0.0;
    } else if (this.circleAnchor.equals(RectangleAnchor.LEFT)) {
      this.xOffset = 0.0;
      this.yOffset = -this.circleHeight / 2.0;
    } else if (this.circleAnchor.equals(RectangleAnchor.CENTER)) {
      this.xOffset = -this.circleWidth / 2.0;
      this.yOffset = -this.circleHeight / 2.0;
    } else if (this.circleAnchor.equals(RectangleAnchor.RIGHT)) {
      this.xOffset = -this.circleWidth;
      this.yOffset = -this.circleHeight / 2.0;
    } else if (this.circleAnchor.equals(RectangleAnchor.TOP_LEFT)) {
      this.xOffset = 0.0;
      this.yOffset = -this.circleHeight;
    } else if (this.circleAnchor.equals(RectangleAnchor.TOP)) {
      this.xOffset = -this.circleWidth / 2.0;
      this.yOffset = -this.circleHeight;
    } else if (this.circleAnchor.equals(RectangleAnchor.TOP_RIGHT)) {
      this.xOffset = -this.circleWidth;
      this.yOffset = -this.circleHeight;
    }
  }

  /**
   * Returns the lower and upper bounds (range) of the x-values in the specified dataset.
   *
   * @param dataset the dataset ({@code null} permitted).
   *
   * @return The range ({@code null} if the dataset is {@code null} or empty).
   *
   * @see #findRangeBounds(XYDataset)
   */
  @Override
  public Range findDomainBounds(XYDataset dataset) {
    if (dataset == null) {
      return null;
    }
    Range r = DatasetUtils.findDomainBounds(dataset, false);
    if (r == null) {
      return null;
    }
    return new Range(r.getLowerBound() + this.xOffset,
        r.getUpperBound() + this.circleWidth + this.xOffset);
  }

  /**
   * Returns the range of values the renderer requires to display all the items from the specified
   * dataset.
   *
   * @param dataset the dataset ({@code null} permitted).
   *
   * @return The range ({@code null} if the dataset is {@code null} or empty).
   *
   * @see #findDomainBounds(XYDataset)
   */
  @Override
  public Range findRangeBounds(XYDataset dataset) {
    if (dataset != null) {
      Range r = DatasetUtils.findRangeBounds(dataset, false);
      if (r == null) {
        return null;
      } else {
        return new Range(r.getLowerBound() + this.yOffset,
            r.getUpperBound() + this.circleHeight + this.yOffset);
      }
    } else {
      return null;
    }
  }

  /**
   * Draws the circle representing the specified item.
   *
   * @param g2 the graphics device.
   * @param state the state.
   * @param dataArea the data area.
   * @param info the plot rendering info.
   * @param plot the plot.
   * @param domainAxis the x-axis.
   * @param rangeAxis the y-axis.
   * @param dataset the dataset.
   * @param series the series index.
   * @param item the item index.
   * @param crosshairState the crosshair state.
   * @param pass the pass index.
   */
  @Override
  public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
      PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
      XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) {

    double x = dataset.getXValue(series, item);
    double y = dataset.getYValue(series, item);
    double z = 0.0;
    double bubbleSize = 0;
    double minBubbleSize;
    double maxBubbleSize;
    Color specificDatasetColor = null;
    if (dataset instanceof KendrickMassPlotXYDataset) {
      double[] bubbleSizeValues = ((KendrickMassPlotXYDataset) dataset).getBubbleSizeValues();
      minBubbleSize = Arrays.stream(bubbleSizeValues).min().getAsDouble();
      maxBubbleSize = Arrays.stream(bubbleSizeValues).max().getAsDouble();
      bubbleSize = scaleBubbeSize(minBubbleSize, maxBubbleSize,
          ((KendrickMassPlotXYDataset) dataset).getBubbleSize(series, item));
      if (((KendrickMassPlotXYDataset) dataset).getColor() != null) {
        specificDatasetColor = ((KendrickMassPlotXYDataset) dataset).getColor();
      }
    }
    if (dataset instanceof KendrickMassPlotXYZDataset) {
      z = ((KendrickMassPlotXYZDataset) dataset).getZValue(series, item);
      double[] bubbleSizeValues = ((KendrickMassPlotXYZDataset) dataset).getBubbleSizeValues();
      minBubbleSize = Arrays.stream(bubbleSizeValues).min().getAsDouble();
      maxBubbleSize = Arrays.stream(bubbleSizeValues).max().getAsDouble();
      bubbleSize = scaleBubbeSize(minBubbleSize, maxBubbleSize,
          ((KendrickMassPlotXYZDataset) dataset).getBubbleSize(series, item));
    }

    // create new color with alpha
    Paint oldPaint = this.paintScale.getPaint(z);
    Color awtColor = (Color) oldPaint;
    Color p = new Color(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue(), 150);
    if (specificDatasetColor != null) {
      p = new Color(specificDatasetColor.getRed(), specificDatasetColor.getGreen(),
          specificDatasetColor.getBlue(), 150);
    }

    double xx0 = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()) - bubbleSize / 2;
    double yy0 = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()) - bubbleSize / 2;
    double xx1 = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()) - bubbleSize / 2;
    double yy1 = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()) - bubbleSize / 2;
    Ellipse2D circle;
    PlotOrientation orientation = plot.getOrientation();
    if (orientation.equals(PlotOrientation.HORIZONTAL)) {
      circle = new Ellipse2D.Double(Math.min(yy0, yy1), Math.min(xx0, xx1), bubbleSize, bubbleSize);
    } else {
      circle = new Ellipse2D.Double(Math.min(xx0, xx1), Math.min(yy0, yy1), bubbleSize, bubbleSize);
    }
    g2.setPaint(p);
    g2.fill(circle);
    g2.setStroke(new BasicStroke(1.0f));
    g2.draw(circle);
    if (isItemLabelVisible(series, item)) {
      drawItemLabel(g2, orientation, dataset, series, item, circle.getCenterX(),
          circle.getCenterY(), y < 0.0);
    }

    int datasetIndex = plot.indexOf(dataset);
    double transX = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge());
    double transY = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge());
    updateCrosshairValues(crosshairState, x, y, datasetIndex, transX, transY, orientation);

    EntityCollection entities = state.getEntityCollection();
    if (entities != null) {
      addEntity(entities, circle, dataset, series, item, circle.getCenterX(), circle.getCenterY());
    }

  }

  /**
   * Tests this {@code XYCircleRenderer} for equality with an arbitrary object. This method returns
   * {@code true} if and only if:
   *

   *
{@code obj} is an instance of {@code XYCircleRenderer} (not {@code null});

   *
{@code obj} has the same field values as this {@code XYCircleRenderer};

   *

   *
   * @param obj the object ({@code null} permitted).
   *
   * @return A boolean.
   */
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof XYCirclePixelSizeRenderer)) {
      return false;
    }
    XYCirclePixelSizeRenderer that = (XYCirclePixelSizeRenderer) obj;
    if (this.circleHeight != that.circleHeight) {
      return false;
    }
    if (this.circleWidth != that.circleWidth) {
      return false;
    }
    if (!this.circleAnchor.equals(that.circleAnchor)) {
      return false;
    }
    if (!this.paintScale.equals(that.paintScale)) {
      return false;
    }
    return super.equals(obj);
  }

  /**
   * Returns a clone of this renderer.
   *
   * @return A clone of this renderer.
   *
   * @throws CloneNotSupportedException if there is a problem creating the clone.
   */
  @Override
  public Object clone() throws CloneNotSupportedException {
    XYCirclePixelSizeRenderer clone = (XYCirclePixelSizeRenderer) super.clone();
    if (this.paintScale instanceof PublicCloneable) {
      PublicCloneable pc = (PublicCloneable) this.paintScale;
      clone.paintScale = (PaintScale) pc.clone();
    }
    return clone;
  }

  private double scaleBubbeSize(double min, double max, double value) {
    double maximumSize = 15;
    double minimumSize = 3;
    if (min == max) {
      return 5;
    } else {
      double a = (maximumSize - minimumSize) / (max - min);
      double b = maximumSize - a * max;
      return a * value + b;
    }
  }

}


text:
package com.liuyifeng.test.colortest;

import android.graphics.drawable.Drawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image = (ImageView) findViewById(R.id.image1);
        image.setBackgroundResource(R.color.white);

        Drawable background = image.getBackground();
        background.setAlpha(50);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace _04._10_to_N
{
    public class _10_to_N
    {
        public static void Main()
        {
            string[] arguments = Console.ReadLine().Split();

            BigInteger toBase = BigInteger.Parse(arguments[0]);
            BigInteger number = BigInteger.Parse(arguments[1]);

            string parsedNum = string.Empty;

            do
            {
                parsedNum += number % toBase;
                number /= toBase;
            }
            while (number > 0);

            char[] toBeReversed = parsedNum.ToCharArray();
            Array.Reverse(toBeReversed);
            string result = string.Join(string.Empty, toBeReversed);

            Console.WriteLine(result);
        }

    }
}


text:
package org.apache.lucene.analysis.pattern;

import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.util.BaseTokenStreamFactoryTestCase;

import java.io.Reader;
import java.io.StringReader;

/**
 * Simple tests to ensure this factory is working
 */
public class TestPatternReplaceFilterFactory extends BaseTokenStreamFactoryTestCase {

  public void testReplaceAll() throws Exception {
    Reader reader = new StringReader("aabfooaabfooabfoob ab caaaaaaaaab");
    TokenStream stream = whitespaceMockTokenizer(reader);
    stream = tokenFilterFactory("PatternReplace",
        "pattern", "a*b",
        "replacement", "-").create(stream);

    assertTokenStreamContents(stream,
        new String[] { "-foo-foo-foo-", "-", "c-" });
  }

  /** Test that bogus arguments result in exception */
  public void testBogusArguments() throws Exception {
    try {
      tokenFilterFactory("PatternReplace",
          "pattern", "something",
          "bogusArg", "bogusValue");
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(expected.getMessage().contains("Unknown parameters"));
    }
  }
}


text:
/*
 * FormPreferencias.java
 *
 * Created on 20 de abril de 2008, 06:11 PM
 */

package presentacion;

import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.NumberFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JViewport;

/**
 *
 * @author  Juan TImoteo Ponce Ortiz
 */
public class FormPreferencias extends javax.swing.JDialog implements ActionListener{
    String[] imgs;
    int diff;
    int index;
    String img;

    public static final int FACIL = 0;
    public static final int MEDIO = 1;
    public static final int DIFICIL = 2;

    /** Creates new form FormPreferencias */
    public FormPreferencias(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        init();

        btnFacil.addActionListener( this );
        btnMedio.addActionListener( this );
        btnDificil.addActionListener( this );

        btnCambiar.addActionListener( this );
    }

    public int getDiff() {
        return diff;
    }

    public String getImg() {
        return img;
    }

    public JButton getBtnAceptar() {
        return btnAceptar;
    }

    public JButton getBtnEdit() {
        return btnEdit;
    }

    public JFormattedTextField getTxtFilas() {
        return txtFilas;
    }

    public JFormattedTextField getTxtColumnas() {
        return txtColumnas;
    }

    private void init(){
        imgs = new String[ 4 ];
        for (int i = 0; i < imgs.length; i++) {
            imgs[ i ] = "img"+i;
        }
        index = 0;
        img = imgs[ index ];
        diff = 0;

        panelImg.setViewportView(  getImage( img ) );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Código Generado  ">//GEN-BEGIN:initComponents
    private void initComponents() {
        panelImg = new javax.swing.JScrollPane();
        btnAceptar = new javax.swing.JButton();
        btnFacil = new javax.swing.JButton();
        btnMedio = new javax.swing.JButton();
        btnDificil = new javax.swing.JButton();
        btnCambiar = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        txtFilas = new javax.swing.JFormattedTextField( NumberFormat.getIntegerInstance() );
        txtColumnas = new javax.swing.JFormattedTextField( NumberFormat.getIntegerInstance() );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Preferencias");

        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ops/mono-aceptar.png")));
        btnAceptar.setText("Aceptar");

        btnFacil.setBackground(new java.awt.Color(255, 255, 255));
        btnFacil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/diff/facil.png")));
        btnFacil.setText("Facil");
        btnFacil.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/diff/facil.png")));

        btnMedio.setBackground(new java.awt.Color(255, 255, 255));
        btnMedio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/diff/medio.png")));
        btnMedio.setText("Medio");
        btnMedio.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/diff/medio.png")));

        btnDificil.setBackground(new java.awt.Color(255, 255, 255));
        btnDificil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/diff/dificil.png")));
        btnDificil.setText("Dificil");
        btnDificil.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/diff/dificil.png")));

        btnCambiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ops/cambiar.png")));

        btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ops/edit.png")));
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        txtFilas.setText("0");
        txtFilas.setEnabled(false);

        txtColumnas.setText("0");
        txtColumnas.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(224, 224, 224)
                .addComponent(btnAceptar)
                .addContainerGap(292, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(btnFacil)
                .addGap(45, 45, 45)
                .addComponent(btnMedio)
                .addGap(38, 38, 38)
                .addComponent(btnDificil)
                .addGap(125, 125, 125))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelImg, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtColumnas, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(txtFilas, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btnEdit, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                        .addComponent(btnCambiar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(17, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDificil)
                    .addComponent(btnMedio)
                    .addComponent(btnFacil))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnCambiar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFilas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtColumnas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(panelImg, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addComponent(btnAceptar)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        if( !btnEdit.isSelected() ){
            txtFilas.setEnabled( true );
            txtColumnas.setEnabled( true );
            btnEdit.setSelected( true );
        }else{
            txtFilas.setEnabled( false );
            txtColumnas.setEnabled( false );
            btnEdit.setSelected( false );
        }
    }//GEN-LAST:event_btnEditActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormPreferencias(new javax.swing.JFrame(), true).setVisible(true);
            }
        });*/
        new FormPreferencias( null , true).setVisible( true );
    }

    private ImageComponent getImage(String img) {
        ImageComponent im = new ImageComponent( new ImageIcon( getClass().getResource("/images/tablero/"+img +".png")).getImage()  );
        return im;
    }

    public void actionPerformed(ActionEvent e) {
        if( e.getSource().equals( btnFacil )){
            diff = FACIL;
            btnFacil.setSelected( true );
            btnMedio.setSelected( false );
            btnDificil.setSelected( false );
            return;
        }
        if( e.getSource().equals( btnMedio )){
            diff = MEDIO;
            btnFacil.setSelected( false );
            btnMedio.setSelected( true );
            btnDificil.setSelected( false );
            return;
        }
        if( e.getSource().equals( btnDificil )){
            btnFacil.setSelected( false );
            btnMedio.setSelected( false );
            btnDificil.setSelected( true );
            diff = DIFICIL;
            return;
        }

        if( e.getSource().equals( btnCambiar ) ){
            index = index % 3 +1;
            img = imgs[ index ];
            panelImg.setViewportView(  getImage( img ) );
            return;
        }
    }

    // Declaración de varibales -no modificar//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCambiar;
    private javax.swing.JButton btnDificil;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnFacil;
    private javax.swing.JButton btnMedio;
    private javax.swing.JScrollPane panelImg;
    private javax.swing.JFormattedTextField txtColumnas;
    private javax.swing.JFormattedTextField txtFilas;
    // Fin de declaración de variables//GEN-END:variables

}


text:
namespace NServiceBus.AcceptanceTests.Encryption
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;
    using AcceptanceTesting;
    using EndpointTemplates;
    using NUnit.Framework;

    public class When_using_Rijndael_with_custom : NServiceBusAcceptanceTest
    {
        [Test]
        public async Task Should_receive_decrypted_message()
        {
            var context = await Scenario.Define<Context>()
                .WithEndpoint<Endpoint>(b => b.When(session => session.SendLocal(new MessageWithSecretData
                {
                    Secret = "betcha can't guess my secret",
                    SubProperty = new MySecretSubProperty
                    {
                        Secret = "My sub secret"
                    },
                    CreditCards = new List<CreditCardDetails>
                    {
                        new CreditCardDetails
                        {
                            ValidTo = DateTime.UtcNow.AddYears(1),
                            Number = "312312312312312"
                        },
                        new CreditCardDetails
                        {
                            ValidTo = DateTime.UtcNow.AddYears(2),
                            Number = "543645546546456"
                        }
                    }
                })))
                .Done(c => c.GetTheMessage)
                .Run();

            Assert.AreEqual("betcha can't guess my secret", context.Secret);
            Assert.AreEqual("My sub secret", context.SubPropertySecret);
            CollectionAssert.AreEquivalent(new List<string>
            {
                "312312312312312",
                "543645546546456"
            }, context.CreditCards);
        }

        public class Context : ScenarioContext
        {
            public bool GetTheMessage { get; set; }

            public string Secret { get; set; }

            public string SubPropertySecret { get; set; }

            public List<string> CreditCards { get; set; }
        }

        public class Endpoint : EndpointConfigurationBuilder
        {
            public Endpoint()
            {
                var keys = new Dictionary<string, byte[]>
                {
                    {"1st", Encoding.ASCII.GetBytes("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6")}
                };

                EndpointSetup<DefaultServer>(builder => builder.RijndaelEncryptionService("1st", keys));
            }

            public class Handler : IHandleMessages<MessageWithSecretData>
            {
                public Context Context { get; set; }

                public Task Handle(MessageWithSecretData message, IMessageHandlerContext context)
                {
                    Context.Secret = message.Secret.Value;

                    Context.SubPropertySecret = message.SubProperty.Secret.Value;

                    Context.CreditCards = new List<string>
                    {
                        message.CreditCards[0].Number.Value,
                        message.CreditCards[1].Number.Value
                    };

                    Context.GetTheMessage = true;

                    return Task.FromResult(0);
                }
            }
        }

        [Serializable]
        public class MessageWithSecretData : IMessage
        {
            public WireEncryptedString Secret { get; set; }
            public MySecretSubProperty SubProperty { get; set; }
            public List<CreditCardDetails> CreditCards { get; set; }
        }

        [Serializable]
        public class CreditCardDetails
        {
            public DateTime ValidTo { get; set; }
            public WireEncryptedString Number { get; set; }
        }

        [Serializable]
        public class MySecretSubProperty
        {
            public WireEncryptedString Secret { get; set; }
        }
    }
}


text:
extern crate reddish_lib;

use reddish_lib::enumlinkedlist::EnumLinkedList::{Node, Nil};

fn main() {
    let list = Node(1, box Node(2, box Node(3, box Nil)));

    match list {
        Node(first_value, _) => println!("First value {}", first_value),
        Nil => println!("Nil value")
    }

    match list {
        Node(first_value, box ref second_node) => {
            match second_node {
                &Node(second_value, _) => println!("First value {0}, Second value {1}", first_value, second_value),
                &Nil => println!("Nil value")
            }
        }
        _ => println!("Can't match")
    }

    let dsec = match list {
        Node(_, box ref second_node) => {
            match second_node {
                &Node(second_value, _) => Some(second_value),
                &Nil => None
            }
        },
        Nil => None
    };

    println!("Second value {0}", dsec.unwrap());
}


text:
<?php

namespace Meldon\WotRBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Description of Card
 *
 * @author Russ
 * @ORM\Entity(repositoryClass="CardRepository")
 * @ORM\Table(name="wotrnew.card")
 */
class Card {
    use MagicDetails;
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     *
     * @ORM\ManyToOne(targetEntity="CardDetails", fetch="EAGER")
     */
    private $details;
    /**
     *
     * @ORM\ManyToOne(targetEntity="CardGroup",inversedBy="cards")
     * @ORM\JoinColumn(onDelete="CASCADE")
     */
    private $group;
    /**
     * @ORM\Column(type="integer")
     * @var integer
     */
    private $position;
    /**
     * @ORM\Column(type="boolean")
     * @var boolean
     */
    private $faceup = false;
    public function __construct(CardDetails $details = NULL)
    {
        if ( $details ) $this->setDetails($details);
    }
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set position
     *
     * @param integer $position
     * @return Card
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set group
     *
     * @param \Meldon\WotRBundle\Entity\CardGroup $group
     * @return Card
     */
    public function setGroup(\Meldon\WotRBundle\Entity\CardGroup $group = null)
    {
        if ( $this->group ) {
            $this->removeGroup();
        }
        $this->group = $group;
        $group->addCard($this);
        return $this;
    }

    public function removeGroup()
    {
        $this->getGroup()->removeCard($this);
        $this->group = NULL;
    }

    /**
     * Get group
     *
     * @return \Meldon\WotRBundle\Entity\CardGroup
     */
    public function getGroup()
    {
        return $this->group;
    }

    /**
     * Set faceup
     *
     * @param boolean $faceup
     * @return Card
     */
    public function setFaceup($faceup)
    {
        $this->faceup = $faceup;

        return $this;
    }

    /**
     * Get faceup
     *
     * @return boolean
     */
    public function getFaceup()
    {
        return $this->faceup;
    }

    /**
     * Set details
     *
     * @param \Meldon\WotRBundle\Entity\CardDetails $details
     * @return Card
     */
    public function setDetails(\Meldon\WotRBundle\Entity\CardDetails $details = null)
    {
        $this->details = $details;

        return $this;
    }

    /**
     * Get details
     *
     * @return \Meldon\WotRBundle\Entity\CardDetails
     */
    public function getDetails()
    {
        return $this->details;
    }
}


text:
var event = require('../events.json');

exports.view = function(req, res){
	event["index"] = true;
	event["join"] = false;
	event["create"] = false;
	event["unjoin"] = false;
	event["cancel"] = false;
	res.render('index', event);
};

exports.join = function(req, res){
	event["index"] = false;
	event["join"] = false;
	event["create"] = false;
	event["unjoin"] = false;
	event["cancel"] = false;
	res.render('index', event);
};

exports.confirmJoin = function(req, res) {
	event["index"] = false;
	event["join"] = true;
	event["create"] = false;
	event["unjoin"] = false;
	event["cancel"] = false;
	res.render('index', event);
}

exports.confirmCreate = function(req, res) {
	event["index"] = true;
	event["join"] = false;
	event["create"] = true;
	event["unjoin"] = false;
	event["cancel"] = false;
	res.render('index', event);
}

exports.confirmUnjoin = function(req, res) {
	event["index"] = false;
	event["join"] = false;
	event["create"] = false;
	event["unjoin"] = true;
	event["cancel"] = false;
	res.render('index', event);
}

exports.confirmCancel = function(req, res) {
	event["index"] = true;
	event["join"] = false;
	event["create"] = false;
	event["unjoin"] = false;
	event["cancel"] = true;
	res.render('index', event);
}

//var Events = require('../models/event');
//
//exports.view = function(req, res){
//
//	Events
//		.find({"created": true})
//		.exec(renderEvents);
//
//	function renderEvents(err, events) {
//		res.render('index', { 'events': events });
//	}
//
//};


text:
Visualizing graph structures in matlab

We discuss some methods for visualizing graphs/ networks, including automatic
layout of the nodes.
We assume the graph is represented as an adjacency matrix.
If using BNT, you can access the DAG using

G = bnet.dag;

Matlab's biograph function

The Mathworks computational biology toolbox
has many useful graph related functions, including visualization.

Click

here
for a demo.

Cemgil's draw_graph

You can visualize an arbitrary graph (such as one learned using the
structure learning routines) with Matlab code written by

Ali Taylan Cemgil
from the University of Cambridge.
A modified version of this code
is here
(this is already bundled with BNT).
Just type

draw_graph(G);

For example, this is the output produced on a
random QMR-like model:

Pajek

Pajek
is an excellent, free Windows program for graph layout.
Use adj2pajek2.m to convert a graph to the
Pajek file format.

Then Choose File->Network->Read from the menu.

AT&T Graphviz

graphhviz
is an
open-source graph visualization package from AT&T.
Use
graph_to_dot
to convert an adjacency matrix to
the AT&T file format (the "dot" format).
You then use dot to convert it to postscript:

graph_to_dot(G, 'filename', 'foo.dot');
dot -Tps foo.dot -o foo.ps
ghostview foo.ps &


text:
// Qt includes
#include <QApplication>
#include <QDoubleSpinBox>
#include <QLineEdit>
#include <QString>
#include <QStyle>
#include <QStyleOptionSlider>
#include <QTimer>

// CTK includes
#include "ctkDoubleSlider.h"
#include "ctkDoubleSpinBox.h"
#include "ctkSliderWidget.h"
#include "ctkTest.h"

// ----------------------------------------------------------------------------
class ctkSliderWidgetTester: public QObject
{
  Q_OBJECT
private slots:
  void testUI();

  void testSetMinimum();
  void testSetMinimum_data();

  void testSetMaximum();
  void testSetMaximum_data();

  void testDecimalsByValue();
  /// This test makes sure the number of decimals increased with Ctrl+'+' does
  /// not break the synchronization between the value of the slider and the
  /// value of the spinbox.
  void testDecimalsByShortcuts();

  /// This test makes sure a valueChanged signal is fired when moving
  /// the handle to 0 for the first time.
  void testValueChangedWithNoTracking();
};

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testUI()
{
  ctkSliderWidget slider;
  slider.setMinimum(-100.);
  slider.setMaximum(100.);
  slider.setValue(26.2110001);
  slider.setPrefix("A: ");
  slider.show();
#if (QT_VERSION >= 0x50000)
  bool result = QTest::qWaitForWindowActive(&slider);
  Q_UNUSED(result);
#else
  QTest::qWaitForWindowShown(&slider);
#endif
  QObject::connect(&slider, SIGNAL(valueChanged(double)),
                   &slider, SLOT(setValue(double)), Qt::QueuedConnection);

  //qApp->exec();
}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testSetMinimum()
{
  ctkSliderWidget slider;
  QFETCH(double, minimum);
  slider.setMinimum(minimum);

  QFETCH(double, expectedMinimum);
  QFETCH(double, expectedValue);

  QCOMPARE(slider.minimum(), expectedMinimum);
  QCOMPARE(slider.value(), expectedValue);
}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testSetMinimum_data()
{
  QTest::addColumn<double>("minimum");
  QTest::addColumn<double>("expectedMinimum");
  QTest::addColumn<double>("expectedValue");

  QTest::newRow("0. -> 0.]") << 0. << 0. << 0.;
  QTest::newRow("10.0123 -> 10.0123]") << 10.0123 << 10.0123 << 10.0123;
  QTest::newRow("-10.0123 -> -10.0123]") << -10.0123 << -10.0123 << 0.;
  QTest::newRow("200.0123 -> 200.0123]") << 200.0123 << 200.0123 << 200.0123;
}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testSetMaximum()
{
  ctkSliderWidget slider;
  QFETCH(double, maximum);
  slider.setMaximum(maximum);

  QFETCH(double, expectedMaximum);
  QFETCH(double, expectedValue);
  QCOMPARE(slider.maximum(), expectedMaximum);
  QCOMPARE(slider.value(), expectedValue);

}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testSetMaximum_data()
{
  QTest::addColumn<double>("maximum");
  QTest::addColumn<double>("expectedMaximum");
  QTest::addColumn<double>("expectedValue");

  QTest::newRow("0. -> 0.") << 0. << 0. << 0.;
  QTest::newRow("10.0123 -> 0.") << 10.0123 << 10.0123 << 0.;
  QTest::newRow("-10.0123 -> -10.0123") << -10.0123 << -10.0123 << -10.0123;
  QTest::newRow("200.0123 -> 0.") << 200.0123 << 200.0123 << 0.;
}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testDecimalsByValue()
{
  ctkSliderWidget slider;
  slider.spinBox()->setDecimalsOption(
    ctkDoubleSpinBox::DecimalsByValue | ctkDoubleSpinBox::DecimalsByShortcuts );
  slider.setValue(-12.4);

  //slider.show();
  //QTest::qWaitForWindowShown(&slider);
  //qApp->exec();
  //QSignalSpy spy(&slider, SIGNAL(decimalsChanged(int)));

  slider.setSingleStep(1.3);
  slider.setRange(-87.2949, 81.7045);
  slider.setValue(-15);

  slider.slider()->triggerAction(QAbstractSlider::SliderSingleStepSub);
  slider.setSingleStep(1.3);
}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testDecimalsByShortcuts()
{
  ctkSliderWidget slider;
  slider.spinBox()->setDecimalsOption(ctkDoubleSpinBox::DecimalsByShortcuts);
  slider.setSingleStep(1.299995422363281);
  slider.setPageStep(1.299995422363281);
  slider.setRange(-100., 100.);
  slider.setValue( -2.145195007324205 );

  slider.show();
#if (QT_VERSION >= 0x50000)
  bool result = QTest::qWaitForWindowActive(&slider);
  Q_UNUSED(result);
#else
  QTest::qWaitForWindowShown(&slider);
#endif
  //qApp->exec();
  //QSignalSpy spy(&slider, SIGNAL(decimalsChanged(int)));

  slider.slider()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
  slider.slider()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
  slider.slider()->triggerAction(QAbstractSlider::SliderSingleStepAdd);

  QTest::keyClick(slider.spinBox(), Qt::Key_Plus, Qt::ControlModifier);
  QTest::keyClick(slider.spinBox(), Qt::Key_Plus, Qt::ControlModifier);
  QTest::keyClick(slider.spinBox(), Qt::Key_Plus, Qt::ControlModifier);
  QCOMPARE(slider.decimals(), 5);
}

// ----------------------------------------------------------------------------
void ctkSliderWidgetTester::testValueChangedWithNoTracking()
{
  ctkSliderWidget slider;
  slider.setValue((slider.maximum() + slider.minimum()) / 2);

  slider.show();
#if (QT_VERSION >= 0x50000)
  bool result = QTest::qWaitForWindowActive(&slider);
  Q_UNUSED(result);
#else
  QTest::qWaitForWindowShown(&slider);
#endif

  slider.setTracking(false);
  QSignalSpy spy(&slider, SIGNAL(valueChanged(double)));

  QPoint currentPoint = slider.slider()->rect().center();
  QPoint nextPoint = QPoint(slider.slider()->rect().left(), currentPoint.y());

  QTest::mousePress(slider.slider()->slider(), Qt::LeftButton, 0, currentPoint);
  ctkTest::mouseMove(slider.slider()->slider(), Qt::LeftButton, 0, nextPoint);
  QTest::mouseRelease(slider.slider()->slider(), Qt::LeftButton, 0, nextPoint);

  QCOMPARE(spy.count(), 1);
}

// ----------------------------------------------------------------------------
CTK_TEST_MAIN(ctkSliderWidgetTest)
#include "moc_ctkSliderWidgetTest.cpp"


text:
/********************************************************
 * linkedlist.h - generic linked list by Bastiaan Olij 2016
 *
 * Public domain, use as you say fit, disect, change,
 * or otherwise, all at your own risk
 *
 * This library is given as a single file implementation.
 * Include this in any file that requires it but in one
 * file, and one file only, proceed it with:
 * #define LINKEDLIST_IMPLEMENTATION
 *
 * Revision history:
 * 0.1  15-01-2016  First version with basic functions
 *
 ********************************************************/

#ifndef linkedlisth
#define linkedlisth

// We need bool, it seems to be define differently over platforms
#ifndef bool
typedef int bool;
#endif
#ifndef false
#define false 0
#endif
#ifndef true
#define true 1
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef void(* dataRetainFunc)(void * pData);
typedef void(* dataFreeFunc)(void * pData);

#ifdef __cplusplus
};
#endif

typedef struct llistNode {
  void *              data;           // pointer to data in our node
  struct llistNode *  prev;           // pointer to the previous entry in our linked list
  struct llistNode *  next;           // pointer to the next entry in our linked list
} llistNode;

typedef struct llist {
  llistNode *         first;          // pointer to our first entry in our linked list (NULL if empty)
  llistNode *         last;           // pointer to our last entry in our linked list (NULL if empty)
  dataRetainFunc      dataRetain;     // pointer to function that retains our data
  dataFreeFunc        dataFree;       // pointer to function that frees/releases up our data when we destruct our linked list (NULL = don't free)
  unsigned int        numEntries;     // number of entries contained in our list
} llist;

#ifdef __cplusplus
extern "C" {
#endif

llist * newLlist(dataRetainFunc pDataRetain, dataFreeFunc pDataFree);
void llistFree(llist * pList);
bool llistAddTo(llist * pList, void * pData);
bool llistRemove(llist * pList, void * pData);
bool llistMerge(llist * pList, llist * pMergeWith);
void * llistDataAtIndex(llist * pList, unsigned int pIndex);

#ifdef __cplusplus
};
#endif

#ifdef LINKEDLIST_IMPLEMENTATION

// creates a new linked list
// llist * myList = newLlist((dataRetainFunc) myRetainFunc, (dataReleaseFunc) myReleaseFunc);
llist * newLlist(dataRetainFunc pDataRetain, dataFreeFunc pDataFree) {
  llist * newList = (llist *) malloc(sizeof(llist));
  if (newList != NULL) {
    newList->first = NULL;
    newList->last = NULL;
    newList->dataRetain = pDataRetain;
    newList->dataFree = pDataFree;
    newList->numEntries = 0;
  };
  return newList;
};

// frees the memory related to our linked list. If a release function was provided all objects are released.
// llistFree(myList);
void llistFree(llist * pList) {
  llistNode * nextNode;

  if (pList == NULL) {
    return;
  };

  nextNode = pList->first;
  while (nextNode != NULL) {
    llistNode * currNode = nextNode;
    nextNode = currNode->next;

    // if we have a function to free/release up our data, then call that
    if ((currNode->data != NULL) && (pList->dataFree != NULL)) {
      pList->dataFree(currNode->data);
      currNode->data = NULL;
    };

    // now free our node
    free(currNode);
  };

  // and free our list
  free(pList);
};

// adds a node at the end of our linked list, if a retain function was provided the object is retained
// llistAddTo(myList, myObject);
bool llistAddTo(llist * pList, void * pData) {
  llistNode * newNode;

  if (pList == NULL) {
    return false;
  };

  // create our node
  newNode = (llistNode *) malloc(sizeof(llistNode));
  if (newNode == NULL) {
    return false;
  };
  newNode->data = pData;
  if ((pData != NULL) && (pList->dataRetain != NULL)) {
    // if we can retain our data we do so
    pList->dataRetain(pData);
  };
  newNode->prev = pList->last; // our last node becomes our previous node
  newNode->next = NULL; // we are the last node

  // if our first pointer is NULL, this is our first entry
  if (pList->first == NULL) {
    pList->first = newNode;
  };

  if (pList->last != NULL) {
    // our last is no longer our last, have it point to our new node
    pList->last->next = newNode;
  };
  // we are our new last node
  pList->last = newNode;

//  syslog(LOG_ALERT, "Added node: %p, prev: %p, data: %p", newNode, newNode->prev, newNode->data);

  pList->numEntries++;

  return true;
};

// removes a node from our linked list
// data is only freed if we're using a retain function
// llistRemove(myList, myObject);
bool llistRemove(llist * pList, void * pData) {
  llistNode * node;

  if (pList == NULL) {
    return false;
  };

  node = pList->first;
  while (node != NULL) {
    if (node->data == pData) {
      if (node->prev != NULL) {
        // our previous node now points to our next node
        node->prev->next = node->next;
      } else {
        // our next node becomes our first node
        pList->first = node->next;
      };

      if (node->next != NULL) {
        // our next node now points to our previous node
        node->next->prev = node->prev;
      } else {
        // our previous node becomes our last node
        pList->last = node->prev;
      };

      // and clean up
      if ((node->data != NULL) && (pList->dataRetain != NULL) && (pList->dataFree != NULL)) {
        pList->dataFree(node->data);
        node->data = NULL;
      };
      free(node);
      pList->numEntries--;
      return true;
    };

    // check our next node
    node = node->next;
  };

  return false;
};

// add the contents of one list to another list
// llistMerge(myList, myOtherList);
// llistFree(myOtherList); // this has now been added to our list, we can clean this up...
bool llistMerge(llist * pList, llist * pMergeWith) {
  if (pList == NULL) {
    return false;
  };

  if (pMergeWith != NULL) {
    llistNode * node = pMergeWith->first;

    while (node != NULL) {
      if (!llistAddTo(pList, node->data)) {
        return false;
      };

      node = node->next;
    };
  };

  return true;
};

// return our data pointer at index, returns NULL if none is found
// mystruct * object = (mystruct *) llistDataAtIndex(myList, 15);
void * llistDataAtIndex(llist * pList, unsigned int pIndex) {
  bool reverse;
  unsigned int index;
  llistNode * node;

  if (pList == NULL) {
    return NULL;
  } else if (pList->numEntries == 0) {
    // no entries!
    return NULL;
  } else if (pIndex>=pList->numEntries) {
    // index out of bounds!
    return NULL;
  };

  // if the index we're looking for is in our second half of our list, faster to work backwards
  reverse = pIndex > (pList->numEntries / 2);
  if (reverse) {
    index = pList->numEntries - 1;
    node = pList->last;
  } else {
    index = 1;
    node = pList->first;
  };

  while (node != NULL) {
    // is this the node we're looking for?
    if (index == pIndex) {
      return node;
    };

    // check the previous/next node
    if (reverse) {
      node = node->prev;
      index--;
    } else {
      node = node->next;
      index++;
    };
  };

  return NULL;
};

#endif /* LINKEDLIST_IMPLEMENTATION */

#endif /* !linkedlisth */


text:
try:
    import simplejson as json
except ImportError:
    import json

from django.db import models
from django.utils import six

import psycopg2.extras

if hasattr(psycopg2.extras, 'Json'):
    from psycopg2.extras import Json

    class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
        description = """PostgreSQL JSON field."""

        def db_type(self, connection):
            return "json"

        def get_prep_value(self, value):
            return Json(value)

        def to_python(self, value):
            if isinstance(value, dict):
                return value
            return json.loads(value)


text:
package com.breadwallet.crypto.blockchaindb.apis.bdb;

import android.support.annotation.Nullable;

import com.breadwallet.crypto.blockchaindb.apis.PagedCompletionHandler;
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
import com.breadwallet.crypto.blockchaindb.models.bdb.Block;
import com.breadwallet.crypto.utility.CompletionHandler;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.primitives.UnsignedLong;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

public class BlockApi {

    private final BdbApiClient jsonClient;
    private final ExecutorService executorService;

    public BlockApi(BdbApiClient jsonClient,
                    ExecutorService executorService) {
        this.jsonClient = jsonClient;
        this.executorService = executorService;
    }

    public void getBlocks(String id,
                          UnsignedLong beginBlockNumber,
                          UnsignedLong endBlockNumber,
                          boolean includeRaw,
                          boolean includeTx,
                          boolean includeTxRaw,
                          boolean includeTxProof,
                          @Nullable Integer maxPageSize,
                          CompletionHandler<List<Block>, QueryError> handler) {
        ImmutableListMultimap.Builder<String, String> paramsBuilder = ImmutableListMultimap.builder();
        paramsBuilder.put("blockchain_id", id);
        paramsBuilder.put("include_raw", String.valueOf(includeRaw));
        paramsBuilder.put("include_tx", String.valueOf(includeTx));
        paramsBuilder.put("include_tx_raw", String.valueOf(includeTxRaw));
        paramsBuilder.put("include_tx_proof", String.valueOf(includeTxProof));
        paramsBuilder.put("start_height", beginBlockNumber.toString());
        paramsBuilder.put("end_height", endBlockNumber.toString());
        if (null != maxPageSize) paramsBuilder.put("max_page_size", maxPageSize.toString());
        ImmutableMultimap<String, String> params = paramsBuilder.build();

        PagedCompletionHandler<List<Block>, QueryError> pagedHandler = createPagedResultsHandler(handler);
        jsonClient.sendGetForArrayWithPaging("blocks", params, Block.class, pagedHandler);
    }

    public void getBlock(String id,
                         boolean includeRaw,
                         boolean includeTx,
                         boolean includeTxRaw,
                         boolean includeTxProof,
                         CompletionHandler<Block, QueryError> handler) {
        Multimap<String, String> params = ImmutableListMultimap.of(
                "include_raw", String.valueOf(includeRaw),
                "include_tx", String.valueOf(includeTx),
                "include_tx_raw", String.valueOf(includeTxRaw),
                "include_tx_proof", String.valueOf(includeTxProof));

        jsonClient.sendGetWithId("blocks", id, params, Block.class, handler);
    }

    private void submitGetNextBlocks(String nextUrl, PagedCompletionHandler<List<Block>, QueryError> handler) {
        executorService.submit(() -> getNextBlocks(nextUrl, handler));
    }

    private void getNextBlocks(String nextUrl, PagedCompletionHandler<List<Block>, QueryError> handler) {
        jsonClient.sendGetForArrayWithPaging("blocks", nextUrl, Block.class, handler);
    }

    private PagedCompletionHandler<List<Block>, QueryError> createPagedResultsHandler(CompletionHandler<List<Block>, QueryError> handler) {
        List<Block> allResults = new ArrayList<>();
        return new PagedCompletionHandler<List<Block>, QueryError>() {
            @Override
            public void handleData(List<Block> results, String prevUrl, String nextUrl) {
                allResults.addAll(results);

                if (nextUrl != null) {
                    submitGetNextBlocks(nextUrl, this);

                } else {
                    handler.handleData(allResults);
                }
            }

            @Override
            public void handleError(QueryError error) {
                handler.handleError(error);
            }
        };
    }
}


text:
require 'spec_helper'

describe Shows::BaseDecorator do
end


text:
<#-------------Create Deployment Start------------------#>
Import-Module .\TestLibs\RDFELibs.psm1 -Force
$result = ""
$testResult = ""
$resultArr = @()
$isDeployed = DeployVMS -setupType $currentTestData.setupType -Distro $Distro -xmlConfig $xmlConfig

if ($isDeployed)
{
	try
	{
#        $allVMData = GetAllDeployementData -ResourceGroups $isDeployed
#        Set-Variable -Name allVMData -Value $allVMData -Scope Global
        $testResult = $null
		$clientVMData = $allVMData
		#region CONFIGURE VM FOR N SERIES GPU TEST
		LogMsg "Test VM details :"
		LogMsg "  RoleName : $($clientVMData.RoleName)"
		LogMsg "  Public IP : $($clientVMData.PublicIP)"
		LogMsg "  SSH Port : $($clientVMData.SSHPort)"

		#endregion

		#region Deprovision the VM.
        LogMsg "Deprovisioning $($clientVMData.RoleName)"
		$testJob = RunLinuxCmd -ip $clientVMData.PublicIP -port $clientVMData.SSHPort -username $user -password $password -command "waagent -deprovision --force" -runAsSudo
		LogMsg "Deprovisioning done."
        #endregion
        LogMsg "Shutting down VM.."

        $stopVM = Stop-AzureRmVM -Name $clientVMData.RoleName -ResourceGroupName $clientVMData.ResourceGroupName -Force -Verbose
        if ($stopVM.Status -eq "Succeeded")
        {
            LogMsg "Shutdown successful."
            #Copy the OS VHD with different name.
            $vhdSuffix = ($CurrentTestData.TestParameters.param).Trim()
            $newVHDName = "SS-AUTOBUILT-$($ARMImage.Publisher)-$($ARMImage.Offer)-$($ARMImage.Sku)-$($ARMImage.Version)-$vhdSuffix"
            $newVHDName = $newVHDName.ToUpper()
            $newVHDName = "$newVHDName.vhd"

            $newVHDNameWithTimeStamp = "$newVHDName-$(Get-Date -Format "MM-dd-yyyy")"
            $newVHDNameWithTimeStamp = $newVHDNameWithTimeStamp.ToUpper()
            $newVHDNameWithTimeStamp = "$newVHDNameWithTimeStamp.vhd"
            LogMsg "Sleeping 30 seconds..."
            Sleep -Seconds 30

            #Collect current VHD, Storage Account and Key
            LogMsg "---------------Copy #1: START----------------"
            $saInfoCollected = $false
            $retryCount = 0
            $maxRetryCount = 999
            while(!$saInfoCollected -and ($retryCount -lt $maxRetryCount))
            {
                try
                {
                    $retryCount += 1
                    LogMsg "[Attempt $retryCount/$maxRetryCount] : Getting Storage Account details ..."
                    $GetAzureRMStorageAccount = $null
                    $GetAzureRMStorageAccount = Get-AzureRmStorageAccount
                    if ($GetAzureRMStorageAccount -eq $null)
                    {
                        throw
                    }
                    $saInfoCollected = $true
                }
                catch
                {
                    LogErr "Error in fetching Storage Account info. Retrying in 10 seconds."
                    sleep -Seconds 10
                }
            }
            LogMsg "Collecting OS Disk VHD information."
            $OSDiskVHD = (Get-AzureRmVM -ResourceGroupName $clientVMData.ResourceGroupName -Name $clientVMData.RoleName).StorageProfile.OsDisk.Vhd.Uri
            $currentVHDName = $OSDiskVHD.Trim().Split("/")[($OSDiskVHD.Trim().Split("/").Count -1)]
            $testStorageAccount = $OSDiskVHD.Replace("http://","").Replace("https://","").Trim().Split(".")[0]
            $testStorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $(($GetAzureRmStorageAccount  | Where {$_.StorageAccountName -eq "$testStorageAccount"}).ResourceGroupName) -Name $testStorageAccount)[0].Value

            $targetStorageAccounts = $GetAzureRmStorageAccount.StorageAccountName | where { $_ -imatch "konkaci"}
            $destContextArr = @()
            foreach ($targetSA in $targetStorageAccounts)
            {
                #region Copy as Latest VHD
                [string]$SrcStorageAccount = $testStorageAccount
                [string]$SrcStorageBlob = $currentVHDName
                $SrcStorageAccountKey = $testStorageAccountKey
                $SrcStorageContainer = "vhds"

                [string]$DestAccountName =  $targetSA
                [string]$DestBlob = $newVHDName
                $DestAccountKey= (Get-AzureRmStorageAccountKey -ResourceGroupName $(($GetAzureRmStorageAccount  | Where {$_.StorageAccountName -eq "$targetSA"}).ResourceGroupName) -Name $targetSA)[0].Value
                $DestContainer = "vhds"

                $context = New-AzureStorageContext -StorageAccountName $srcStorageAccount -StorageAccountKey $srcStorageAccountKey
                $expireTime = Get-Date
                $expireTime = $expireTime.AddYears(1)
                $SasUrl = New-AzureStorageBlobSASToken -container $srcStorageContainer -Blob $srcStorageBlob -Permission R -ExpiryTime $expireTime -FullUri -Context $Context

                #
                # Start Replication to DogFood
                #

                $destContext = New-AzureStorageContext -StorageAccountName $destAccountName -StorageAccountKey $destAccountKey
                $destContextArr += $destContext
                $testContainer = Get-AzureStorageContainer -Name $destContainer -Context $destContext -ErrorAction Ignore
                if ($testContainer -eq $null) {
                    New-AzureStorageContainer -Name $destContainer -context $destContext
                }
                # Start the Copy
                LogMsg "Copying $SrcStorageBlob as $DestBlob from and to storage account $DestAccountName/$DestContainer"
                $out = Start-AzureStorageBlobCopy -AbsoluteUri $SasUrl  -DestContainer $destContainer -DestContext $destContext -DestBlob $destBlob -Force
            }
            #
            # Monitor replication status
            #
            $destContextArr
            $CopyingInProgress = $true
            while($CopyingInProgress)
            {
                $CopyingInProgress = $false
                $newDestContextArr = @()
                foreach ($destContext in $destContextArr)
                {
                    $status = Get-AzureStorageBlobCopyState -Container $destContainer -Blob $destBlob -Context $destContext
                    if ($status.Status -ne "Success")
                    {
                        sleep -Milliseconds 100
                        $CopyingInProgress = $true
                        $newDestContextArr += $destContext
                        LogMsg "$DestBlob : $($destContext.StorageAccountName) : Running"
                    }
                    else
                    {
                        $resultSummary +=  CreateResultSummary -testResult "Done" -metaData "$DestBlob : $($destContext.StorageAccountName)" -checkValues "PASS,FAIL,ABORTED" -testName $currentTestData.testName
                        LogMsg "$DestBlob : $($destContext.StorageAccountName) : Done"
                    }
                }
                if ($CopyingInProgress)
                {
                    LogMsg "$($newDestContextArr.Count) copy operations still in progress."
                    $destContextArr = $newDestContextArr
                    Sleep -Seconds 10
                }
            }
            LogMsg "Copy Done. Bytes Copied:$($status.BytesCopied), Total Bytes:$($status.TotalBytes)"

            LogMsg "---------------Copy #1: END----------------"
            #endregion

            $testResult = "PASS"
        }
        else
        {
            LogErr "Failed to shutdown VM."
            $testResult = "FAIL"
        }
	}
	catch
	{
		$ErrorMessage =  $_.Exception.Message
		LogMsg "EXCEPTION : $ErrorMessage"
	}
	Finally
	{
		$metaData = "GPU Verification"
		if (!$testResult)
		{
			$testResult = "Aborted"
		}
		$resultArr += $testResult
	}
}

else
{
	$testResult = "Aborted"
	$resultArr += $testResult
}

$result = GetFinalResultHeader -resultarr $resultArr

#Clean up the setup
DoTestCleanUp -result $result -testName $currentTestData.testName -deployedServices $isDeployed -ResourceGroups $isDeployed -SkipVerifyKernelLogs

#Return the result and summery to the test suite script..
return $result, $resultSummary


text:
import { defaultValue, getTimestamp } from "../Source/Cesium.js";

function pollToPromise(f, options) {
  options = defaultValue(options, defaultValue.EMPTY_OBJECT);

  const pollInterval = defaultValue(options.pollInterval, 1);
  const timeout = defaultValue(options.timeout, 5000);

  return new Promise(function (resolve, reject) {
    const startTimestamp = getTimestamp();
    const endTimestamp = startTimestamp + timeout;

    function poller() {
      let result = false;
      try {
        result = f();
      } catch (e) {
        reject(e);
        return;
      }

      if (result) {
        resolve();
      } else if (getTimestamp() > endTimestamp) {
        reject(
          new Error(`Timeout - function did not complete within ${timeout}ms`)
        );
      } else {
        setTimeout(poller, pollInterval);
      }
    }

    poller();
  });
}
export default pollToPromise;