Categories
discuss

Cannot read property ‘call’ of undefined Webpack Bootstrap React

I’m having an issue that I have found others too have had. The only problem I am running into is that all solutions I have found do not seem to work for me. When I build my project everything succeeds without error. I then start webpack-dev-server on my built project within my dist folder. When I open the browser I receive the following error: Dev tools error log

Now this does not occur when I am running webpack-dev-server in development mode. The simple explanation is because I am not performing any code splitting in my webpack.config.dev.js file. So I know the problem is occurring with my CommonsChunkPlugin. I just cannot nail down exactly why. Here is the link to the repo that I am working on: Nappstir/react-landing-page. There is nothing complex about this project. I am simply trying to build a template for basic landing pages that will be built in React, thus no Redux is wired. Any ideas on what could be causing this error?

You can clone this project and simply run npm install and npm run build to build the project. Then just visit ‘http://localhost:3000/`

Answer

I actually found the reasoning as to why this error was occurring. It appears the issue had to do with the file order that my html-webpack-plugin was injecting the files. What was done to resolve this was use the chunks & chunksSortMode properties provided by html-webpack-plugin. The code would look something like this:

chunks: ['manifest', 'vendor', 'main'],
chunksSortMode: function (a, b) {
  let orders = ['manifest', 'vendor', 'main'];
  if (orders.indexOf(a.names[0]) > orders.indexOf(b.names[0])) {
    return 1;
  } else if (orders.indexOf(a.names[0]) < orders.indexOf(b.names[0])) {
    return -1;
  } else {
    return 0;
  }
},

This then returns each chunk in specified order of your chunks array.

Categories
discuss

Android JNI – Call function on Android UI thread from C++

Our game engine Cocos2d-x runs natively on android on its own non-Java-UI-thread. We need to call certain Java functions from C++ via JNI on the Android UI thread.

For calling JNI-Functions, we’re using the JNIHelper.h/cpp from here (GitHub): JniHelper.h, JniHelper.cpp

For example this C++ code:

auto retVal = JniHelper::callStaticStringMethod("org/utils/Facebook",
                         "getFacebookTokenString");

Ideally, we’d like to have all these calls happen on the Android UI thread and pass an std::function as a parameter which is called with the return value on the Cocos2d-x-thread again once the function call is done.

Ideal way to call the function:

auto retVal = JniHelper::callStaticStringMethod("org/utils/Facebook",
  "getFacebookTokenString", [=](std::string retVal) {
 printf("This is the retval on the C++ caller thread again: %s", retVal.c_str());
});

But there are also many calls without any return value, so for those it should be easier to just call them on the java thread.

Answer

As @Elviss has mentioned – to post your code to main thread you should use Looper. Actually this may be done without extra coping with JNI and creating of custom java.lang.Runnable and posting it via complicated JNI stuff.

Android NDK offers extremely lightweight and efficient way to post your native code to the arbitrary looper. The key point is that you should provide arbitrary file descriptor to the looper and specify what file events you are interested in (input, output, so on). Under the hood looper will poll that file descriptor and once event becomes available – it runs your callback on proper thread.

There is the minimal example (no error checks and teardowns):

#include <android/looper.h>
#include <unistd.h>

#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "sergik", __VA_ARGS__)

static ALooper* mainThreadLooper;
static int messagePipe[2];

static int looperCallback(int fd, int events, void* data);

void someJniFuncThatYouShouldCallOnceOnMainThread() {
    mainThreadLooper = ALooper_forThread(); // get looper for this thread
    ALooper_acquire(mainThreadLooper); // add reference to keep object alive
    pipe(messagePipe); //create send-receive pipe
    // listen for pipe read end, if there is something to read
    // - notify via provided callback on main thread
    ALooper_addFd(mainThreadLooper, messagePipe[0],
                  0, ALOOPER_EVENT_INPUT, looperCallback, nullptr);
    LOGI("fd is registered");    

    // send few messages from arbitrary thread
    std::thread worker([]() {
        for(char msg = 100; msg < 110; msg++) {
            LOGI("send message #%d", msg);
            write(messagePipe[1], &msg, 1);
            sleep(1);
        }
    });
    worker.detach();
}

// this will be called on main thread
static int looperCallback(int fd, int events, void* data) {
    char msg;
    read(fd, &msg, 1); // read message from pipe
    LOGI("got message #%d", msg);
    return 1; // continue listening for events
}

This code produces next output:

06-28 23:28:27.076 30930-30930/? I/sergik: fd is registered
06-28 23:28:27.076 30930-30945/? I/sergik: send message #100
06-28 23:28:27.089 30930-30930/? I/sergik: got message #100
06-28 23:28:28.077 30930-30945/? I/sergik: send message #101
06-28 23:28:28.077 30930-30930/? I/sergik: got message #101
06-28 23:28:29.077 30930-30945/? I/sergik: send message #102
06-28 23:28:29.078 30930-30930/? I/sergik: got message #102
06-28 23:28:30.078 30930-30945/? I/sergik: send message #103
06-28 23:28:30.078 30930-30930/? I/sergik: got message #103
06-28 23:28:31.079 30930-30945/? I/sergik: send message #104
06-28 23:28:31.079 30930-30930/? I/sergik: got message #104
06-28 23:28:32.079 30930-30945/? I/sergik: send message #105
06-28 23:28:32.080 30930-30930/? I/sergik: got message #105
06-28 23:28:33.080 30930-30945/? I/sergik: send message #106
06-28 23:28:33.080 30930-30930/? I/sergik: got message #106
06-28 23:28:34.081 30930-30945/? I/sergik: send message #107
06-28 23:28:34.081 30930-30930/? I/sergik: got message #107
06-28 23:28:35.081 30930-30945/? I/sergik: send message #108
06-28 23:28:35.082 30930-30930/? I/sergik: got message #108
06-28 23:28:36.082 30930-30945/? I/sergik: send message #109
06-28 23:28:36.083 30930-30930/? I/sergik: got message #109

As you see from pid-tid pairs – messages are received on main thread. And of course you may send something more complicated than one-byte messages.

Categories
discuss

VueJS component not rendering

I have a very basic vueJS app which I’m following from the website.

Here’s the code, why is the component not rendering?

HTML

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
</div>

<div>
<ol>
  <todo-item></todo-item>
</ol>
</div>

JS

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  }
})

Vue.component('todo-item', {
    template: '<li>This is a list item</li>'
})

Answer

Better, you can use the Single File Components to define the todo-item component inside another file:

app.vue

 import TodoItem from './components/todo-item'

 new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  components: {
    TodoItem
  }
})

components/todo-item.vue

<template>
  <li>This is a list item</li>
</template>

<script>
  export default {
    name: 'todo-item'
  }
</script>

In many Vue projects, global components will be defined using Vue.component, followed by new Vue({ el: '#container' }) to target a container element in the body of every page.

This can work very well for small to medium-sized projects, where JavaScript is only used to enhance certain views. In more complex projects however, or when your frontend is entirely driven by JavaScript, these disadvantages become apparent:

  • Global definitions force unique names for every component
  • String templates lack syntax highlighting and require ugly slashes for multiline HTML
  • No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out
  • No build step restricts us to HTML and ES5 JavaScript, rather than preprocessors like Pug (formerly Jade) and Babel

All of these are solved by single-file components with a .vue extension, made possible with build tools such as Webpack or Browserify.

Categories
discuss

Can I run a JS script from another using `fetch`?

Lower intermediate JS/JQ person here.

I’m trying to escape callback hell by using JS fetch. This is billed as “the replacement for AJAX” and seems to be pretty powerful. I can see how you can get HTML and JSON objects with it… but is it capable of running another JS script from the one you’re in? Maybe there’s another new function in ES6 to do:

$.getScript( 'xxx.js' );

i.e.

$.ajax({ url : 'xxx.js', dataType : "script", });

…?

later, response to Joseph The Dreamer:

Tried this:

const createdScript = $(document.createElement('script')).attr('src', 'generic.js');
fetch( createdScript )...

… it didn’t run the script “generic.js”. Did you mean something else?

Answer

Fetch API is supposed to provide promise-based API to fetch remote data. Loading random remote script is not AJAX – even if jQuery.ajax is capable of that. It won’t be handled by Fetch API.

Script can be appended dynamically and wrapped with a promise:

const scriptPromise = new Promise((resolve, reject) => {
  const script = document.createElement('script');
  document.body.appendChild(script);
  script.onload = resolve;
  script.onerror = reject;
  script.async = true;
  script.src = 'foo.js';
});

scriptPromise.then(() => { ... });

SystemJS is supposed to provide promise-based API for script loading and can be used as well:

System.config({
  meta: {
    '*': { format: 'global' }
  }
});

System.import('foo.js').then(() => { ... });
Categories
discuss

Java 8 lambda and alpha equivalence

I am wondering, is any nice way (if it is possible at all) to implement an alpha-equivalence comparison in Java-8?

Obviously these two lambda-s are alpha-equivalent. Let us suppose that for some circumstances we want to detect this fact. How it can be achieved?

Predicate<Integer> l1 = x -> x == 1;
Predicate<Integer> l2 = y -> y == 1;

Answer

I’m going out on a limb with this answer, but it may be worth mentioning this:

There is no way to do this. As Brian Goetz pointed out in an answer to a related question, there are no specified, reliable ways of obtaining the “contents” of a lambda, in that sense.

But (and now comes the vague, handwaving part) :

There is no way to do this yet.

It might be possible to do this in the future. Maybe not with Java 9, but later. The Project Panama has ambituous goals, among them, giving the developer a deeper access to lambdas, aiding in further (runtime) optimizations, translations and processing.

And recently, Radosław Smogura posted in the mailing list :

I try to capture lambda expression to get them as expression tree during runtime. I’m able to do it for simple lambdas like (o) -> (var == var) && ((varX == varX) && (someField + 1 == 1)), so later user can use (missing) API to examine tree.

Right now tree can be accessed with code like this:

Method m = BasicMatadataTest.class.getDeclaredMethod("lambda$meta0");
Expression e = (Expression) m.invoke(null);
BinaryExpression top = (BinaryExpression) e;
BinaryExpression vars = (BinaryExpression) top.getLefthandExpression(); // represents (var == var)
(VariableExpression) vars.getLefthandExpression() // represents first var, and it’s reference equal to vars.getRighthandExpression() as it’s same variable 

The key point here may be the comment:

represents first var, and it’s reference equal to vars.getRighthandExpression() as it’s same variable

(e.b.m)

So if I understood your question and this mailing list post correctly, then it might be possible to determine the equivalence between such expressions: Comparing the tree structure would be fairly trivial (given the functionality sketched above). And then it might boil down to treating two VariableExpression as being “equal”, regardless of the actual variable name.

The mailing list message points to the repositories:

(Disclaimer: I have not tested this, and don’t know how to get this running (or whether it works at all) – but to my understanding, it is at least very close to what the question was actually about).

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..