text:
package com.intellij.spellchecker.compress;

import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.spellchecker.DefaultBundledDictionariesProvider;
import com.intellij.spellchecker.StreamLoader;
import com.intellij.spellchecker.dictionary.Dictionary;
import com.intellij.spellchecker.dictionary.Loader;
import com.intellij.spellchecker.engine.Transformation;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.Consumer;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Set;

import static com.intellij.openapi.util.Pair.pair;
import static org.junit.Assert.*;

public class DictionaryTest {
  private static final String JETBRAINS_DIC = "jetbrains.dic";
  private static final String ENGLISH_DIC = "english.dic";

  private final Transformation myTransformation = new Transformation();

  @Test
  public void testJBDictionaryPerformance() {
    Dictionary dictionary = loadDictionaryPerformanceTest(JETBRAINS_DIC, 10);
    containsWordPerformanceTest(dictionary, 5);
    containsWordTest(dictionary);
  }

  @Test
  public void testEnglishDictionaryPerformance() {
    Dictionary dictionary = loadDictionaryPerformanceTest(ENGLISH_DIC, 500);
    containsWordPerformanceTest(dictionary, 200);
    containsWordTest(dictionary);
  }

  @Test
  public void testDictionaryLoadedFully() {
    final Set<String> onDisk = new THashSet<>();
    getLoader(JETBRAINS_DIC).load(s -> {
      assertNotNull(s);
      String t = myTransformation.transform(s);
      if (t != null) {
        onDisk.add(t);
      }
    });

    Dictionary dictionary = CompressedDictionary.create(getLoader(JETBRAINS_DIC), myTransformation);

    assertEquals(onDisk, dictionary.getWords());
  }

  @Test
  public void testGetSuggestions(){
    final ArrayList<String> suggestions = new ArrayList<>();
    Dictionary dictionary = CompressedDictionary.create(getLoader(ENGLISH_DIC), myTransformation);
    dictionary.getSuggestions("typpo",suggestions::add);
    assert suggestions.contains("typo");
    assert suggestions.stream().anyMatch(a -> a.charAt(0) == 't');
  }

  @Test
  public void testNoSuggestions(){
    final ArrayList<String> suggestions = new ArrayList<>();
    Dictionary dictionary = CompressedDictionary.create(getLoader(ENGLISH_DIC), myTransformation);
    dictionary.getSuggestions("руссский",suggestions::add);
    assert suggestions.isEmpty();
  }

  private Dictionary loadDictionaryPerformanceTest(final String name, int time) {
    final Ref<Dictionary> ref = Ref.create();

    PlatformTestUtil.startPerformanceTest(
      "load dictionary", time, () -> ref.set(CompressedDictionary.create(getLoader(name), myTransformation))
    ).assertTiming();

    assertFalse(ref.isNull());
    return ref.get();
  }

  private void containsWordPerformanceTest(final Dictionary dictionary, int time) {
    final Set<String> wordsToCheck = createWordSets(dictionary, 50000, 1).first;
    PlatformTestUtil.startPerformanceTest("contains word", time, () -> {
      for (String s : wordsToCheck) {
        assertEquals(Boolean.TRUE, dictionary.contains(s));
      }
    }).assertTiming();
  }

  private void containsWordTest(Dictionary dictionary) {
    Pair<Set<String>, Set<String>> sets = createWordSets(dictionary, 50000, 2);
    CompressedDictionary half = CompressedDictionary.create(new TestLoader(sets.first), myTransformation);
    for (String s : sets.second) {
      if (!sets.first.contains(s)) {
        assertEquals(s, Boolean.FALSE, half.contains(s));
      }
    }
  }

  private static StreamLoader getLoader(@NotNull String name) {
    return new StreamLoader(DefaultBundledDictionariesProvider.class.getResourceAsStream(name), name);
  }

  private Pair<Set<String>, Set<String>> createWordSets(Dictionary dictionary, int maxCount, int mod) {
    Set<String> wordsToStore = new THashSet<>();
    Set<String> wordsToCheck = new THashSet<>();

    Set<String> words = dictionary.getWords();
    assertNotNull(words);
    int counter = 0;
    for (String s : words) {
      String transformed = myTransformation.transform(s);
      if (transformed != null) {
        (counter % mod == 0 ? wordsToStore : wordsToCheck).add(transformed);
        if (++counter > maxCount) break;
      }
    }

    return pair(wordsToStore, wordsToCheck);
  }

  private static class TestLoader implements Loader {
    private final Set<String> myWords;

    TestLoader(Set<String> words) {
      myWords = words;
    }

    @Override
    public void load(@NotNull Consumer<String> consumer) {
      for (String word : myWords) {
        consumer.consume(word);
      }
    }

    @Override
    public String getName() {
      return "test";
    }
  }
}


text:
<manifest package="com.andremion.floatingnavigationview">

    <application />

</manifest>

redpajama_set_name: RedPajamaGithub


text:
function [vert, textureCoord, vnormals, faces] = stereoReproject(texIm)
%this function will return mesh elements for the PSITRES stereo system
%aboard the RV Polarster. It uses the mean stereo plane and generates the
%mesh parametrically. It takes an input image from the camera system to so
%it can use the right size. It returns a set of vertices, corresponding texture
%coordinates, vertex normals, and faces. It is set up to be able to be
%written to an obj file.
load('Ark27params')
load('meanPlane')

camMat = params.calib_params.left.A;
R = eye(3);
[height,width,~] = size(texIm);
xskip=50;
yskip = 50;
index = 0;
scale = 1/1000; % to convert to meters

for xi = 1:xskip:width %the full image in x direction
    for yi =1:yskip:height  % the full image in y direction
        %calculating vertex Location
        index = index + 1;

        rayDir = getCameraRay(camMat',R,[xi,yi]);
        intersectionPoint = planeIntersect(meanCentroid,meanPlaneNorm',[0,0,0],rayDir);
        vert(index,:)=scale*intersectionPoint.*[-1,-1,-1];

        %texture coordinates
        textureCoord(index,:) = [1-xi/width,1-yi/height];

        %vertex normals
        vnorm = [meanPlaneNorm];
        vnormals(index,:) = (vnorm/norm(vnorm));

    end
end
meshInd = 0;
ySteps = numel(1:yskip:height);
xSteps = numel(1:xskip:height);

%generating faces
%upper triangular meshes
for x = 1:(xSteps-1)
    for y = 1:(ySteps-1);
        meshInd = meshInd + 1;
        ind1 = y + (ySteps*(x-1));
        ind2 = ind1 + 1;
        ind3 = ind1 + ySteps + 1;
        faces(meshInd,:)=[ind1,ind2,ind3];
    end
end

%lower triangular meshes
for x = 1:(xSteps-1)
    for y = 1:(ySteps-1);
        meshInd = meshInd + 1;
        ind1 = y + (ySteps*(x-1));
        ind2 = ind1 + ySteps + 1;
        ind3 = ind1 + ySteps;
        faces(meshInd,:)=[ind1,ind2,ind3];
    end
end

load('PSITREStransform.mat')
outVert = rotmat*vert';
outNorms = rotmat*vnormals';
vnormals = outNorms';

repTrans =repmat(psitresTranslation',1,size(outVert,2));
outVert = outVert + repTrans;
vert = outVert';
end


text:
package org.apache.geode.internal.statistics;

import java.io.File;
import java.util.Optional;

import org.apache.geode.logging.internal.spi.LogFile;

/**
 * Defines the contract enabling the {@link StatArchiveHandler} to retrieve configuration details
 * (some of which may change at runtime).
 *
 *

 * Implemented by {@link HostStatSampler}.
 *
 *

 * Note: This interface changes the return types of file limit properties from int to long so that
 * the Stat Sampler tests can change the units from MB to KB.
 *
 * @since GemFire 7.0
 */
public interface StatArchiveHandlerConfig {

  /**
   * Gets the name of the archive file.
   */
  File getArchiveFileName();

  /**
   * Gets the archive size limit in bytes.
   */
  long getArchiveFileSizeLimit();

  /**
   * Gets the archive disk space limit in bytes.
   */
  long getArchiveDiskSpaceLimit();

  /**
   * Returns a unique id for the sampler's system.
   */
  long getSystemId();

  /**
   * Returns the time this sampler's system was started.
   */
  long getSystemStartTime();

  /**
   * Returns the path to this sampler's system directory; if it has one.
   */
  String getSystemDirectoryPath();

  /**
   * Returns a description of the product that the stats are on
   */
  String getProductDescription();

  /**
   * Returns the log file to provide info about main id and child id.
   */
  Optional<LogFile> getLogFile();
}


text:
package jadx.core.dex.trycatch;

import java.util.*;

import jadx.core.*;
import jadx.core.dex.info.*;
import jadx.core.dex.instructions.args.*;
import jadx.core.dex.nodes.*;
import jadx.core.utils.*;

public class ExceptionHandler {

	private final ClassInfo catchType;
	private final int handleOffset;

	private BlockNode handlerBlock;
	private final List<BlockNode> blocks = new ArrayList<BlockNode>();
	private IContainer handlerRegion;
	private InsnArg arg;

	private TryCatchBlock tryBlock;
	private boolean isFinally;

	public ExceptionHandler(int addr, ClassInfo type) {
		this.handleOffset = addr;
		this.catchType = type;
	}

	public ClassInfo getCatchType() {
		return catchType;
	}

	public boolean isCatchAll() {
		return catchType == null || catchType.getFullName().equals(Consts.CLASS_THROWABLE);
	}

	public int getHandleOffset() {
		return handleOffset;
	}

	public BlockNode getHandlerBlock() {
		return handlerBlock;
	}

	public void setHandlerBlock(BlockNode handlerBlock) {
		this.handlerBlock = handlerBlock;
	}

	public List<BlockNode> getBlocks() {
		return blocks;
	}

	public void addBlock(BlockNode node) {
		blocks.add(node);
	}

	public IContainer getHandlerRegion() {
		return handlerRegion;
	}

	public void setHandlerRegion(IContainer handlerRegion) {
		this.handlerRegion = handlerRegion;
	}

	public InsnArg getArg() {
		return arg;
	}

	public void setArg(InsnArg arg) {
		this.arg = arg;
	}

	public void setTryBlock(TryCatchBlock tryBlock) {
		this.tryBlock = tryBlock;
	}

	public TryCatchBlock getTryBlock() {
		return tryBlock;
	}

	public boolean isFinally() {
		return isFinally;
	}

	public void setFinally(boolean isFinally) {
		this.isFinally = isFinally;
	}

	@Override
	public int hashCode() {
		return (catchType == null ? 0 : 31 * catchType.hashCode()) + handleOffset;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		ExceptionHandler other = (ExceptionHandler) obj;
		if (catchType == null) {
			if (other.catchType != null) {
				return false;
			}
		} else if (!catchType.equals(other.catchType)) {
			return false;
		}
		return handleOffset == other.handleOffset;
	}

	@Override
	public String toString() {
		return (catchType == null ? "all"
				: catchType.getShortName()) + " -> " + InsnUtils.formatOffset(handleOffset);
	}

}


text:
DemLocator is a Javascript library for geolocating website visitors using HTML5
browser geolocation (especially useful on mobile devices w/ GPS) but adds a
transparent fallback to IP geolocation when HTML5 isn't available or fails.

It depends on Google's AJAX & Maps APIs. Include them before you include
demlocator.js. It uses the ClientLocation API for IP-based geolocation and
the Maps API for getting country, city, state, etc. information.

## WORDS TO THE WISE

Be aware that most browsers don't know where they are. And
IP-based geolocation is even worse. Some IPs have no geographic data associated
with them at all, and the computer holding the address might not be that close
to that location even when they do. The person using the computer could also be
halfway around the world using it remotely. You just never know.

Unless you get a fix from a GPS-equipped device, you shouldn't rely on this
information for anything important (and maybe not even then, see above). For
example, we at the DNC use it to make an educated guess and hopefully shortcut
people to the right information for their area. But we still ask them for their
address and ZIP code and only rely on their location data once we have that.

## Usage Example

Here's an example (put this in the <head> section of your HTML & insert your
Google API key where appropriate):

    <script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=[YOUR_GOOGLE_API_KEY_GOES_HERE]"></script>
    <script type="text/javascript" src="http://www.google.com/jsapi?key=[YOUR_GOOGLE_API_KEY_GOES_HERE]"></script>
    <script type="text/javascript" src="/path/to/demlocator.js"></script>

Then, using jQuery, you can do this to call it when the document is ready:
    <script type="text/javascript">

      // success callback
      function handle_demlocator_success(result) {
        if (result.country && result.country == 'US') {
          console.log("You might be in " + result.state + ", USA!");
        }
      }

      // error callback
      function handle_demlocator_error(error) {
        console.log("DemLocator failed. Sorry.");
      }

      // kick the whole thing off
      $(document).ready(function() {
        var locator = new DemLocator();
        locator.getLocation(handle_demlocator_success, handle_demlocator_error);
      });

    </script>

And that should be it.

## Testing

If you have SpiderMonkey installed (Mozilla's Javascript engine which can be
installed as a standalone executable), then you can run the included test
suite:

    js test.js

## Github, FTW.

Fork the project here: [http://github.com/dnclabs/demlocator](http://github.com/dnclabs/demlocator)

Report bugs here: [http://github.com/dnclabs/demlocator/issues](http://github.com/dnclabs/demlocator/issues)

Have fun storming the castle!


text:
define([
    "geometria/GDictionary",
    "geometria/GMainContainer",
    "geometria/GNavigator",
    "geometria/GWidgets"
], function(dict, mainContainer, navigator, widgets) {

    return {

        icon: "geometriaIcon24 geometriaIcon24RenameFile",

        label: dict.get("action.RenameFile"),

        execute: function() {
            var onSuccess = function(item) {
                if (mainContainer.currentDocument.navigatorItemId == item.id) {
                    window.document.title = "Geometria: " + item.name;
                }
            };

            var onError = function(message) {
                widgets.errorDialog(message);
            };

            navigator.rename().then(onSuccess, onError);
        },

        updateState: function() {
            this.base.enabled = !mainContainer.readOnly && navigator.isSelectedItemRemovable();
        },

        tooltip: function() {
            return mainContainer.readOnly ? dict.get("ReadOnly") : "";
        }
    };
});


text:
title: Bag of words
category: Machine Learning, NLP
---

* Bag-of-words [BoW] (*sac de mots* en français), aussi appelé modèle *unigramme*, est un modèle linguistique basé sur le comptage des mots — le nombre de fois qu'ils apparaissent. Il est donc très simple mais a de nombreux cas d'utilisation, comme

  * déterminer les thèmes d'une chanson
  * filtrer les spams dans une boîte mail
  * déterminer si un avis client est positif ou négatif
  * créer un nuage de mot

* Il y a deux manières d'implémenter un BoW:

  1. Utiliser un dictionnaire
     Chaque mot du document est associé au nombre de fois qu'il apparaît.

     ![](https://i.imgur.com/Nv5w7ak.png)

  2. Utiliser un vecteur
     Créer un dictionnaire des caractéristiques (*feature dictionary*) à partir de l'ensemble des documents. Chaque mot est assigné à un index. Puis pour chaque document, créer un vecteur qui enregistre le nombre d'occurences des mots du document à l'index du dictionnaire des caractéristiques.

     ![](https://i.imgur.com/9dYzqzS.png)

* On peut ensuite comparer les vecteurs BoW avec d'autres vecteurs BoW pour les classifier — par exemple avec un algorithme de Naive Bayes.

* Et on peut représenter une phrase comme la somme des vecteurs one-hot encodés.

  ![](https://i.imgur.com/Q78r5iEm.png)

[Bag Of Words.ipynb](notebooks/Bag Of Words.html)


text:
require 'english/inflect'

English::Inflect.word 'postgres'

module DataMapper
  module Inflection
    class << self
      # Take an underscored name and make it into a camelized name
      #
      # Examples
      #   "egg_and_hams".classify #=> "EggAndHam"
      #   "post".classify #=> "Post"
      #
      def classify(name)
        camelize(singularize(name.to_s.sub(/.*\./, '')))
      end

      # By default, camelize converts strings to UpperCamelCase.
      #
      # camelize will also convert '/' to '::' which is useful for converting paths to namespaces
      #
      # Examples
      #   "active_record".camelize #=> "ActiveRecord"
      #   "active_record/errors".camelize #=> "ActiveRecord::Errors"
      #
      def camelize(lower_case_and_underscored_word, *args)
        lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
      end

      # The reverse of +camelize+. Makes an underscored form from the expression in the string.
      #
      # Changes '::' to '/' to convert namespaces to paths.
      #
      # Examples
      #   "ActiveRecord".underscore #=> "active_record"
      #   "ActiveRecord::Errors".underscore #=> active_record/errors
      #
      def underscore(camel_cased_word)
        camel_cased_word.to_s.gsub(/::/, '/').
          gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
          gsub(/([a-z\d])([A-Z])/,'\1_\2').
          tr("-", "_").
          downcase
      end

      # Capitalizes the first word and turns underscores into spaces and strips _id.
      # Like titleize, this is meant for creating pretty output.
      #
      # Examples
      #   "employee_salary" #=> "Employee salary"
      #   "author_id" #=> "Author"
      #
      def humanize(lower_case_and_underscored_word)
        lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
      end

      # Removes the module part from the expression in the string
      #
      # Examples
      #   "ActiveRecord::CoreExtensions::String::Inflections".demodulize #=> "Inflections"
      #   "Inflections".demodulize #=> "Inflections"
      def demodulize(class_name_in_module)
        class_name_in_module.to_s.gsub(/^.*::/, '')
      end

      # Create the name of a table like Rails does for models to table names. This method
      # uses the pluralize method on the last word in the string.
      #
      # Examples
      #   "RawScaledScorer".tableize #=> "raw_scaled_scorers"
      #   "egg_and_ham".tableize #=> "egg_and_hams"
      #   "fancyCategory".tableize #=> "fancy_categories"
      def tableize(class_name)
        pluralize(underscore(class_name))
      end

      # Creates a foreign key name from a class name.
      #
      # Examples
      #   "Message".foreign_key #=> "message_id"
      #   "Admin::Post".foreign_key #=> "post_id"
      def foreign_key(class_name, key = "id")
        underscore(demodulize(class_name.to_s)) << "_" << key.to_s
      end

      # Constantize tries to find a declared constant with the name specified
      # in the string. It raises a NameError when the name is not in CamelCase
      # or is not initialized.
      #
      # Examples
      #   "Module".constantize #=> Module
      #   "Class".constantize #=> Class
      def constantize(camel_cased_word)
        unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
          raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
        end

        Object.module_eval("::#{$1}", __FILE__, __LINE__)
      end

      # The reverse of pluralize, returns the singular form of a word in a string.
      # Wraps the English gem
      # Examples
      #   "posts".singularize #=> "post"
      #   "octopi".singularize #=> "octopus"
      #   "sheep".singluarize #=> "sheep"
      #   "word".singluarize #=> "word"
      #   "the blue mailmen".singularize #=> "the blue mailman"
      #   "CamelOctopi".singularize #=> "CamelOctopus"
      #
      def singularize(word)
        word.singular
      end

      # Returns the plural form of the word in the string.
      #
      # Examples
      #   "post".pluralize #=> "posts"
      #   "octopus".pluralize #=> "octopi"
      #   "sheep".pluralize #=> "sheep"
      #   "words".pluralize #=> "words"
      #   "the blue mailman".pluralize #=> "the blue mailmen"
      #   "CamelOctopus".pluralize #=> "CamelOctopi"
      #
      def pluralize(word)
        word.plural
      end

    end
  end # module Inflection
end # module DataMapper


text:
package com.jpventura.alexandria;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jpventura.alexandria.data.AlexandriaContract;
import com.jpventura.alexandria.services.BookService;
import com.jpventura.alexandria.services.DownloadImage;

public class BookDetail extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    public static final String EAN_KEY = "EAN";
    private final int LOADER_ID = 10;
    private View rootView;
    private String ean;
    private String bookTitle;
    private ShareActionProvider shareActionProvider;

    public BookDetail(){
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Bundle arguments = getArguments();
        if (arguments != null) {
            ean = arguments.getString(BookDetail.EAN_KEY);
            getLoaderManager().restartLoader(LOADER_ID, null, this);
        }

        rootView = inflater.inflate(R.layout.fragment_full_book, container, false);
        rootView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent bookIntent = new Intent(getActivity(), BookService.class);
                bookIntent.putExtra(BookService.EAN, ean);
                bookIntent.setAction(BookService.DELETE_BOOK);
                getActivity().startService(bookIntent);
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.book_detail, menu);

        MenuItem menuItem = menu.findItem(R.id.action_share);
        shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
    }

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(
                getActivity(),
                AlexandriaContract.BookEntry.buildFullBookUri(Long.parseLong(ean)),
                null,
                null,
                null,
                null
        );
    }

    @Override
    public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
        if (!data.moveToFirst()) {
            return;
        }

        bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
        ((TextView) rootView.findViewById(R.id.fullBookTitle)).setText(bookTitle);

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_text)+bookTitle);
        shareActionProvider.setShareIntent(shareIntent);

        String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
        ((TextView) rootView.findViewById(R.id.fullBookSubTitle)).setText(bookSubTitle);

        String desc = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.DESC));
        ((TextView) rootView.findViewById(R.id.fullBookDesc)).setText(desc);

        String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
        String[] authorsArr = authors.split(",");
        ((TextView) rootView.findViewById(R.id.authors)).setLines(authorsArr.length);
        ((TextView) rootView.findViewById(R.id.authors)).setText(authors.replace(",","\n"));
        String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
        if(Patterns.WEB_URL.matcher(imgUrl).matches()){
            new DownloadImage((ImageView) rootView.findViewById(R.id.fullBookCover)).execute(imgUrl);
            rootView.findViewById(R.id.fullBookCover).setVisibility(View.VISIBLE);
        }

        String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
        ((TextView) rootView.findViewById(R.id.categories)).setText(categories);

        if(rootView.findViewById(R.id.right_container)!=null){
            rootView.findViewById(R.id.backButton).setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {

    }

    @Override
    public void onPause() {
        super.onDestroyView();
        if(MainActivity.IS_TABLET && rootView.findViewById(R.id.right_container)==null){
            getActivity().getSupportFragmentManager().popBackStack();
        }
    }
}


text:
package mypackage

import (
	"fmt"
)

func myFunc() {
	fmt.Println(T("And the entire human race"))
	fmt.Println("Tomatoes")
}


text:
<!DOCTYPE html>

    <title>Status Enumeration Reference</title>
    <link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
    <meta charset="utf-8">

           Docs

         (37% documented)

        <form role="search" action="../../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

       Reference

      Status Enumeration Reference

            JenkinsiOS Other

                Constants

                – Defaults

                – Paths

                – Config

                – UI

                – Identifiers

                – JSON

                – Networking

                – API

            JenkinsiOS Utils

                PersistenceUtils

            JenkinsiOS Controller

                ParametersViewControllerDelegate

            JenkinsiOS Model

                ApplicationUser

                Favoratible

                UserRequest

                Favorite

                – FavoriteType

                Account

            JenkinsiOS Model JenkinsAPI

                JenkinsColor

            JenkinsiOS Model JenkinsAPI Plugin

                Dependency

                PluginList

                Plugin

            JenkinsiOS Model JenkinsAPI TestResult

                TestResult

                Suite

                Result

                Child

                Case

                – Status

                ChildReport

            JenkinsiOS Model JenkinsAPI User

                User

                Project

                UserList

            JenkinsiOS Model JenkinsAPI Job

                View

                JobListResult

                Parameter

                ParameterValue

                ParameterType

                JobListQuietingDown

                JobList

                HealthReportResult

                Job

            JenkinsiOS Model JenkinsAPI BuildQueue

                BuildQueue

                QueueItem

            JenkinsiOS Model JenkinsAPI Build

                Item

                Cause

                Author

                Build

                ChangeSet

                Actions

                Artifact

            JenkinsiOS Model JenkinsAPI Computer

                ComputerList

                MonitorData

                Computer

            JenkinsiOS View

                JobTableViewCell

            JenkinsiOS Service

                LoggingManager

                JenkinsAction

                NetworkManager

                – HTTPMethod

                AccountManager

                NetworkActivityIndicatorManager

                URLSessionTaskController

                ApplicationUserManager

                LoggableContentView

            JenkinsiOSTodayExtension

                TodayViewController

                DataRetriever

                FavoriteTableViewCell

            Other Enumerations

                ANSIColor

                AccountManagerError

                BuildError

                NetworkManagerError

                ParsingError

            Other Extensions

                Bool

                Dictionary

                Double

                Int

                NSNumber

                Optional

                String

                TimeInterval

                UIFont

                UIImageView

                UILabel

                UITableViewController

                UIView

                UIViewController

                URL

            Other Functions

                ==(_:_:)

            Other Protocols

                URLSessionTaskControllerDelegate

Status

enum Status : String

Undocumented

                    passed

Undocumented

Declaration

Swift

case passed = "PASSED"

                    skipped

Undocumented

Declaration

Swift

case skipped = "SKIPPED"

                    failed

Undocumented

Declaration

Swift

case failed = "FAILED"

© 2018 MobiLab Solutions GmbH. All rights reserved. (Last updated: 2018-11-12)

Generated by jazzy ♪♫ v0.9.4, a Realm project.


text:
from __future__ import print_function
import pickle
import json
import csv
import sys

# Allow us to import the deepmoji directory
from os.path import dirname, abspath
sys.path.insert(0, dirname(dirname(abspath(__file__))))

from deepmoji.sentence_tokenizer import SentenceTokenizer, coverage

OUTPUT_PATH = 'coverage.csv'
DATASET_PATHS = [
    '../data/Olympic/raw.pickle',
    '../data/PsychExp/raw.pickle',
    '../data/SCv1/raw.pickle',
    '../data/SCv2-GEN/raw.pickle',
    '../data/SE0714/raw.pickle',
    # '../data/SE1604/raw.pickle', # Excluded due to Twitter's ToS
    '../data/SS-Twitter/raw.pickle',
    '../data/SS-Youtube/raw.pickle',
]

with open('../model/vocabulary.json', 'r') as f:
    vocab = json.load(f)

results = []
for p in DATASET_PATHS:
    coverage_result = [p]
    print('Calculating coverage for {}'.format(p))
    with open(p) as f:
        s = pickle.load(f)

    # Decode data
    try:
        s['texts'] = [unicode(x) for x in s['texts']]
    except UnicodeDecodeError:
        s['texts'] = [x.decode('utf-8') for x in s['texts']]

    # Own
    st = SentenceTokenizer({}, 30)
    tests, dicts, _ = st.split_train_val_test(s['texts'], s['info'],
                                              [s['train_ind'],
                                               s['val_ind'],
                                               s['test_ind']],
                                              extend_with=10000)
    coverage_result.append(coverage(tests[2]))

    # Last
    st = SentenceTokenizer(vocab, 30)
    tests, dicts, _ = st.split_train_val_test(s['texts'], s['info'],
                                              [s['train_ind'],
                                               s['val_ind'],
                                               s['test_ind']],
                                              extend_with=0)
    coverage_result.append(coverage(tests[2]))

    # Full
    st = SentenceTokenizer(vocab, 30)
    tests, dicts, _ = st.split_train_val_test(s['texts'], s['info'],
                                              [s['train_ind'],
                                               s['val_ind'],
                                               s['test_ind']],
                                              extend_with=10000)
    coverage_result.append(coverage(tests[2]))

    results.append(coverage_result)

with open(OUTPUT_PATH, 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter='\t', lineterminator='\n')
    writer.writerow(['Dataset', 'Own', 'Last', 'Full'])
    for i, row in enumerate(results):
        try:
            writer.writerow(row)
        except Exception:
            print("Exception at row {}!".format(i))

print('Saved to {}'.format(OUTPUT_PATH))


text:
<?php
namespace JWhy\JodelPHP;

class JodelPost
{

    public function theTest()
    {
        return 'verify';
    }
}


text:
"""GCIComment logic methods.
"""

from google.appengine.ext import db
from google.appengine.ext import ndb

from soc.tasks import mailer

from soc.modules.gci.logic.helper import notifications
from soc.modules.gci.models import comment as comment_model

def storeAndNotify(comment):
  """Stores and notifies those that are subscribed about a comment on a task.

  Args:
    comment: A GCIComment instance
  """
  db.run_in_transaction(storeAndNotifyTxn(comment))

def storeAndNotifyTxn(comment, task=None):
  """Returns a method to be run in a transaction to notify subscribers.

  Args:
    comment: A GCIComment instance
    task: optional GCITask instance that is the parent of the specified comment
  """
  if not task:
    task = comment.parent()
  elif task.key() != comment.parent_key():
    raise ValueError("The specified task must be the parent of the comment")

  if comment_model.GCIComment.created_by.get_value_for_datastore(comment):
    author_key = ndb.Key.from_old_key(
        comment_model.GCIComment.created_by.get_value_for_datastore(comment))
  else:
    author_key = None

  to_emails = []
  profiles = ndb.get_multi(map(ndb.Key.from_old_key, task.subscribers))
  for profile in profiles:
    if profile and ((not author_key) or profile.key.parent() != author_key):
      to_emails.append(profile.contact.email)

  # Send out an email to an entire organization when set.
  org = task.org
  if org.notification_mailing_list:
    to_emails.append(org.notification_mailing_list)

  context = notifications.getTaskCommentContext(task, comment, to_emails)
  sub_txn = mailer.getSpawnMailTaskTxn(context, parent=task)
  def txn():
    sub_txn()
    comment.put()

  return txn


text:
title: "What Hitchhiker's Guide to the Galaxy Taught Me About Machine Learning"
date: "July 17, 2019"
layout: post
comments: true
---

I realize this is a sci-fi classic and I should have read it a long time ago, however, I recently finished reading *Hitchhiker's Guide to the Galaxy*.  I was surprised that a book written in the 1980s could be so present in its commentary on modern computing and machine learning, especially considering how fast the field is advancing. As I was reading, I dog-eared a few pages that I thought were particularly poignant and extremely relevant to my work as a data scientist. In the following sections, I've written up my top three takeaways from the book as they relate to my work. I hope you enjoy and if not anything else, convince you to read the book!

<!--break-->

## Simple systems are often superior to their complex counterparts.

The main character Arthur Dent haphazardly finds himself on a stolen spacecraft called the *Heart of Gold*.  The ship has a *Nutri-Matic* machine that serves individualized, appetite and digestion-optimized beverages. This machine must a distant cousin of our modern-day recommendation engine.

>[Arthur] found a Nutri-Matic machine which had provided him with a plastic cup filled with a liquid that was almost, but not quite, entirely like unlike tea. The way it functioned was very interesting. When the *Drink* button was pressed it made an instant but highly detailed examination of the subject's taste buds, a spectroscopic analysis of the subject's metabolism and then sent tiny experimental signals down the neural pathways to the taste centers of the subject's brain to see what was likely to go down well. However, no one know quite why it did this because it invariably delivered a cupful of liquid that was almost, but not quite, entirely unlike tea.

As a data scientist, I often like to dig into the details and make systems more complex than they need to be. I like to test a bunch of different models and optimize performance by tuning hyperparameters or using different feature transforms. From my experience, the gains in model performance from hyperparameter tuning are small compared to getting a basic, simplistic model up and running. This is especially true when we have models like random forests and neural networks that can fit many different data structures very well out of the box.

Before even applying machine learning, ask yourself whether machine learning is necessary to solve your problem. Often times a simple rule or heuristic can prove to be very effective. This speaks strongly to [Google's Rule #1 of Machine Learning](https://developers.google.com/machine-learning/guides/rules-of-ml/) – don't be afraid to launch a product without machine learning.

Perhaps the *Nutri-Matic* machine would have pleased Arthur if it was recognized that he was an *Earthman* and served him the most popular drink (besides water) from his home planet -- tea.

## Computers can't help if you're asking the wrong questions.

In *Hitchhiker's Guide to the Galaxy*, a supercomputer *Deep Thought* has been asked the "Answer to the Ultimate Question of Life, the Universe, and Everything". The computer concludes (with high certainty, of course) that the answer is simply "Forty-two". Two characters, Loonqual and Phouchg, who trained for and spent their lives preparing to receive this answer (which also took seven and a half million years to calculate) were clearly dissatisfied with the results.

>"Forty-two!" yelled Loonquawl. "Is that all you've got to show for seven and a half million years' work?"
>
>"I checked it very thoroughly," said the computer, "and that quite definitely is the answer. I think the problem, to be quite honest with you, is that you've never actually known what the question is."

Humans play a critical role in designing a machine learning system. Framing the problem and effectively designing a solution to solve it is often more work than implementing a model (which can often be done in a few lines of code). If there is a flaw in the design or the wrong question is being asked, machine learning will produce bias results, poor-quality output, or even a solution that is ill-fit to the problem.

How do we know whether we are asking the right questions? The computer, *Deep Thought*, later states it is unable to tell the humans the right question to answer.

>"Look, all right, all right," said Loonquawl, "can you just please tell us the question?"
>
>"The Ultimate Question?"
>
>"Yes!"
>
>"Of Life, the Universe and Everything?"
>
>"Yes!"
>
>Deep Thought pondered a moment.
>
>"Tricky," he said.
>
>"But can you do it?" cried Loonquawl.
>
>Deep Thought pondered this for another long moment.
>
>Finally: "No," he said firmly.

I've personally found it helpful to explicitly write the goal or the question I'm trying to answer out in a single, coherent sentence. If you feel like you are unable to do this or do not have a clear vision of the question you are attempting to answer -- ask a peer. Industry experts and coworkers can be great resources to help you nail down the end goal and how to approach the problem. If these steps are not taken, you may find yourself in the shoes of Loonqual and Phouchg and receive a disappointing result of your work.

## A lot can be accomplished with little compute.

In the last section, I mentioned that a supercomputer *Deep Thought* had been asked the answer to "the Ultimate Question of Life, the Universe, and Everything". Two programmers, Lunkwill and Fook, were responsible for activating the computer on the day of the Great On-turning (i.e., they kicked off the job). The two were disappointed when *eep Thought* informed them that it would take seven and a half million years to calculate the response.

>"All I wanted to say," bellowed the computer, "is that my circuits are now irrevocably committed to calculating the answer to the Ultimate Question of Life, the Universe, and Everything." He paused and satisfied himself that he now had everyone's attention before continuing more quietly. "But the the program will take me a little while to run."
>
>Fook glanced impatiently at his watch.
>
>"How long?" he said.
>
>"Seven and a half million years," said Deep Thought.
>
>Lunkwill and Fook blinked at each other.
>
>"Seven and a half million years!" they cried in chorus.

I understand we are in a deep learning boom and many of the best in class machine learning models for text classification and image recognition have been dependent on recent improvements in computing. However, for many problems, I've found success in starting with a simple model or heuristic that can often be trained or implemented on my local machine. And then, over time, layer in complexity.

I also can't tell you how many times I've waited for a memory-intensive process to run, only to find that it failed or there was a bug in the code. Start simple, validate your progress, and build up.

And that wraps it up. Thanks for reading! I'm off to read the next book in the series, *The Restaurant at the End of the Universe*.


text:
#ifndef __DALI_INTERNAL_SCENE_GRAPH_RENDER_MANAGER_H__
#define __DALI_INTERNAL_SCENE_GRAPH_RENDER_MANAGER_H__

// INTERNAL INCLUDES
#include <dali/public-api/math/rect.h>
#include <dali/internal/common/shader-saver.h>
#include <dali/internal/update/resources/resource-manager-declarations.h>
#include <dali/internal/render/common/texture-uploaded-dispatcher.h>
#include <dali/internal/render/gl-resources/gpu-buffer.h>
#include <dali/internal/render/renderers/render-property-buffer.h>
#include <dali/internal/event/rendering/texture-impl.h>

namespace Dali
{

namespace Integration
{
class GlAbstraction;
class GlSyncAbstraction;
class RenderStatus;
}

struct Vector4;

namespace Internal
{
class Context;
class ProgramCache;
class ShaderSaver;

namespace Render
{
class FrameBuffer;
class Renderer;
struct Sampler;
class RenderTracker;
class Geometry;
class NewTexture;
}

namespace SceneGraph
{
class RenderQueue;
class TextureCache;
class RenderInstruction;
class RenderInstructionContainer;
class Shader;
class PropertyBufferDataProvider;
class GeometryBatcher;

/**
 * RenderManager is responsible for rendering the result of the previous "update", which
 * is provided in a RenderCommand during UpdateManager::Update().
 */
class RenderManager : public TextureUploadedDispatcher
{
public:

  /**
   * Construct a new RenderManager.
   * @param[in]  glAbstraction The GL abstraction used for rendering.
   * @param[in]  glSyncAbstraction The GL sync abstraction used fence sync creation/deletion.
   * @param[in]  geometryBatcher The geometry batcher instance
   * @param[out] resourcePostProcessQueue A queue for sending rendered texture ids to the update-thread.*
   */
  static RenderManager* New( Integration::GlAbstraction& glAbstraction,
                             Integration::GlSyncAbstraction& glSyncAbstraction,
                             SceneGraph::GeometryBatcher& geometryBatcher,
                             LockedResourceQueue& resourcePostProcessQueue );

  /**
   * Non-virtual destructor; not intended as a base class
   */
  ~RenderManager();

  /**
   * Retrieve the RenderQueue. Messages should only be added to this from the update-thread.
   * @return The render queue.
   */
  RenderQueue& GetRenderQueue();

  /**
   * Retrieve the texture cache. Messages should only be sent to this from the update thread,
   * accessor methods should only be used from the render thread.
   * @return The texture cache
   */
  TextureCache& GetTextureCache();

  /**
   * @copydoc Dali::Integration::Core::ContextCreated()
   */
  void ContextCreated();

  /**
   * @copydoc Dali::Integration::Core::ContextToBeDestroyed()
   */
  void ContextDestroyed();

  /**
   * Dispatch requests onto the postProcessResourcesQueue
   * @param[in] resource The Id of the resource to dispatch
   */
  virtual void DispatchTextureUploaded( ResourceId resource );

  /**
   * Set the upstream interface for compiled shader binaries to be sent back to for eventual
   * caching and saving.
   * @param[in] upstream The abstract interface to send any received ShaderDatas onwards to..
   * @note This should be called during core initialisation if shader binaries are to be used.
   */
  void SetShaderSaver( ShaderSaver& upstream );

  /**
   * Retrieve the render instructions; these should be set during each "update" traversal.
   * @return The render instruction container.
   */
  RenderInstructionContainer& GetRenderInstructionContainer();

  // The following methods should be called via RenderQueue messages

  /**
   * Set the background color i.e. the glClear color used at the beginning of each frame.
   * @param[in] color The new background color.
   */
  void SetBackgroundColor( const Vector4& color );

  /*
   * Set the frame time delta (time elapsed since the last frame.
   * @param[in] deltaTime the delta time
   */
  void SetFrameDeltaTime( float deltaTime );

  /**
   * Returns the rectangle for the default surface (probably the application window).
   * @return Rectangle for the surface.
   */
  void SetDefaultSurfaceRect( const Rect<int>& rect );

  /**
   * Add a Renderer to the render manager.
   * @param[in] renderer The renderer to add.
   * @post renderer is owned by RenderManager
   */
  void AddRenderer( Render::Renderer* renderer );

  /**
   * Remove a Renderer from the render manager.
   * @param[in] renderer The renderer to remove.
   * @post renderer is destroyed.
   */
  void RemoveRenderer( Render::Renderer* renderer );

  /**
   * Add a sampler to the render manager.
   * @param[in] sampler The sampler to add.
   * @post sampler is owned by RenderManager
   */
  void AddSampler( Render::Sampler* sampler );

  /**
   * Remove a sampler from the render manager.
   * @param[in] sampler The sampler to remove.
   * @post sampler is destroyed.
   */
  void RemoveSampler( Render::Sampler* sampler );

  /**
   * Set minification and magnification filter modes for a sampler
   * @param[in] minFilterMode Filter mode to use when the texture is minificated
   * @param[in] magFilterMode Filter mode to use when the texture is magnified
   */
  void SetFilterMode( Render::Sampler* sampler, unsigned int minFilterMode, unsigned int magFilterMode );

  /**
   * Set wrapping mode for a sampler
   * @param[in] rWrapMode Wrap mode in the z direction
   * @param[in] uWrapMode Wrap mode in the x direction
   * @param[in] vWrapMode Wrap mode in the y direction
   */
  void SetWrapMode( Render::Sampler* sampler, unsigned int rWrapMode, unsigned int sWrapMode, unsigned int tWrapMode );

  /**
   * Add a property buffer to the render manager.
   * @param[in] propertyBuffer The property buffer to add.
   * @post propertBuffer is owned by RenderManager
   */
  void AddPropertyBuffer( Render::PropertyBuffer* propertyBuffer );

  /**
   * Remove a property buffer from the render manager.
   * @param[in] propertyBuffer The property buffer to remove.
   * @post propertyBuffer is destroyed.
   */
  void RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer );

  /**
   * Add a geometry to the render manager.
   * @param[in] geometry The geometry to add.
   * @post geometry is owned by RenderManager
   */
  void AddGeometry( Render::Geometry* geometry );

  /**
   * Remove a geometry from the render manager.
   * @param[in] geometry The geometry to remove.
   * @post geometry is destroyed.
   */
  void RemoveGeometry( Render::Geometry* geometry );

  /**
   * Adds a property buffer to a geometry from the render manager.
   * @param[in] geometry The geometry
   * @param[in] propertyBuffer The property buffer to remove.
   */
  void AddVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer );

  /**
   * Remove a property buffer from a Render::Geometry from the render manager.
   * @param[in] geometry The geometry
   * @param[in] propertyBuffer The property buffer to remove.
   * @post property buffer is destroyed.
   */
  void RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer );

  /**
   * Sets the format of an existing property buffer
   * @param[in] propertyBuffer The property buffer.
   * @param[in] format The new format of the buffer
   */
  void SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, Render::PropertyBuffer::Format* format );

  /**
   * Sets the data of an existing property buffer
   * @param[in] propertyBuffer The property buffer.
   * @param[in] data The new data of the buffer
   * @param[in] size The new size of the buffer
   */
  void SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, Dali::Vector<char>* data, size_t size );

  /**
   * Sets the data for the index buffer of an existing geometry
   * @param[in] geometry The geometry
   * @param[in] data A vector containing the indices
   */
  void SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<unsigned short>& data );

  /**
   * Set the geometry type of an existing render geometry
   * @param[in] geometry The render geometry
   * @param[in] geometryType The new geometry type
   */
  void SetGeometryType( Render::Geometry* geometry, unsigned int geometryType );

  /**
   * Adds a texture to the render manager
   * @param[in] texture The texture to add
   */
  void AddTexture( Render::NewTexture* texture );

  /**
   * Removes a texture from the render manager
   * @param[in] texture The texture to remove
   */
  void RemoveTexture( Render::NewTexture* texture );

  /**
   * Uploads data to an existing texture
   * @param[in] texture The texture
   * @param[in] pixelData The pixel data object
   * @param[in] params The parameters for the upload
   */
  void UploadTexture( Render::NewTexture* texture, PixelDataPtr pixelData, const NewTexture::UploadParams& params );

  /**
   * Generates mipmaps for a given texture
   * @param[in] texture The texture
   */
  void GenerateMipmaps( Render::NewTexture* texture );

  /**
   * Adds a framebuffer to the render manager
   * @param[in] frameBuffer The framebuffer to add
   */
  void AddFrameBuffer( Render::FrameBuffer* frameBuffer );

  /**
   * Removes a framebuffer from the render manager
   * @param[in] frameBuffer The framebuffer to remove
   */
  void RemoveFrameBuffer( Render::FrameBuffer* frameBuffer );

  /**
   * Attach a texture as color output to an existing FrameBuffer
   * @param[in] frameBuffer The FrameBuffer
   * @param[in] texture The texture that will be used as output when rendering
   * @param[in] mipmapLevel The mipmap of the texture to be attached
   * @param[in] layer Indicates which layer of a cube map or array texture to attach. Unused for 2D textures
   */
  void AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::NewTexture* texture, unsigned int mipmapLevel, unsigned int layer );

  /**
   * Adds a render tracker to the RenderManager. RenderManager takes ownership of the
   * tracker. The lifetime of the tracker is related to the lifetime of the tracked
   * object, usually an offscreen render task.
   * @param[in] renderTracker The render tracker
   */
  void AddRenderTracker( Render::RenderTracker* renderTracker );

  /**
   * Removes a render tracker from the RenderManager.
   * @param[in] renderTracker The render tracker to remove.
   */
  void RemoveRenderTracker( Render::RenderTracker* renderTracker );

  /**
   * Set the default shader that is to be used in absence of custom shader
   * @param[in] shader that is the default one
   */
  void SetDefaultShader( Shader* shader );

  /**
   * returns the Program controller for sending program messages
   * @return the ProgramController
   */
  ProgramCache* GetProgramCache();

  // This method should be called from Core::Render()

  /**
   * Renders the results of the previous "update" traversal.
   * @param[out] status contains the flag that indicates if render instructions exist
   * @return true if a further update is required
   */
  bool Render( Integration::RenderStatus& status );

private:

  /**
   * Helper to process a single RenderInstruction.
   * @param[in] instruction A description of the rendering operation.
   * @param[in] defaultShader default shader to use.
   */
  void DoRender( RenderInstruction& instruction, Shader& defaultShader );

private:

  /**
   * Construct a new RenderManager.
   */
  RenderManager();

  // Undefined
  RenderManager( const RenderManager& );

  // Undefined
  RenderManager& operator=( const RenderManager& rhs );

private:

  struct Impl;
  Impl* mImpl;

};

} // namespace SceneGraph

} // namespace Internal

} // namespace Dali

#endif // __DALI_INTERNAL_SCENE_GRAPH_RENDER_MANAGER_H__


text:
$(function (ready) {
    $("#SignalHeader").click(function() {
        GetSignals();
    });
    //$.validator.unobtrusive.parse($("#SignalSearchContainer"));
    $.validator.unobtrusive.parse($('form'));
});
function AddEventsForSignalSearch() {
    $("#FilterButton").click(function() { GetSignals(1); });
    $("#ClearFilterButton").click(function() {
        ClearSignalSearch();
    });
}

function ClearSignalSearch() {
    $("#Filters").val(null);
    $("#FilterCriteria").val(null);
    GetSignals(1);
}

//$("#SignalID").keypress(function (e) {
//    if (e.which == 13) {
//        e.preventDefault();
//        GetSignalLocation();
//    }
//});

function SignalIdPress(e) {
    if (e.which == 13) {
        e.preventDefault();
        GetSignalLocation();
    }
}

function GetSignals(page) {
    var filterType = $("#Filters").val();
    var filterCriteria = $("#FilterCriteria").val();
    var tosend = {};
    tosend.page = page;
    tosend.filterType = filterType;
    tosend.filterCriteria = filterCriteria;
    $.ajax({
        url: urlpathFillSignals,
        type: "POST",
        cache: false,
        async: true,
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(tosend),
        success: function (data) {
            $('#SignalsPlaceHolder').html(data);
            AddEventsForSignalSearch();
        },
        onerror: function () { alert("Error"); }

    });
}


text:
#ifndef PROXIMITY_H_
#define PROXIMITY_H_

#include "localizer.h"

#include <qjson/parser.h>
#include <qjson/serializer.h>

#include <QNetworkReply>
#include <QNetworkRequest>

class Proximity : public QObject
{
  //friend QDebug operator<<(QDebug dbg, const Proximity &proximity);
  Q_OBJECT

 public:
  Proximity(QObject *parent = 0, Localizer *localizer = 0);

 private:
  Localizer *m_localizer;
  bool m_active;
  QString m_name;
  QTimer m_updateTimer;

  void setTimer ();

 private slots:
  void update();
  void handleUpdateResponse();
  void handleProximitySettings(bool activate, QString name);
};

#endif /* PROXIMITY_H_ */


text:
package com.github.gquintana.elasticsearch;

public class Product {
    private String id;
    private String title;
    private String description;

    public Product() {
    }

    public Product(String id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}


text:
@extends ('layouts.master')
@section('content')

    @include('dashboard.sidebar')
    @yield('main')

@endsection


text:
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"

	"io"
)

type TestFailedError struct {
	Exit         *exec.ExitError
	StderrOutput []byte
}

func (e *TestFailedError) Error() string {
	return "test failed"
}

type packageSetSnapshot struct {
	*packageSet

	Packages []packageSnapshot
	TreeId   string

	InitGoPath func() (string, error)
	GoPath     string
}

func newPackageSetSnapshot(set *packageSet, treeId string) *packageSetSnapshot {
	snapshot := packageSetSnapshot{
		packageSet: set,
		Packages:   make([]packageSnapshot, len(set.relPackagePaths)),
		TreeId:     treeId,
	}
	for i, rpp := range set.relPackagePaths {
		snapshot.Packages[i] = packageSnapshot{
			relPackagePath: rpp,
			PackageSet:     &snapshot,
		}
	}
	return &snapshot
}

type packageSnapshot struct {
	relPackagePath string
	PackageSet     *packageSetSnapshot
	Cache          *packageSnapshotCache
}

// Runs go command in the repo snapshot.
// Redirects stderr to current redStderr.
func (s *packageSetSnapshot) Go(args ...string) (*exec.Cmd, error) {
	cmd := exec.Command("go", args...)
	if s.GoPath == "" && s.InitGoPath != nil {
		var err error
		if s.GoPath, err = s.InitGoPath(); err != nil {
			return nil, err
		}
	}
	if s.GoPath != "" {
		cmd.Env = append(cmd.Env, fmt.Sprintf("GOPATH=%s:%s", s.GoPath, os.Getenv("GOPATH")))
	}
	cmd.Stderr = redStderr
	return cmd, nil
}

// GetBenchmarks returns a mapping {relPackagePath -> benchmarks}
// cb is called on each benchmark as soon as it is received.
func (s *packageSetSnapshot) GetBenchmarks(benchRegex string, cb func(*benchmarkRun)) (map[string]benchmarkRunSlice, error) {
	results := make(map[string]benchmarkRunSlice, len(s.Packages))
	for i := range s.Packages {
		p := &s.Packages[i]
		var err error
		results[p.relPackagePath], err = p.GetBenchmarks(benchRegex, cb)
		if err != nil {
			return nil, err
		}
	}
	return results, nil
}

// cacheFilename returns path to the snapshot cache file.
func (s *packageSnapshot) cacheFilename() string {
	return filepath.Join(
		s.PackageSet.repo.root,
		s.PackageSet.repo.gitDir,
		"ggt",
		"tree-cache",
		s.PackageSet.TreeId,
		s.relPackagePath,
		"dir-cache.json")
}

// LoadCache loads s.Cache from the cache file.
func (s *packageSnapshot) LoadCache() {
	if s.Cache == nil {
		s.Cache = &packageSnapshotCache{}
	}
	if err := s.Cache.Load(s.cacheFilename()); err != nil {
		log.Printf("could not load cache: %s\n", err)
	}
}

// LoadCache loads s.Cache from the cache file if it was not loaded before.
func (s *packageSnapshot) EnsureCacheLoaded() {
	if s.Cache == nil {
		s.LoadCache()
	}
}

// SaveCache saves s.Cache to the cache file.
func (s *packageSnapshot) SaveCache() {
	if s.Cache == nil {
		panic("cache not loaded")
	}
	if err := s.Cache.Save(s.cacheFilename()); err != nil {
		log.Printf("could not save test results: %s\n", err)
	}
}

// GetBenchmarkNames returns a slice of all benchmark names in the snapshot.
func (s *packageSnapshot) GetBenchmarkNames() ([]string, error) {
	s.EnsureCacheLoaded()

	if s.Cache.AllBenchmarkNames != nil {
		return s.Cache.AllBenchmarkNames, nil
	}

	importPath := filepath.Join(s.PackageSet.rootPackageImportPath, s.relPackagePath)
	test, err := s.PackageSet.Go("test", "-run=@", "-bench=.", "-benchtime=0", importPath)
	if err != nil {
		return nil, err
	}
	out, err := trimOutput(test)
	if err != nil {
		return nil, err
	}
	testNames := []string{} // must be non-nil
	for _, line := range strings.Split(out, "\n") {
		benchmark := parseBenchmarkRun(line)
		if benchmark != nil {
			testNames = append(testNames, benchmark.Name)
		}
	}

	s.Cache.AllBenchmarkNames = testNames
	s.SaveCache()
	return testNames, nil
}

// RunBenchmarks runs `go test -run=@ -bench=<benchRegex>` and returns parsed benchmarks.
// if benchRegex is "", it is defaulted to ".".
func (s *packageSnapshot) RunBenchmarks(benchRegex string, cb func(*benchmarkRun)) (benchmarkRunSlice, error) {
	s.EnsureCacheLoaded()
	if benchRegex == "" {
		benchRegex = "."
	}

	importPath := filepath.Join(s.PackageSet.rootPackageImportPath, s.relPackagePath)
	test, err := s.PackageSet.Go("test", "-run=@", "-bench="+benchRegex, importPath)
	if err != nil {
		return nil, err
	}
	testNames := []string{} // must be non-nil
	var result benchmarkRunSlice

	var stderr bytes.Buffer
	test.Stderr = io.MultiWriter(redStderr, &stderr)
	err = forEachLineOutput(test, func(line string) error {
		verbose.Print("\t", line)
		benchmark := parseBenchmarkRun(line)
		if benchmark == nil {
			return nil
		}
		verbose.Println("this is a benchmark")
		if cb != nil {
			cb(benchmark)
		}
		if err = result.Add(benchmark); err != nil {
			return err
		}
		if err = s.Cache.Benchmarks.Add(benchmark); err != nil {
			return err
		}
		testNames = append(testNames, benchmark.Name)
		return nil
	})
	if err != nil {
		if err, ok := err.(*exec.ExitError); ok {
			return nil, &TestFailedError{err, stderr.Bytes()}
		}
		return nil, err
	}

	if benchRegex == "." {
		s.Cache.BenchmarksIsComplete = true
		s.Cache.AllBenchmarkNames = testNames
	}
	s.SaveCache()

	return result, nil
}

// loadBenchmarksFromCache attempts to load benchmarks from cache. If some benchmarks are missing, runs them.
func (s *packageSnapshot) loadBenchmarksFromCache(benchRegex string, cb func(*benchmarkRun)) (benchmarkRunSlice, error) {
	s.EnsureCacheLoaded()

	if len(s.Cache.Benchmarks) == 0 {
		verbose.Println("nothing in cache")
		return nil, nil
	}

	compiledBenchRegex, err := regexp.Compile(benchRegex)
	if err != nil {
		return nil, fmt.Errorf("invalid regexp: %s", benchRegex)
	}

	var result benchmarkRunSlice
	verbose.Printf("benchmarks in cache: %s\n", s.Cache.Benchmarks)
	for i := range s.Cache.Benchmarks {
		b := &s.Cache.Benchmarks[i]
		if compiledBenchRegex.MatchString(b.Name) {
			if cb != nil {
				cb(b)
			}
			if err := result.Add(b); err != nil {
				return nil, err
			}
		}
	}

	if !s.Cache.BenchmarksIsComplete {
		verbose.Println("not all tests are in cache. Getting full benchmark name list.")
		all, err := s.GetBenchmarkNames()
		if err != nil {
			return nil, err
		}
		var missing []string
		for _, t := range all {
			if !compiledBenchRegex.MatchString(t) {
				continue
			}
			if result.Find(t) == nil {
				missing = append(missing, t)
			}
		}
		if len(missing) > 0 {
			verbose.Printf("the benchmarks loaded from cache miss requested tests: %s.\n", missing)
			missingRgx := "^(" + strings.Join(missing, "|") + ")$"
			missingBenchmarks, err := s.RunBenchmarks(missingRgx, cb)
			if err != nil {
				return nil, err
			}
			for _, name := range missing {
				b := missingBenchmarks.Find(name)
				if b == nil {
					return nil, fmt.Errorf("requested benchmark %s didn't run.", name)
				}
				if err := result.Add(b); err != nil {
					return nil, err
				}
			}
		}
	}
	return result, nil
}

// GetBenchmarks returns benchmarks from cache or by running them.
// cb is called as soon as a benchmark is available.
// benchRegex is defaulted to "."
func (s *packageSnapshot) GetBenchmarks(benchRegex string, cb func(*benchmarkRun)) (benchmarkRunSlice, error) {
	if cb == nil {
		cb = func(*benchmarkRun) {}
	}

	if caching {
		benchmarks, err := s.loadBenchmarksFromCache(benchRegex, cb)
		if err != nil || benchmarks != nil {
			return benchmarks, err
		}
	}

	return s.RunBenchmarks(benchRegex, cb)
}


text:
using System.Web.Http;
using App.Infrastructure;
using App.Infrastructure.Web;
using App.Server.ReferenceData;
using MileageStats.Domain.Handlers;

namespace App.Server.Vehicle
{
    public class GetVehicleController : ApiController
    {
        readonly GetVehicleById getVehicleById;

        public GetVehicleController(GetVehicleById getVehicleById)
        {
            this.getVehicleById = getVehicleById;
        }

        public object GetVehicle(int vehicleId)
        {
            var vehicle = getVehicleById.Execute(1, vehicleId);
            return new Page("Vehicles/Details/init")
            {
                Title = vehicle.Name,
                MasterPage = Url.Resource<GetVehicleMasterPageController>(),
                Data = new
                {
                    name = vehicle.Name,
                    year = vehicle.Year,
                    make = vehicle.MakeName,
                    model = vehicle.ModelName,
                    odometer = vehicle.Odometer,
                    photo = Url.Get<GetVehiclePhotoController>(),
                    save = Url.Put<PutVehicleController>(),
                    delete = Url.Delete<DeleteVehicleController>(),
                    years = Url.Get<GetYearsController>()
                }
            };
        }
    }
}


text:
using testing::_;
using testing::BitEq;
using testing::IsNaN;

namespace v8 {
namespace internal {
namespace compiler {

namespace {

const size_t kIndices[] = {0, 1, 42, 100, 1024};

Type const kJSTypes[] = {Type::Undefined(), Type::Null(),   Type::Boolean(),
                         Type::Number(),    Type::String(), Type::Object()};

}  // namespace

class JSTypedLoweringTest : public TypedGraphTest {
 public:
  JSTypedLoweringTest() : TypedGraphTest(3), javascript_(zone()) {}
  ~JSTypedLoweringTest() override = default;

 protected:
  Reduction Reduce(Node* node) {
    JSHeapCopyReducer heap_copy_reducer(broker());
    CHECK(!heap_copy_reducer.Reduce(node).Changed());
    MachineOperatorBuilder machine(zone());
    SimplifiedOperatorBuilder simplified(zone());
    JSGraph jsgraph(isolate(), graph(), common(), javascript(), &simplified,
                    &machine);
    GraphReducer graph_reducer(zone(), graph(), tick_counter(), broker());
    JSTypedLowering reducer(&graph_reducer, &jsgraph, broker(), zone());
    return reducer.Reduce(node);
  }

  JSOperatorBuilder* javascript() { return &javascript_; }

 private:
  JSOperatorBuilder javascript_;
};

// -----------------------------------------------------------------------------
// JSToName

TEST_F(JSTypedLoweringTest, JSToNameWithString) {
  Node* const input = Parameter(Type::String(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToName(), input, context,
                                        EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_EQ(input, r.replacement());
}

TEST_F(JSTypedLoweringTest, JSToNameWithSymbol) {
  Node* const input = Parameter(Type::Symbol(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToName(), input, context,
                                        EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_EQ(input, r.replacement());
}

TEST_F(JSTypedLoweringTest, JSToNameWithAny) {
  Node* const input = Parameter(Type::Any(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToName(), input, context,
                                        EmptyFrameState(), effect, control));
  ASSERT_FALSE(r.Changed());
}

// -----------------------------------------------------------------------------
// JSToNumber

TEST_F(JSTypedLoweringTest, JSToNumberWithPlainPrimitive) {
  Node* const input = Parameter(Type::PlainPrimitive(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r =
      Reduce(graph()->NewNode(javascript()->ToNumber(), input, context,
                              EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsPlainPrimitiveToNumber(input));
}

// -----------------------------------------------------------------------------
// JSToObject

TEST_F(JSTypedLoweringTest, JSToObjectWithAny) {
  Node* const input = Parameter(Type::Any(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const frame_state = EmptyFrameState();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToObject(), input,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsPhi(MachineRepresentation::kTagged, _, _, _));
}

TEST_F(JSTypedLoweringTest, JSToObjectWithReceiver) {
  Node* const input = Parameter(Type::Receiver(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const frame_state = EmptyFrameState();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToObject(), input,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_EQ(input, r.replacement());
}

// -----------------------------------------------------------------------------
// JSToString

TEST_F(JSTypedLoweringTest, JSToStringWithBoolean) {
  Node* const input = Parameter(Type::Boolean(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const frame_state = EmptyFrameState();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToString(), input,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(),
              IsSelect(MachineRepresentation::kTagged, input,
                       IsHeapConstant(factory()->true_string()),
                       IsHeapConstant(factory()->false_string())));
}

// -----------------------------------------------------------------------------
// JSStrictEqual

namespace {

FeedbackSource FeedbackSourceWithOneBinarySlot(JSTypedLoweringTest* R) {
  return FeedbackSource{
      FeedbackVector::NewWithOneBinarySlotForTesting(R->zone(), R->isolate()),
      FeedbackSlot{0}};
}

FeedbackSource FeedbackSourceWithOneCompareSlot(JSTypedLoweringTest* R) {
  return FeedbackSource{
      FeedbackVector::NewWithOneCompareSlotForTesting(R->zone(), R->isolate()),
      FeedbackSlot{0}};
}

}  // namespace

TEST_F(JSTypedLoweringTest, JSStrictEqualWithTheHole) {
  Node* const the_hole = HeapConstant(factory()->the_hole_value());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FOREACH(Type, type, kJSTypes) {
    Node* const lhs = Parameter(type);
    Reduction r = Reduce(graph()->NewNode(
        javascript()->StrictEqual(FeedbackSourceWithOneCompareSlot(this)), lhs,
        the_hole, feedback, context, effect, control));
    ASSERT_FALSE(r.Changed());
  }
}

TEST_F(JSTypedLoweringTest, JSStrictEqualWithUnique) {
  Node* const lhs = Parameter(Type::Unique(), 0);
  Node* const rhs = Parameter(Type::Unique(), 1);
  Node* const feedback = UndefinedConstant();
  Node* const context = Parameter(Type::Any(), 2);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(
      javascript()->StrictEqual(FeedbackSourceWithOneCompareSlot(this)), lhs,
      rhs, feedback, context, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsReferenceEqual(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSShiftLeft

TEST_F(JSTypedLoweringTest, JSShiftLeftWithSigned32AndConstant) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FORRANGE(double, rhs, 0, 31) {
    Reduction r = Reduce(graph()->NewNode(
        javascript()->ShiftLeft(FeedbackSourceWithOneBinarySlot(this)), lhs,
        NumberConstant(rhs), feedback, context, EmptyFrameState(), effect,
        control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(),
                IsNumberShiftLeft(lhs, IsNumberConstant(BitEq(rhs))));
  }
}

TEST_F(JSTypedLoweringTest, JSShiftLeftWithSigned32AndUnsigned32) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const rhs = Parameter(Type::Unsigned32());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(
      javascript()->ShiftLeft(FeedbackSourceWithOneBinarySlot(this)), lhs, rhs,
      feedback, context, EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsNumberShiftLeft(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSShiftRight

TEST_F(JSTypedLoweringTest, JSShiftRightWithSigned32AndConstant) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FORRANGE(double, rhs, 0, 31) {
    Reduction r = Reduce(graph()->NewNode(
        javascript()->ShiftRight(FeedbackSourceWithOneBinarySlot(this)), lhs,
        NumberConstant(rhs), feedback, context, EmptyFrameState(), effect,
        control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(),
                IsNumberShiftRight(lhs, IsNumberConstant(BitEq(rhs))));
  }
}

TEST_F(JSTypedLoweringTest, JSShiftRightWithSigned32AndUnsigned32) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const rhs = Parameter(Type::Unsigned32());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(
      javascript()->ShiftRight(FeedbackSourceWithOneBinarySlot(this)), lhs, rhs,
      feedback, context, EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsNumberShiftRight(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSShiftRightLogical

TEST_F(JSTypedLoweringTest,
                   JSShiftRightLogicalWithUnsigned32AndConstant) {
  Node* const lhs = Parameter(Type::Unsigned32());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FORRANGE(double, rhs, 0, 31) {
    Reduction r = Reduce(graph()->NewNode(
        javascript()->ShiftRightLogical(FeedbackSourceWithOneBinarySlot(this)),
        lhs, NumberConstant(rhs), feedback, context, EmptyFrameState(), effect,
        control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(),
                IsNumberShiftRightLogical(lhs, IsNumberConstant(BitEq(rhs))));
  }
}

TEST_F(JSTypedLoweringTest, JSShiftRightLogicalWithUnsigned32AndUnsigned32) {
  Node* const lhs = Parameter(Type::Unsigned32());
  Node* const rhs = Parameter(Type::Unsigned32());
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(
      javascript()->ShiftRightLogical(FeedbackSourceWithOneBinarySlot(this)),
      lhs, rhs, feedback, context, EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsNumberShiftRightLogical(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSLoadContext

TEST_F(JSTypedLoweringTest, JSLoadContext) {
  Node* const context = Parameter(Type::Any());
  Node* const effect = graph()->start();
  static bool kBooleans[] = {false, true};
  TRACED_FOREACH(size_t, index, kIndices) {
    TRACED_FOREACH(bool, immutable, kBooleans) {
      Reduction const r1 = Reduce(graph()->NewNode(
          javascript()->LoadContext(0, index, immutable), context, effect));
      ASSERT_TRUE(r1.Changed());
      EXPECT_THAT(r1.replacement(),
                  IsLoadField(AccessBuilder::ForContextSlot(index), context,
                              effect, graph()->start()));

      Reduction const r2 = Reduce(graph()->NewNode(
          javascript()->LoadContext(1, index, immutable), context, effect));
      ASSERT_TRUE(r2.Changed());
      EXPECT_THAT(
          r2.replacement(),
          IsLoadField(AccessBuilder::ForContextSlot(index),
                      IsLoadField(AccessBuilder::ForContextSlotKnownPointer(
                                      Context::PREVIOUS_INDEX),
                                  context, effect, graph()->start()),
                      _, graph()->start()));
    }
  }
}

// -----------------------------------------------------------------------------
// JSStoreContext

TEST_F(JSTypedLoweringTest, JSStoreContext) {
  Node* const context = Parameter(Type::Any());
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FOREACH(size_t, index, kIndices) {
    TRACED_FOREACH(Type, type, kJSTypes) {
      Node* const value = Parameter(type);

      Reduction const r1 =
          Reduce(graph()->NewNode(javascript()->StoreContext(0, index), value,
                                  context, effect, control));
      ASSERT_TRUE(r1.Changed());
      EXPECT_THAT(r1.replacement(),
                  IsStoreField(AccessBuilder::ForContextSlot(index), context,
                               value, effect, control));

      Reduction const r2 =
          Reduce(graph()->NewNode(javascript()->StoreContext(1, index), value,
                                  context, effect, control));
      ASSERT_TRUE(r2.Changed());
      EXPECT_THAT(
          r2.replacement(),
          IsStoreField(AccessBuilder::ForContextSlot(index),
                       IsLoadField(AccessBuilder::ForContextSlotKnownPointer(
                                       Context::PREVIOUS_INDEX),
                                   context, effect, graph()->start()),
                       value, _, control));
    }
  }
}

// -----------------------------------------------------------------------------
// JSLoadNamed

TEST_F(JSTypedLoweringTest, JSLoadNamedStringLength) {
  Handle<Name> name = factory()->length_string();
  Node* const receiver = Parameter(Type::String(), 0);
  Node* const feedback = UndefinedConstant();
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction const r = Reduce(graph()->NewNode(
      javascript()->LoadNamed(name, FeedbackSource{}), receiver, feedback,
      context, EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsStringLength(receiver));
}

// -----------------------------------------------------------------------------
// JSAdd

TEST_F(JSTypedLoweringTest, JSAddWithString) {
  Node* lhs = Parameter(Type::String(), 0);
  Node* rhs = Parameter(Type::String(), 1);
  Node* const feedback = UndefinedConstant();
  Node* context = Parameter(Type::Any(), 2);
  Node* frame_state = EmptyFrameState();
  Node* effect = graph()->start();
  Node* control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(
      javascript()->Add(FeedbackSourceWithOneBinarySlot(this)), lhs, rhs,
      feedback, context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsStringConcat(_, lhs, rhs));
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8


text:
package anewStart;

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

public class Player{

	//coord van station waar hij zal afstappen!!!
	 float coordX;
	 float coordY;
	// -1 if not at stop;
	 float stop_id;

	public Player(float coordX, float coordY, float stop_id){
		this.setCoord(coordX, coordY, stop_id);
	}

	public void setCoord(float coordX, float coordY, float stop_id){
		this.coordX=coordX;
		this.coordY=coordY;
		this.stop_id=stop_id;
	}

	List<Train> trains = new ArrayList<Train>();

	public void getOnTrains(List<Train> trains){
		this.trains=trains;
	}

}


text:
//----------------------------------*-C++-*----------------------------------//
/*!
 * \file   utilities/SP.hh
 * \author Jeremy Roberts
 * \brief  SP member definitions.
 * \note   Modified version of Tom Evan's SP class from Denovo.
 */
//---------------------------------------------------------------------------//

#ifndef SP_I_HH_
#define SP_I_HH_

namespace detran_utilities
{

//---------------------------------------------------------------------------//
// OVERLOADED OPERATORS
//---------------------------------------------------------------------------//

/*!
 * \brief Do equality check with a free pointer.
 */
template<class T>
bool operator==(const T *pt, const SP<T> &sp)
{
    return sp == pt;
}

/*!
 * \brief Do inequality check with a free pointer.
 */
template<class T>
bool operator!=(const T *pt, const SP<T> &sp)
{
    return sp != pt;
}

//---------------------------------------------------------------------------//
// INLINE FUNCTIONS
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
 * \brief Explicit constructor for type T *.
 *
 * This constructor is used to initialize a SP with a pointer, ie.
 * \code
 *     Foo *f = new Foo;
 *     SP<Foo> spf(f);   // f now owned by spf
 *     SP<Foo> spf2 = f; // error! does not do implicit conversion
 * \endcode
 * Once a pointer is "given" to a SP, the SP takes control. This means that
 * spf will delete f when the last SP to f is destroyed.
 *
 * \param p_in pointer to type T
 */
template<class T>
SP<T>::SP(T *p_in)
    : p(p_in),
      r(new SPref)
{
    Ensure (r);
    Ensure (r->refs() == 1);
}

//---------------------------------------------------------------------------//
/*!
 * \brief  Explicit constructor for type X *.
 *
 * This constructor is used to initialize a base class smart pointer of type
 * T with a derived class pointer of type X or, equivalently, any types in
 * which X * is convertible to T * through a dynamic_cast.  Consider,
 * \code
 *     class Base {//...};
 *     class Derived : public Base {//...};
 *
 *     SP<Base> spb(new Derived); // spb base class SP to Derived type
 *     Derived *d = new Derived;
 *     SP<Base> spb2(d);          // different syntax
 *     SP<Base> spb3 = d;         // error! no implicit conversion
 *
 *     Derived *d2;
 *     SP<Base> spb4(d2);         // error! cannot initialize with NULL
 *                                // pointer of different type than T
 * \endcode
 * The pointer to X must not be equal to NULL.  The SP owns the pointer when
 * it is constructed.
 *
 * \param px_in pointer to type X that is convertible to T *
 */
template<class T>
template<class X>
SP<T>::SP(X *px_in)
{
    Require (px_in);

    // make a dynamic cast to check that we can cast between X and T
    T *np = dynamic_cast<T *>(px_in);

    // check that we have made a successfull cast if px exists
    Insist(np, "Incompatible dumb pointer conversion between " +
           std::string(typeid(X).name()) + " and SP<" +
           std::string(typeid(T).name()) + ">.");

    // assign the pointer and reference
    p = np;
    r = new SPref;

    Ensure (p);
    Ensure (r);
    Ensure (r->refs() == 1);
}

//---------------------------------------------------------------------------//
/*!
 * \brief Copy constructor for SP<T>.
 *
 * \param sp_in smart pointer of type SP<T>
 */
template<class T>
SP<T>::SP(const SP<T> &sp_in)
    : p(sp_in.p),
      r(sp_in.r)
{
    Require (r);

    // advance the reference to T
    r->increment();
}

//---------------------------------------------------------------------------//
/*!
 * \brief Copy constructor for SP<X>.
 *
 * This copy constructor Requires that X * is convertible to T * through a
 * dynamic_cast.  The pointer in spx_in can point to NULL; however, it must
 * still be convertible to T * through a dynamic_cast.
 *
 * \param spx_in smart pointer of type SP<X>
 */
template<class T>
template<class X>
SP<T>::SP(const SP<X> &spx_in)
{
  Require(spx_in.r);

  // make a pointer to T *
  T *np = dynamic_cast<T *>(spx_in.p);
  Insist(spx_in.p ? np != 0 : true,
         "Incompatible SP conversion between SP<" +
         std::string(typeid(X).name()) + "> and SP<" +
         std::string(typeid(T).name()) + ">.");

  // assign the pointer and reference
  p = np;
  r = spx_in.r;

  // advance the reference to T
  r->increment();
}

//---------------------------------------------------------------------------//
/*!
 * \brief Assignment operator for type T *.
 *
 * The assignment operator checks the existing count of the smart pointer and
 * then assigns the smart pointer to the raw pointer.  As in copy
 * construction, the smart pointer owns the pointer after assignment. Here is
 * an example of usage:
 * \code
 *     SP<Foo> f;         // has reference to NULL pointer
 *     f      = new Foo;  // now has 1 count of Foo
 *     Foo *g = new Foo;
 *     f      = g;        // f's original pointer to Foo is deleted
 *                        // because count goes to zero; f now has
 *                        // 1 reference to g
 * \endcode
 *
 * \param p_in pointer to T
 */
template<class T>
SP<T>& SP<T>::operator=(T *p_in)
{
  // check if we already own this pointer
  if (p == p_in)
    return *this;

  // next free the existing pointer
  free();

  // now make add p_in to this pointer and make a new reference to it
  p = p_in;
  r = new SPref;

  Ensure (r->refs() == 1);
  return *this;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Assignment operator for type X *.
 *
 * This assignment Requires that X * is convertible to T * through a
 * dynamic_cast.  It follows the same principle as SP(X*); however,
 * this is assignment:
 * \code
 *     SP<Base> b;
 *     b = new Derived;
 * \endcode
 * The pointer to X must not be equal to NULL.
 *
 * \param px_in pointer to type X * that is convertible to type T * through a
 * dynamic cast
 */
template<class T>
template<class X>
SP<T>& SP<T>::operator=(X *px_in)
{
  Require (px_in);

  // do a dynamic cast to Ensure convertiblility between T* and X*
  T *np = dynamic_cast<T *>(px_in);
  Insist(np, "Incompatible dumb pointer conversion between " +
         std::string(typeid(X).name()) + " and SP<" +
         std::string(typeid(T).name()) + ">.");

  // now assign this to np (using previously defined assignment operator)
  *this = np;

  Ensure (r->refs() == 1);
  return *this;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Assignment operator for type SP<T>.
 *
 * \param sp_in smart pointer of type SP<T>
 */
template<class T>
SP<T>& SP<T>::operator=(const SP<T> sp_in)
{
  Require (sp_in.r);

  // see if they are equal
  if (this == &sp_in || p == sp_in.p)
    return *this;

  // free the existing pointer
  free();

  // assign p and r to sp_in
  p = sp_in.p;
  r = sp_in.r;

  // add the reference count and return
  r->increment();
  return *this;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Assignment operator for type SP<X>.
 *
 * This assignment Requires that X * is convertible to T * through a
 * dynamic_cast.  The pointer in spx_in can point to NULL; however, it must
 * still be convertible to T * through a dynamic_cast.
 *
 * \param spx_in smart pointer of type SP<X>
 */
template<class T>
template<class X>
SP<T>& SP<T>::operator=(const SP<X> spx_in)
{
  Require (spx_in.r);

  // make a pointer to T *
  T *np = dynamic_cast<T *>(spx_in.p);
  Insist(spx_in.p ? np != 0 : true,
         "Incompatible SP conversion between SP<" +
         std::string(typeid(X).name()) + "> and SP<" +
         std::string(typeid(T).name()) + ">.");
  // check to see if we are holding the same pointer (and np is not NULL);
  // to NULL pointers to the same type are defined to be equal by the
  // standard
  if (p == np && p)
  {
	  // if the pointers are the same the reference count better be the
	  // same
	  Assert (r == spx_in.r);
	  return *this;
  }

  // we don't need to worry about the case where p == np and np == NULL
  // because this combination is impossible; if np is NULL then it belongs
  // to a different smart pointer; in other words, if p == np and np ==
  // NULL then r != spx_in.r

  // free the existing pointer and reference
  free();

  // assign new values
  p = np;
  r = spx_in.r;

  // advance the counter and return
  r->increment();
  return *this;
}

//---------------------------------------------------------------------------//
// PRIVATE IMPLEMENTATION
//---------------------------------------------------------------------------//
/*!
 * \brief Decrement the count and free the pointer if count is zero.
 *
 * Note that it is perfectly acceptable to call delete on a NULL pointer.
 */
template<class T>
void SP<T>::free()
{

  Require (r);
  r->decrement();
  // if the count goes to zero then we free the data
  if (r->refs() == 0)
  {
    delete p;
    delete r;
  }

}

} // end namespace detran_utilities

#endif // SP_I_HH_

//---------------------------------------------------------------------------//
//              end of utils/SP.i.hh
//---------------------------------------------------------------------------//