text:
/*
 * This is not the original file distributed by the Apache Software Foundation
 * It has been modified by the Hipparchus project
 */
package org.hipparchus.stat.descriptive;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Locale;

import org.hipparchus.UnitTestUtils;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.util.FastMath;
import org.junit.Test;

/**
 * Test cases for the {@link MultivariateSummaryStatistics} class.
 */
public class MultivariateSummaryStatisticsTest {

    protected MultivariateSummaryStatistics createMultivariateSummaryStatistics(int k, boolean covarianceBiasCorrected) {
        return new MultivariateSummaryStatistics(k, covarianceBiasCorrected);
    }

    @Test
    public void testToString() {
        MultivariateSummaryStatistics stats = createMultivariateSummaryStatistics(2, true);
        stats.addValue(new double[] {1, 3});
        stats.addValue(new double[] {2, 2});
        stats.addValue(new double[] {3, 1});
        Locale d = Locale.getDefault();
        Locale.setDefault(Locale.US);
        final String suffix = System.getProperty("line.separator");
        assertEquals("MultivariateSummaryStatistics:" + suffix+
                     "n: 3" +suffix+
                     "min: 1.0, 1.0" +suffix+
                     "max: 3.0, 3.0" +suffix+
                     "mean: 2.0, 2.0" +suffix+
                     "geometric mean: 1.817..., 1.817..." +suffix+
                     "sum of squares: 14.0, 14.0" +suffix+
                     "sum of logarithms: 1.791..., 1.791..." +suffix+
                     "standard deviation: 1.0, 1.0" +suffix+
                     "covariance: Array2DRowRealMatrix{{1.0,-1.0},{-1.0,1.0}}" +suffix,
                     stats.toString().replaceAll("([0-9]+\\.[0-9][0-9][0-9])[0-9]+", "$1..."));
        Locale.setDefault(d);
    }

    @Test
    public void testDimension() {
        try {
            createMultivariateSummaryStatistics(2, true).addValue(new double[3]);
            fail("Expecting MathIllegalArgumentException");
        } catch (MathIllegalArgumentException dme) {
            // expected behavior
        }
    }

    /** test stats */
    @Test
    public void testStats() {
        MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(2, true);
        assertEquals(0, u.getN());
        u.addValue(new double[] { 1, 2 });
        u.addValue(new double[] { 2, 3 });
        u.addValue(new double[] { 2, 3 });
        u.addValue(new double[] { 3, 4 });
        assertEquals( 4, u.getN());
        assertEquals( 8, u.getSum()[0], 1.0e-10);
        assertEquals(12, u.getSum()[1], 1.0e-10);
        assertEquals(18, u.getSumSq()[0], 1.0e-10);
        assertEquals(38, u.getSumSq()[1], 1.0e-10);
        assertEquals( 1, u.getMin()[0], 1.0e-10);
        assertEquals( 2, u.getMin()[1], 1.0e-10);
        assertEquals( 3, u.getMax()[0], 1.0e-10);
        assertEquals( 4, u.getMax()[1], 1.0e-10);
        assertEquals(2.4849066497880003102, u.getSumLog()[0], 1.0e-10);
        assertEquals( 4.276666119016055311, u.getSumLog()[1], 1.0e-10);
        assertEquals( 1.8612097182041991979, u.getGeometricMean()[0], 1.0e-10);
        assertEquals( 2.9129506302439405217, u.getGeometricMean()[1], 1.0e-10);
        assertEquals( 2, u.getMean()[0], 1.0e-10);
        assertEquals( 3, u.getMean()[1], 1.0e-10);
        assertEquals(FastMath.sqrt(2.0 / 3.0), u.getStandardDeviation()[0], 1.0e-10);
        assertEquals(FastMath.sqrt(2.0 / 3.0), u.getStandardDeviation()[1], 1.0e-10);
        assertEquals(2.0 / 3.0, u.getCovariance().getEntry(0, 0), 1.0e-10);
        assertEquals(2.0 / 3.0, u.getCovariance().getEntry(0, 1), 1.0e-10);
        assertEquals(2.0 / 3.0, u.getCovariance().getEntry(1, 0), 1.0e-10);
        assertEquals(2.0 / 3.0, u.getCovariance().getEntry(1, 1), 1.0e-10);
        u.clear();
        assertEquals(0, u.getN());
    }

    @Test
    public void testN0andN1Conditions() {
        MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(1, true);
        assertTrue(Double.isNaN(u.getMean()[0]));
        assertTrue(Double.isNaN(u.getStandardDeviation()[0]));

        /* n=1 */
        u.addValue(new double[] { 1 });
        assertEquals(1.0, u.getMean()[0], 1.0e-10);
        assertEquals(1.0, u.getGeometricMean()[0], 1.0e-10);
        assertEquals(0.0, u.getStandardDeviation()[0], 1.0e-10);

        /* n=2 */
        u.addValue(new double[] { 2 });
        assertTrue(u.getStandardDeviation()[0] > 0);

    }

    @Test
    public void testNaNContracts() {
        MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(1, true);
        assertTrue(Double.isNaN(u.getMean()[0]));
        assertTrue(Double.isNaN(u.getMin()[0]));
        assertTrue(Double.isNaN(u.getStandardDeviation()[0]));
        assertTrue(Double.isNaN(u.getGeometricMean()[0]));

        u.addValue(new double[] { 1.0 });
        assertFalse(Double.isNaN(u.getMean()[0]));
        assertFalse(Double.isNaN(u.getMin()[0]));
        assertFalse(Double.isNaN(u.getStandardDeviation()[0]));
        assertFalse(Double.isNaN(u.getGeometricMean()[0]));

    }

    @Test
    public void testSerialization() {
        MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(2, true);
        // Empty test
        UnitTestUtils.checkSerializedEquality(u);
        MultivariateSummaryStatistics s = (MultivariateSummaryStatistics) UnitTestUtils.serializeAndRecover(u);
        assertEquals(u, s);

        // Add some data
        u.addValue(new double[] { 2d, 1d });
        u.addValue(new double[] { 1d, 1d });
        u.addValue(new double[] { 3d, 1d });
        u.addValue(new double[] { 4d, 1d });
        u.addValue(new double[] { 5d, 1d });

        // Test again
        UnitTestUtils.checkSerializedEquality(u);
        s = (MultivariateSummaryStatistics) UnitTestUtils.serializeAndRecover(u);
        assertEquals(u, s);

    }

    @SuppressWarnings("unlikely-arg-type")
    @Test
    public void testEqualsAndHashCode() {
        MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(2, true);
        MultivariateSummaryStatistics t = null;
        int emptyHash = u.hashCode();
        assertTrue(u.equals(u));
        assertFalse(u.equals(t));
        assertFalse(u.equals(Double.valueOf(0)));
        t = createMultivariateSummaryStatistics(2, true);
        assertTrue(t.equals(u));
        assertTrue(u.equals(t));
        assertEquals(emptyHash, t.hashCode());

        // Add some data to u
        u.addValue(new double[] { 2d, 1d });
        u.addValue(new double[] { 1d, 1d });
        u.addValue(new double[] { 3d, 1d });
        u.addValue(new double[] { 4d, 1d });
        u.addValue(new double[] { 5d, 1d });
        assertFalse(t.equals(u));
        assertFalse(u.equals(t));
        assertTrue(u.hashCode() != t.hashCode());

        //Add data in same order to t
        t.addValue(new double[] { 2d, 1d });
        t.addValue(new double[] { 1d, 1d });
        t.addValue(new double[] { 3d, 1d });
        t.addValue(new double[] { 4d, 1d });
        t.addValue(new double[] { 5d, 1d });
        assertTrue(t.equals(u));
        assertTrue(u.equals(t));
        assertEquals(u.hashCode(), t.hashCode());

        // Clear and make sure summaries are indistinguishable from empty summary
        u.clear();
        t.clear();
        assertTrue(t.equals(u));
        assertTrue(u.equals(t));
        assertEquals(emptyHash, t.hashCode());
        assertEquals(emptyHash, u.hashCode());
    }
}


text:
Register

Join Our Soccer Community

redpajama_set_name: RedPajamaGithub


text:
package pruebasJena;

import java.io.InputStream;

import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;

/**
 * Task 07: Querying ontologies (RDFs)
 * @author elozano
 *
 */
public class Task07
{
	public static String ns = "http://somewhere#";

	public static void main(String args[])
	{
		String filename = "src/pruebasJena/examplesRDF/example6.rdf";

		// Create an empty model
		OntModel model = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM);

		// Use the FileManager to find the input file
		InputStream in = FileManager.get().open(filename);

		if (in == null)
			throw new IllegalArgumentException("File: "+filename+" not found");

		// Read the RDF/XML file
		model.read(in, null);

		// ** TASK 7.1: List all individuals of "Person" **
		OntClass person = model.getOntClass(ns+"Person");
		ExtendedIterator<Individual> personIterator = model.listIndividuals(person);
		System.out.println("Individuals: ");
		while(personIterator.hasNext()){
			Individual individual = personIterator.next();
			System.out.println(individual);
		}

		// ** TASK 7.2: List all subclasses of "Person" **
		ExtendedIterator<OntClass> personIterator2 = person.listSubClasses();
		System.out.println("Subclasses: ");
		while(personIterator2.hasNext()){
			OntClass individual = personIterator2.next();
			System.out.println(individual);
		}

		// ** TASK 7.3: Make the necessary changes to get as well indirect instances and subclasses. TIP: you need some inference... **

	}
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/* Id for tracking automatic refresh of crash list.  */
var refreshCrashListId = undefined;

/**
 * Requests the list of crashes from the backend.
 */
function requestCrashes() {
  chrome.send('requestCrashList');
}

/**
 * Callback from backend with the list of crashes. Builds the UI.
 * @param {boolean} enabled Whether or not crash reporting is enabled.
 * @param {boolean} dynamicBackend Whether the crash backend is dynamic.
 * @param {array} crashes The list of crashes.
 * @param {string} version The browser version.
 * @param {string} os The OS name and version.
 */
function updateCrashList(enabled, dynamicBackend, crashes, version, os) {
  $('countBanner').textContent =
      loadTimeData.getStringF('crashCountFormat',
                              crashes.length.toLocaleString());

  var crashSection = $('crashList');

  $('enabledMode').hidden = !enabled;
  $('disabledMode').hidden = enabled;
  $('crashUploadStatus').hidden = !enabled || !dynamicBackend;

  if (!enabled)
    return;

  // Clear any previous list.
  crashSection.textContent = '';

  var productName = loadTimeData.getString('shortProductName');

  for (var i = 0; i < crashes.length; i++) {
    var crash = crashes[i];
    if (crash['local_id'] == '')
      crash['local_id'] = productName;

    var crashBlock = document.createElement('div');
    if (crash['state'] != 'uploaded')
      crashBlock.className = 'notUploaded';
    var title = document.createElement('h3');
    var uploaded = crash['state'] == 'uploaded';
    if (uploaded) {
      title.textContent = loadTimeData.getStringF('crashHeaderFormat',
                                                  crash['id'],
                                                  crash['local_id']);
    } else {
      title.textContent = loadTimeData.getStringF('crashHeaderFormatLocalOnly',
                                                  crash['local_id']);
    }
    crashBlock.appendChild(title);
    if (uploaded) {
      var date = document.createElement('p');
      date.textContent = loadTimeData.getStringF('crashTimeFormat',
                                                 crash['time']);
      crashBlock.appendChild(date);
      var linkBlock = document.createElement('p');
      var link = document.createElement('a');
      var commentLines = [
        'IMPORTANT: Your crash has already been automatically reported ' +
        'to our crash system. Please file this bug only if you can provide ' +
        'more information about it.',
        '',
        '',
        'Chrome Version: ' + version,
        'Operating System: ' + os,
        '',
        'URL (if applicable) where crash occurred:',
        '',
        'Can you reproduce this crash?',
        '',
        'What steps will reproduce this crash? (If it\'s not ' +
        'reproducible, what were you doing just before the crash?)',
        '1.', '2.', '3.',
        '',
        '****DO NOT CHANGE BELOW THIS LINE****',
        'Crash ID: crash/' + crash.id
      ];
      var params = {
        template: 'Crash Report',
        comment: commentLines.join('\n'),
        // TODO(scottmg): Use add_labels to add 'User-Submitted' rather than
        // duplicating the template's labels (the first two) once
        // https://bugs.chromium.org/p/monorail/issues/detail?id=1488 is done.
        labels: 'Restrict-View-EditIssue,Stability-Crash,User-Submitted',
      };
      var href = 'https://code.google.com/p/chromium/issues/entry';
      for (var param in params) {
        href = appendParam(href, param, params[param]);
      }
      link.href = href;
      link.target = '_blank';
      link.textContent = loadTimeData.getString('bugLinkText');
      linkBlock.appendChild(link);
      crashBlock.appendChild(linkBlock);
    } else if (crash['state'] == 'pending') {
      var pending = document.createElement('p');
      pending.textContent = loadTimeData.getStringF('crashPending',
                                                    crash['time']);
      crashBlock.appendChild(pending);
    } else if (crash['state'] == 'not_uploaded') {
      var not_uploaded = document.createElement('p');
      not_uploaded.textContent = loadTimeData.getStringF('crashNotUploaded',
                                                         crash['time']);
      crashBlock.appendChild(not_uploaded);
    }
    crashSection.appendChild(crashBlock);
  }

  $('noCrashes').hidden = crashes.length != 0;
}

/**
 * Request crashes get uploaded in the background.
 */
function requestCrashUpload() {
  // Don't need locking with this call because the system crash reporter
  // has locking built into itself.
  chrome.send('requestCrashUpload');

  // Trigger a refresh in 5 seconds.  Clear any previous requests.
  clearTimeout(refreshCrashListId);
  refreshCrashListId = setTimeout(requestCrashes, 5000);
}

document.addEventListener('DOMContentLoaded', function() {
  $('uploadCrashes').onclick = requestCrashUpload;
  requestCrashes();
});


text:
import React from 'react';
import { Link } from 'react-router';

export class NotFoundView extends React.Component {
  render () {
    return (

Aw Snap!

Something went wrong...where were you trying to go?

        <Link to='/'>Back To Home View</Link>

    );
  }
}

export default NotFoundView;


text:
import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
import HashRouter from "../HashRouter";

describe("A <HashRouter>", () => {
  it("puts history on context.router", () => {
    let history;
    const ContextChecker = (props, context) => {
      history = context.router.history;
      return null;
    };

    ContextChecker.contextTypes = {
      router: PropTypes.object.isRequired
    };

    const node = document.createElement("div");

    ReactDOM.render(
      <HashRouter>
        <ContextChecker />
      </HashRouter>,
      node
    );

    expect(typeof history).toBe("object");
  });

  it("warns when passed a history prop", () => {
    const history = {};
    const node = document.createElement("div");

    spyOn(console, "error");

    ReactDOM.render(<HashRouter history={history} />, node);

    expect(console.error).toHaveBeenCalledTimes(1);
    expect(console.error).toHaveBeenCalledWith(
      expect.stringContaining("<HashRouter> ignores the history prop")
    );
  });
});


text:
package org.nybatis.core.log.converter;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class CallerConverterForFile extends ClassicConverter {

	public String convert( ILoggingEvent event ) {
		return new StackTracer( event ).getFileName();
	}

}


text:
package org.yafra.tests;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;

import org.yafra.model.MYafraUser;
import org.yafra.server.ws.remote.MHIYafraUserRemote;
import org.yafra.server.ws.remote.YafraSessionRemote;
import org.yafra.utils.Logging;
import org.yafra.utils.WhichUser;

/**
 * Test of web services

 * @version $Id: $
 * @author Martin Weber
 * @since 1.0
 */
public final class TestClient
{
	private static Logging tstlog = null;
	private static final String dev = "stdout";
  	public Service service_ys = null;
	protected static Service service_yuser = null;
	protected static Service service_ysession = null;

	/**
	 * startup application - main entrypoint
	 */
	public static void main(String[] args)
		{
		YafraSessionRemote yafrases = null;
		MHIYafraUserRemote user = null;

		tstlog = new Logging();
		tstlog.setDebugFlag(true);
		tstlog.YafraDebug("\norg.yafra.tests - start off with getting session", dev);

		// get login name from system
		String username = null;
		WhichUser UserID = new WhichUser();
		username = UserID.getUser();
		tstlog.YafraDebug(" - username = " + username, dev);

		// get web service yafrasession
		set_ysession("http://remote.ws.server.yafra.org/", "YafraSessionRemote", "http://localhost:9000/yafraSession");
     	yafrases = service_ysession.getPort(YafraSessionRemote.class);

     	// TODO add exception handling here
		tstlog.YafraDebug(" - got remote session class", dev);
		yafrases.init();
		tstlog.YafraDebug(" - got remote session init", dev);
		tstlog.YafraDebug(" - version got from server: " + yafrases.getVersion(),dev);
		tstlog.YafraDebug(" - sessionid got from server: " + yafrases.getSessionId(),dev);
		if (yafrases.Login(username, ""))
			tstlog.YafraDebug(" - login OK", dev);
		else
			{
			tstlog.YafraDebug(" - login NOT OK - EXIT NOW", dev);
			yafrases.Logout();
			return;
			}

		tstlog.YafraDebug(" - do query 1 - Select one user object", dev);

		set_yuser("http://remote.ws.server.yafra.org/", "MHIYafraUserRemote", "http://localhost:9000/yafraUser");
		user = service_yuser.getPort(MHIYafraUserRemote.class);

		// TODO implement data binding for MYafraUser
		//MYafraUser oneuser = user.selectUserByName("Test");
	   //tstlog.YafraDebug(oneuser.toString(), dev);
	   tstlog.YafraDebug(user.getNameFromId("jd10"), dev);
		tstlog.YafraDebug("\norg.yafra.tests - logout session and exit client", dev);
		yafrases.Logout();
    	System.exit(0);
		}

	protected static void set_ysession(String qnameurl, String qnameclass, String endpoint) {
		QName SERVICE_NAME = new QName(qnameurl, qnameclass);
		QName PORT_NAME = new QName(qnameurl, qnameclass+"Port");
		service_ysession = Service.create(SERVICE_NAME);
		service_ysession.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpoint);
	}

	protected static void set_yuser(String qnameurl, String qnameclass, String endpoint) {
		QName SERVICE_NAME = new QName(qnameurl, qnameclass);
		QName PORT_NAME = new QName(qnameurl, qnameclass+"Port");
		service_yuser = Service.create(SERVICE_NAME);
		service_yuser.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpoint);
	}

}


text:
source ./proxy.sh

sed -i "s/^.*requiretty/#Defaults requiretty/" /etc/sudoers

cd /etc/yum.repos.d
wget https://public-yum.oracle.com/public-yum-el5.repo

cd /tmp
wget http://download.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -Uvh epel-release-5-4.noarch.rpm
rm -f /tmp/epel-release-5-4.noarch.rpm
# Not flexible to switch between direct Internet access and behind firewall
# --httpproxy HOST --httpport PORT
# rpm -ivh http://download.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm

echo "UseDNS no" >> /etc/ssh/sshd_config

sed -i "s/^HOSTNAME=.*/HOSTNAME=oracle.vagrantup.com/" /etc/sysconfig/network

yum -y install gcc make gcc-c++ kernel-devel-`uname -r` \
  kernel-uek-devel-`uname -r` zlib-devel openssl-devel \
  readline-devel sqlite-devel perl wget curl bzip2 dkms

yum -y update


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

<TITLE>
Class Hierarchy
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For All Packages

Package Hierarchies:
info.ganglia, info.ganglia.metric, info.ganglia.metric.type

Class Hierarchy

java.lang.Object

info.ganglia.GConnector
info.ganglia.metric.GMetric

info.ganglia.metric.type.GMetricDouble (implements info.ganglia.metric.Incrementable, info.ganglia.metric.Metricable)

info.ganglia.metric.type.GMetricFloat (implements info.ganglia.metric.Incrementable, info.ganglia.metric.Metricable)

info.ganglia.metric.type.GMetricInteger (implements info.ganglia.metric.Incrementable, info.ganglia.metric.Metricable)

info.ganglia.metric.type.GMetricString (implements info.ganglia.metric.Metricable)

info.ganglia.GMonitor

Interface Hierarchy

info.ganglia.metric.Incrementable
info.ganglia.metric.Metricable

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
[#]: collector: (lujun9972)
[#]: translator: (WangYueScream )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Introducing kids to computational thinking with Python)
[#]: via: (https://opensource.com/article/19/2/break-down-stereotypes-python)
[#]: author: (Don Watkins https://opensource.com/users/don-watkins)

Introducing kids to computational thinking with Python
======
Coding program gives low-income students the skills, confidence, and knowledge to break free from economic and societal disadvantages.

![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/idea_innovation_kid_education.png?itok=3lRp6gFa)

When the [Parkman Branch][1] of the Detroit Public Library was flooded with bored children taking up all the computers during summer break, the library saw it not as a problem, rather an opportunity. They started a coding club, the [Parkman Coders][2], led by [Qumisha Goss][3], a librarian who is leveraging the power of Python to introduce disadvantaged children to computational thinking.

When she started the Parkman Coders program about four years ago, "Q" (as she is known) didn't know much about coding. Since then, she's become a specialist in library instruction and technology and a certified Raspberry Pi instructor.

The program began by using [Scratch][4], but the students got bored with the block coding interface, which they regarded as "baby stuff." She says, "I knew we need to make a change to something that was still beginner friendly, but that would be more challenging for them to continue to hold their attention." At this point, she started teaching them Python.

Q first saw Python while playing a game with dungeons and skeleton monsters on [Code.org][5]. She began to learn Python by reading books like [Python Programming: An Introduction to Computer Science][6] and [Python for Kids][7]. She also recommends [Automate the Boring Stuff with Python][8] and [Lauren Ipsum: A Story about Computer Science and Other Improbable Things][9].

### Setting up a Raspberry Pi makerspace

Q decided to use [Raspberry Pi][10] computers to avoid the possibility that the students might be able to hack into the library system's computers, which weren't arranged in a way conducive to a makerspace anyway. The Pi's affordability, plus its flexibility and the included free software, lent more credibility to her decision.

While the coder program was the library's effort keep the peace and create a learning space that would engage the children, it quickly grew so popular that it ran out of space, computers, and adequate electrical outlets in a building built in 1921. They started with 10 Raspberry Pi computers shared among 20 children, but the library obtained funding from individuals, companies including Microsoft, the 4H, and the Detroit Public Library Foundation to get more equipment and expand the program.

Currently, about 40 children participate in each session and they have enough Raspberry Pi's for one device per child and some to give away. Many of the Parkman Coders come from low socio-economic backgrounds and don't have a computer at home, so the library provides them with donated Chromebooks.

Q says, "when kids demonstrate that they have a good understanding of how to use a Raspberry Pi or a [Microbit][11] and have been coming to programs regularly, we give them equipment to take home with them. This process is very challenging, however, because [they may not] have internet access at home [or] all the peripheral things they need like monitors, keyboards, and mice."

### Learning life skills and breaking stereotypes with Python

Q says, "I believe that the mainstays of learning computer science are learning critical thinking and problem-solving skills. My hope is that these lessons will stay with the kids as they grow and pursue futures in whatever field they choose. In addition, I'm hoping to inspire some pride in creatorship. It's a very powerful feeling to know 'I made this thing,' and once they've had these successes early, I hope they will approach new challenges with zeal."

She also says, "in learning to program, you have to learn to be hyper-vigilant about spelling and capitalization, and for some of our kids, reading is an issue. To make sure that the program is inclusive, we spell aloud during our lessons, and we encourage kids to speak up if they don't know a word or can't spell it correctly."

Q also tries to give extra attention to children who need it. She says, "if I recognize that someone has a more severe problem, we try to get them paired with a tutor at our library outside of program time, but still allow them to come to the program. We want to help them without discouraging them from participating."

Most importantly, the Parkman Coders program seeks to help every child realize that each has a unique skill set and abilities. Most of the children are African-American and half are girls. Q says, "we live in a world where we grow up with societal stigmas that frequently limit our own belief of what we can accomplish." She believes that children need a nonjudgmental space where "they can try new things, mess up, and discover."

The environment Q and the Parkman Coders program creates helps the participants break away from economic and societal disadvantages. She says that the secret sauce is to "make sure you have a welcoming space so anyone can come and that your space is forgiving and understanding. Let people come as they are, and be prepared to teach and to learn; when people feel comfortable and engaged, they want to stay."

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

via: https://opensource.com/article/19/2/break-down-stereotypes-python

作者:[Don Watkins][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/don-watkins
[b]: https://github.com/lujun9972
[1]: https://detroitpubliclibrary.org/locations/parkman
[2]: https://www.dplfound.org/single-post/2016/05/15/Parkman-Branch-Coders
[3]: https://www.linkedin.com/in/qumisha-goss-b3bb5470
[4]: https://scratch.mit.edu/
[5]: http://Code.org
[6]: https://www.amazon.com/Python-Programming-Introduction-Computer-Science/dp/1887902996
[7]: https://nostarch.com/pythonforkids
[8]: https://automatetheboringstuff.com/
[9]: https://nostarch.com/laurenipsum
[10]: https://www.raspberrypi.org/
[11]: https://microbit.org/guide/


text:
using System;
using System.IO;
using System.Text;

namespace OctoAwesome
{
    /// <summary>
    /// Standard-Implementierung des Planeten.
    /// </summary>
    public class Planet : IPlanet
    {
        /// <summary>
        /// ID des Planeten.
        /// </summary>
        public int Id { get; private set; }

        /// <summary>
        /// Referenz auf das Parent Universe
        /// </summary>
        public Guid Universe { get; private set; }

        /// <summary>
        /// Die Klimakarte des Planeten
        /// </summary>
        public IClimateMap ClimateMap { get; protected set; }

        /// <summary>
        /// Seed des Zufallsgenerators dieses Planeten.
        /// </summary>
        public int Seed { get; private set; }

        /// <summary>
        /// Die Größe des Planeten in Chunks.
        /// </summary>
        public Index3 Size { get; private set; }

        /// <summary>
        /// Gravitation des Planeten.
        /// </summary>
        public float Gravity { get; protected set; }

        /// <summary>
        /// Der Generator des Planeten.
        /// </summary>
        public IMapGenerator Generator { get; set; }

        /// <summary>
        /// Initialisierung des Planeten.
        /// </summary>
        /// <param name="id">ID des Planeten.</param>
        /// <param name="universe">ID des Universums.</param>
        /// <param name="size">Größe des Planeten in Zweierpotenzen Chunks.</param>
        /// <param name="seed">Seed des Zufallsgenerators.</param>
        public Planet(int id, Guid universe, Index3 size, int seed)
        {
            Id = id;
            Universe = universe;
            Size = new Index3(
                (int)Math.Pow(2, size.X),
                (int)Math.Pow(2, size.Y),
                (int)Math.Pow(2, size.Z));
            Seed = seed;
        }

        /// <summary>
        /// Erzeugt eine neue Instanz eines Planeten.
        /// </summary>
        public Planet()
        {

        }

        /// <summary>
        /// Serialisiert den Planeten in den angegebenen Stream.
        /// </summary>
        /// <param name="stream">Zielstream</param>
        public void Serialize(BinaryWriter writer, IDefinitionManager definitionManager)
        {
            writer.Write(Id);
            writer.Write(Seed);
            writer.Write(Gravity);
            writer.Write(Size.X);
            writer.Write(Size.Y);
            writer.Write(Size.Z);
            writer.Write(Universe.ToByteArray());
        }

        /// <summary>
        /// Deserialisiert den Planeten aus dem angegebenen Stream.
        /// </summary>
        /// <param name="stream">Quellstream</param>
        public void Deserialize(BinaryReader reader, IDefinitionManager definitionManager)
        {
            Id = reader.ReadInt32();
            Seed = reader.ReadInt32();
            Gravity = reader.ReadSingle();
            Size = new Index3(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32());
            Universe = new Guid(reader.ReadBytes(16));
            //var name = reader.ReadString();
        }
    }
}


text:
package org.ops4j.pax.exam.invoker.junit.internal;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.List;

import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.ops4j.pax.exam.ProbeInvoker;
import org.ops4j.pax.exam.TestContainerException;
import org.ops4j.pax.exam.WrappedTestContainerException;
import org.ops4j.pax.exam.util.Injector;
import org.osgi.framework.BundleContext;

/**
 * A ProbeInvoker which delegates the test method invocation to JUnit.
 *

 * By doing so, JUnit can handle {@code @Before}, {@code @After} and {@code @Rule} annotations in
 * the usual way.
 *

 * The test method to be executed is defined by an encoded instruction from
 * {@code org.ops4j.pax.exam.spi.intern.DefaultTestAddress}.
 *
 * @author Harald Wellmann
 * @since 2.3.0, August 2011
 */
public class JUnitProbeInvoker implements ProbeInvoker {

    private BundleContext ctx;
    private String clazz;
    private String method;
    private Injector injector;

    private Class<?> testClass;

    public JUnitProbeInvoker(String encodedInstruction, BundleContext bundleContext, Injector injector) {
        // parse class and method out of expression:
        String[] parts = encodedInstruction.split(";");
        clazz = parts[0];
        method = parts[1];
        ctx = bundleContext;
        this.injector = injector;
        try {
            testClass = ctx.getBundle().loadClass(clazz);
        }
        catch (ClassNotFoundException e) {
            throw new TestContainerException(e);
        }
    }

    public void call(Object... args) {
        if (!(findAndInvoke(args))) {
            throw new TestContainerException(" Test " + method + " not found in test class "
                + testClass.getName());
        }
    }

    private boolean findAndInvoke(Object...args) {
        Integer index = null;
        try {
            /*
             * If args are present, we expect exactly one integer argument, defining the index of
             * the parameter set for a parameterized test.
             */
            if (args.length > 0) {
                if (!(args[0] instanceof Integer)) {
                    throw new TestContainerException("Integer argument expected");
                }
                index = (Integer) args[0];
            }

            // find matching method
            for (Method m : testClass.getMethods()) {
                if (m.getName().equals(method)) {
                    // we assume its correct:
                    invokeViaJUnit(m, index);
                    return true;
                }
            }
        }
        catch (NoClassDefFoundError e) {
            throw new TestContainerException(e);
        }
        return false;
    }

    /**
     * Invokes a given method of a given test class via {@link JUnitCore} and injects dependencies
     * into the instantiated test class.
     *

     * This requires building a {@code Request} which is aware of an {@code Injector} and a
     * {@code BundleContext}.
     *
     * @param testClass
     * @param testMethod
     * @throws TestContainerException
     */
    private void invokeViaJUnit(final Method testMethod, Integer index) {
        Request classRequest = new ContainerTestRunnerClassRequest(testClass, injector, index);
        Description methodDescription = Description.createTestDescription(testClass, method);
        Request request = classRequest.filterWith(methodDescription);
        JUnitCore junit = new JUnitCore();
        Result result = junit.run(request);
        List<Failure> failures = result.getFailures();
        if (!failures.isEmpty()) {
            throw createTestContainerException(failures.toString(), failures.get(0).getException());
        }
    }

    /**
     * Creates exception for test failure and makes sure it is serializable.
     * @param message
     * @param ex
     * @return serializable exception
     */
    private TestContainerException createTestContainerException(String message, Throwable ex) {
        return isSerializable(ex)
            ? new TestContainerException(message, ex)
            : new WrappedTestContainerException(message, ex);
    }

    /**
     * Check if given exception is serializable by doing a serialization and
     * checking the exception
     *
     * @param ex exception to check
     * @return if the given exception is serializable
     */
    private boolean isSerializable(Throwable ex) {
        try {
            new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(ex);
            return true;
        }
        // CHECKSTYLE:SKIP
        catch (Throwable ex2) {
            return false;
        }
    }
}


text:
require 'rufus/verbs'

require 'json' # gem install 'json' or 'json_pure'

begin

  require 'md5'

  def md5 (s)
    MD5.md5(s).to_s
  end

rescue LoadError # ruby 1.9.x

  require 'digest/md5'

  def md5 (s)
    Digest::MD5.hexdigest(s)
  end
end

module Rufus
module RTM

  VERSION = '0.1.3'

  AUTH_ENDPOINT = "http://www.rememberthemilk.com/services/auth/"
  REST_ENDPOINT = "http://api.rememberthemilk.com/services/rest/"

  # Signs the RTM request (sets the 'api_sig' parameter).
  #
  def self.sign (params, secret) #:nodoc:

    params['api_sig'] = md5(secret + params.sort.flatten.join)

    params
  end

  # Calls an API method (milk the cow).
  #
  def self.milk (params={}) #:nodoc:

    sleep 1

    endpoint = params.delete(:endpoint)
    endpoint = AUTH_ENDPOINT if endpoint == :auth
    endpoint = endpoint || REST_ENDPOINT

    ps = params.inject({}) { |r, (k, v)| r[k.to_s] = v; r }

    ps['api_key'] = params[:api_key] || ENV['RTM_API_KEY']

    raise 'API_KEY missing from environment or parameters, cannot proceed' \
      unless ps['api_key']

    ps['frob'] = params[:frob] || ENV['RTM_FROB']
    ps.delete('frob') if ps['frob'] == nil

    ps['auth_token'] = params[:auth_token] || ENV['RTM_AUTH_TOKEN']
    ps.delete('auth_token') if ps['auth_token'] == nil

    ps['format'] = 'json'

    secret = params[:shared_secret] || ENV['RTM_SHARED_SECRET']

    sign(ps, secret)

    res = Rufus::Verbs.get(endpoint, :query => ps)

    JSON.parse(res.body)['rsp']
  end

  # Requests a timeline from RTM.
  #
  def self.get_timeline #:nodoc:

    milk(:method => 'rtm.timelines.create')['timeline']
  end

end
end


text:
package org.apache.spark.deploy.k8s.features

import scala.collection.JavaConverters._

import io.fabric8.kubernetes.api.model._

import org.apache.spark.{SecurityManager, SparkConf, SparkException}
import org.apache.spark.deploy.k8s._
import org.apache.spark.deploy.k8s.Config._
import org.apache.spark.deploy.k8s.Constants._
import org.apache.spark.deploy.k8s.submit.KubernetesClientUtils
import org.apache.spark.internal.Logging
import org.apache.spark.internal.config._
import org.apache.spark.resource.{ExecutorResourceRequest, ResourceProfile}
import org.apache.spark.rpc.RpcEndpointAddress
import org.apache.spark.scheduler.cluster.CoarseGrainedSchedulerBackend
import org.apache.spark.util.Utils

private[spark] class BasicExecutorFeatureStep(
    kubernetesConf: KubernetesExecutorConf,
    secMgr: SecurityManager,
    resourceProfile: ResourceProfile)
  extends KubernetesFeatureConfigStep with Logging {

  // Consider moving some of these fields to KubernetesConf or KubernetesExecutorSpecificConf
  private val executorContainerImage = kubernetesConf
    .get(EXECUTOR_CONTAINER_IMAGE)
    .getOrElse(throw new SparkException("Must specify the executor container image"))
  private val blockManagerPort = kubernetesConf
    .sparkConf
    .getInt(BLOCK_MANAGER_PORT.key, DEFAULT_BLOCKMANAGER_PORT)

  require(blockManagerPort == 0 || (1024 <= blockManagerPort && blockManagerPort < 65536),
    "port number must be 0 or in [1024, 65535]")

  private val executorPodNamePrefix = kubernetesConf.resourceNamePrefix

  private val driverUrl = RpcEndpointAddress(
    kubernetesConf.get(DRIVER_HOST_ADDRESS),
    kubernetesConf.sparkConf.getInt(DRIVER_PORT.key, DEFAULT_DRIVER_PORT),
    CoarseGrainedSchedulerBackend.ENDPOINT_NAME).toString

  private val isDefaultProfile = resourceProfile.id == ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID
  private val isPythonApp = kubernetesConf.get(APP_RESOURCE_TYPE) == Some(APP_RESOURCE_TYPE_PYTHON)
  private val disableConfigMap = kubernetesConf.get(KUBERNETES_EXECUTOR_DISABLE_CONFIGMAP)

  val execResources = ResourceProfile.getResourcesForClusterManager(
    resourceProfile.id,
    resourceProfile.executorResources,
    kubernetesConf.get(MEMORY_OVERHEAD_FACTOR),
    kubernetesConf.sparkConf,
    isPythonApp,
    Map.empty)

  private val executorMemoryString = s"${execResources.executorMemoryMiB}m"
  // we don't include any kubernetes conf specific requests or limits when using custom
  // ResourceProfiles because we don't have a way of overriding them if needed
  private val executorCoresRequest =
    if (isDefaultProfile && kubernetesConf.sparkConf.contains(KUBERNETES_EXECUTOR_REQUEST_CORES)) {
      kubernetesConf.get(KUBERNETES_EXECUTOR_REQUEST_CORES).get
    } else {
      execResources.cores.toString
    }
  private val executorLimitCores = kubernetesConf.get(KUBERNETES_EXECUTOR_LIMIT_CORES)

  private def buildExecutorResourcesQuantities(
      customResources: Set[ExecutorResourceRequest]): Map[String, Quantity] = {
    customResources.map { request =>
      val vendorDomain = if (request.vendor.nonEmpty) {
        request.vendor
      } else {
        throw new SparkException(s"Resource: ${request.resourceName} was requested, " +
          "but vendor was not specified.")
      }
      val quantity = new Quantity(request.amount.toString)
      (KubernetesConf.buildKubernetesResourceName(vendorDomain, request.resourceName), quantity)
    }.toMap
  }

  override def configurePod(pod: SparkPod): SparkPod = {
    val name = s"$executorPodNamePrefix-exec-${kubernetesConf.executorId}"
    val configMapName = KubernetesClientUtils.configMapNameExecutor
    val confFilesMap = KubernetesClientUtils
      .buildSparkConfDirFilesMap(configMapName, kubernetesConf.sparkConf, Map.empty)
    val keyToPaths = KubernetesClientUtils.buildKeyToPathObjects(confFilesMap)
    // According to
    // https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-label-names,
    // hostname must be no longer than `KUBERNETES_DNSNAME_MAX_LENGTH`(63) characters,
    // so take the last 63 characters of the pod name as the hostname.
    // This preserves uniqueness since the end of name contains executorId
    val hostname = name.substring(Math.max(0, name.length - KUBERNETES_DNSNAME_MAX_LENGTH))
      // Remove non-word characters from the start of the hostname
      .replaceAll("^[^\\w]+", "")
      // Replace dangerous characters in the remaining string with a safe alternative.
      .replaceAll("[^\\w-]+", "_")

    val executorMemoryQuantity = new Quantity(s"${execResources.totalMemMiB}Mi")
    val executorCpuQuantity = new Quantity(executorCoresRequest)
    val executorResourceQuantities =
      buildExecutorResourcesQuantities(execResources.customResources.values.toSet)

    val executorEnv: Seq[EnvVar] = {
        (Seq(
          (ENV_DRIVER_URL, driverUrl),
          (ENV_EXECUTOR_CORES, execResources.cores.toString),
          (ENV_EXECUTOR_MEMORY, executorMemoryString),
          (ENV_APPLICATION_ID, kubernetesConf.appId),
          // This is to set the SPARK_CONF_DIR to be /opt/spark/conf
          (ENV_SPARK_CONF_DIR, SPARK_CONF_DIR_INTERNAL),
          (ENV_EXECUTOR_ID, kubernetesConf.executorId),
          (ENV_RESOURCE_PROFILE_ID, resourceProfile.id.toString)
        ) ++ kubernetesConf.environment).map { case (k, v) =>
          new EnvVarBuilder()
            .withName(k)
            .withValue(v)
            .build()
        }
      } ++ {
        Seq(new EnvVarBuilder()
          .withName(ENV_EXECUTOR_POD_IP)
          .withValueFrom(new EnvVarSourceBuilder()
            .withNewFieldRef("v1", "status.podIP")
            .build())
          .build())
      } ++ {
        if (kubernetesConf.get(AUTH_SECRET_FILE_EXECUTOR).isEmpty) {
          Option(secMgr.getSecretKey()).map { authSecret =>
            new EnvVarBuilder()
              .withName(SecurityManager.ENV_AUTH_SECRET)
              .withValue(authSecret)
              .build()
          }
        } else None
      } ++ {
        kubernetesConf.get(EXECUTOR_CLASS_PATH).map { cp =>
          new EnvVarBuilder()
            .withName(ENV_CLASSPATH)
            .withValue(cp)
            .build()
        }
      } ++ {
        val userOpts = kubernetesConf.get(EXECUTOR_JAVA_OPTIONS).toSeq.flatMap { opts =>
          val subsOpts = Utils.substituteAppNExecIds(opts, kubernetesConf.appId,
            kubernetesConf.executorId)
          Utils.splitCommandString(subsOpts)
        }

        val sparkOpts = Utils.sparkJavaOpts(kubernetesConf.sparkConf,
          SparkConf.isExecutorStartupConf)

        (userOpts ++ sparkOpts).zipWithIndex.map { case (opt, index) =>
          new EnvVarBuilder()
            .withName(s"$ENV_JAVA_OPT_PREFIX$index")
            .withValue(opt)
            .build()
        }
      }
    executorEnv.find(_.getName == ENV_EXECUTOR_DIRS).foreach { e =>
      e.setValue(e.getValue
        .replaceAll(ENV_APPLICATION_ID, kubernetesConf.appId)
        .replaceAll(ENV_EXECUTOR_ID, kubernetesConf.executorId))
    }

    // 0 is invalid as kubernetes containerPort request, we shall leave it unmounted
    val requiredPorts = if (blockManagerPort != 0) {
      Seq(
        (BLOCK_MANAGER_PORT_NAME, blockManagerPort))
        .map { case (name, port) =>
          new ContainerPortBuilder()
            .withName(name)
            .withContainerPort(port)
            .build()
        }
    } else Nil

    if (!isDefaultProfile) {
      if (pod.container != null && pod.container.getResources() != null) {
        logDebug("NOT using the default profile and removing template resources")
        pod.container.setResources(new ResourceRequirements())
      }
    }

    val executorContainer = new ContainerBuilder(pod.container)
      .withName(Option(pod.container.getName).getOrElse(DEFAULT_EXECUTOR_CONTAINER_NAME))
      .withImage(executorContainerImage)
      .withImagePullPolicy(kubernetesConf.imagePullPolicy)
      .editOrNewResources()
        .addToRequests("memory", executorMemoryQuantity)
        .addToLimits("memory", executorMemoryQuantity)
        .addToRequests("cpu", executorCpuQuantity)
        .addToLimits(executorResourceQuantities.asJava)
        .endResources()
      .addNewEnv()
        .withName(ENV_SPARK_USER)
        .withValue(Utils.getCurrentUserName())
        .endEnv()
      .addAllToEnv(executorEnv.asJava)
      .withPorts(requiredPorts.asJava)
      .addToArgs("executor")
      .build()
    val executorContainerWithConfVolume = if (disableConfigMap) {
      executorContainer
    } else {
      new ContainerBuilder(executorContainer)
        .addNewVolumeMount()
          .withName(SPARK_CONF_VOLUME_EXEC)
          .withMountPath(SPARK_CONF_DIR_INTERNAL)
          .endVolumeMount()
        .build()
    }
    val containerWithLimitCores = if (isDefaultProfile) {
      executorLimitCores.map { limitCores =>
        val executorCpuLimitQuantity = new Quantity(limitCores)
        new ContainerBuilder(executorContainerWithConfVolume)
          .editResources()
          .addToLimits("cpu", executorCpuLimitQuantity)
          .endResources()
          .build()
      }.getOrElse(executorContainerWithConfVolume)
    } else {
      executorContainer
    }
    val containerWithLifecycle =
      if (!kubernetesConf.workerDecommissioning) {
        logInfo("Decommissioning not enabled, skipping shutdown script")
        containerWithLimitCores
      } else {
        logInfo("Adding decommission script to lifecycle")
        new ContainerBuilder(containerWithLimitCores).withNewLifecycle()
          .withNewPreStop()
            .withNewExec()
              .addToCommand(kubernetesConf.get(DECOMMISSION_SCRIPT))
            .endExec()
          .endPreStop()
          .endLifecycle()
          .build()
      }
    val ownerReference = kubernetesConf.driverPod.map { pod =>
      new OwnerReferenceBuilder()
        .withController(true)
        .withApiVersion(pod.getApiVersion)
        .withKind(pod.getKind)
        .withName(pod.getMetadata.getName)
        .withUid(pod.getMetadata.getUid)
        .build()
    }
    val executorPodBuilder = new PodBuilder(pod.pod)
      .editOrNewMetadata()
        .withName(name)
        .addToLabels(kubernetesConf.labels.asJava)
        .addToAnnotations(kubernetesConf.annotations.asJava)
        .addToOwnerReferences(ownerReference.toSeq: _*)
        .endMetadata()
      .editOrNewSpec()
        .withHostname(hostname)
        .withRestartPolicy("Never")
        .addToNodeSelector(kubernetesConf.nodeSelector.asJava)
        .addToNodeSelector(kubernetesConf.executorNodeSelector.asJava)
        .addToImagePullSecrets(kubernetesConf.imagePullSecrets: _*)
    val executorPod = if (disableConfigMap) {
      executorPodBuilder.endSpec().build()
    } else {
      executorPodBuilder
        .addNewVolume()
          .withName(SPARK_CONF_VOLUME_EXEC)
          .withNewConfigMap()
            .withItems(keyToPaths.asJava)
            .withName(configMapName)
            .endConfigMap()
          .endVolume()
        .endSpec()
      .build()
    }
    kubernetesConf.get(KUBERNETES_EXECUTOR_SCHEDULER_NAME)
      .foreach(executorPod.getSpec.setSchedulerName)

    SparkPod(executorPod, containerWithLifecycle)
  }
}


text:
#include "channelhandler.h"

#include <TelepathyQt4/TextChannel>
#include <TelepathyQt4/IncomingFileTransferChannel>
#include <TelepathyQt4/OutgoingFileTransferChannel>
#include <TelepathyQt4/Types>
#include <TelepathyQt4/Constants>
#include <TelepathyQt4/MethodInvocationContext>
#include <TelepathyQt4/ChannelDispatchOperation>
#include <TelepathyQt4/ChannelClassSpecList>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/ChannelRequest>
#include <TelepathyQt4/ChannelInterfaceSASLAuthenticationInterface>
#include <TelepathyQt4Yell/ChannelClassSpec>

ChannelHandler::ChannelHandler(QObject *parent) :
    QObject(parent),
    Tp::AbstractClientHandler(
        channelFilters(),
        channelCapabilites())
{
}

ChannelHandler::~ChannelHandler()
{
}

void ChannelHandler::handleChannels(const Tp::MethodInvocationContextPtr<> &context,
                                    const Tp::AccountPtr &account,
                                    const Tp::ConnectionPtr &connection,
                                    const QList<Tp::ChannelPtr> &channels,
                                    const QList<Tp::ChannelRequestPtr> &requestsSatisfied,
                                    const QDateTime &userActionTime,
                                    const Tp::AbstractClientHandler::HandlerInfo &handlerInfo)
{
    qDebug() << "ChannelHandler::handleChannels: "
             << " account=" << account->uniqueIdentifier()
             << " connection=" << connection.data()
             << " numChannels=" << channels.size();
             //<< " handlerInfo=" << handlerInfo;

    Q_UNUSED(connection);
    Q_UNUSED(userActionTime);
    Q_UNUSED(handlerInfo);

    foreach (Tp::ChannelPtr channel, channels) {

        qDebug() << "ChannelHandler::handleChannels: checking channel=" << channel.data();

        if (channel->channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION) {
            emit serverAuthChannelAvailable(account->uniqueIdentifier(), channel);
            continue;
        }

        Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(channel);
        if (!textChannel.isNull()) {
            // todo fix hack: stick a property to have accountId handy when we get the stream
            textChannel->setProperty("accountId", QVariant(account->uniqueIdentifier()));
            qDebug() << "ChannelHandler::handleChannels: handling text channel - becomeReady "
                     << " immutableProperties=" << textChannel->immutableProperties();
            connect(textChannel->becomeReady(Tp::Features()
                                             << Tp::TextChannel::FeatureCore
                                             << Tp::TextChannel::FeatureChatState
                                             << Tp::TextChannel::FeatureMessageCapabilities
                                             << Tp::TextChannel::FeatureMessageQueue
                                             << Tp::TextChannel::FeatureMessageSentSignal),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(onTextChannelReady(Tp::PendingOperation*)));
            //emit textChannelAvailable(account, textChannel);
            continue;
        }

        Tpy::CallChannelPtr callChannel = Tpy::CallChannelPtr::dynamicCast(channel);
        if (!callChannel.isNull()) {
            // todo fix hack: stick a property to have accountId handy when we get the stream
            callChannel->setProperty("accountId", QVariant(account->uniqueIdentifier()));
            qDebug() << "ChannelHandler::handleChannels: handling call channel - becomeReady"
                     << " immutableProperties=" << callChannel->immutableProperties();
            connect(callChannel->becomeReady(Tp::Features()
                                             << Tpy::CallChannel::FeatureCore
                                             << Tpy::CallChannel::FeatureContents),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(onCallChannelReady(Tp::PendingOperation*)));
            continue;
        }

        Tp::IncomingFileTransferChannelPtr incomingFileTransferChannel = Tp::IncomingFileTransferChannelPtr::dynamicCast(channel);
        if (!incomingFileTransferChannel.isNull()) {
            // todo fix hack: stick a property to have accountId handy when we get the stream
            incomingFileTransferChannel->setProperty("accountId", QVariant(account->uniqueIdentifier()));
            qDebug() << "ChannelHandler::handleChannels: handling incoming file transfer channel - becomeReady"
                     << " immutableProperties=" << incomingFileTransferChannel->immutableProperties();
            connect(incomingFileTransferChannel->becomeReady(Tp::Features()
                                                             << Tp::IncomingFileTransferChannel::FeatureCore),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(onIncomingFileTransferChannelReady(Tp::PendingOperation*)));
            continue;
        }

        Tp::OutgoingFileTransferChannelPtr outgoingFileTransferChannel = Tp::OutgoingFileTransferChannelPtr::dynamicCast(channel);
        if (!outgoingFileTransferChannel.isNull()) {
            // todo fix hack: stick a property to have accountId handy when we get the stream
            outgoingFileTransferChannel->setProperty("accountId", QVariant(account->uniqueIdentifier()));
            qDebug() << "ChannelHandler::handleChannels: handling outgoing file transfer channel - becomeReady"
                     << " immutableProperties=" << outgoingFileTransferChannel->immutableProperties();
            connect(outgoingFileTransferChannel->becomeReady(Tp::Features()
                                                             << Tp::OutgoingFileTransferChannel::FeatureCore),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(onOutgoingFileTransferChannelReady(Tp::PendingOperation*)));
            if (requestsSatisfied.count()) {
                mOutgoingRequests[outgoingFileTransferChannel.data()] = requestsSatisfied.first();
            }

            continue;
        }

        // reached here without handling the channel, bit weird
        qDebug() << "ChannelHandler::handleChannels: unhandled channel " << "channelType=" << channel->channelType()
                    << "objectName=" << channel->objectName() << "objectPath=" << channel->objectPath();
    }

    context->setFinished();
}

bool ChannelHandler::bypassApproval() const
{
    return false;
}

Tp::AbstractClientHandler::Capabilities ChannelHandler::channelCapabilites()
{
    Tp::AbstractClientHandler::Capabilities capabilities;

    capabilities.setGTalkP2PNATTraversalToken();
    capabilities.setICEUDPNATTraversalToken();
    capabilities.setAudioCodecToken("speex");
    capabilities.setVideoCodecToken("theora");
    capabilities.setVideoCodecToken("h264");

    return capabilities;
}

Tp::ChannelClassSpecList ChannelHandler::channelFilters()
{
    Tp::ChannelClassSpecList specList;
    specList << Tp::ChannelClassSpec::textChat();
    specList << Tp::ChannelClassSpec::textChatroom();
    specList << Tpy::ChannelClassSpec::mediaCall();
    specList << Tpy::ChannelClassSpec::audioCall();
    specList << Tpy::ChannelClassSpec::videoCall();
    specList << Tpy::ChannelClassSpec::videoCallWithAudio();
    specList << Tp::ChannelClassSpec::incomingFileTransfer();
    specList << Tp::ChannelClassSpec::outgoingFileTransfer();

    QMap<QString, QDBusVariant> filter;
    filter.insert(QString::fromLatin1(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                  QDBusVariant(QString::fromLatin1(TELEPATHY_INTERFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION)));
    filter.insert(QString::fromLatin1(TELEPATHY_INTERFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION ".AuthenticationMethod"),
                  QDBusVariant(QString::fromLatin1(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_SASL_AUTHENTICATION)));
    filter.insert(QString::fromLatin1(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                  QDBusVariant(Tp::HandleTypeNone));
    specList << Tp::ChannelClassSpec(Tp::ChannelClass(filter));

    qDebug() << "Appending filter for type" << TELEPATHY_INTERFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION;
    qDebug() << TELEPATHY_INTERFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION ".AuthenticationMethod = " << TELEPATHY_INTERFACE_CHANNEL_INTERFACE_SASL_AUTHENTICATION;
    return specList;
}

void ChannelHandler::onCallChannelReady(Tp::PendingOperation *op)
{
    qDebug() << "ChannelHandler::onCallChannelReady: channel ready";

    Tp::PendingReady *pr = qobject_cast<Tp::PendingReady*>(op);
    if (!pr || pr->isError()) {
        qDebug() << "ChannelHandler::onCallChannelReady: error "
                 << (op ? op->errorName() : "")
                 << (op ? op->errorMessage() : "");
        return;
    }

    Tpy::CallChannelPtr callChannel = Tpy::CallChannelPtr::dynamicCast(pr->object());
    if (callChannel.isNull()) {
        qDebug() << "ChannelHandler::onCallChannelReady: call channel invalid";
        return;
    }
    QString accountId = callChannel->property("accountId").toString();

    qDebug() << "ChannelHandler::onCallChannelReady: channel=" << callChannel.data();

    emit callChannelAvailable(accountId, callChannel);
}

void ChannelHandler::onTextChannelReady(Tp::PendingOperation *op)
{
    qDebug() << "ChannelHandler::onTextChannelReady: channel ready";

    Tp::PendingReady *pr = qobject_cast<Tp::PendingReady*>(op);
    if (!pr || pr->isError()) {
        qDebug() << "ChannelHandler::onTextChannelReady: error "
                 << (op ? op->errorName() : "")
                 << (op ? op->errorMessage() : "");
        return;
    }

    Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(pr->object());
    if (textChannel.isNull()) {
        qDebug() << "ChannelHandler::onTextChannelReady: stream invalid";
        return;
    }
    QString accountId = textChannel->property("accountId").toString();

    emit textChannelAvailable(accountId, textChannel);
}

void ChannelHandler::onIncomingFileTransferChannelReady(Tp::PendingOperation *op)
{
    qDebug() << "ChannelHandler::onIncomingFileTransferChannelReady: channel ready";

    Tp::PendingReady *pr = qobject_cast<Tp::PendingReady*>(op);
    if (!pr || pr->isError()) {
        qDebug() << "ChannelHandler::onFileTransferChannelReady: error "
                 << (op ? op->errorName() : "")
                 << (op ? op->errorMessage() : "");
        return;
    }

    Tp::IncomingFileTransferChannelPtr fileTransferChannel = Tp::IncomingFileTransferChannelPtr::dynamicCast(pr->object());
    if (fileTransferChannel.isNull()) {
        qDebug() << "ChannelHandler::onIncomingFileTransferChannelReady: channel invalid";
        return;
    }
    QString accountId = fileTransferChannel->property("accountId").toString();

    qDebug() << "File name:" << fileTransferChannel->fileName();

    emit incomingFileTransferChannelAvailable(accountId, fileTransferChannel);
}

void ChannelHandler::onOutgoingFileTransferChannelReady(Tp::PendingOperation *op)
{
    qDebug() << "ChannelHandler::onOutgoingFileTransferChannelReady: channel ready";

    Tp::PendingReady *pr = qobject_cast<Tp::PendingReady*>(op);
    if (!pr || pr->isError()) {
        qDebug() << "ChannelHandler::onFileTransferChannelReady: error "
                 << (op ? op->errorName() : "")
                 << (op ? op->errorMessage() : "");
        return;
    }

    Tp::OutgoingFileTransferChannelPtr fileTransferChannel = Tp::OutgoingFileTransferChannelPtr::dynamicCast(pr->object());
    if (fileTransferChannel.isNull()) {
        qDebug() << "ChannelHandler::onOutgoingFileTransferChannelReady: channel invalid";
        return;
    }

    Tp::ChannelRequestPtr request;
    if (mOutgoingRequests.contains(fileTransferChannel.data())) {
        request = mOutgoingRequests.take(fileTransferChannel.data());
    }
    QString accountId = fileTransferChannel->property("accountId").toString();
    emit outgoingFileTransferChannelAvailable(accountId, fileTransferChannel, request);
}


text:
Bumblebee
=========

Bumblebee is a .NET layer on top of the Selenium browser automation framework that allows for the standardized creation of page objects, even for dynamic web pages. There are a few features that define Bumblebee's usability.

* Standardized UI interfaces
* Modular page objects
* IntelliSense-driven automations
* Test Framework independence
* Parallelization mindfulness
* Flexibility

Like other `page object models`_, Bumblebee divides testing into two parts. The page objects model the subject of the testing, and the automation uses the page objects to tell the browser what to do.

Bumblebee standardizes the design of page objects and makes the automation scripting trivial. Develop page objects quickly by modeling which parts of the page can be interacted with. Then in the automation, use Intellisense to browse through the available options and build a script.

The basic idea behind Bumblebee is to break each page down into :doc:`blocks` and :doc:`elements`. Use the classes provided by Bumblebee to model your site into page objects that you can consume in your automation code. If page objects are well designed, writing the automation code should take no effort at all.

.. _page object models: https://github.com/SeleniumHQ/selenium/wiki/PageObjects

If you are new to Bumblebee, check out the :doc:`getting-started` page first.

.. toctree::
   :maxdepth: 2
   :hidden:
   :caption: User Documentation

   benefits
   getting-started

.. toctree::
   :maxdepth: 2
   :caption: Feature Documentation

   concepts
   blocks
   elements
   sessions
   settings
   driver-environments
   verification
   using-linq
   conveniences
   dependencies


text:
package com.linkedin.pinot.routing;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linkedin.pinot.common.response.ServerInstance;
import com.linkedin.pinot.common.utils.CommonConstants;
import com.linkedin.pinot.common.utils.EqualityUtils;
import com.linkedin.pinot.transport.common.SegmentId;
import com.linkedin.pinot.transport.common.SegmentIdSet;

/**
 * Data structure to hold a whole mapping from ServerInstances to all the queryable segments.
 *
 *
 */
public class ServerToSegmentSetMap {
  private static final ObjectMapper mapper = new ObjectMapper();
  private static final Logger logger = LoggerFactory.getLogger(ServerToSegmentSetMap.class);

  private Map<String, Set<String>> _serverToSegmentSetMap;
  private Map<ServerInstance, SegmentIdSet> _routingTable;

  public static final String NAME_PORT_DELIMITER = "_";

  public ServerToSegmentSetMap(Map<String, Set<String>> serverToSegmentSetMap) {
    _serverToSegmentSetMap = serverToSegmentSetMap;
    _routingTable = new HashMap<ServerInstance, SegmentIdSet>();
    for (Entry<String, Set<String>> entry : _serverToSegmentSetMap.entrySet()) {
      String namePortStr = entry.getKey().split(CommonConstants.Helix.PREFIX_OF_SERVER_INSTANCE)[1];
      String hostName = namePortStr.split(NAME_PORT_DELIMITER)[0];
      int port;
      try {
        port = Integer.parseInt(namePortStr.split(NAME_PORT_DELIMITER)[1]);
      } catch (Exception e) {
        port = CommonConstants.Helix.DEFAULT_SERVER_NETTY_PORT;
      }

      ServerInstance serverInstance = new ServerInstance(hostName, port);
      SegmentIdSet segmentIdSet = new SegmentIdSet();
      for (String segmentId : entry.getValue()) {
        segmentIdSet.addSegment(new SegmentId(segmentId));
      }
      _routingTable.put(serverInstance, segmentIdSet);
    }
  }

  public Set<String> getServerSet() {
    return _serverToSegmentSetMap.keySet();
  }

  public Set<String> getSegmentSet(String server) {
    return _serverToSegmentSetMap.get(server);
  }

  public Map<ServerInstance, SegmentIdSet> getRouting() {
    return _routingTable;
  }

  @Override
  public String toString() {
    try {
      JSONObject ret = new JSONObject();
      for (ServerInstance i : _routingTable.keySet()) {
        JSONArray serverInstanceSegmentList = new JSONArray();
        List<String> sortedSegmentIds = new ArrayList<>();

        for (SegmentId segmentId : _routingTable.get(i).getSegments()) {
          sortedSegmentIds.add(segmentId.getSegmentId());
        }

        Collections.sort(sortedSegmentIds);

        for (String sortedSegmentId : sortedSegmentIds) {
          serverInstanceSegmentList.put(sortedSegmentId);
        }

        ret.put(i.toString(), serverInstanceSegmentList);
      }
      return ret.toString();
    } catch (Exception e) {
      logger.error("error toString()", e);
      return "routing table : [ " + _routingTable + " ] ";
    }
  }

  @Override
  public boolean equals(Object o) {
    if (EqualityUtils.isSameReference(this, o)) {
      return true;
    }

    if (EqualityUtils.isNullOrNotSameClass(this, o)) {
      return false;
    }

    ServerToSegmentSetMap other = (ServerToSegmentSetMap) o;

    return
        EqualityUtils.isEqual(_serverToSegmentSetMap, other._serverToSegmentSetMap) &&
        EqualityUtils.isEqual(_routingTable, other._routingTable);
  }

  @Override
  public int hashCode() {
    int result = EqualityUtils.hashCodeOf(_serverToSegmentSetMap);
    result = EqualityUtils.hashCodeOf(result, _routingTable);
    return result;
  }
}


text:
readonly DEFAULT_BOXPATH="./rhel-6.8_vb-5.1.30"
echo Verifying vagrant box \"rhel-6.8_vb-5.1.30\" added...
vagrant box list | grep rhel-6.8_vb-5.1.30 >/dev/null 2>&1 || {
    echo Box not found.
    read -p "path to box file ($DEFAULT_BOXPATH): " boxpath
    boxpath=${boxpath:-$DEFAULT_BOXPATH}
    if [ -f $boxpath ]; then
        vagrant box add rhel-6.8-5.1.30 $boxpath
    else
        echo $boxpath not found
        exit 1
    fi
}

# install vagrant plugins if not installed
echo Checking vagrant plugins...
plugins=`vagrant plugin list`
echo $plugins | grep vagrant-reload >/dev/null 2>&1 || vagrant plugin install vagrant-reload
echo $plugins | grep vagrant-vbguest >/dev/null 2>&1 || vagrant plugin install vagrant-vbguest
echo $plugins | grep vagrant-triggers >/dev/null 2>&1 || vagrant plugin install vagrant-triggers

# Copy Vagrantfile.example if Vagrantfile not found
if [ ! -f Vagrantfile ]; then
    echo Copying Vagrantfile.example to Vagrantfile
    cp Vagrantfile.example Vagrantfile
    read -n1 -p "Would you like to stop this script and make changes to ./Vagrantfile? [y/n] " stop
    case $stop in
        y|Y) echo; echo "Exiting"; exit 0 ;;
    esac
    echo
fi

# get RedHat credentials from env or stdin
if [ "$RH_USER" -a "$RH_PASS" ]; then
    username=${RH_USER}
    password=${RH_PASS}
else
    echo Enter your RedHat Developer Account credentials
    read -p "username: " username
    read -s -p "password: " password
    echo
fi

# Setup system name for RHEL Subscription Management
if [ "$RHSN_SYSTEM_NAME" ]; then
  rhsn_system_name=$RHSN_SYSTEM_NAME
else
  echo "Enter a unique name to identify this system in the RedHat Subscription Management interface"
  read -p "RHSN Name: " rhsn_system_name
fi

# Choose VMs to start up.
default="default "
sentry="sentry "
elk="elk "

vms=""
echo "Choose the VMs to startup using this script (enter y to start the vm)"
read -n1 -p "Default Machine: " vm
case $vm in
    y|Y) echo; vms+=${default}
esac
read -n1 -p "Sentry Machine: " vm
case $vm in
    y|Y) echo; vms+=${sentry}
esac
read -n1 -p "ELK Machine: " vm
case $vm in
    y|Y) echo; vms+=${elk}
esac

echo ${vms}

# vagrant up with RedHat credentials as environment variables
RH_USER=${username} RH_PASSWORD=${password} RHSN_SYSTEM_NAME=${rhsn_system_name} vagrant up ${vms}