text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Dodgy Missed Phonecalls | Lee Kelleher - Umbraco Consultant</title>
	<meta name="description" content="Just noticed that I had a missed call on my mobile from 02920368792, (I didn’t even hear it ring). So I googled the number. I found out it a Spam/Cold-Caller number.
Now I’m a bit pee’d off, as yesterday I signed up for TSB’s text message alerts – coincidence or what?
">
	<meta name="keywords" content="lee,rants,spam">
	<meta name="generator" content="Wyam">
	<meta name="twitter:card" content="summary">
	<meta name="twitter:site" content="@leekelleher">
	<meta name="twitter:url" property="og:url" content="https://leekelleher.com/2007/03/20/dodgy-missed-phonecalls/">
	<meta name="twitter:title" property="og:title" content="Dodgy Missed Phonecalls">
	<meta name="twitter:description" property="og:description" content="Just noticed that I had a missed call on my mobile from 02920368792, (I didn’t even hear it ring). So I googled the number. I found out it a Spam/Cold-Caller number.
Now I’m a bit pee’d off, as yesterday I signed up for TSB’s text message alerts – coincidence or what?
">
	<meta name="twitter:image" property="og:image" content="https://leekelleher.com/assets/img/nxnw_300x300.jpg">
	<link rel="alternate" href="https://leekelleher.com/feed/" type="application/rss+xml">
	<link rel="canonical" href="https://leekelleher.com/2007/03/20/dodgy-missed-phonecalls/">
	<link rel="pingback" href="https://webmention.io/leekelleher.com/xmlrpc">
	<link rel="webmention" href="https://webmention.io/leekelleher.com/webmention">
	<link rel="stylesheet" href="/assets/css/style.css">

Lee Kelleher

About

Now

Contact

Dodgy Missed Phonecalls

				Posted on <time datetime="2007-03-20T16:54+00:00" class="dt-published">20/03/2007</time>.
				Estimated read time: under a minute (54 words)

Just noticed that I had a missed call on my mobile from 02920368792, (I didn't even hear it ring). So I googled the number. I found out it a Spam/Cold-Caller number.

Now I'm a bit pee'd off, as yesterday I signed up for TSB's text message alerts – coincidence or what?

Tags: Lee, rants, spam

Permalink: https://leekelleher.com/2007/03/20/dodgy-missed-phonecalls/

For any feedback, comments or questions, feel free to ask me via my contact page, on Twitter, or on GitHub.

Be notified of new posts, subscribe to my RSS feed.

All content by Lee Kelleher (© 2006-2021) and licensed under Creative Commons. All code snippets are licensed under the MIT license.

This website is statically generated using Wyam. All code and content for this blog is available as open source on GitHub.


text:
#ifndef _SAMR21_PORT_INSTANCE_
#define _SAMR21_PORT_INSTANCE_

/* ========== Register definition for PORT peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_PORT_DIR0              (0x41004400) /**< \brief (PORT) Data Direction 0 */
#define REG_PORT_DIRCLR0           (0x41004404) /**< \brief (PORT) Data Direction Clear 0 */
#define REG_PORT_DIRSET0           (0x41004408) /**< \brief (PORT) Data Direction Set 0 */
#define REG_PORT_DIRTGL0           (0x4100440C) /**< \brief (PORT) Data Direction Toggle 0 */
#define REG_PORT_OUT0              (0x41004410) /**< \brief (PORT) Data Output Value 0 */
#define REG_PORT_OUTCLR0           (0x41004414) /**< \brief (PORT) Data Output Value Clear 0 */
#define REG_PORT_OUTSET0           (0x41004418) /**< \brief (PORT) Data Output Value Set 0 */
#define REG_PORT_OUTTGL0           (0x4100441C) /**< \brief (PORT) Data Output Value Toggle 0 */
#define REG_PORT_IN0               (0x41004420) /**< \brief (PORT) Data Input Value 0 */
#define REG_PORT_CTRL0             (0x41004424) /**< \brief (PORT) Control 0 */
#define REG_PORT_WRCONFIG0         (0x41004428) /**< \brief (PORT) Write Configuration 0 */
#define REG_PORT_PMUX0             (0x41004430) /**< \brief (PORT) Peripheral Multiplexing 0 */
#define REG_PORT_PINCFG0           (0x41004440) /**< \brief (PORT) Pin Configuration 0 */
#define REG_PORT_DIR1              (0x41004480) /**< \brief (PORT) Data Direction 1 */
#define REG_PORT_DIRCLR1           (0x41004484) /**< \brief (PORT) Data Direction Clear 1 */
#define REG_PORT_DIRSET1           (0x41004488) /**< \brief (PORT) Data Direction Set 1 */
#define REG_PORT_DIRTGL1           (0x4100448C) /**< \brief (PORT) Data Direction Toggle 1 */
#define REG_PORT_OUT1              (0x41004490) /**< \brief (PORT) Data Output Value 1 */
#define REG_PORT_OUTCLR1           (0x41004494) /**< \brief (PORT) Data Output Value Clear 1 */
#define REG_PORT_OUTSET1           (0x41004498) /**< \brief (PORT) Data Output Value Set 1 */
#define REG_PORT_OUTTGL1           (0x4100449C) /**< \brief (PORT) Data Output Value Toggle 1 */
#define REG_PORT_IN1               (0x410044A0) /**< \brief (PORT) Data Input Value 1 */
#define REG_PORT_CTRL1             (0x410044A4) /**< \brief (PORT) Control 1 */
#define REG_PORT_WRCONFIG1         (0x410044A8) /**< \brief (PORT) Write Configuration 1 */
#define REG_PORT_PMUX1             (0x410044B0) /**< \brief (PORT) Peripheral Multiplexing 1 */
#define REG_PORT_PINCFG1           (0x410044C0) /**< \brief (PORT) Pin Configuration 1 */
#define REG_PORT_DIR2              (0x41004500) /**< \brief (PORT) Data Direction 2 */
#define REG_PORT_DIRCLR2           (0x41004504) /**< \brief (PORT) Data Direction Clear 2 */
#define REG_PORT_DIRSET2           (0x41004508) /**< \brief (PORT) Data Direction Set 2 */
#define REG_PORT_DIRTGL2           (0x4100450C) /**< \brief (PORT) Data Direction Toggle 2 */
#define REG_PORT_OUT2              (0x41004510) /**< \brief (PORT) Data Output Value 2 */
#define REG_PORT_OUTCLR2           (0x41004514) /**< \brief (PORT) Data Output Value Clear 2 */
#define REG_PORT_OUTSET2           (0x41004518) /**< \brief (PORT) Data Output Value Set 2 */
#define REG_PORT_OUTTGL2           (0x4100451C) /**< \brief (PORT) Data Output Value Toggle 2 */
#define REG_PORT_IN2               (0x41004520) /**< \brief (PORT) Data Input Value 2 */
#define REG_PORT_CTRL2             (0x41004524) /**< \brief (PORT) Control 2 */
#define REG_PORT_WRCONFIG2         (0x41004528) /**< \brief (PORT) Write Configuration 2 */
#define REG_PORT_PMUX2             (0x41004530) /**< \brief (PORT) Peripheral Multiplexing 2 */
#define REG_PORT_PINCFG2           (0x41004540) /**< \brief (PORT) Pin Configuration 2 */
#else
#define REG_PORT_DIR0              (*(RwReg  *)0x41004400UL) /**< \brief (PORT) Data Direction 0 */
#define REG_PORT_DIRCLR0           (*(RwReg  *)0x41004404UL) /**< \brief (PORT) Data Direction Clear 0 */
#define REG_PORT_DIRSET0           (*(RwReg  *)0x41004408UL) /**< \brief (PORT) Data Direction Set 0 */
#define REG_PORT_DIRTGL0           (*(RwReg  *)0x4100440CUL) /**< \brief (PORT) Data Direction Toggle 0 */
#define REG_PORT_OUT0              (*(RwReg  *)0x41004410UL) /**< \brief (PORT) Data Output Value 0 */
#define REG_PORT_OUTCLR0           (*(RwReg  *)0x41004414UL) /**< \brief (PORT) Data Output Value Clear 0 */
#define REG_PORT_OUTSET0           (*(RwReg  *)0x41004418UL) /**< \brief (PORT) Data Output Value Set 0 */
#define REG_PORT_OUTTGL0           (*(RwReg  *)0x4100441CUL) /**< \brief (PORT) Data Output Value Toggle 0 */
#define REG_PORT_IN0               (*(RoReg  *)0x41004420UL) /**< \brief (PORT) Data Input Value 0 */
#define REG_PORT_CTRL0             (*(RwReg  *)0x41004424UL) /**< \brief (PORT) Control 0 */
#define REG_PORT_WRCONFIG0         (*(WoReg  *)0x41004428UL) /**< \brief (PORT) Write Configuration 0 */
#define REG_PORT_PMUX0             (*(RwReg  *)0x41004430UL) /**< \brief (PORT) Peripheral Multiplexing 0 */
#define REG_PORT_PINCFG0           (*(RwReg  *)0x41004440UL) /**< \brief (PORT) Pin Configuration 0 */
#define REG_PORT_DIR1              (*(RwReg  *)0x41004480UL) /**< \brief (PORT) Data Direction 1 */
#define REG_PORT_DIRCLR1           (*(RwReg  *)0x41004484UL) /**< \brief (PORT) Data Direction Clear 1 */
#define REG_PORT_DIRSET1           (*(RwReg  *)0x41004488UL) /**< \brief (PORT) Data Direction Set 1 */
#define REG_PORT_DIRTGL1           (*(RwReg  *)0x4100448CUL) /**< \brief (PORT) Data Direction Toggle 1 */
#define REG_PORT_OUT1              (*(RwReg  *)0x41004490UL) /**< \brief (PORT) Data Output Value 1 */
#define REG_PORT_OUTCLR1           (*(RwReg  *)0x41004494UL) /**< \brief (PORT) Data Output Value Clear 1 */
#define REG_PORT_OUTSET1           (*(RwReg  *)0x41004498UL) /**< \brief (PORT) Data Output Value Set 1 */
#define REG_PORT_OUTTGL1           (*(RwReg  *)0x4100449CUL) /**< \brief (PORT) Data Output Value Toggle 1 */
#define REG_PORT_IN1               (*(RoReg  *)0x410044A0UL) /**< \brief (PORT) Data Input Value 1 */
#define REG_PORT_CTRL1             (*(RwReg  *)0x410044A4UL) /**< \brief (PORT) Control 1 */
#define REG_PORT_WRCONFIG1         (*(WoReg  *)0x410044A8UL) /**< \brief (PORT) Write Configuration 1 */
#define REG_PORT_PMUX1             (*(RwReg  *)0x410044B0UL) /**< \brief (PORT) Peripheral Multiplexing 1 */
#define REG_PORT_PINCFG1           (*(RwReg  *)0x410044C0UL) /**< \brief (PORT) Pin Configuration 1 */
#define REG_PORT_DIR2              (*(RwReg  *)0x41004500UL) /**< \brief (PORT) Data Direction 2 */
#define REG_PORT_DIRCLR2           (*(RwReg  *)0x41004504UL) /**< \brief (PORT) Data Direction Clear 2 */
#define REG_PORT_DIRSET2           (*(RwReg  *)0x41004508UL) /**< \brief (PORT) Data Direction Set 2 */
#define REG_PORT_DIRTGL2           (*(RwReg  *)0x4100450CUL) /**< \brief (PORT) Data Direction Toggle 2 */
#define REG_PORT_OUT2              (*(RwReg  *)0x41004510UL) /**< \brief (PORT) Data Output Value 2 */
#define REG_PORT_OUTCLR2           (*(RwReg  *)0x41004514UL) /**< \brief (PORT) Data Output Value Clear 2 */
#define REG_PORT_OUTSET2           (*(RwReg  *)0x41004518UL) /**< \brief (PORT) Data Output Value Set 2 */
#define REG_PORT_OUTTGL2           (*(RwReg  *)0x4100451CUL) /**< \brief (PORT) Data Output Value Toggle 2 */
#define REG_PORT_IN2               (*(RoReg  *)0x41004520UL) /**< \brief (PORT) Data Input Value 2 */
#define REG_PORT_CTRL2             (*(RwReg  *)0x41004524UL) /**< \brief (PORT) Control 2 */
#define REG_PORT_WRCONFIG2         (*(WoReg  *)0x41004528UL) /**< \brief (PORT) Write Configuration 2 */
#define REG_PORT_PMUX2             (*(RwReg  *)0x41004530UL) /**< \brief (PORT) Peripheral Multiplexing 2 */
#define REG_PORT_PINCFG2           (*(RwReg  *)0x41004540UL) /**< \brief (PORT) Pin Configuration 2 */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */

/* ========== Instance parameters for PORT peripheral ========== */
#define PORT_BITS                   84       // Number of PORT pins
#define PORT_DIR_DEFAULT_VAL        { 0x00000000, 0x00000000, 0x00000000 } // Default value for DIR of all pins
#define PORT_DIR_IMPLEMENTED        { 0xDBFFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Implementation mask for DIR of all pins
#define PORT_DRVSTR                 1        // DRVSTR supported
#define PORT_DRVSTR_DEFAULT_VAL     { 0xD8FFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Default value for DRVSTR of all pins
#define PORT_DRVSTR_IMPLEMENTED     { 0xD8FFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Implementation mask for DRVSTR of all pins
#define PORT_EVENT_IMPLEMENTED      { 0x00000000, 0x00000000, 0x00000000 }
#define PORT_INEN_DEFAULT_VAL       { 0x00000000, 0x00000000, 0x00000000 } // Default value for INEN of all pins
#define PORT_INEN_IMPLEMENTED       { 0xD8FFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Implementation mask for INEN of all pins
#define PORT_ODRAIN                 0        // ODRAIN supported
#define PORT_ODRAIN_DEFAULT_VAL     { 0x00000000, 0x00000000, 0x00000000 } // Default value for ODRAIN of all pins
#define PORT_ODRAIN_IMPLEMENTED     { 0x00000000, 0x00000000, 0x00000000 } // Implementation mask for ODRAIN of all pins
#define PORT_OUT_DEFAULT_VAL        { 0x00000000, 0x00000000, 0x00000000 } // Default value for OUT of all pins
#define PORT_OUT_IMPLEMENTED        { 0xDBFFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Implementation mask for OUT of all pins
#define PORT_PIN_IMPLEMENTED        { 0xDBFFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Implementation mask for all PORT pins
#define PORT_PMUXBIT0_DEFAULT_VAL   { 0x00000000, 0x00000000, 0x00000000 } // Default value for PMUX[0] of all pins
#define PORT_PMUXBIT0_IMPLEMENTED   { 0xDBFFFFFF, 0xC0C3FFFF, 0x000D0000 } // Implementation mask for PMUX[0] of all pins
#define PORT_PMUXBIT1_DEFAULT_VAL   { 0x40000000, 0x00000000, 0x00000000 } // Default value for PMUX[1] of all pins
#define PORT_PMUXBIT1_IMPLEMENTED   { 0xDBFFFFF3, 0xC0C3FF0F, 0x00000000 } // Implementation mask for PMUX[1] of all pins
#define PORT_PMUXBIT2_DEFAULT_VAL   { 0x40000000, 0x00000000, 0x00000000 } // Default value for PMUX[2] of all pins
#define PORT_PMUXBIT2_IMPLEMENTED   { 0xDBFFFFF3, 0xC0C3FF0F, 0x000D0000 } // Implementation mask for PMUX[2] of all pins
#define PORT_PMUXBIT3_DEFAULT_VAL   { 0x00000000, 0x00000000, 0x00000000 } // Default value for PMUX[3] of all pins
#define PORT_PMUXBIT3_IMPLEMENTED   { 0x00000000, 0x00000000, 0x00000000 } // Implementation mask for PMUX[3] of all pins
#define PORT_PMUXEN_DEFAULT_VAL     { 0x64000000, 0x3F3C0000, 0x00000000 } // Default value for PMUXEN of all pins
#define PORT_PMUXEN_IMPLEMENTED     { 0xDBFFFFFF, 0xC0C3FFFF, 0x000F7FFE } // Implementation mask for PMUXEN of all pins
#define PORT_PULLEN_DEFAULT_VAL     { 0x00000000, 0x00000000, 0x00000000 } // Default value for PULLEN of all pins
#define PORT_PULLEN_IMPLEMENTED     { 0xDBFFFFFF, 0xC0C3FFFF, 0x000FFFFF } // Implementation mask for PULLEN of all pins
#define PORT_SLEWLIM                0        // SLEWLIM supported
#define PORT_SLEWLIM_DEFAULT_VAL    { 0x00000000, 0x00000000, 0x00000000 } // Default value for SLEWLIM of all pins
#define PORT_SLEWLIM_IMPLEMENTED    { 0x00000000, 0x00000000, 0x00000000 } // Implementation mask for SLEWLIM of all pins

#endif /* _SAMR21_PORT_INSTANCE_ */

redpajama_set_name: RedPajamaGithub


text:
package com.mozilla.pig.eval.json;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.pig.data.Tuple;

public class JsonTupleMap extends JsonMap {

    /**
     * Converts List objects to Tuple to keep Pig happy
     *
     * @param l
     * @return
     */
    @SuppressWarnings("unchecked")
    private Tuple convertListToTuple(List<Object> l) {
        Tuple t = tupleFactory.newTuple();
        for (Object o : l) {
            if (o instanceof List) {
                t.append(convertListToTuple((List<Object>) o));
            } else {
                t.append(o);
            }
        }

        return t;
    }

    /**
     * Convert map and its values to types that Pig can handle
     *
     * @param m
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    protected Map<String, Object> makeSafe(Map<String, Object> m) {
        Map<String, Object> safeValues = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : m.entrySet()) {
            Object v = entry.getValue();
            if (v != null && v instanceof List) {
                // This is the main diff from the parent class
                // in that it converts lists to
                Tuple t = convertListToTuple((List<Object>) v);
                safeValues.put(entry.getKey(), t);
            } else if (v != null && v instanceof Map) {
                safeValues.put(entry.getKey(), makeSafe((Map<String, Object>) v));
            } else {
                safeValues.put(entry.getKey(), v);
            }
        }

        return safeValues;
    }
}


text:
.. IMPACT-Pipeline documentation master file, created by
   sphinx-quickstart on Wed Oct 14 13:23:35 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

IMPACT-Pipeline: MSK-IMPACT assay data analysis framework to process data on LSF/SGE
====================================================================================

:Author: `Ronak H Shah <https://github.com/rhshah>`_, Donavan Cheng, `Ahmet Zehir <https://github.com/ahmetz>`_, Aijazuddin Syed, `Raghu Chandramohan <https://github.com/rghu>`_, Meera Prasad et.al
:Contact: rons.shah@gmail.com
:Source code: http://github.com/rhshah/IMPACT-Pipeline
:License: `Apache License 2.0 <http://www.apache.org/licenses/LICENSE-2.0>`_

IMPACT-Pipeline is a Perl/Python/R command-line software toolkit to process data, call somatic aberrations (SNV,INDELS,SV,CNV) generated by NGS based MSK-IMPACT assay.
It is designed for use with hybrid capture, including both whole-exome and custom target panels, and short-read sequencing platforms such as Illumina.

.. image:: https://zenodo.org/badge/doi/10.5281/zenodo.32716.svg
   :target: http://dx.doi.org/10.5281/zenodo.32716

Contents:

.. toctree::
   :maxdepth: 5

   install
   requirements
   usage
   subscripts
   filedescriptions

Citation
========

If you use this software in a publication, please cite our paper

`Memorial Sloan Kettering-Integrated Mutation Profiling of Actionable Cancer Targets (MSK-IMPACT): A Hybridization Capture-Based Next-Generation Sequencing Clinical Assay for Solid Tumor Molecular Oncology <http://www.sciencedirect.com/science/article/pii/S1525157815000458>`_.


text:
package org.apache.hadoop.hdfs.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.util.ByteArrayManager.Counter;
import org.apache.hadoop.hdfs.util.ByteArrayManager.CounterMap;
import org.apache.hadoop.hdfs.util.ByteArrayManager.FixedLengthManager;
import org.apache.hadoop.hdfs.util.ByteArrayManager.ManagerMap;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Time;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Test;

/**
 * Test {@link ByteArrayManager}.
 */
public class TestByteArrayManager {
  static {
    GenericTestUtils.setLogLevel(LogFactory.getLog(ByteArrayManager.class),
        Level.ALL);
  }

  static final Log LOG = LogFactory.getLog(TestByteArrayManager.class);

  private static final Comparator<Future<Integer>> CMP = new Comparator<Future<Integer>>() {
    @Override
    public int compare(Future<Integer> left, Future<Integer> right) {
      try {
        return left.get().intValue() - right.get().intValue();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  };

  @Test
  public void testCounter() throws Exception {
    final long countResetTimePeriodMs = 200L;
    final Counter c = new Counter(countResetTimePeriodMs);

    final int n = ThreadLocalRandom.current().nextInt(512) + 512;
    final List<Future<Integer>> futures = new ArrayList<Future<Integer>>(n);

    final ExecutorService pool = Executors.newFixedThreadPool(32);
    try {
      // increment
      for(int i = 0; i < n; i++) {
        futures.add(pool.submit(new Callable<Integer>() {
          @Override
          public Integer call() throws Exception {
            return (int)c.increment();
          }
        }));
      }

      // sort and wait for the futures
      Collections.sort(futures, CMP);
    } finally {
      pool.shutdown();
    }

    // check futures
    Assert.assertEquals(n, futures.size());
    for(int i = 0; i < n; i++) {
      Assert.assertEquals(i + 1, futures.get(i).get().intValue());
    }
    Assert.assertEquals(n, c.getCount());

    // test auto-reset
    Thread.sleep(countResetTimePeriodMs + 100);
    Assert.assertEquals(1, c.increment());
  }

  @Test
  public void testAllocateRecycle() throws Exception {
    final int countThreshold = 4;
    final int countLimit = 8;
    final long countResetTimePeriodMs = 200L;
    final ByteArrayManager.Impl bam = new ByteArrayManager.Impl(
        new ByteArrayManager.Conf(
            countThreshold, countLimit, countResetTimePeriodMs));

    final CounterMap counters = bam.getCounters();
    final ManagerMap managers = bam.getManagers();

    final int[] uncommonArrays = {0, 1, 2, 4, 8, 16, 32, 64};
    final int arrayLength = 1024;

    final Allocator allocator = new Allocator(bam);
    final Recycler recycler = new Recycler(bam);
    try {
      { // allocate within threshold
        for(int i = 0; i < countThreshold; i++) {
          allocator.submit(arrayLength);
        }
        waitForAll(allocator.futures);

        Assert.assertEquals(countThreshold,
            counters.get(arrayLength, false).getCount());
        Assert.assertNull(managers.get(arrayLength, false));
        for(int n : uncommonArrays) {
          Assert.assertNull(counters.get(n, false));
          Assert.assertNull(managers.get(n, false));
        }
      }

      { // recycle half of the arrays
        for(int i = 0; i < countThreshold/2; i++) {
          recycler.submit(removeLast(allocator.futures).get());
        }

        for(Future<Integer> f : recycler.furtures) {
          Assert.assertEquals(-1, f.get().intValue());
        }
        recycler.furtures.clear();
      }

      { // allocate one more
        allocator.submit(arrayLength).get();

        Assert.assertEquals(countThreshold + 1, counters.get(arrayLength, false).getCount());
        Assert.assertNotNull(managers.get(arrayLength, false));
      }

      { // recycle the remaining arrays
        final int n = allocator.recycleAll(recycler);

        recycler.verify(n);
      }

      {
        // allocate until the maximum.
        for(int i = 0; i < countLimit; i++) {
          allocator.submit(arrayLength);
        }
        waitForAll(allocator.futures);

        // allocate one more should be blocked
        final AllocatorThread t = new AllocatorThread(arrayLength, bam);
        t.start();

        // check if the thread is waiting, timed wait or runnable.
        for(int i = 0; i < 5; i++) {
          Thread.sleep(100);
          final Thread.State threadState = t.getState();
          if (threadState != Thread.State.RUNNABLE
              && threadState != Thread.State.WAITING
              && threadState != Thread.State.TIMED_WAITING) {
            Assert.fail("threadState = " + threadState);
          }
        }

        // recycle an array
        recycler.submit(removeLast(allocator.futures).get());
        Assert.assertEquals(1, removeLast(recycler.furtures).get().intValue());

        // check if the thread is unblocked
        Thread.sleep(100);
        Assert.assertEquals(Thread.State.TERMINATED, t.getState());

        // recycle the remaining, the recycle should be full.
        Assert.assertEquals(countLimit-1, allocator.recycleAll(recycler));
        recycler.submit(t.array);
        recycler.verify(countLimit);

        // recycle one more; it should not increase the free queue size
        Assert.assertEquals(countLimit, bam.release(new byte[arrayLength]));
      }
    } finally {
      allocator.pool.shutdown();
      recycler.pool.shutdown();
    }
  }

  static <T> Future<T> removeLast(List<Future<T>> furtures) throws Exception {
    return remove(furtures, furtures.size() - 1);
  }
  static <T> Future<T> remove(List<Future<T>> furtures, int i) throws Exception {
    return furtures.isEmpty()? null: furtures.remove(i);
  }

  static <T> void waitForAll(List<Future<T>> furtures) throws Exception {
    for(Future<T> f : furtures) {
      f.get();
    }
  }

  static class AllocatorThread extends Thread {
    private final ByteArrayManager bam;
    private final int arrayLength;
    private byte[] array;

    AllocatorThread(int arrayLength, ByteArrayManager bam) {
      this.bam = bam;
      this.arrayLength = arrayLength;
    }

    @Override
    public void run() {
      try {
        array = bam.newByteArray(arrayLength);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  static class Allocator {
    private final ByteArrayManager bam;
    final ExecutorService pool = Executors.newFixedThreadPool(8);
    final List<Future<byte[]>> futures = new LinkedList<Future<byte[]>>();

    Allocator(ByteArrayManager bam) {
      this.bam = bam;
    }

    Future<byte[]> submit(final int arrayLength) {
      final Future<byte[]> f = pool.submit(new Callable<byte[]>() {
        @Override
        public byte[] call() throws Exception {
          final byte[] array = bam.newByteArray(arrayLength);
          Assert.assertEquals(arrayLength, array.length);
          return array;
        }
      });
      futures.add(f);
      return f;
    }

    int recycleAll(Recycler recycler) throws Exception {
      final int n = futures.size();
      for(Future<byte[]> f : futures) {
        recycler.submit(f.get());
      }
      futures.clear();
      return n;
    }
  }

  static class Recycler {
    private final ByteArrayManager bam;
    final ExecutorService pool = Executors.newFixedThreadPool(8);
    final List<Future<Integer>> furtures = new LinkedList<Future<Integer>>();

    Recycler(ByteArrayManager bam) {
      this.bam = bam;
    }

    Future<Integer> submit(final byte[] array) {
      final Future<Integer> f = pool.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          return bam.release(array);
        }
      });
      furtures.add(f);
      return f;
    }

    void verify(final int expectedSize) throws Exception {
      Assert.assertEquals(expectedSize, furtures.size());
      Collections.sort(furtures, CMP);
      for(int i = 0; i < furtures.size(); i++) {
        Assert.assertEquals(i+1, furtures.get(i).get().intValue());
      }
      furtures.clear();
    }
  }

  @Test
  public void testByteArrayManager() throws Exception {
    final int countThreshold = 32;
    final int countLimit = 64;
    final long countResetTimePeriodMs = 1000L;
    final ByteArrayManager.Impl bam = new ByteArrayManager.Impl(
        new ByteArrayManager.Conf(
            countThreshold, countLimit, countResetTimePeriodMs));

    final CounterMap counters = bam.getCounters();
    final ManagerMap managers = bam.getManagers();

    final ExecutorService pool = Executors.newFixedThreadPool(128);

    final Runner[] runners = new Runner[Runner.NUM_RUNNERS];
    final Thread[] threads = new Thread[runners.length];

    final int num = 1 << 10;
    for(int i = 0; i < runners.length; i++) {
      runners[i] = new Runner(i, countThreshold, countLimit, pool, i, bam);
      threads[i] = runners[i].start(num);
    }

    final List<Exception> exceptions = new ArrayList<Exception>();
    final Thread randomRecycler = new Thread() {
      @Override
      public void run() {
        LOG.info("randomRecycler start");
        for(int i = 0; shouldRun(); i++) {
          final int j = ThreadLocalRandom.current().nextInt(runners.length);
          try {
            runners[j].recycle();
          } catch (Exception e) {
            e.printStackTrace();
            exceptions.add(new Exception(this + " has an exception", e));
          }

          if ((i & 0xFF) == 0) {
            LOG.info("randomRecycler sleep, i=" + i);
            sleepMs(100);
          }
        }
        LOG.info("randomRecycler done");
      }

      boolean shouldRun() {
        for(int i = 0; i < runners.length; i++) {
          if (threads[i].isAlive()) {
            return true;
          }
          if (!runners[i].isEmpty()) {
            return true;
          }
        }
        return false;
      }
    };
    randomRecycler.start();

    randomRecycler.join();
    Assert.assertTrue(exceptions.isEmpty());

    Assert.assertNull(counters.get(0, false));
    for(int i = 1; i < runners.length; i++) {
      if (!runners[i].assertionErrors.isEmpty()) {
        for(AssertionError e : runners[i].assertionErrors) {
          LOG.error("AssertionError " + i, e);
        }
        Assert.fail(runners[i].assertionErrors.size() + " AssertionError(s)");
      }

      final int arrayLength = Runner.index2arrayLength(i);
      final boolean exceedCountThreshold = counters.get(arrayLength, false).getCount() > countThreshold;
      final FixedLengthManager m = managers.get(arrayLength, false);
      if (exceedCountThreshold) {
        Assert.assertNotNull(m);
      } else {
        Assert.assertNull(m);
      }
    }
  }

  static void sleepMs(long ms) {
    try {
      Thread.sleep(ms);
    } catch (InterruptedException e) {
      e.printStackTrace();
      Assert.fail("Sleep is interrupted: " + e);
    }
  }

  static class Runner implements Runnable {
    static final int NUM_RUNNERS = 5;

    static int index2arrayLength(int index) {
      return ByteArrayManager.MIN_ARRAY_LENGTH << (index - 1);
    }

    private final ByteArrayManager bam;
    final int maxArrayLength;
    final int countThreshold;
    final int maxArrays;
    final ExecutorService pool;
    final List<Future<byte[]>> arrays = new ArrayList<Future<byte[]>>();

    final AtomicInteger count = new AtomicInteger();
    final int p;
    private int n;

    final List<AssertionError> assertionErrors = new ArrayList<AssertionError>();

    Runner(int index, int countThreshold, int maxArrays,
        ExecutorService pool, int p, ByteArrayManager bam) {
      this.maxArrayLength = index2arrayLength(index);
      this.countThreshold = countThreshold;
      this.maxArrays = maxArrays;
      this.pool = pool;
      this.p = p;
      this.bam = bam;
    }

    boolean isEmpty() {
      synchronized (arrays) {
        return arrays.isEmpty();
      }
    }

    Future<byte[]> submitAllocate() {
      count.incrementAndGet();

      final Future<byte[]> f = pool.submit(new Callable<byte[]>() {
        @Override
        public byte[] call() throws Exception {
          final int lower = maxArrayLength == ByteArrayManager.MIN_ARRAY_LENGTH?
              0: maxArrayLength >> 1;
          final int arrayLength = ThreadLocalRandom.current().nextInt(
              maxArrayLength - lower) + lower + 1;
          final byte[] array = bam.newByteArray(arrayLength);
          try {
            Assert.assertEquals("arrayLength=" + arrayLength + ", lower=" + lower,
                maxArrayLength, array.length);
          } catch(AssertionError e) {
            assertionErrors.add(e);
          }
          return array;
        }
      });
      synchronized (arrays) {
        arrays.add(f);
      }
      return f;
    }

    Future<byte[]> removeFirst() throws Exception {
      synchronized (arrays) {
        return remove(arrays, 0);
      }
    }

    void recycle() throws Exception {
      final Future<byte[]> f = removeFirst();
      if (f != null) {
        printf("randomRecycler: ");
        try {
          recycle(f.get(10, TimeUnit.MILLISECONDS));
        } catch(TimeoutException e) {
          recycle(new byte[maxArrayLength]);
          printf("timeout, new byte[%d]\n", maxArrayLength);
        }
      }
    }

    int recycle(final byte[] array) {
      return bam.release(array);
    }

    Future<Integer> submitRecycle(final byte[] array) {
      count.decrementAndGet();

      final Future<Integer> f = pool.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          return recycle(array);
        }
      });
      return f;
    }

    @Override
    public void run() {
      for(int i = 0; i < n; i++) {
        final boolean isAllocate = ThreadLocalRandom.current()
            .nextInt(NUM_RUNNERS) < p;
        if (isAllocate) {
          submitAllocate();
        } else {
          try {
            final Future<byte[]> f = removeFirst();
            if (f != null) {
              submitRecycle(f.get());
            }
          } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(this + " has " + e);
          }
        }

        if ((i & 0xFF) == 0) {
          sleepMs(100);
        }
      }
    }

    Thread start(int n) {
      this.n = n;
      final Thread t = new Thread(this);
      t.start();
      return t;
    }

    @Override
    public String toString() {
      return getClass().getSimpleName() + ": max=" + maxArrayLength
          + ", count=" + count;
    }
  }

  static class NewByteArrayWithLimit extends ByteArrayManager {
    private final int maxCount;
    private int count = 0;

    NewByteArrayWithLimit(int maxCount) {
      this.maxCount = maxCount;
    }

    @Override
    public synchronized byte[] newByteArray(int size) throws InterruptedException {
      for(; count >= maxCount; ) {
        wait();
      }
      count++;
      return new byte[size];
    }

    @Override
    public synchronized int release(byte[] array) {
      if (count == maxCount) {
        notifyAll();
      }
      count--;
      return 0;
    }
  }

  public static void main(String[] args) throws Exception {
    GenericTestUtils.setLogLevel(LogFactory.getLog(ByteArrayManager.class),
        Level.OFF);

    final int arrayLength = 64 * 1024; //64k
    final int nThreads = 512;
    final int nAllocations = 1 << 15;
    final int maxArrays = 1 << 10;
    final int nTrials = 5;

    System.out.println("arrayLength=" + arrayLength
        + ", nThreads=" + nThreads
        + ", nAllocations=" + nAllocations
        + ", maxArrays=" + maxArrays);

    final ByteArrayManager[] impls = {
        new ByteArrayManager.NewByteArrayWithoutLimit(),
        new NewByteArrayWithLimit(maxArrays),
        new ByteArrayManager.Impl(new ByteArrayManager.Conf(
            HdfsClientConfigKeys.Write.ByteArrayManager.COUNT_THRESHOLD_DEFAULT,
            maxArrays,
            HdfsClientConfigKeys.Write.ByteArrayManager.COUNT_RESET_TIME_PERIOD_MS_DEFAULT))
    };
    final double[] avg = new double[impls.length];

    for(int i = 0; i < impls.length; i++) {
      double duration = 0;
      printf("%26s:", impls[i].getClass().getSimpleName());
      for(int j = 0; j < nTrials; j++) {
        final int[] sleepTime = new int[nAllocations];
        for(int k = 0; k < sleepTime.length; k++) {
          sleepTime[k] = ThreadLocalRandom.current().nextInt(100);
        }

        final long elapsed = performanceTest(arrayLength, maxArrays, nThreads,
            sleepTime, impls[i]);
        duration += elapsed;
        printf("%5d, ", elapsed);
      }
      avg[i] = duration/nTrials;
      printf("avg=%6.3fs", avg[i]/1000);
      for(int j = 0; j < i; j++) {
        printf(" (%6.2f%%)", percentageDiff(avg[j], avg[i]));
      }
      printf("\n");
    }
  }

  static double percentageDiff(double original, double newValue) {
    return (newValue - original)/original*100;
  }

  static void printf(String format, Object... args) {
    System.out.printf(format, args);
    System.out.flush();
  }

  static long performanceTest(final int arrayLength, final int maxArrays,
      final int nThreads, final int[] sleepTimeMSs, final ByteArrayManager impl)
          throws Exception {
    final ExecutorService pool = Executors.newFixedThreadPool(nThreads);
    final List<Future<Void>> futures = new ArrayList<Future<Void>>(sleepTimeMSs.length);
    final long startTime = Time.monotonicNow();

    for(int i = 0; i < sleepTimeMSs.length; i++) {
      final long sleepTime = sleepTimeMSs[i];
      futures.add(pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          byte[] array = impl.newByteArray(arrayLength);
          sleepMs(sleepTime);
          impl.release(array);
          return null;
        }
      }));
    }
    for(Future<Void> f : futures) {
      f.get();
    }

    final long endTime = Time.monotonicNow();
    pool.shutdown();
    return endTime - startTime;
  }
}


text:
from flask import Flask
from flask_socketio import SocketIO

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on available packages.
async_mode = None

if async_mode is None:
    try:
        import eventlet
        async_mode = 'eventlet'
    except ImportError:
        pass

    if async_mode is None:
        try:
            from gevent import monkey
            async_mode = 'gevent'
        except ImportError:
            pass

    if async_mode is None:
        async_mode = 'threading'

    print('async_mode is ' + async_mode)

# monkey patching is necessary because this application uses
# a background thread
if async_mode == 'eventlet':
    import eventlet
    eventlet.monkey_patch()
elif async_mode == 'gevent':
    from gevent import monkey
    monkey.patch_all()

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)

DEFAULT_IMAGE_PATH = 'static/img/pic.jpg'

from app import views


text:
//
//  SMDSGamma.h
//  SMDisplayServices
//
//  Created by Sam Marshall on 3/31/12.
//  Copyright 2012 Sam Marshall. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface SMDSGamma : NSObject {
	NSUInteger dID;
	CGGammaValue redMin, redMax, redGamma;
	CGGammaValue greenMin, greenMax, greenGamma;
	CGGammaValue blueMin, blueMax, blueGamma;
}

@property (nonatomic, readonly) NSUInteger dID;

@property (nonatomic, readonly) CGGammaValue redMin;
@property (nonatomic, readonly) CGGammaValue redMax;
@property (nonatomic, readonly) CGGammaValue redGamma;

@property (nonatomic, readonly) CGGammaValue greenMin;
@property (nonatomic, readonly) CGGammaValue greenMax;
@property (nonatomic, readonly) CGGammaValue greenGamma;

@property (nonatomic, readonly) CGGammaValue blueMin;
@property (nonatomic, readonly) CGGammaValue blueMax;
@property (nonatomic, readonly) CGGammaValue blueGamma;

- (id)initWithDisplayID:(NSUInteger)_id;
- (BOOL)isSame;
- (void)update;

@end


text:
function img = marbleRemovalPicture(removedMarbleNum,meshComplexity);
% meshString: integer 1-10 for building FEM based on EIDORS point electrode model
% removedMarbleNum: numbers of which marbles to remove; numbers increase
% upwards in the same column after starting at the middle of the column;
% zero is placed at the dead center and then moves up to the top, then down
% from the bottom, then shift to the right one column and repeat; after
% furthest right column is reached, then move leftward. A proper numbering
% system based on geometry could be implemented if so desired.

% Gregory Poore
% BME 462 Design

%% Make common model and modify parameters

dim = 2; % 2 for 2D circle, 3 for 3D cylinder
%removedMarbleNum = [19, 20, 26]; % appears to be X, X+1, X+8 or X+9
% Saved removal numbers:
% [1, 20, 23, 46, 49] "X" spread through center
% [2, 3, 11] center
% [8,9,17] bottom middle triad
% [19, 20, 26] upper right

% Saved reconstruction values
% BigDataDataConfig1 (clumped): [3,4,12]
% BigDataDataConfig2 (spread): [6 20 45]
% Nov 20 - Clumped 1: [1 2 36]
% Nov 20 - Clumped 2: [3 4 38]
% Nov 20 - Clumped 3: [25 31 32]
% Nov 20 - Spread 1: [16 19 36]
% Nov 20 - Spread 2: [8 9 22 48]
% Nov 20 - Spread 3: [

if(nargin==1)
    meshComplexity = 7;
end

meshComplexityOptions = ['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'];
meshChoice = meshComplexityOptions(meshComplexity);
meshString = sprintf('%s2d0d',meshChoice); % for point electrodes

% Make model
nElec = 20;
imdl = mk_common_model(meshString,nElec); % uses point electrodes in model

%% Make image (i.e. conductivity value expression set)

img = mk_image(imdl);

%% Add 3D marble set and remove 3 to solve forward model

marbleCoordDrop3 = marbleCoordinates_v2(1/9, 1/10, dim);
marbleCoordDrop3(removedMarbleNum,:) = [];

DelC1 = -1; % conductivity change of each marble
img.elem_data = 1;
for(i = 1:length(marbleCoordDrop3))
    targets{i} = mk_c2f_circ_mapping(img.fwd_model, ...
        transpose(marbleCoordDrop3(i,:)) );
    img.elem_data = img.elem_data + DelC1*targets{i}(:,1);
end

%% Plotting
figure(1); clf
subplot(1,2,1)
show_fem(img)
title('Location of marble removal')


text:
<template name="design_secondary_inductor">

Engineering Parameters

  Lets start with the approximate size of the secondary coil which you wish to build:

Width <input type="text" id="height"> cm

Height <input type="text" id="width"> cm

  Reccomend an aspect ratio (H/R) from 3-7.

  Now lets pick some wire for our coil: {{> awgDropdown}}
  Next lets figure out how much wire is going on this thing:

Wire Gauges  <input type="text" id="gauge">

Packing Factor <input type="text" id="packing"> %

Ohms per km <input type="text" id="ohms "> Ohms

  Amount of wire:

Electrical Properties:

  Alright, that gives us a ballpark estimate of the secondary coil's inductance:
  {{ inductance }}
  Also, an estimate of the capacatance and resistance.
  {{ capacatance }}, {{ resistance }}
  <button name="calc">Calculate</button>
</template>


text:
package com.javarush.test.level13.lesson11.bonus02;

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

/* Репка
Сказка Репка:
1. Реализовать интерфейс RepkaItem в классе Person.
2. В классе Person реализовать метод pull(Person person), который выводит фразу типа '<name> за <person>'. Пример:
Бабка за Дедку
Дедка за Репку
3. Исправить логическую ошибку цикла в методе tell класса RepkaStory.
4. Выполнить метод main и наслаждаться сказкой!
*/

public class Solution
{
    public static void main(String[] args)
    {
        List<Person> plot = new ArrayList<Person>();
        plot.add(new Person("Репка", "Репку"));
        plot.add(new Person("Дедка", "Дедку"));
        plot.add(new Person("Бабка", "Бабку"));
        plot.add(new Person("Внучка", "Внучку"));
        RepkaStory.tell(plot);
    }
}


text:
namespace DVGui {
class FileField;
class LineEdit;
class CheckBox;
}

class DvDirTreeView;
class QComboBox;

//=============================================================================
// ProjectDvDirModelRootNode

class ProjectDvDirModelRootNode final : public DvDirModelNode {
public:
  ProjectDvDirModelRootNode();
  void refreshChildren() override;
};

//=============================================================================
// ProjectDvDirModelFileFolderNode

class ProjectDvDirModelFileFolderNode : public DvDirModelFileFolderNode {
public:
  ProjectDvDirModelFileFolderNode(DvDirModelNode *parent, std::wstring name,
                                  const TFilePath &path)
      : DvDirModelFileFolderNode(parent, name, path) {}
  ProjectDvDirModelFileFolderNode(DvDirModelNode *parent, const TFilePath &path)
      : DvDirModelFileFolderNode(parent, path) {}
  DvDirModelNode *makeChild(std::wstring name) override;
  DvDirModelFileFolderNode *createNode(DvDirModelNode *parent,
                                       const TFilePath &path);
};

//=============================================================================
// ProjectDvDirModelSpecialFileFolderNode

class ProjectDvDirModelSpecialFileFolderNode final
    : public ProjectDvDirModelFileFolderNode {
  QPixmap m_pixmap;

public:
  ProjectDvDirModelSpecialFileFolderNode(DvDirModelNode *parent,
                                         std::wstring name,
                                         const TFilePath &path)
      : ProjectDvDirModelFileFolderNode(parent, name, path) {}
  QPixmap getPixmap(bool isOpen) const override { return m_pixmap; }
  void setPixmap(const QPixmap &pixmap) { m_pixmap = pixmap; }
};

//=============================================================================
// ProjectDvDirModelProjectNode

class ProjectDvDirModelProjectNode final
    : public ProjectDvDirModelFileFolderNode {
public:
  ProjectDvDirModelProjectNode(DvDirModelNode *parent, const TFilePath &path)
      : ProjectDvDirModelFileFolderNode(parent, path) {}
  void makeCurrent() {}
  QPixmap getPixmap(bool isOpen) const override;
};

//=============================================================================
// ProjectDirModel

class ProjectDirModel final : public QAbstractItemModel {
  DvDirModelNode *m_root;

public:
  ProjectDirModel();
  ~ProjectDirModel();

  DvDirModelNode *getNode(const QModelIndex &index) const;
  QModelIndex index(int row, int column,
                    const QModelIndex &parent) const override;
  QModelIndex parent(const QModelIndex &index) const override;
  QModelIndex childByName(const QModelIndex &parent,
                          const std::wstring &name) const;
  int columnCount(const QModelIndex &parent) const override { return 1; }
  QVariant data(const QModelIndex &index,
                int role = Qt::DisplayRole) const override;
  Qt::ItemFlags flags(const QModelIndex &index) const override;
  bool setData(const QModelIndex &index, const QVariant &value,
               int role = Qt::EditRole) override;
  int rowCount(const QModelIndex &parent = QModelIndex()) const override;
  bool hasChildren(const QModelIndex &parent) const override;
  void refresh(const QModelIndex &index);
  void refreshFolderChild(const QModelIndex &i = QModelIndex());
  QModelIndex getIndexByNode(DvDirModelNode *node) const;
};

//=============================================================================
// ProjectPopup
//-----------------------------------------------------------------------------

class ProjectPopup : public DVGui::Dialog, public TProjectManager::Listener {
  Q_OBJECT

protected:
  ProjectDirModel *m_model;
  DvDirTreeView *m_treeView;
  DVGui::LineEdit *m_nameFld;
  QList<QPair<std::string, DVGui::FileField *>> m_folderFlds;
  QList<QPair<std::string, DVGui::CheckBox *>> m_useScenePathCbs;

  QLabel *m_prjNameLabel;
  QLabel *m_choosePrjLabel;
  QComboBox *m_chooseProjectCombo;
  QList<TFilePath> m_projectPaths;

public:
  ProjectPopup(bool isModal);
  // da TProjectManager::Listener
  void onProjectSwitched() override;
  // da TProjectManager::Listener
  void onProjectChanged() override {}

  void updateProjectFromFields(TProject *);
  void updateFieldsFromProject(TProject *);

  void updateChooseProjectCombo();

protected:
  void showEvent(QShowEvent *) override;
};

//=============================================================================
// ProjectSettingsPopup
//-----------------------------------------------------------------------------

class ProjectSettingsPopup final : public ProjectPopup {
  Q_OBJECT

public:
  ProjectSettingsPopup();

public slots:
  void onFolderChanged();
  void onUseSceneChekboxChanged(int);

  void onChooseProjectChanged(int);
};

//=============================================================================
// ProjectCreatePopup
//-----------------------------------------------------------------------------

class ProjectCreatePopup final : public ProjectPopup {
  Q_OBJECT

public:
  ProjectCreatePopup();

public slots:
  void createProject();

protected:
  void showEvent(QShowEvent *) override;
};

#endif  // PROJECTPOPUP_H


text:
layout: post
title: "Graphics for the ISU LAS College Status of Women Report: Excel to ggplot2"
date: "2019-02-01 13:10:00 CST"
categories: graphics, rstats, ggplot2
---

Slides are [here](../static/presentations/Misc/GraphicsGroupISU/2019-02-01/las-status-women-graphics-group.html).

Note: As much as I love sharing data and code, I cannot for this presentation because the data are not mine to share.


text:
package vfsgen

import (
	"io"
)

// stringWriter writes given bytes to underlying io.Writer as a Go interpreted string literal value,
// not including double quotes. It tracks the total number of bytes written.
type stringWriter struct {
	io.Writer
	N int64 // Total bytes written.
}

func (sw *stringWriter) Write(p []byte) (n int, _ error) {
	const hex = "0123456789abcdef"
	buf := []byte{'\\', 'x', 0, 0}
	for _, b := range p {
		buf[2], buf[3] = hex[b/16], hex[b%16]
		_, err := sw.Writer.Write(buf)
		if err != nil {
			return n, err
		}
		n++
		sw.N++
	}
	return n, nil
}


text:
#pragma once

#include <string>

#include "Eigen/Dense"

#include "modules/perception/lib/thread/thread_worker.h"
#include "modules/perception/lidar/common/cloud_mask.h"
#include "modules/perception/lidar/lib/detector/cnn_segmentation/spp_engine/spp_cluster.h"
#include "modules/perception/lidar/lib/detector/cnn_segmentation/spp_engine/spp_cluster_list.h"
#include "modules/perception/lidar/lib/detector/cnn_segmentation/spp_engine/spp_seg_cc_2d.h"
#include "modules/perception/lidar/lib/detector/cnn_segmentation/spp_engine/spp_struct.h"

namespace apollo {
namespace perception {
namespace lidar {

class SppEngine {
 public:
  SppEngine() = default;
  ~SppEngine() = default;
  // @brief: initialize spp engine
  // @param [in]: feature map width
  // @param [in]: feature map height
  // @param [in]: feature map range
  // @param [in]: sensor name
  void Init(size_t width, size_t height, float range,
            const SppParams& param = SppParams(),
            const std::string& sensor_name = "velodyne64");
  // @brief: process foreground segmentation
  // @param [in]: point cloud
  // @return: size of foreground clusters
  size_t ProcessForegroundSegmentation(
      const base::PointFCloudConstPtr point_cloud);
  // @brief: remove ground points in foreground cluster
  // @param [in]: point cloud
  // @param [in]: roi indices of point cloud
  // @param [in]: non ground indices in roi of point cloud
  size_t RemoveGroundPointsInForegroundCluster(
      const base::PointFCloudConstPtr full_point_cloud,
      const base::PointIndices& roi_indices,
      const base::PointIndices& roi_non_ground_indices);
  // @brief: get cluster list, const version
  // @return: cluster list
  inline const SppClusterList& clusters() const { return clusters_; }
  // @brief: get cluster list, const version
  // @return: cluster list
  inline SppClusterList& clusters() { return clusters_; }
  // @brief: get feature data, need to filled first
  inline SppData& GetSppData() { return data_; }
  // @brief: get feature data, need to filled first, const version
  inline const SppData& GetSppData() const { return data_; }

 private:
  // @brief: process clustering on input feature map
  // @param [in]: point cloud
  // @param [in]: point cloud mask
  size_t ProcessConnectedComponentCluster(
      const base::PointFCloudConstPtr point_cloud, const CloudMask& mask);

 private:
  // feature size
  size_t width_ = 0;
  size_t height_ = 0;
  float range_ = 0.f;
  // label image
  SppLabelImage labels_2d_;
  // clusters
  SppClusterList clusters_;
  // cloud mask
  CloudMask mask_;
  CloudMask roi_mask_;
  // clustering method
  SppCCDetector detector_2d_cc_;
  // global parameters
  SppParams params_;
  // const spp data pointer
  SppData data_;
  // thread worker for sync data
  lib::ThreadWorker worker_;
};

}  // namespace lidar
}  // namespace perception
}  // namespace apollo


text:
package hydrograph.ui.propertywindow.widgets.utility;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import hydrograph.ui.common.util.Constants;
import hydrograph.ui.common.util.ParameterUtil;
import hydrograph.ui.common.util.TransformMappingFeatureUtility;
import hydrograph.ui.datastructure.property.BasicSchemaGridRow;
import hydrograph.ui.datastructure.property.ComponentsOutputSchema;
import hydrograph.ui.datastructure.property.FilterProperties;
import hydrograph.ui.datastructure.property.FixedWidthGridRow;
import hydrograph.ui.datastructure.property.GridRow;
import hydrograph.ui.datastructure.property.NameValueProperty;
import hydrograph.ui.datastructure.property.Schema;
import hydrograph.ui.datastructure.property.mapping.ErrorObject;
import hydrograph.ui.datastructure.property.mapping.InputField;
import hydrograph.ui.datastructure.property.mapping.MappingSheetRow;
import hydrograph.ui.datastructure.property.mapping.TransformMapping;
import hydrograph.ui.graph.model.Component;
import hydrograph.ui.graph.model.Link;
import hydrograph.ui.graph.schema.propagation.SchemaPropagation;
import hydrograph.ui.propertywindow.schema.propagation.helper.SchemaPropagationHelper;

/**
 * @author Bitwise
 *
 *helper class for output record count widget
 */
public class OutputRecordCountUtility {
	public static final OutputRecordCountUtility INSTANCE= new OutputRecordCountUtility();

	private GridRow getFieldSchema(String fieldName,Component component)
	{
		List<GridRow> schemaGridRows = getInputFieldSchema(component);
		for (GridRow schemaGridRow : schemaGridRows)
		{
			if (schemaGridRow.getFieldName().equals(fieldName))
			{
				return schemaGridRow;
			}
		}
		return null;
	}
	private List<GridRow> getInputFieldSchema(Component component) {
		ComponentsOutputSchema outputSchema = null;
		List<GridRow> schemaGridRows = new LinkedList<>();
		for (Link link : component.getTargetConnections())
		{
			outputSchema = SchemaPropagation.INSTANCE.getComponentsOutputSchema(link);
			if (outputSchema != null)
				for (GridRow row : outputSchema.getSchemaGridOutputFields(null))
				{
					schemaGridRows.add(row);
				}
		}
		return schemaGridRows;
	}
	private GridRow getCurrentSchemaField(String fieldName,Component component)
	{
		Schema schema = (Schema) component.getProperties().get(Constants.SCHEMA_PROPERTY_NAME);
		if (schema != null) {
			for (GridRow gridRow : schema.getGridRow()) {
				if(gridRow.getFieldName().equals(fieldName))
					return gridRow;
			}
		}
		return null;
	}
	private String getPortCount(String sourceTerminalId) {
		String portCount=null;
		if(StringUtils.startsWithIgnoreCase(sourceTerminalId, Constants.UNUSED_SOCKET_TYPE)){
			portCount=StringUtils.remove(sourceTerminalId, Constants.UNUSED_SOCKET_TYPE);
		}else if(StringUtils.startsWithIgnoreCase(sourceTerminalId, Constants.OUTPUT_SOCKET_TYPE)){
			portCount=StringUtils.remove(sourceTerminalId, Constants.OUTPUT_SOCKET_TYPE);
		}
		return portCount;
	}

	private void backwardJobComapatabilityCode(TransformMapping transformMapping)
    {
    		List<NameValueProperty> tempNameValuePropertyList=new ArrayList<>();
    		for(NameValueProperty nameValueProperty:transformMapping.getMapAndPassthroughField())
    		{
    			NameValueProperty newNameValueProperty=new NameValueProperty();
    			newNameValueProperty.setPropertyName(nameValueProperty.getPropertyName());
    			newNameValueProperty.setPropertyValue(nameValueProperty.getPropertyValue());
    			newNameValueProperty.getFilterProperty().setPropertyname(nameValueProperty.getPropertyValue());
    			tempNameValuePropertyList.add(newNameValueProperty);
    			transformMapping.getOutputFieldList().add(newNameValueProperty.getFilterProperty());
    		}
    		transformMapping.getMapAndPassthroughField().clear();
    		transformMapping.getMapAndPassthroughField().addAll(tempNameValuePropertyList);
    		tempNameValuePropertyList.clear();
    }

	/**
	 * Add Map field to internal schema object.
	 * @param mapFields
	 */
	public void addMapFieldsToSchema(Map<String, String> mapFields,Schema schemaData,Component component)
	{
		BasicSchemaGridRow tempSchemaGridRow = null;
		Schema schema = schemaData;
		List<String> currentFieldsInProppogatedSchemaObject = new LinkedList<>();
		for (GridRow gridRow : schema.getGridRow()) {
			currentFieldsInProppogatedSchemaObject.add(gridRow.getFieldName());
		}

	  for (Map.Entry<String,String> entry: mapFields.entrySet())
	  {
			tempSchemaGridRow = (BasicSchemaGridRow) getFieldSchema(entry.getValue(),component);
			BasicSchemaGridRow schemaGridRow=null ;
			if (tempSchemaGridRow != null) {
				schemaGridRow= (BasicSchemaGridRow) tempSchemaGridRow.copy();
				schemaGridRow.setFieldName(entry.getKey());
			}
			else{
				schemaGridRow = SchemaPropagationHelper.INSTANCE.createSchemaGridRow(entry.getKey());
			}
				if (!currentFieldsInProppogatedSchemaObject.contains(entry.getKey()) && !schema.getGridRow().contains(schemaGridRow)) {
							schema.getGridRow().add(schemaGridRow);
				} else {
					for (int index = 0; index < schema.getGridRow().size(); index++) {
						if (schema.getGridRow().get(index).getFieldName().equals(entry.getKey())) {
							schema.getGridRow().set(index, schemaGridRow);
						}
					}
				}

		}

	}
	/**
	 * Add Pass through field to schema
	 * @param passThroughFields
	 */
	public void addPassthroughFieldsToSchema(List<String> passThroughFields,Schema schemaData,Component component) {
		Schema schema = schemaData;
		List<String> currentFieldsInProppogatedSchemaObject = new LinkedList<>();
		for (GridRow gridRow : schema.getGridRow()) {
			currentFieldsInProppogatedSchemaObject.add(gridRow.getFieldName());
		}

		for (String passThroughField : passThroughFields) {
			GridRow schemaGridRow= getFieldSchema(passThroughField,component);
			if(schemaGridRow!=null){
				BasicSchemaGridRow tempSchemaGrid =(BasicSchemaGridRow) schemaGridRow.copy();

				if (!currentFieldsInProppogatedSchemaObject.contains(passThroughField) && !schema.getGridRow().contains(tempSchemaGrid)) {
					schema.getGridRow().add(tempSchemaGrid);
				} else {
					for (int index = 0; index < schema.getGridRow().size(); index++) {
						if (schema.getGridRow().get(index).getFieldName().equals(passThroughField)) {
							schema.getGridRow().set(index, tempSchemaGrid);
						}
					}
				}
			}else{
				schema.getGridRow().add(SchemaPropagationHelper.INSTANCE.createSchemaGridRow(passThroughField));
			}
			}
	}
	/**
	 * 	Add Operation field to internal schema object
	 * 	@param operationFields
	 */
	public void addOperationFieldsToSchema(List<FilterProperties> operationFields,Schema schemaData,Component component)
	{
		Schema schema = schemaData;
		GridRow schemaGridRow=null;
		List<String> currentFieldsInProppogatedSchemaObject = new LinkedList<>();
		for (GridRow gridRow : schema.getGridRow())
		{
			currentFieldsInProppogatedSchemaObject.add(gridRow.getFieldName());
		}

		for (FilterProperties operationField : operationFields) {
			if(!ParameterUtil.isParameter(operationField.getPropertyname())){

				if(getCurrentSchemaField(operationField.getPropertyname(),component)!=null){
					schemaGridRow=getCurrentSchemaField(operationField.getPropertyname(),component);
					schemaGridRow=schemaGridRow.copy();
				}
				else
					schemaGridRow = SchemaPropagationHelper.INSTANCE.createSchemaGridRow(operationField.getPropertyname());

				if (!currentFieldsInProppogatedSchemaObject.contains(operationField.getPropertyname()) && !schema.getGridRow().contains(schemaGridRow)) {
					schema.getGridRow().add(schemaGridRow);
				} else {
					for (int index = 0; index < schema.getGridRow().size(); index++) {
						if (schema.getGridRow().get(index).getFieldName().equals(operationField.getPropertyname())) {
							schema.getGridRow().set(index, schemaGridRow);

						}
					}
				}
			}
		}
	}

	/**
	 * @param component
	 * @return input schema fixed width row object
	 */
	public List<FixedWidthGridRow> getInputSchema(Component component)
	{

		List<FixedWidthGridRow> fixedWidthSchemaGridRows=new ArrayList<>();
		for(Link link:component.getTargetConnections()){
			Schema previousComponentSchema=SubjobUtility.INSTANCE.getSchemaFromPreviousComponentSchema(component,link);

			if(previousComponentSchema!=null &&!previousComponentSchema.getGridRow().isEmpty())
			{
				fixedWidthSchemaGridRows=SchemaSyncUtility.INSTANCE.
						convertGridRowsSchemaToFixedSchemaGridRows(previousComponentSchema.getGridRow());
			}
			break;
		}
		return fixedWidthSchemaGridRows;
	}

	/**
	 * @param component
	 * @return list of filterproperties created from component schema object
	 */
	public List<FilterProperties> convertSchemaToFilterProperty(Component component)
	{
		List<FilterProperties> outputFileds = new ArrayList<>();
		Schema schema = (Schema) component.getProperties().get(Constants.SCHEMA_PROPERTY_NAME);
		    if(schema==null)
		    {
			 return outputFileds;
		    }
			 for (GridRow gridRow : schema.getGridRow())
			 {
				FilterProperties filterProperty = new FilterProperties();
				filterProperty.setPropertyname(gridRow.getFieldName());
				outputFileds.add(filterProperty);
			 }
		return outputFileds;
	}

	/**
	 * @param mapFields
	 * @param passThroughFields
	 * @param component
	 * add pass through,map fields to componentOutputschema
	 */
	public void addPassthroughFieldsAndMappingFieldsToComponentOuputSchema(Map<String, String> mapFields,
			List<String> passThroughFields,Component component)
    {
		ComponentsOutputSchema componentsOutputSchema = null;
		Map<String, ComponentsOutputSchema> schemaMap = (Map<String, ComponentsOutputSchema>) component
				.getProperties().get(Constants.SCHEMA_TO_PROPAGATE);
		if (schemaMap != null && schemaMap.get(Constants.FIXED_OUTSOCKET_ID) != null)
		{
			componentsOutputSchema = schemaMap.get(Constants.FIXED_OUTSOCKET_ID);
		}
		else {
			componentsOutputSchema = new ComponentsOutputSchema();
			schemaMap = new LinkedHashMap<>();
			schemaMap.put(Constants.FIXED_OUTSOCKET_ID, componentsOutputSchema);
		}
		component.getProperties().put(Constants.SCHEMA_TO_PROPAGATE, schemaMap);

		componentsOutputSchema.getPassthroughFields().clear();
		componentsOutputSchema.getMapFields().clear();
		componentsOutputSchema.getPassthroughFields().addAll(passThroughFields);
		componentsOutputSchema.getMapFields().putAll(mapFields);
	}

	/**
	 * @param nameValueProperties
	 * @return map<String,String>
	 */
	public  Map<String,String> getMapFields(List<NameValueProperty> nameValueProperties)
	{
		Map<String,String> mapField = new LinkedHashMap<>();
		if (!nameValueProperties.isEmpty()) {

			for (NameValueProperty nameValueProperty : nameValueProperties) {
				if (!(nameValueProperty.getPropertyName().equals(
						nameValueProperty.getPropertyValue()))) {
					mapField.put(nameValueProperty.getPropertyValue(),nameValueProperty.getPropertyName());
				}
			}

		}
		return mapField;
	}
    /**
     * @param nameValueProperties
     * @return list of pass through field
     */
    public List<String> getPassThroughFields(
			List<NameValueProperty> nameValueProperties)
			{
		List<String> passthroughField = new LinkedList<>();
		if (!nameValueProperties.isEmpty()) {

			for (NameValueProperty nameValueProperty : nameValueProperties) {
				if (nameValueProperty.getPropertyName().equals(
						nameValueProperty.getPropertyValue())) {
					passthroughField.add(nameValueProperty.getPropertyValue());
				}
			}

		}
		return passthroughField;
			}
	/**
	 * @param mappingSheetRow
	 * @return list of filter properties
	 */
	public List<FilterProperties> getOpeartionFields(MappingSheetRow mappingSheetRow) {
		List<FilterProperties> operationFields = new LinkedList<>();
		operationFields.addAll(mappingSheetRow.getOutputList());
		return operationFields;
	}

	/**
	 * @param transformMapping
	 * @param component
	 *
	 * populate input fields of mapping window
	 */
	public void getPropagatedSchema(TransformMapping transformMapping,Component component) {
		InputField inputField = null;
		transformMapping.getInputFields().clear();
		for (Link link : component.getTargetConnections()) {
			String sourceTerminalId=link.getSourceTerminal();
			List<BasicSchemaGridRow> basicSchemaGridRows=SchemaPropagationHelper.INSTANCE.
			getBasicSchemaGridRowList(Constants.INPUT_SOCKET_TYPE+getPortCount(sourceTerminalId)
					, link);
			if (basicSchemaGridRows != null){
				for (BasicSchemaGridRow row :basicSchemaGridRows ) {
					inputField = new InputField(row.getFieldName(), new ErrorObject(false, ""));
						transformMapping.getInputFields().add(inputField);
				}
			}
		}
	}
	/**
	 * @param transformMapping
	 *
	 * add expression output field to mapping window output fields
	 */
	public void addExpressionOutputFieldToOuterListOfMappingWindow(TransformMapping transformMapping)
	{
        	for(MappingSheetRow mappingSheetRow:transformMapping.getMappingSheetRows())
        	{
        		if(transformMapping.isExpression()&&mappingSheetRow.isExpression()&&mappingSheetRow.isActive())
        		{
        			transformMapping.getOutputFieldList().addAll(mappingSheetRow.getOutputList());
        		}
        	}
	}
	/**
	 * @param transformMapping
	 * add operation output fields to mapping window output fields
	 */
	public void addOperationOutputFieldToOuterListOfMappingWindow(TransformMapping transformMapping)
	{
    	for(MappingSheetRow mappingSheetRow:transformMapping.getMappingSheetRows())
    	{
    		if(!transformMapping.isExpression()&&!mappingSheetRow.isExpression()&&mappingSheetRow.isActive())
    		{
    			transformMapping.getOutputFieldList().addAll(mappingSheetRow.getOutputList());
    		}
    	}
    }
	/**
	 * @param transformMapping
	 * @param component
	 *
	 * create output fields of mapping window in case of import xml
	 */
	public void populateMappingOutputFieldIfTargetXmlImported(TransformMapping transformMapping,Component component)
	{
		if(!transformMapping.getMappingSheetRows().isEmpty())
		{
			List<MappingSheetRow> activeMappingSheetRow=TransformMappingFeatureUtility.INSTANCE.
					getActiveMappingSheetRow(transformMapping.getMappingSheetRows());
			if(activeMappingSheetRow.size()==transformMapping.getMappingSheetRows().size())
			{
				for(MappingSheetRow mappingSheetRow:transformMapping.getMappingSheetRows())
			 	{
					transformMapping.getOutputFieldList().addAll(mappingSheetRow.getOutputList());
			 	}
				if(!transformMapping.getMapAndPassthroughField().isEmpty()&&
			 			transformMapping.getMapAndPassthroughField().get(0).getFilterProperty()==null)
			 	{
			 		backwardJobComapatabilityCode(transformMapping);
			 	}
				for(NameValueProperty nameValueProperty:transformMapping.getMapAndPassthroughField())
			 	{
			 		transformMapping.getOutputFieldList().add(nameValueProperty.getFilterProperty());
			 	}
			 	List<FilterProperties> finalSortedList=SchemaSyncUtility.INSTANCE.
			 	sortOutputFieldToMatchSchemaSequence(OutputRecordCountUtility.INSTANCE.convertSchemaToFilterProperty(component),
			 			transformMapping);
			 	transformMapping.getOutputFieldList().clear();
			 	transformMapping.getOutputFieldList().addAll(finalSortedList);

			}

		}
		else if(!transformMapping.getMapAndPassthroughField().isEmpty()&&transformMapping.getOutputFieldList().isEmpty())
		{
			if(transformMapping.getMapAndPassthroughField().get(0).getFilterProperty()==null)
			{
			backwardJobComapatabilityCode(transformMapping);
			}
			for(NameValueProperty nameValueProperty:transformMapping.getMapAndPassthroughField())
		 	{
		 		transformMapping.getOutputFieldList().add(nameValueProperty.getFilterProperty());
		 	}
			List<FilterProperties> finalSortedList=SchemaSyncUtility.INSTANCE.
				 	sortOutputFieldToMatchSchemaSequence(OutputRecordCountUtility.INSTANCE.convertSchemaToFilterProperty(component),
				 			transformMapping);
				 	transformMapping.getOutputFieldList().clear();
				 	transformMapping.getOutputFieldList().addAll(finalSortedList);
		}
	}

	/**
	 * @param transformMapping
	 *
	 * remove expression output field from mapping output fields
	 */
	public void removeExpressionFieldFromOutputList(TransformMapping transformMapping)
	{
		for(MappingSheetRow mappingSheetRow:transformMapping.getMappingSheetRows())
		{
			if(!transformMapping.isExpression()&&mappingSheetRow.isExpression()&&mappingSheetRow.isActive())
			transformMapping.getOutputFieldList().removeAll(mappingSheetRow.getOutputList());
		}
	}

	/**
	 * @param transformMapping
	 *
	 * remove operation output fields from mapping output fields
	 */
	public void removeOperationFieldFromOutputList(TransformMapping transformMapping)
	{
		for(MappingSheetRow mappingSheetRow:transformMapping.getMappingSheetRows())
		{
			if(transformMapping.isExpression()&&!mappingSheetRow.isExpression()&&mappingSheetRow.isActive())
			transformMapping.getOutputFieldList().removeAll(mappingSheetRow.getOutputList());
		}
	}

	/**
	 * @param transformMapping
	 * @param schema
	 * @param component
	 * @param outputList
	 * @param operationFieldListOfString
	 *
	 * propagate output fields of mapping window to schema widget
	 */
	public void propagateOuputFieldsToSchemaTabFromTransformWidget(TransformMapping transformMapping,Schema schema,Component component,
			List<FilterProperties> outputList)
	{
    	if (transformMapping == null || transformMapping.getMappingSheetRows() == null){
			return;
    	}
    	schema.getGridRow().clear();
        List<String> finalPassThroughFields=new LinkedList<String>();
		Map<String, String> finalMapFields=new LinkedHashMap<String, String>();
        List<FilterProperties> operationFieldList=new LinkedList<FilterProperties>();
        for (MappingSheetRow mappingSheetRow : transformMapping.getMappingSheetRows()){
			List<FilterProperties> operationFields = OutputRecordCountUtility.INSTANCE.getOpeartionFields(mappingSheetRow);
         	operationFieldList.addAll(operationFields);
		    addOperationFieldsToSchema(operationFields,schema,component);
		}
		List<String> passThroughFields =getPassThroughFields(transformMapping.getMapAndPassthroughField());
		Map<String, String> mapFields = getMapFields(transformMapping.getMapAndPassthroughField());
		finalMapFields.putAll(mapFields);
		finalPassThroughFields.addAll(passThroughFields);
        addPassthroughFieldsToSchema(passThroughFields,schema,component);
		addMapFieldsToSchema(mapFields,schema,component);
        addPassthroughFieldsAndMappingFieldsToComponentOuputSchema(finalMapFields, finalPassThroughFields,component);
		if(!outputList.isEmpty())
		{
		 List<GridRow> sortedList=new ArrayList<>();
		 for(int i=0;i<outputList.size();i++)
		 {
			 GridRow gridRowTemp = null;
			 for(GridRow gridRow:schema.getGridRow())
			 {
				 if(StringUtils.equals(gridRow.getFieldName(), outputList.get(i).getPropertyname()))
				 {
					 gridRowTemp=gridRow;
					 break;
				 }

			 }
			 if(gridRowTemp!=null)
			 sortedList.add(gridRowTemp);
		 }
		 schema.getGridRow().clear();
		 schema.getGridRow().addAll(sortedList);
		 sortedList.clear();
		}
		else{
		schema.getGridRow().clear();
		}
	}
	/**
	 * @param transformMapping
	 *
	 * add pass through fields to mapping output field
	 */
	public void addPassThroughFieldsToSchema(TransformMapping transformMapping,Component component,Schema schema)
	{
		List<FilterProperties> outputList=new ArrayList<>();
		List<InputField> inputFieldList=transformMapping.getInputFields();
		for(InputField inputField:inputFieldList)
		{
			NameValueProperty nameValueProperty=new NameValueProperty();
			nameValueProperty.setPropertyName(inputField.getFieldName());
			nameValueProperty.setPropertyValue(inputField.getFieldName());
			nameValueProperty.getFilterProperty().setPropertyname(inputField.getFieldName());

			if(!transformMapping.getMapAndPassthroughField().contains(nameValueProperty))
			{
			transformMapping.getOutputFieldList().add(nameValueProperty.getFilterProperty());
			transformMapping.getMapAndPassthroughField().add(nameValueProperty);
			}

	     }
		updatePassThroughFieldAndOutputFields(transformMapping,component, transformMapping.getOutputFieldList());
		SchemaSyncUtility.INSTANCE.unionFilter(transformMapping.getOutputFieldList(),outputList);
		List<String> passthroughFields=getPassThroughFields(transformMapping.getMapAndPassthroughField());
		addPassthroughFieldsToSchema(passthroughFields, schema, component);
		updateComponentOutputSchemaAndSchema(component, schema);

	}

	private void updateComponentOutputSchemaAndSchema(Component component, Schema schema) {

		Map<String, ComponentsOutputSchema> schemaMap = (Map<String, ComponentsOutputSchema>) component.getProperties()
				.get(Constants.SCHEMA_TO_PROPAGATE);
		if (schemaMap != null && schemaMap.get(Constants.FIXED_OUTSOCKET_ID) != null) {
			ComponentsOutputSchema componentsOutputSchema = schemaMap.get(Constants.FIXED_OUTSOCKET_ID);
			componentsOutputSchema.setFixedWidthGridRowsOutputFields(new ArrayList<>());
			List<GridRow> gridRows = schema.getGridRow();
			for (GridRow gridRow : gridRows) {
				componentsOutputSchema.addSchemaFields(gridRow);
			}
		}

		component.getProperties().put(Constants.SCHEMA, schema);
	}

	// Removed pass through field according to new input.
	private void updatePassThroughFieldAndOutputFields(TransformMapping transformMapping, Component component, List<FilterProperties> outputLists) {

		List<NameValueProperty> mapAndPassthroughFields = transformMapping.getMapAndPassthroughField();
		Iterator<NameValueProperty> iterator = mapAndPassthroughFields.iterator();
		while (iterator.hasNext()) {
			NameValueProperty nameValueProperty = iterator.next();
			if (isPassThroughField(nameValueProperty) && !isPassThroughFieldPresentInInput(transformMapping, nameValueProperty)) {
				iterator.remove();
				outputLists.remove(nameValueProperty.getFilterProperty());
			}
		}

	}

	private boolean isPassThroughFieldPresentInInput(TransformMapping transformMapping,
			NameValueProperty nameValueProperty) {
		List<InputField> inputFields = transformMapping.getInputFields();
		boolean isFound = false;
		for (InputField inputField : inputFields) {
			if (inputField.getFieldName().equals(nameValueProperty.getPropertyName())) {
				isFound = true;
				break;
			}
		}
		return isFound;
	}

	private boolean isPassThroughField(NameValueProperty nameValueProperty) {
		if (nameValueProperty.getPropertyName().endsWith(nameValueProperty.getPropertyValue())) {
			return true;
		} else {
			return false;
		}
	}

}


text:
package com.spring.persistence.service.payment;

import com.spring.core.event.payment.*;

/**
 * @author vahid hosseinzadeh
 * @version 1.0
 * @since 1.0
 */

public interface PaymentPersistenceService {
    public AllPaymentsDetailsEvent requestAllPaymentsDetails(RequestAllPaymentsDetailsEvent event);

    public PaymentDetailsEvent requestPaymentDetails(RequestPaymentDetailsEvent event);

    public PaymentCreatedEvent createPayment(CreatePaymentEvent event);

    public PaymentUpdatedEvent updatePayment(UpdatePaymentEvent event);

    public PaymentDeletedEvent deletePayment(DeletePaymentEvent event);
}


text:
module App
  class Web < Sinatra::Base

    configure do
      set :root, "#{File.dirname(__FILE__)}/../"
      set :public_folder, "#{File.dirname(__FILE__)}/../../public"
      set :views, Proc.new { File.join(root, "views") }

      set :protection, :except => :frame_options
    end

    helpers do
      def current_user
        @current_user ||= User.get(session[:user_id]) if session[:user_id]
      end
    end

    use Rack::Session::Cookie, secret: "7898cb07b5dc3ed138840767d743b4aa"

    use OmniAuth::Builder do
      provider :facebook, '203597956466980','c85ffc4e033df8623470014c7a3be1d0', scope: "user_likes"
    end

    get '/' do
      if current_user
        erb :index
      else
        erb :login
      end
    end

    get '/auth/:name/callback' do

      auth = request.env["omniauth.auth"]
      user = User.first_or_create({ :uid => auth["uid"]}, {
        :uid => auth["uid"],
        :nickname => auth["info"]["nickname"],
        :image => auth["info"]["image"],
        :name => auth["info"]["name"],
        :token => auth["credentials"]["token"],
        :created_at => Time.now })
      session[:user_id] = user.id

      puts "Facebook:"
      puts facebook(user)
      puts "\n"
      puts "Deezer:"
      puts deezer(user)

      redirect '/'
    end

    # Facebook
    #
    def facebook(user)

      return if user.nil?

      data = RestClient.get("https://graph.facebook.com/#{user.uid}/music?access_token=#{user.token}")

      results = MultiJson.load(data.body)

      results["data"].each do |d|
        Artist.first_or_create({ name: d["name"], user_id: user.id})
      end

      return results["data"].size

    end

    # Deezer
    #
    def deezer(user)

      return if user.nil?

      artists = Artist.all(user_id: user.id)
      artists.each do |a|
        data = RestClient.get("http://api.deezer.com/2.0/search?q=#{CGI.escape(a.name)}")
        results = MultiJson.load(data.body)
        if (r = results["data"]).any?
          r.each do |s|
            Playlist.first_or_create({ user_id: user.id, link: s["preview"] }, {
              title: s["title"],
              artist_name: s["artist"]["name"],
              album_title: s["album"]["title"],
              album_cover: s["artist"]["cover"],
              duration: s["duration"]
            })
          end
        end
      end
      return "OK!"
    end

    get '/success' do
      erb :success
    end

    get '/auth/failure' do
      content_type 'application/json'
      MultiJson.encode(request.env)
    end

    get '/logout' do
      session[:user_id] = nil
      redirect "/"
    end

    get '/playing' do
      content_type 'application/json', :charset => 'utf-8'

      p = Playlist.first(playing: true)
      if p
        {
          title: p.title,
          artist_name: p.artist_name,
          album_title: p.album_title,
          album_cover: p.album_cover,
          duration: p.duration
        }.to_json
      else
        {}.to_json
      end
    end

  end
end


text:
module Activejob
  module Lock
    VERSION = "0.0.2"
  end
end


text:
package io.pebbletemplates.spring.extension;

import io.pebbletemplates.pebble.extension.AbstractExtension;
import io.pebbletemplates.pebble.extension.Function;
import io.pebbletemplates.spring.extension.function.HrefFunction;
import io.pebbletemplates.spring.extension.function.MessageSourceFunction;
import io.pebbletemplates.spring.extension.function.bindingresult.GetAllErrorsFunction;
import io.pebbletemplates.spring.extension.function.bindingresult.GetFieldErrorsFunction;
import io.pebbletemplates.spring.extension.function.bindingresult.GetGlobalErrorsFunction;
import io.pebbletemplates.spring.extension.function.bindingresult.HasErrorsFunction;
import io.pebbletemplates.spring.extension.function.bindingresult.HasFieldErrorsFunction;
import io.pebbletemplates.spring.extension.function.bindingresult.HasGlobalErrorsFunction;
import java.util.HashMap;
import java.util.Map;

import org.springframework.context.MessageSource;

/**
 * <p>
 * Extension for PebbleEngine to add spring functionality
 * </p>
 *
 * @author Eric Bussieres
 */
public class SpringExtension extends AbstractExtension {

  private final MessageSource messageSource;

  public SpringExtension(MessageSource messageSource) {
    this.messageSource = messageSource;
  }

  @Override
  public Map<String, Function> getFunctions() {
    Map<String, Function> functions = new HashMap<>();
    functions
        .put(MessageSourceFunction.FUNCTION_NAME, new MessageSourceFunction(this.messageSource));
    functions.put(HasErrorsFunction.FUNCTION_NAME, new HasErrorsFunction());
    functions.put(HasGlobalErrorsFunction.FUNCTION_NAME, new HasGlobalErrorsFunction());
    functions.put(HasFieldErrorsFunction.FUNCTION_NAME, new HasFieldErrorsFunction());
    functions.put(GetAllErrorsFunction.FUNCTION_NAME, new GetAllErrorsFunction(this.messageSource));
    functions.put(GetGlobalErrorsFunction.FUNCTION_NAME,
        new GetGlobalErrorsFunction(this.messageSource));
    functions
        .put(GetFieldErrorsFunction.FUNCTION_NAME, new GetFieldErrorsFunction(this.messageSource));
    functions.put(HrefFunction.FUNCTION_NAME, new HrefFunction());
    return functions;
  }
}


text:
package de.unima.peoplesearch.extraction;

import java.io.IOException;

public class ParallelPipeline extends Pipeline {

	private int numberOfWorker = 0;
	private int curr_link = 0;
	private int calledBackWorkers = 0;

	/**
	 * Initialize pipeline
	 * @param maxLinks
	 * @param numberOfWorker
	 */
	public ParallelPipeline(int maxLinks, int numberOfWorker, int NECHECKERTYPE,double threshold, int getRequestTimeOut) {
		super(maxLinks, NECHECKERTYPE, threshold, getRequestTimeOut);
		this.numberOfWorker = numberOfWorker;
	}

	public synchronized String getNextLink(){
		if(curr_link >= super.maxLinks) return null;
		if(curr_link >= links.size()) return null;
		String link = links.get(curr_link);
		curr_link++;
		notifyAll();
		return link;
	}

	public synchronized void callBack(){
		System.out.println("callback");
		calledBackWorkers++;
		System.out.println(calledBackWorkers +"---- "+ this.numberOfWorker);
		notifyAll();
	}

	@Override
	public void extractPeople() throws IOException, InterruptedException {
		for(int i = 0; i < numberOfWorker; i++){
			PersonExtractionTask pet = new PersonExtractionTask(this);
			pet.start();
		}
		boolean test1= false;
		//busy waiting for all workers
		while(calledBackWorkers < numberOfWorker){
			if(test1 == true){
				continue;
			}
			Thread.sleep(1000);
			System.out.println(curr_link);
		}
		System.out.println("Execute post processing steps");
	}

	public static void main(String args[]){

		ParallelPipeline pp = new ParallelPipeline(Integer.MAX_VALUE, 5,0,0.33,1000);

		try {
			pp.startExtraction();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: vidhey
 * Date: 15/4/16
 * Time: 8:09 PM
 */

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\models\ContactForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
?>

<?php $form = ActiveForm::begin(['id'=>'changeform']); ?>

<?= $form->field($model, 'current')->passwordInput() ?>

<?= $form->field($model, 'new')->passwordInput() ?>

<?= $form->field($model, 'confirm')->passwordInput() ?>

<div class="form-group">
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'submit-button']) ?>
</div>

<?php ActiveForm::end(); ?>


text:
package com.BeeFramework.view;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import java.io.*;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class AsyncImageLoader {

	private HashMap<String, SoftReference<Bitmap>> imageCache;

	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
	}

	/**
	 * 载入图片资源,如果缓存中不存在图片资源,则从本地加载,本地没有则从网络下载
	 *
	 * @param imageUrl
	 * @param imageCallback
	 * @param localPath 缓存到本地的图片
	 * @return
	 */
	public Bitmap loadDrawable(final String imageUrl,final String localPath,final ImageCallback imageCallback) {
		final String fileName = imageUrl.substring(imageUrl.lastIndexOf("/"));
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			Bitmap drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}
		File file = new File(localPath+fileName);
//		System.out.println("文件"+(localPath+fileName)+file.exists());
		if (file.exists()) {
			System.out.println("SD卡存在图片文件:"+file.getAbsolutePath());
			Bitmap drawable = BitmapFactory.decodeFile(localPath+fileName);
			imageCache.put(imageUrl, new SoftReference<Bitmap>(drawable));
			return drawable;
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				if (imageCallback != null) {
					imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
				}
			}
		};
		new Thread() {
			@Override
			public void run() {
				if (imageUrl != null) {
					String localFilePath = saveUrlAsFile(imageUrl,localPath);
					System.out.println("异步下载AsyncImageLoader*******"+imageUrl);
					System.out.println("异步下载AsyncImageLoader*******"+localPath);
					if(localFilePath!=null){
						Bitmap drawable = BitmapFactory.decodeFile(localPath+fileName);
						imageCache.put(imageUrl, new SoftReference<Bitmap>(drawable));
						Message msg = handler.obtainMessage(0, drawable);
						handler.sendMessage(msg);
					}else{
//						System.out.println("异步下载的图片为空!");
					}
//					Bitmap drawable = loadImageFromUrl(imageUrl);
//					imageCache.put(imageUrl,new SoftReference<Bitmap>(drawable));
//					Message msg = handler.obtainMessage(0, drawable);
//					handler.sendMessage(msg);
				}
			}
		}.start();
		return null;
	}

	public Bitmap loadImageFromUrl(String url) {
		URL m = null;
		InputStream i = null;
		BufferedInputStream bis = null;
		ByteArrayOutputStream out = null;
		Bitmap bitmap = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
			bis = new BufferedInputStream(i, 1024 * 8);
			out = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = bis.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			byte[] data = out.toByteArray();
			BitmapFactory.Options opts = new BitmapFactory.Options();
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
			out.close();
			bis.close();
			i.close();
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 把网络上的图片下载并存储到本地磁盘
	 * @param fileUrl
	 * @param savePath
	 * @return
	 */
	public static String saveUrlAsFile(String fileUrl, String savePath)/*fileUrl网络资源地址*/
    {
		String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
		File dir = new File(savePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File file = new File(savePath+fileName);
		if(!file.exists()){
			try {
				file.getParentFile().mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
         try
         {
            URL url = new URL(fileUrl);/*将网络资源地址传给,即赋值给url*/
            /*此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流*/
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            /*此处也可用BufferedInputStream与BufferedOutputStream*/
            DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
            /*将参数savePath,即将截取的图片的存储在本地地址赋值给out输出流所指定的地址*/
            byte[] buffer = new byte[4096];
            int count = 0;
            int num = 0;
            while ((count = in.read(buffer)) > 0)/*将输入流以字节的形式读取并写入buffer中*/
            {
            	num += count;
                out.write(buffer, 0, count);
            }
            out.close();/*后面三行为关闭输入输出流以及网络资源的固定格式*/
            in.close();
            connection.disconnect();
            if(num==0){
            	file.delete();
            	return null;
            }
            return savePath+fileName;/*网络资源截取并存储本地成功返回true*/
        }
        catch (Exception e)
        {
             System.out.println(e + fileUrl + savePath);
             return null;
        }
    }

	public Bitmap loadImageFromUrl2(String url) {
		URL m;
		InputStream i = null;
		BufferedInputStream bis = null;
		ByteArrayOutputStream out = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
			bis = new BufferedInputStream(i, 1024 * 8);
			out = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = bis.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			byte[] data = out.toByteArray();
			BitmapFactory.Options opts = new BitmapFactory.Options();

			Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			out.close();
			bis.close();
			i.close();
			// Drawable d = Drawable.createFromStream(i, "src");
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/***
	 * 从SD卡读取Android文件
	 *
	 * @param url
	 */
	public void loadImageFromSDCard(String url) {

	}

	public interface ImageCallback {
		public void imageLoaded(Bitmap imageDrawable, String imageUrl);
	}
}


text:
package net.sf.jasperreports.charts.fill;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.charts.JRTimePeriodDataset;
import net.sf.jasperreports.charts.JRTimePeriodSeries;
import net.sf.jasperreports.charts.util.TimePeriodDatasetLabelGenerator;
import net.sf.jasperreports.engine.JRChartDataset;
import net.sf.jasperreports.engine.JRExpressionCollector;
import net.sf.jasperreports.engine.JRPrintHyperlink;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.design.JRVerifier;
import net.sf.jasperreports.engine.fill.JRCalculator;
import net.sf.jasperreports.engine.fill.JRExpressionEvalException;
import net.sf.jasperreports.engine.fill.JRFillChartDataset;
import net.sf.jasperreports.engine.fill.JRFillObjectFactory;

import org.jfree.data.general.Dataset;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.time.TimePeriodValues;
import org.jfree.data.time.TimePeriodValuesCollection;

/**
 * @author Flavius Sana (flavius_sana@users.sourceforge.net)
 * @version $Id: JRFillTimePeriodDataset.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JRFillTimePeriodDataset extends JRFillChartDataset implements JRTimePeriodDataset
{

	/**
	 *
	 */
	protected JRFillTimePeriodSeries[] timePeriodSeries;

	private List<Comparable<?>> seriesNames;
	private Map<Comparable<?>, TimePeriodValues> seriesMap;
	private Map<Comparable<?>, Map<TimePeriod, String>> labelsMap;
	private Map<Comparable<?>, Map<TimePeriod, JRPrintHyperlink>> itemHyperlinks;

	/**
	 *
	 */
	public JRFillTimePeriodDataset(
		JRTimePeriodDataset timePeriodDataset,
		JRFillObjectFactory factory
		)
	{
		super(timePeriodDataset, factory);

		JRTimePeriodSeries[] srcTimePeriodSeries = timePeriodDataset.getSeries();
		if (srcTimePeriodSeries != null && srcTimePeriodSeries.length > 0)
		{
			timePeriodSeries = new JRFillTimePeriodSeries[srcTimePeriodSeries.length];
			for (int i = 0; i < timePeriodSeries.length; i++)
			{
				timePeriodSeries[i] =
					(JRFillTimePeriodSeries)factory.getTimePeriodSeries(srcTimePeriodSeries[i]);
			}
		}
	}

	public JRTimePeriodSeries[] getSeries()
	{
		return timePeriodSeries;
	}

	protected void customInitialize()
	{
		seriesNames = null;
		seriesMap = null;
		labelsMap = null;
		itemHyperlinks = null;
	}

	protected void customEvaluate(JRCalculator calculator)
			throws JRExpressionEvalException
	{
		if (timePeriodSeries != null && timePeriodSeries.length > 0)
		{
			for (int i = 0; i < timePeriodSeries.length; i++)
			{
				timePeriodSeries[i].evaluate(calculator);
			}
		}
	}

	protected void customIncrement()
	{
		if (timePeriodSeries != null && timePeriodSeries.length > 0)
		{
			if (seriesNames == null)
			{
				seriesNames = new ArrayList<Comparable<?>>();
				seriesMap = new HashMap<Comparable<?>, TimePeriodValues>();
				labelsMap = new HashMap<Comparable<?>, Map<TimePeriod, String>>();
				itemHyperlinks = new HashMap<Comparable<?>, Map<TimePeriod, JRPrintHyperlink>>();
			}

			for (int i = 0; i < timePeriodSeries.length; i++)
			{
				JRFillTimePeriodSeries crtTimePeriodSeries = timePeriodSeries[i];

				Comparable<?> seriesName = crtTimePeriodSeries.getSeries();
				if (seriesName == null)
				{
					throw new JRRuntimeException("Time period series name is null.");
				}

				TimePeriodValues timePeriodValues = seriesMap.get(seriesName);
				if (timePeriodValues == null)
				{
					timePeriodValues = new TimePeriodValues(seriesName.toString());
					seriesNames.add(seriesName);
					seriesMap.put(seriesName, timePeriodValues);
				}

				SimpleTimePeriod stp =
					new SimpleTimePeriod(
						crtTimePeriodSeries.getStartDate(),
						crtTimePeriodSeries.getEndDate()
						);

				timePeriodValues.add(stp, crtTimePeriodSeries.getValue());

				if (crtTimePeriodSeries.getLabelExpression() != null)
				{
					Map<TimePeriod, String> seriesLabels = labelsMap.get(seriesName);
					if (seriesLabels == null)
					{
						seriesLabels = new HashMap<TimePeriod, String>();
						labelsMap.put(seriesName, seriesLabels);
					}

					seriesLabels.put(stp, crtTimePeriodSeries.getLabel());
				}

				if (crtTimePeriodSeries.hasItemHyperlink())
				{
					Map<TimePeriod, JRPrintHyperlink> seriesLinks = itemHyperlinks.get(seriesName);
					if (seriesLinks == null)
					{
						seriesLinks = new HashMap<TimePeriod, JRPrintHyperlink>();
						itemHyperlinks.put(seriesName, seriesLinks);
					}

					seriesLinks.put(stp, crtTimePeriodSeries.getPrintItemHyperlink());
				}
			}
		}
	}

	public Dataset getCustomDataset()
	{
		TimePeriodValuesCollection dataset = new TimePeriodValuesCollection();
		if (seriesNames != null)
		{
			for(int i = 0; i < seriesNames.size(); i++)
			{
				Comparable<?> seriesName = seriesNames.get(i);
				dataset.addSeries(seriesMap.get(seriesName));
			}
		}
		return dataset;
	}

	/**
	 *
	 */
	public byte getDatasetType()
	{
		return JRChartDataset.TIMEPERIOD_DATASET;
	}

	/**
	 *
	 */
	public Object getLabelGenerator()
	{
		return new TimePeriodDatasetLabelGenerator(labelsMap);
	}

	/**
	 *
	 */
	public void collectExpressions(JRExpressionCollector collector)
	{
		collector.collect(this);
	}

	public boolean hasItemHyperlinks()
	{
		boolean foundLinks = false;
		if (timePeriodSeries != null && timePeriodSeries.length > 0)
		{
			for (int i = 0; i < timePeriodSeries.length && !foundLinks; i++)
			{
				foundLinks = timePeriodSeries[i].hasItemHyperlink();
			}
		}
		return foundLinks;
	}

	public Map<Comparable<?>, Map<TimePeriod, JRPrintHyperlink>> getItemHyperlinks()
	{
		return itemHyperlinks;
	}

	public void validate(JRVerifier verifier)
	{
		verifier.verify(this);
	}

}


text:
import urllib.request as request
import json
import datetime
import platform
from django.http import HttpResponse

API_KEY = 'AIzaSyAd1WmhQs7jNW__qAszJSsKJVaayQv_Tsc'

# get iss position
def iss_position():
    iss_api_url = 'http://api.open-notify.org/iss-now.json'
    try:
        with request.urlopen(iss_api_url) as url:
            response = url.read()
        obj = json.loads(response.decode('utf-8'))
        return obj['iss_position']['latitude'], obj['iss_position']['longitude']
    except:
        return '40.714224', '-73.961452'  # for test

# get geo location
def geo_location(lat, lng):
    (lat, lng) = '40.714224', '-73.961452'  # for test
    geo_api_url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s' % (lat, lng, API_KEY)
    try:
        with request.urlopen(geo_api_url) as url:
            response = url.read()
        obj = json.loads(response.decode('utf-8'))
        return obj['results'][0]['formatted_address']
    except:
        return 'NO_RESULTS'

# get weather
def weather_forecast():
    #yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Tokyo, jp")'.encode()
    yql_query = 'select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Tokyo%2C%20jp%22)'
    weather_api_url = 'https://query.yahooapis.com/v1/public/yql?q=%s&format=json' % yql_query
    try:
        with request.urlopen(weather_api_url) as url:
            response = url.read()
        obj = json.loads(response.decode('utf-8'))
        return obj['query']['results']['channel']['item']['forecast']
    except:
        return 'NO_RESULTS'

# show my dashboard
def my_dashboard(request):
    html = '
My Dashboard

'

    html += '
Dashboard: System Information
'
    html += 'Now: %s
' % datetime.datetime.now()
    html += 'Platform: %s
' % platform.platform()
    html += 'Version: %s
' % platform.version()
    html += 'Processor: %s
' % platform.processor()

    weathers = weather_forecast()
    html += '
Dashboard: Weather Forecast (Tokyo, JP)
'
    for weather in weathers:
        html += '[%s]: %s
' % (weather['date'], weather['text'])

    (latitude, longitude) = iss_position()
    location = geo_location(latitude, longitude)
    html += '
Dashboard: ISS Location
'
    html += 'The International Space Station is currently over
'
    html += '| Address: %s
| Geocode: %s, %s' % (location, latitude, longitude)

    html += ''

    return HttpResponse(html)


text:
django-responsive-images
========================

Provides responsive image generation in Django.

Getting Started
===============

This project has a dependancy on [etianen/django-optimizations](https://github.com/etianen/django-optimizations) which handles the actual image resizing and jQuery for the front-end image selection.  You will need to add a few configuation lines to your settings file. You can add as many images sizes as you like.

```
RESPONSIVE_IMAGES_SIZES = [
    {
        "width": 1440,
        "height": 810
    },
    {
        "width": 1280,
        "height": 720
    },
    {
        "width": 1024,
        "height": 576
    },
    {
        "width": 768,
        "height": 432
    },
    {
        "width": 480,
        "height": 270
    }
]

```

You will also need to add 'responsive_images' to your INSTALLED_APPS and load the Javascript file into your template.

To actually make your images responsive you will need to import the supplied templatetag and use it as follows:

```
{% load responsive_images %}

{% responsive_img project.image.file method="crop" %}
```

When the page loads it will perform all of the resizes and pass them into a data- attribute on the image tag, the Javascript code will then select the best image size for the given container size.