Categories
discuss

Java: Many-to-one bidirectional lookup

I have data in a many-to-one relationship. I’d like to be able to lookup data from both directions. An example:

0 : a
1 : b
2 : b
3 : b
4 : c

get(0) --> a
get(1) --> b
get(a) --> 0
get(b) --> (1:3)

Does this make sense? Is it possible?

Answer

It is definitely possible. Here is a fragment of code for adding items:

Map<Integer,String> forwardMap = new HashMap<>();
Map<String,Set<Integer>> reverseMap = new HashMap<>();

void add(Integer x, String y) {
    forwardMap.put(x, y);
    if (!reverseMap.containsKey(y))
        reverseMap.put(y, new HashSet<Integer>());
    reverseMap.get(y).add(x);
}

Footnote: Apache Commons has BidiMap and Google Guava has BiMap, but these appear to be one-to-one maps, disallowing the many-to-one case asked in the question.

Categories
discuss

Website won’t load in android webview but works fine in android browsers

This has been annoying me for a while now and I could really use some help. I have a website created on portfoliobox.net which works fine in chrome and every other browser I tried on android (actual phones, not emulators), however I wanted to make it into an app for part of a University project. My webview app loads other websites fine but not mine for some reason, so yes I have set the permissions right and I have javascript enabled. It could be something simple but I’m a major noob and haven’t got much of a clue.

Here is the logcat

04-30 22:08:56.954: W/BindingManager(8365): Cannot call determinedVisibility() - never saw a connection for the pid: 8365
04-30 22:08:56.962: E/com.parse.push(8365): successfully subscribed to the broadcast channel.
04-30 22:08:56.973: D/GCM(2579): COMPAT: Multi user ser=0 current=0
04-30 22:08:56.989: D/GCM(11959): GcmService start Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms cmp=com.google.android.gms/.gcm.GcmService (has extras) } com.google.android.c2dm.intent.REGISTER
04-30 22:08:57.145: I/Icing(2579): Indexing DBC59092704C7216FC04EAC8683F4EE7F5C1F3E0 from com.google.android.googlequicksearchbox
04-30 22:08:57.302: W/SQLiteConnectionPool(2579): A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
04-30 22:08:57.302: W/SQLiteConnectionPool(2579): A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/help_responses.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
04-30 22:08:57.306: W/SQLiteConnectionPool(2579): A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
04-30 22:08:57.333: I/Icing(2579): Indexing done DBC59092704C7216FC04EAC8683F4EE7F5C1F3E0
04-30 22:08:57.333: D/PowerManagerService(912): releaseWakeLockInternal: lock=289528107 [Icing], flags=0x0
04-30 22:08:57.377: D/PowerManagerService(912): acquireWakeLockInternal: lock=1014891468, flags=0x1, tag="NetworkStats", ws=null, uid=1000, pid=912
04-30 22:08:57.406: D/PowerManagerService(912): releaseWakeLockInternal: lock=1014891468 [NetworkStats], flags=0x0
04-30 22:08:58.035: I/chromium(8365): [INFO:CONSOLE(0)] "'webkitIDBRequest' is deprecated. Please use 'IDBRequest' instead.", source:  (0)
04-30 22:08:58.270: I/chromium(8365): [INFO:CONSOLE(1)] "HARD RESET!!", source: http://www.broadbentstudios.com/application/_output/pb.out.front.js?v=7 (1)
04-30 22:08:58.277: I/chromium(8365): [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'clear' of null", source: http://www.broadbentstudios.com/application/_output/pb.out.front.js?v=7 (1)

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/mainWebView"
      android:scrollbarSize="10dp"
      android:scrollbarThumbVertical="@drawable/customscroll">
     </WebView>


</LinearLayout>

BroadbentStudios.java

package com.broadbentstudios;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.parse.ParseAnalytics;

public class BroadbentStudios extends Activity {

    WebView webView;
    /** Called when the activity is first created. */
    @SuppressLint("SetJavaScriptEnabled")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView) findViewById(R.id.mainWebView);
        webView.setBackgroundColor(0x00000000);
        webView.setHorizontalScrollBarEnabled(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.loadUrl("http://www.broadbentstudios.com/");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }



        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView!=null && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    {

        ParseAnalytics.trackAppOpenedInBackground(getIntent());
    }

}

I also use Parse for push notifications for new content but I tried a clean webview app without it too and that didn’t work so I’m pretty sure it’s not that.

I would think that because it works fine in browsers it is my app messing up somewhere, but I could be wrong I guess. any help would be greatly appreciated, even if it’s my website and not my app, it would be good to know. Thank you.

Answer

Well I’ve been searching for about 2 months for an answer to this and as soon as I come here for help I find it myself haha, typical. Anyway, for anybody in a similar situation, as well as enabling javascript you also need to enable Dom storage by adding in;

webView.getSettings().setDomStorageEnabled(true);

Change webView to whatever yours is called and you should be good to go.

Hope this helps someone.

Categories
discuss

Passing named functions as arguments

Java 8 added lambda expressions. Using lambdas in a similar fashion to anonymous classes is pretty straight forward, but I’m wondering if the related functionality of using named functions as arguments to other functions exists. For example, is there a Java way to write the following Python code:

list1 = (1,2,3)
list2 = (4,5,6)

def add(a, b):
  return a+b

for e in map(add, list1, list2):
  print(e)

output

5
7
9

Answer

Yes, you can use method references like Integer::sum where lambdas are allowed.

int six = IntStream.of(1, 2, 3)
    .reduce(0, Integer::sum);

This is equivalent to

int six = IntStream.of(1, 2, 3)
    .reduce(0, (a, b) -> Integer.sum(a, b));

Methods like Integer.sum and Double.max were added in Java 8 precisely so they could be used in lambdas like this.

There’s no built-in way to “zip” together multiple lists the way Python does, though.

Categories
discuss

How can I pause/serialize a genetic algorithm in Encog?

How can I pause a genetic algorithm in Encog 3.4 (the version currently under development in Github)?

I am using the Java version of Encog.

I am trying to modify the Lunar example that comes with Encog. I want to pause/serialize the genetic algorithm and then continue/deserialize at a later stage.

When I call train.pause(); it simply returns null – which is pretty obvious from the code since the method always returns null.

I would assume that it would be pretty straight forward since there can be a scenario in which I want to train a neural network, use it for some predictions and then continue training with the genetic algorithm as I get more data before resuming with more predictions – without having to restart the training from the beginning.

Please note that I am not trying to serialize or persist a neural network but rather the entire genetic algorithm.

Answer

Not all trainers in Encog support the simple pause/resume. If they do not support it, they return null, like this one. The genetic algorithm trainer is much more complex than a simple propagation trainer that supports pause/resume. To save the state of the genetic algorithm, you must save the entire population, as well as the scoring function (which may or may not be serializable). I modified the Lunar Lander example to show you how you might save/reload your population of neural networks to do this.

You can see that it trains 50 iterations, then round-trips (load/saves) the genetic algorithm, then trains 50 more.

package org.encog.examples.neural.lunar;

import java.io.File;
import java.io.IOException;

import org.encog.Encog;
import org.encog.engine.network.activation.ActivationTANH;
import org.encog.ml.MLMethod;
import org.encog.ml.MLResettable;
import org.encog.ml.MethodFactory;
import org.encog.ml.ea.population.Population;
import org.encog.ml.genetic.MLMethodGeneticAlgorithm;
import org.encog.ml.genetic.MLMethodGenomeFactory;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.pattern.FeedForwardPattern;
import org.encog.util.obj.SerializeObject;

public class LunarLander {

    public static BasicNetwork createNetwork()
    {
        FeedForwardPattern pattern = new FeedForwardPattern();
        pattern.setInputNeurons(3);
        pattern.addHiddenLayer(50);
        pattern.setOutputNeurons(1);
        pattern.setActivationFunction(new ActivationTANH());
        BasicNetwork network = (BasicNetwork)pattern.generate();
        network.reset();
        return network;
    }

    public static void saveMLMethodGeneticAlgorithm(String file, MLMethodGeneticAlgorithm ga ) throws IOException
    {
        ga.getGenetic().getPopulation().setGenomeFactory(null);
        SerializeObject.save(new File(file),ga.getGenetic().getPopulation());   
    }

    public static MLMethodGeneticAlgorithm loadMLMethodGeneticAlgorithm(String filename) throws ClassNotFoundException, IOException {
        Population pop = (Population) SerializeObject.load(new File(filename));
        pop.setGenomeFactory(new MLMethodGenomeFactory(new MethodFactory(){
            @Override
            public MLMethod factor() {
                final BasicNetwork result = createNetwork();
                ((MLResettable)result).reset();
                return result;
            }},pop));

        MLMethodGeneticAlgorithm result = new MLMethodGeneticAlgorithm(new MethodFactory(){
            @Override
            public MLMethod factor() {
                return createNetwork();
            }},new PilotScore(),1);

        result.getGenetic().setPopulation(pop);

        return result;
    }


    public static void main(String args[])
    {
        BasicNetwork network = createNetwork();

        MLMethodGeneticAlgorithm train;


        train = new MLMethodGeneticAlgorithm(new MethodFactory(){
            @Override
            public MLMethod factor() {
                final BasicNetwork result = createNetwork();
                ((MLResettable)result).reset();
                return result;
            }},new PilotScore(),500);

        try {
            int epoch = 1;

            for(int i=0;i<50;i++) {
                train.iteration();
                System.out
                        .println("Epoch #" + epoch + " Score:" + train.getError());
                epoch++;
            } 
            train.finishTraining();

            // Round trip the GA and then train again
            LunarLander.saveMLMethodGeneticAlgorithm("/Users/jeff/projects/trainer.bin",train);
            train = LunarLander.loadMLMethodGeneticAlgorithm("/Users/jeff/projects/trainer.bin");

            // Train again
            for(int i=0;i<50;i++) {
                train.iteration();
                System.out
                        .println("Epoch #" + epoch + " Score:" + train.getError());
                epoch++;
            } 
            train.finishTraining();

        } catch(IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int epoch = 1;

        for(int i=0;i<50;i++) {
            train.iteration();
            System.out
                    .println("Epoch #" + epoch + " Score:" + train.getError());
            epoch++;
        } 
        train.finishTraining();

        System.out.println("nHow the winning network landed:");
        network = (BasicNetwork)train.getMethod();
        NeuralPilot pilot = new NeuralPilot(network,true);
        System.out.println(pilot.scorePilot());
        Encog.getInstance().shutdown();
    }
}
Categories
discuss

How should I handle a leave animation in componentWillUnmount in React?

I was wondering if anyone could provide some insight about how they handle leave animations in React.js. I have been using Greensock TweenMax and the enter animations work fine on componentDidMount, but I haven’t found a reliable way to animate a component out.

My feeling is that it should go in componentWillUnmount, but React provides no callback mechanism for you to indicate when you are ready to let go of a component. Therefore the transition animation never completes since the animations are asynchronous to React. Instead, you see a tiny fraction of a second of animation, the component disappears, and is replaced by the next component animating in.

This is a problem I have struggled with since I started using React 9 months ago. I can’t help but think there has to be a solution out there other than ReactCSSTransitionGroup which I find to be cumbersome and finicky, especially with react-router.

Answer

ReactTransitionGroup (upon which ReactCSSTransitionGroup is built) is the base component that allows asynchronous entering and leaving. It provides lifecycle hooks that you can use to hook into JS-based animations. The docs list the allowed hooks:

ReactTransitionGroup is the basis for animations. When children are declaratively added or removed from it (as in the example above) special lifecycle hooks are called on them. There are 3 ways to get starting using ReactCSSTransitionGroups:

import ReactCSSTransitionGroup from 'react-addons-css-transition-group' // ES6
var ReactCSSTransitionGroup = require('react-addons-css-transition-group') // ES5 with npm
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; // ES5 with react-with-addons.js

componentWillAppear(callback)

This is called at the same time as componentDidMount() for components that are initially mounted in a TransitionGroup. It will block other animations from occurring until callback is called. It is only called on the initial render of a TransitionGroup.

componentDidAppear()

This is called after the callback function that was passed to componentWillAppear is called.

componentWillEnter(callback)

This is called at the same time as componentDidMount() for components added to an existing TransitionGroup. It will block other animations from occurring until callback is called. It will not be called on the initial render of a TransitionGroup.

componentDidEnter()

This is called after the callback function that was passed to componentWillEnter is called.

componentWillLeave(callback)

This is called when the child has been removed from the ReactTransitionGroup. Though the child has been removed, ReactTransitionGroup will keep it in the DOM until callback is called.

componentDidLeave()

This is called when the willLeave callback is called (at the same time as componentWillUnmount).

Animation – Low-level API

In order to animate a child out, you’d need to start your animation in componentWillLeave and call the provided callback when the animation is complete. As an example, here’s a JSFiddle showing a component that stagger-animates its children in and out: http://jsfiddle.net/BinaryMuse/f51jbw2k/

The relevant code for animating out is:

componentWillLeave: function(callback) {
  this._animateOut(callback);
},

_animateOut(callback) {
  var el = ReactDOM.findDOMNode(this);
  setTimeout(function() {
    TweenLite.to(el, 1, {opacity: 0}).play().eventCallback("onComplete", callback);
  }, this.props.animateOutDelay);
},
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..