Friday 30 November 2018

Loop through properties in JavaScript object with Lodash

Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this:

myObject.options = {
  property1: 'value 1',
  property2: 'value 2'
};

Properties will get dynamically added to this object. Is there a way for me to just loop through and do a check if a property exists? If so, how?



from Loop through properties in JavaScript object with Lodash

How can I wait until I receive a data using Python socket?

I am creating a socket client and trying to obtain some data. In order to do so, I need to connect to a web server via socket and the server actually creates another socket which listens and awaits for the data after which sends back to the client. The problem I have with the code below is that my socket client does not wait for the incoming data from the server and just accepts an empty data.

How can I wait for a non-empty data from the server using Python sockets?

My code:

import sys
import json
import socketIO_client
import time

host = 'https://SOME_URL'

socketIO = socketIO_client.SocketIO(host, params={"email" : "edmund@gmail.com"})
def on_connect(*args):
    print "socket.io connected"

def on_disconnect(*args):
    print "socketIO diconnected"

socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)

def on_response_state(*args):
    print args # Prints ()

socketIO.emit('receive_state',on_response_state)
socketIO.wait_for_callbacks(seconds=3)



from How can I wait until I receive a data using Python socket?

BottomNavigationView goes up when keyboard appears using Android WebView

This answer doesn't work for WebViews, this doesn't either. So this question is specifically for when using a WebView. Below code loads a webpage with a text input field. When clicking the text input field, the keyboard comes up.

public class MainActivity extends AppCompatActivity {

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        final WebView webView = (WebView) findViewById(R.id.textFavorites);
        BottomNavigationView bottomNavigationView = (BottomNavigationView)
                findViewById(R.id.bottom_navigation);

        webView.loadUrl("https://www.journaldev.com");

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.action_favorites:
                                webView.loadUrl("https://www.journaldev.com");
                                break;
                        }
                        return false;
                    }
                });
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/textFavorites"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="?attr/actionBarSize"/>

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/bottom_navigation_main" />

</RelativeLayout>

Androidmanifest.xml:

    <activity
        android:name=".MainActivity"
        android:windowSoftInputMode="adjustPan">
    </activity>

bottom_navigation_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_favorites"
        android:enabled="true"
        android:icon="@drawable/ic_favorite_white_24dp"
        android:title="@string/text_favorites"
        app:showAsAction="ifRoom" />
</menu>



from BottomNavigationView goes up when keyboard appears using Android WebView

Android WebView - scrollbar don't fill the layout_height

I have a WebView with large text content. I'm using the following WebView settings:

    settings.setJavaScriptEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setSupportZoom(false);
    settings.setBuiltInZoomControls(false);
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webview.setScrollbarFadingEnabled(false);

The Html viewport settings are:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

The problem is that the scrollbar is going outside the layout, as follow:

My Android Layout is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <LinearLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />


    </LinearLayout>
</LinearLayout>



from Android WebView - scrollbar don't fill the layout_height

Check array for duplicate values if cookies aren't set, don't check if cookies are set

I'm working on a chatroom page where you first set your username and it sets the username value inside cookies. after this it loads different input boxes where you can send messages from in realtime. At this point you can reload the page and it will give you a pop-up which will display a welcome back message with the name value saved inside the cookies, which will also just set it as the username again and load the chatting page.

The problem is that I want to be able to prevent multiple duplicates of a name to be set from the username setting input field, but allow the username be set multiple times inside the array via cookies.

this function sets the original username:

//index.html
function setUsername() {
    var textbox = document.getElementById("name");
    var txtboxval = textbox.value;
    if(textbox.value.length <= 20 && textbox.value.length >= 4){
      socket.emit('setUsername', document.getElementById('name').value);
      setCookie("username", txtboxval, 30);
      socket.on('userExists', function(data) {

      });
    }
    else{
        alert("The name has to be at least 4 characters long");
        return false;
      }
    };

and these two set it on cookie load:

  //index.html
  function setUsername2() {
    var nimi = getCookie('username');
    socket.emit('setUsername', nimi);
  }

  function checkCookie() {
      var user = getCookie("username");
      if (user != "") {
          alert("Welcome again " + user);
          setUsername2();
          document.body.innerHTML = '<div class="wrapper"><div class="messagebox"><input type = "text" id = "message" placeholder = "Write your message here">\
          <button type = "button" id="sending" name = "button" onclick = "sendMessage()">Send</button></div>\
          <div id = "message-container"></div></div>';
      }
    }

now this here actually sets the username into the array where it digs it from on the index.html page:

  //app.js
  users = [];
  io.on('connection', function(socket){
    console.log('an user connected');
    console.log(users);
    socket.on('setUsername', function(data) {
      console.log(data);

        users.push(data);
        socket.emit('userSet', {username: data});
        console.log(users);
  });

I would like this piece of code to run when first setting the username, but not when it loads from cookies:

//app.js
if(users.indexOf(data) > -1) {
          socket.emit('userExists', data + ' Username is already taken.');
        } else {
          users.push(data);
          socket.emit('userSet', {username: data});
          console.log(users);
        }

Is there something I'm missing on why I can't get it to work as I would like it to? If something is unclear please ask.



from Check array for duplicate values if cookies aren't set, don't check if cookies are set

Fatal error: Use of unimplemented initializer 'init()' for class Swift

I am using MarkdownTextView to add basic markdown to a UITextView. The TextView is a subclass of MarkdownTextView.

However when using copy and paste I get the following error

Fatal error: Use of unimplemented initializer 'init()' for class MarkdownTextStorage

This is how I use the TextStorage in my ViewController

let fonty = UIFont(name: font, size: fsize)

attributes.defaultAttributes[NSFontAttributeName] = fonty
attributes.orderedListAttributes?[NSFontAttributeName] = fonty
attributes.orderedListItemAttributes?[NSFontAttributeName] = fonty
attributes.unorderedListAttributes?[NSFontAttributeName] = fonty
attributes.unorderedListItemAttributes?[NSFontAttributeName] = fonty

let textStorage = MarkdownTextStorage(attributes: attributes)

do {
   textStorage.addHighlighter(try LinkHighlighter())
} catch let error {
    fatalError("Error initializing LinkHighlighter: \(error)")
}
   textStorage.addHighlighter(MarkdownStrikethroughHighlighter())
   textStorage.addHighlighter(MarkdownSuperscriptHighlighter())

if let codeBlockAttributes = attributes.codeBlockAttributes {
        textStorage.addHighlighter(MarkdownFencedCodeHighlighter(attributes: codeBlockAttributes))
 }

I have used the following initialiser but still have no luck

required public init?(coder aDecoder: NSCoder) {
    attributes = MarkdownAttributes()
    super.init(coder: aDecoder)
    commonInit()
}

Here's the full source code for the class

open class MarkdownTextStorage: HighlighterTextStorage {

fileprivate let attributes: MarkdownAttributes

// MARK: Initialization

/**
Creates a new instance of the receiver.

:param: attributes Attributes used to style the text.

:returns: An initialized instance of `MarkdownTextStorage`
*/
public init(attributes: MarkdownAttributes = MarkdownAttributes()) {
    self.attributes = attributes
    super.init()
    commonInit()

    if let headerAttributes = attributes.headerAttributes {
        addHighlighter(MarkdownHeaderHighlighter(attributes: headerAttributes))
    }
    addHighlighter(MarkdownLinkHighlighter())
    addHighlighter(MarkdownListHighlighter(markerPattern: "[*+-]", attributes: attributes.unorderedListAttributes, itemAttributes: attributes.unorderedListItemAttributes))
    addHighlighter(MarkdownListHighlighter(markerPattern: "\\d+[.]", attributes: attributes.orderedListAttributes, itemAttributes: attributes.orderedListItemAttributes))

    // From markdown.pl v1.0.1 <http://daringfireball.net/projects/markdown/>

    // Code blocks
    addPattern("(?:\n\n|\\A)((?:(?:[ ]{4}|\t).*\n+)+)((?=^[ ]{0,4}\\S)|\\Z)", attributes.codeBlockAttributes)

    // Block quotes
    addPattern("(?:^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+", attributes.blockQuoteAttributes)

    // Se-text style headers
    // H1
    addPattern("^(?:.+)[ \t]*\n=+[ \t]*\n+", attributes.headerAttributes?.h1Attributes)

    // H2
    addPattern("^(?:.+)[ \t]*\n-+[ \t]*\n+", attributes.headerAttributes?.h2Attributes)

    // Emphasis
    addPattern("(\\*|_)(?=\\S)(.+?)(?<=\\S)\\1", attributesForTraits(.traitItalic, attributes.emphasisAttributes))

    // Strong
    addPattern("(\\*\\*|__)(?=\\S)(?:.+?[*_]*)(?<=\\S)\\1", attributesForTraits(.traitBold, attributes.strongAttributes))

    // Inline code
    addPattern("(`+)(?:.+?)(?<!`)\\1(?!`)", attributes.inlineCodeAttributes)
}

required public init?(coder aDecoder: NSCoder) {
    attributes = MarkdownAttributes()
    super.init(coder: aDecoder)
    commonInit()
}

fileprivate func commonInit() {
    defaultAttributes = attributes.defaultAttributes
}

// MARK: Helpers

fileprivate func addPattern(_ pattern: String, _ attributes: TextAttributes?) {
    if let attributes = attributes {
        let highlighter = RegularExpressionHighlighter(regularExpression: regexFromPattern(pattern), attributes: attributes)
        addHighlighter(highlighter)
    }
}

private func attributesForTraits(_ traits: UIFontDescriptorSymbolicTraits, _ attributes: TextAttributes?) -> TextAttributes? {
    var attributes = attributes
    if let defaultFont = defaultAttributes[NSFontAttributeName] as? UIFont , attributes == nil {
        attributes = [
            NSFontAttributeName: fontWithTraits(traits, font: defaultFont)
        ]
    }
    return attributes
}

}

Full Error Screenshot

enter image description here

Does anyone have any suggestions on how to fix the issue ?



from Fatal error: Use of unimplemented initializer 'init()' for class Swift

Multiline `ReplacementSpan` drawing issue

My custom replacement span works as long as text is not too long but as soon as text is longer than one line, span drawing completely breaks apart. My understanding is that draw() gets called twice in this case causing span to draw twice. There is no way to differentiate that second draw call from first one, giving you control over what to draw and where. start and end become useless as they report wrong values.

Is ReplacementSpan supposed to even work for multiline text? I would appreciate any help to resolve this issue.

enter image description here

This is what happens when I change selected text to my CustomReplacementSpan:

enter image description here

CustomReplacementSpan.kt

import android.graphics.Canvas
import android.graphics.Paint
import android.os.Build
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ReplacementSpan
import androidx.core.graphics.withTranslation

class CustomReplacementSpan(val spanText: String, val color: Int) : ReplacementSpan() {

    override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
        return paint.measureText(spanText).toInt()
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence?,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        paint.color = color

        canvas.drawMultilineText(
            text = spanText,
            textPaint = paint as TextPaint,
            width = canvas.width,
            x = x,
            y = top.toFloat()
        )
    }


}

fun Canvas.drawMultilineText(
    text: CharSequence,
    textPaint: TextPaint,
    width: Int,
    x: Float,
    y: Float,
    start: Int = 0,
    end: Int = text.length,
    alignment: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL,
    spacingMult: Float = 1f,
    spacingAdd: Float = 0f,
    includePad: Boolean = true,
    ellipsizedWidth: Int = width,
    ellipsize: TextUtils.TruncateAt? = null
) {
    val staticLayout =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StaticLayout.Builder.obtain(text, start, end, textPaint, width)
                .setAlignment(alignment)
                .setLineSpacing(spacingAdd, spacingMult)
                .setIncludePad(includePad)
                .setEllipsizedWidth(ellipsizedWidth)
                .setEllipsize(ellipsize)
                .build()
        } else {
            StaticLayout(
                text, start, end, textPaint, width, alignment,
                spacingMult, spacingAdd, includePad, ellipsize, ellipsizedWidth
            )
        }

    staticLayout.draw(this, x, y)
}

private fun StaticLayout.draw(canvas: Canvas, x: Float, y: Float) {
    canvas.withTranslation(x, y) {
        draw(this)
    }
}

MainActivity.kt

import android.os.Bundle
import android.text.Spannable
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun applySpan(view: View) {
        val editText = findViewById<EditText>(R.id.edit)
        if (editText.selectionStart < 0 || editText.selectionEnd < 0) {
            return
        }
        val fullText = editText.text
        val text = fullText.subSequence(editText.selectionStart, editText.selectionEnd)
        val span = CustomReplacementSpan(text.toString(), ContextCompat.getColor(this, android.R.color.holo_blue_dark))
        editText.text.setSpan(span, editText.selectionStart, editText.selectionEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edit"
        style="@style/Widget.AppCompat.EditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="applySpan"
        android:text="Make it span" />

</LinearLayout>



from Multiline `ReplacementSpan` drawing issue

Python: hide warning for "TIFFSetField"

I'm working with some TIFF files

The script will output "TIFFSetField: tempfile.tif: Unknown pseudo-tag 65538."

Is it possible to ignore/hide this?

Things I have tried running with:

-W ignore

and including this:

import warnings
warnings.filterwarnings("ignore")



from Python: hide warning for "TIFFSetField"

Cannot get two android emulators connectable

I create one socket server on AE1, and then create a client on AE2. I want to access the server on AE1 from AE2. So I follow the introduction. And still cannot get it work.

I understand that I should let the server in AE1 listen on 10.0.2.15:8080, and then I use redir add tcp:8080:8080 command in AE1's console to redirect all tcp connections to localhost:8080 to a private address 10.0.2.15:8080 which is in AE1. And in AE2, I should let AE2 connect to 10.0.2.2:8080 which is actually the localhost of host machine.

I understand this structure, but not matter how I try, I just cannot make it work. Don't know what's wrong with it. Further, I cannot even access the server in AE1 from my host machine. I guess I just haven't really redirect the localhost:8080 to 10.0.2.15:8080 successfully.

My OS is: Linux Mint 19

Android SDK: 28

And help is apperciated!



from Cannot get two android emulators connectable

Check array for duplicate values if cookies aren't set, don't check if cookies are set

I'm working on a chatroom page where you first set your username and it sets the username value inside cookies. after this it loads different input boxes where you can send messages from in realtime. At this point you can reload the page and it will give you a pop-up which will display a welcome back message with the name value saved inside the cookies, which will also just set it as the username again and load the chatting page.

The problem is that I want to be able to prevent multiple duplicates of a name to be set from the username setting input field, but allow the username be set multiple times inside the array via cookies.

this function sets the original username:

//index.html
function setUsername() {
    var textbox = document.getElementById("name");
    var txtboxval = textbox.value;
    if(textbox.value.length <= 20 && textbox.value.length >= 4){
      socket.emit('setUsername', document.getElementById('name').value);
      setCookie("username", txtboxval, 30);
      socket.on('userExists', function(data) {

      });
    }
    else{
        alert("The name has to be at least 4 characters long");
        return false;
      }
    };

and these two set it on cookie load:

  //index.html
  function setUsername2() {
    var nimi = getCookie('username');
    socket.emit('setUsername', nimi);
  }

  function checkCookie() {
      var user = getCookie("username");
      if (user != "") {
          alert("Welcome again " + user);
          setUsername2();
          document.body.innerHTML = '<div class="wrapper"><div class="messagebox"><input type = "text" id = "message" placeholder = "Write your message here">\
          <button type = "button" id="sending" name = "button" onclick = "sendMessage()">Send</button></div>\
          <div id = "message-container"></div></div>';
      }
    }

now this here actually sets the username into the array where it digs it from on the index.html page:

  //app.js
  users = [];
  io.on('connection', function(socket){
    console.log('an user connected');
    console.log(users);
    socket.on('setUsername', function(data) {
      console.log(data);

        users.push(data);
        socket.emit('userSet', {username: data});
        console.log(users);
  });

I would like this piece of code to run when first setting the username, but not when it loads from cookies:

//app.js
if(users.indexOf(data) > -1) {
          socket.emit('userExists', data + ' Username is already taken.');
        } else {
          users.push(data);
          socket.emit('userSet', {username: data});
          console.log(users);
        }

Is there something I'm missing on why I can't get it to work as I would like it to? If something is unclear please ask.



from Check array for duplicate values if cookies aren't set, don't check if cookies are set

double-precision 64-bit why append zeros to the end?

I was reading about double-precision 64-bitin javascript and in the examples i saw appending zeros to the end of mantissa and not to the start. No one in the examples explains it.

0 00000000010 10000000000000000000000000000000000000000
 why not 
0 00000000010 00000000000000000000000000000000000000001

Thank youu



from double-precision 64-bit why append zeros to the end?

Please recommend a Node module for writing IPTC data do images?

I have a node.js server whose job it is to download jpeg images, write certain data to a couple of IPTC fields (e.g. Iptc.Application2.Caption) and pass the image on to another service.

Ideally, I'd like to write the IPTC data to the in-memory buffer (without writing the image to the local file system). Failing that, I can live with a solution where I download, store the file to the FS, then apply the IPTC data.

I've got this working with https://github.com/dberesford/exiv2node, but it doesn't work on node.js v10. And it depends on exiv2 C++ library which makes it messy to run containerized.

So my question is: Is there a decent node module which enables IPTC data write, and does not depend on some monster C library?



from Please recommend a Node module for writing IPTC data do images?

tvOS launch image not visible

I'm creating a tvOS app and struggle for 2 days now with the launch image. It used to correctly show, then since few days ago the launch image no longer show, instead a blur is showing.

I've checked the image and it doesn't use an alpha canal, though in an other tvOS I work on the launch image do uses an alpha canal and it shows (and is accepted when uploaded to the store). The target is correctly set to use the launchImage.

Out of idea, I ended up creating a new singleview tvOS project, and set the valid project's launch image as launchImage. And it stil doesn't work.

For an unknown reason, the launchImage was showing at some point, but I could not reproduce it. I've then tried to clean the build folder multiple times, changing the deployment target between 9 and 12, setting "not launch image" and switch back, deleting the app from simulator or device before building... none worked.

What is going on?

edit: SO, I've downloaded tvOS 11.4 simulator. First try on the 11.4 simulator and the launch Image does show on it. Switching back on tvOS 12 simulator after and the launch image now also shows. I killed the simulator and retried on both versions: no launch image.

I just don't understand what is going on.

edit 2: It looks like I'e found a pattern: The launch Image only shows if the app is launched on the same session during which the app was installed on the simulator, and is not the first time the app is launched since install. In all other cases, not launch image.

Examples: run 1 (simulator launch and app installation) setup: app not installed, simulator not running result: launchImage is not shown

run 2 (app new launch): setup: app already installed, simulator already running result: launchImage is shown

run 3 (app new launch): setup: app already installed, simulator already running result: launchImage is shown

Now I close the simulator.

run 4 (app installation): setup: app already installed, simulator not running result: launchimage is not shown

run 5 (app new launch): setup: app already installed, simulator running result: launchimage is not shown

Now I delete the app

run 6 (app installation): setup: app not installed, simulator running result: launch image is not shown

It still never shows on a tvOS 12 device.



from tvOS launch image not visible

How to get list of paid apps by a user from google play?

I recently came across this app - Purchase Apps, which is somehow able to retrieve apps I've paid for in google play after I signed in using my google account.

I'm trying to find out how it is being done as I want to build a similar app, but for the free apps which were downloaded.

However, I cant find which OAuth API Scope was used for retrieving that information. I went through the entire list of APIs here.

Google Sign in asking for access to androidmarket

Please help.


EDIT: I'm putting a new bounty on this question, as suggested by a similar question I've asked about here, and because here and there I don't see a real answer about how to do it, and what can be done with it.

I'd like to refine the questions into multiple pieces:

  1. What is the API that can be used to get information of purchased apps? Where can I read about it? Please show a full, working example of how to do it.

  2. Can it do more ? Maybe perform search? Maybe show free apps that were installed? Maybe the time they were installed and uninstalled? And the categories of those apps?

  3. Are there any special requirements for using this API ?


EDIT: I'm putting a max bounty on this, because no matter how much I've read and tried, I still failed to make a POC that can query the apps from the Play Store that the user has downloaded (name, package name, date installed and/or removed, icon URL, price...) .

Please, if anyone finds a working sample, show how it's done, and also show how you've found about it (documentation or anything that has led you to the solution) . I can't find it anywhere, and the current solutions here are too vague for me to start from.



from How to get list of paid apps by a user from google play?

How do I unnest a column in a pandas DataFrame?

I have the following DataFrame where one of the columns is an object (list type cell):

df=pd.DataFrame({'A':[1,2],'B':[[1,2],[1,2]]})
df
Out[458]: 
   A       B
0  1  [1, 2]
1  2  [1, 2]

My expected output is:

   A  B
0  1  1
1  1  2
3  2  1
4  2  2

What should I do to achieve this?



from How do I unnest a column in a pandas DataFrame?

api-version is not being sent correctly

Dear friends I have a weird issue I try to connect to an API and when I try to do the API requests in postman or insomnia everything is okay but when I use the same code on my website or even localhost the leads request doesn't work and tells me that api-version is not defined.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://affiliate-api.tradingcrm.com:4477/token",
        "method": "POST",
        "data": "{ userName: \"alpt\", password: \"Alpt@12345\" }"
}

$.ajax(settings).done(function (response) {
        var settings2 = {
          "async": true,
          "crossDomain": true,
          "url": "https://affiliate-api.tradingcrm.com:4477/accounts/lead",
          "method": "POST",
          "headers": {
            "Authorization": "Bearer " + response.Token,
            "Api-Version": "3",
            "Content-Type": "application/json"
          },
          "data": "{firstName:\"test\",lastName:\"test2\",email:\"test@test.test\"}"
        }
        
        $.ajax(settings2).done(function (response2) {
          console.log(response2.accountId);
        });
        
});
</script>


from api-version is not being sent correctly

api-version is not being sent correctly

Dear friends I have a weird issue I try to connect to an API and when I try to do the API requests in postman or insomnia everything is okay but when I use the same code on my website or even localhost the leads request doesn't work and tells me that api-version is not defined.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://affiliate-api.tradingcrm.com:4477/token",
        "method": "POST",
        "data": "{ userName: \"alpt\", password: \"Alpt@12345\" }"
}

$.ajax(settings).done(function (response) {
        var settings2 = {
          "async": true,
          "crossDomain": true,
          "url": "https://affiliate-api.tradingcrm.com:4477/accounts/lead",
          "method": "POST",
          "headers": {
            "Authorization": "Bearer " + response.Token,
            "Api-Version": "3",
            "Content-Type": "application/json"
          },
          "data": "{firstName:\"test\",lastName:\"test2\",email:\"test@test.test\"}"
        }
        
        $.ajax(settings2).done(function (response2) {
          console.log(response2.accountId);
        });
        
});
</script>


from api-version is not being sent correctly

simpleSAMLphp: Unable to find the current binding

I am the SP, I can not loggedin into the SP using IDP of my client, I got below error:

SimpleSAML_Error_Error: ACSPARAMS

Backtrace:
1 modules/saml/www/sp/saml2-acs.php:21 (require)
0 www/module.php:135 (N/A)
Caused by: Exception: Unable to find the current binding.
Backtrace:
2 vendor/simplesamlphp/saml2/src/SAML2/Binding.php:99 (SAML2\Binding::getCurrentBinding)
1 modules/saml/www/sp/saml2-acs.php:16 (require)
0 www/module.php:135 (N/A)

My Configuration for authsource.php is like below:

'abc-live-sp' => array(
        'saml:SP',
         'privatekey' => 'saml.pem',
         'certificate' => 'saml.crt',
         'entityID' => null,
         'idp' => 'https://federation-a.parnassiagroep.nl/superbrains',
         'discoURL' => null,
         'NameIDPolicy' => false,

    ),

Is there anything i am missing?

help will be appreciated.



from simpleSAMLphp: Unable to find the current binding

Tensorflow: Dataset Map With num_parallel_calls Offers No Speedup

I'm using TensorFlow and the tf.data.Dataset API to perform some text preprocessing. Without using num_parallel_calls in my dataset.map call, it takes 0.03s to preprocess 10K records.

When I use num_parallel_trials=8 (the number of cores on my machine), it also takes 0.03s to preprocess 10K records.

I googled around and came across this: Parallelism isn't reducing the time in dataset map

where they indicate that you need to use TensorFlow operations to see a speedup. Here's the thing: I am using only TensorFlow operations. Specifically, I'm mapping this function:

def preprocess(self, x, data_table):
    x['reviews'] = tf.string_split(x['reviews'], delimiter=' ')
    x['reviews'] = tf.sparse_tensor_to_dense(x['reviews'], default_value=' ')
    x['reviews'] = tf.cast(data_table.lookup(x['reviews']), tf.int32)
    nbatch = tf.cast(tf.shape(x['reviews'])[0], tf.int32)
    nseq = tf.cast(tf.shape(x['reviews'])[1], tf.int32)
    padding = tf.cond(tf.less(nseq, 100),
                      lambda: 0 * tf.ones([nbatch, 100 - nseq], tf.int32),
                      lambda: 0 * tf.ones([nbatch, 0], tf.int32))
    x['reviews'] = tf.concat((x['reviews'], padding), axis=1)[:, :100]
    x['reviews'].set_shape([None, 100])
    return x

Any idea why I don't see any speedup?

Thanks!



from Tensorflow: Dataset Map With num_parallel_calls Offers No Speedup

php - autoload not working with static method

I using spl_autoload_register to autoload class like

My Structure

index.php
Module\Autoloader.php
Module\MyClass.php
Test\test.php

in index.php file

require_once ("Module\Autoloader.php");
use Module\MyClass;
include 'Test\test.php';

in Module\Autoloader.php file

class Autoloader {
static public function loader($className) {
    $filename = __DIR__."/" . str_replace("\\", '/', $className) . ".php";
    echo $filename.'<br>';
    if (file_exists($filename)) {
        include($filename);
    }
}

} spl_autoload_register('Autoloader::loader');

in Module\MyClass.php file

namespace Module;
class MyClass {
    public static function run() {
        echo 'run';
    }
}

in Test\test.php file

MyClass::run();

But it has error

Fatal error: Uncaught Error: Class 'MyClass' not found in ..\Test\test.php

How to fix that thank



from php - autoload not working with static method

Django how to use connection_created signal

I am looking to find out when a connection is made to my Django database, or when my Django server is restarted. I found the connection_created Django signal. The description is:

Sent when the database wrapper makes the initial connection to the database. This is particularly useful if you’d like to send any post connection commands to the SQL backend.

So I think using this signal will be a good solution for my case. I want to run a function once the connection is made. I can't find any documentations on the use cases of this signal. connection_created.connect is probably the function to use. This function takes in a bunch of arguments, but the ones that are relevant are self, receiver, sender and weak. Does anyone know how I can use these arguments and this function to run my function at a new connection instance?

Also if anyone has any alternative solutions other than this signal, I'd love to hear them.



from Django how to use connection_created signal

Using Google map marker cluster in Vuejs

I'm building a small application on Vuejs, where I'm using npm package a substitute for js-marker-clusterer I'm trying to load the map after I get a response from the API, following is my code:

var MarkerClusterer = require('node-js-marker-clusterer');
let rawMarkers=[];
let rawMarkers2=[];
$.each(response.data.data, function( key, value) {
    if((value.latitude != null) && (value.longitude != null) )
    {
        rawMarkers.push({
            name:value.name,
            lat:parseFloat(value.latitude),
            long:parseFloat(value.longitude),
            // conAr:value.technical_description.construction_area,
        });
    }
});
// console.log( rawMarkers);
// console.log( rawMarkers.map(obj => Object.values(obj)));

rawMarkers2=rawMarkers.map(obj => Object.values(obj));
let markers =rawMarkers2;

let displayDetails=[];
$.each(response.data.data, function( key, value) {
    let det='<div class="info_content">' +
        // '<h3>'+value.name+'</h3>' +
        '<a href="/#/projectprofile/'+value.slug+'" target="_blank">'+value.name+'</a>'+
        '</div>';
    displayDetails.push({
        det:det,
    });
    det='';
});
// console.log( displayDetails.map(obj => Object.values(obj)));
let infoWindowContent =displayDetails.map(obj => Object.values(obj));

if (this.mapState.initMap) { // map is already ready
    /*console.log("from mounted :"+this.mapState.initMap);
    alert("from mounted :"+this.mapState.initMap);*/


    let bounds = new google.maps.LatLngBounds();

    let map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: {lat: 21.7679, lng: 78.8718},
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    let labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';


    let markerBg = {
        url: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
        // This marker is 20 pixels wide by 32 pixels high.
        size: new google.maps.Size(80, 30),
        // The origin for this image is (0, 0).
        origin: new google.maps.Point(0, 0),
        // The anchor for this image is the base of the flagpole at (0, 32).
        anchor: new google.maps.Point(0, 32)
    };

    // Info Window Content
    // console.log(infoWindowContent);

    // Display multiple markers on a map
    let infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map
    for( i = 0; i < markers.length; i++ ) {
        let position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            label: markers[i][3],
            title: markers[i][0],
            animation: google.maps.Animation.DROP,
            icon: markerBg,
        });

        //Marker Cluster operation
        var mcOptions = {
            //imagePath: 'https://googlemaps.github.io/js-marker-clusterer/images/m',
            styles:[{

                url: "https://googlemaps.github.io/js-marker-clusterer/images/m1.png",
                width: 53,
                height:53,
                fontFamily:"comic sans ms",
                textSize:15,
                textColor:"red",
                //color: #00FF00,
            }]

        };
        var mc = new MarkerClusterer(map, marker, mcOptions);

        // Allow each marker to have an info window
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);
    }
}

But this shows the map like this:

Marker image

I want the images should appear like this:

enter image description here

I get code reference from this JSFiddle

Help me out in achieving this. Thanks



from Using Google map marker cluster in Vuejs

Python mysql sqlalchemy different results on localhost and server (heroku) | Look at last EDIT

I am using celery/redis and python/flask to process some very long background tasks. I am using heroku to host the project.

For the background tasks (I have 12 in total) I connect to an external MySQL DB (This means there should actually be no difference localhost vs heroku). For this I use sqlalchemy. Here is the connection:

DB_URI = 'mysql+pymysql://USER:PW@SERVER/DB'

engine = create_engine(stats_config.DB_URI, convert_unicode=True, echo_pool=True)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

In the task I am connecting to a mysql DB. I am using pymysql here and sqlalchemy.

The tasks are executed one by one.

The issue is that I get slightly different results for some of my tasks on localhost and on heroku. The result difference is really small, f.e. one of my tasks returns on localhost always 30111 and on heroku 29881.

The tasks, which return wrong values are always the same and the wrong values are always the same.

The only difference between localhost and heroku is, that I am using windows on localhost and linux on heroku. (I have red already some threads).

I am already using the same timezone by executing:

db_session.execute("SET SESSION time_zone = 'Europe/Berlin'")

So it cant be a time_zone issue.

Here is an example of a task with different results:

@shared_task(bind=True, name="get_gross_revenue_task")
def get_gross_revenue_task(self, g_start_date, g_end_date, START_TIME_FORM):

    db_session.close()
    start_date = datetime.strptime(g_start_date, '%d-%m-%Y')
    end_date = datetime.strptime(g_end_date, '%d-%m-%Y')

    gross_rev_trans_VK = db_session.query(func.sum(UsersTransactionsVK.amount)).filter(UsersTransactionsVK.date_added >= start_date, UsersTransactionsVK.date_added <= end_date, UsersTransactionsVK.payed == 'Yes').scalar()
    gross_rev_trans_Stripe = db_session.query(func.sum(UsersTransactionsStripe.amount)).filter(UsersTransactionsStripe.date_added >= start_date, UsersTransactionsStripe.date_added <= end_date, UsersTransactionsStripe.payed == 'Yes').scalar()
    gross_rev_trans = db_session.query(func.sum(UsersTransactions.amount)).filter(UsersTransactions.date_added >= start_date, UsersTransactions.date_added <= end_date, UsersTransactions.on_hold == 'No').scalar()

    if gross_rev_trans_VK is None:
        gross_rev_trans_VK = 0

    if gross_rev_trans_Stripe is None:
        gross_rev_trans_Stripe = 0

    if gross_rev_trans is None:
        gross_rev_trans = 0

    print ('gross', gross_rev_trans_VK, gross_rev_trans_Stripe, gross_rev_trans)

    total_gross_rev = gross_rev_trans_VK + gross_rev_trans_Stripe + gross_rev_trans

    return {'total_rev' : str(total_gross_rev / 100), 'current': 100, 'total': 100, 'statistic': 'get_gross_revenue', 'time_benchmark': (datetime.today() - START_TIME_FORM).total_seconds()}

# Selects gross revenue between selected dates
@app.route('/get-gross-revenue', methods=["POST"])
@basic_auth.required
@check_verified
def get_gross_revenue():
    if request.method == "POST":
        task = get_gross_revenue_task.apply_async([session['g_start_date'], session['g_end_date'], session['START_TIME_FORM']])
        return json.dumps({}), 202, {'Location': url_for('taskstatus_get_gross_revenue', task_id=task.id)}

Its actually very simple and fast, it finishes in a few seconds.

So what could be the issue here and how to address it?

P.S.: I forgot to mention, that sometimes the values are not wrong. I dont know yet why, I'd say if I execute the task 10 times on heroku, it will return 5 times the correct value 30111 and 5 times the wrong one 29881

EDIT

In the worker logs I noticed some SQL errors:

2013 Lost connection to MySQL

sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically

2014 commands out of sync

It seems like everytime these errors appear, the returned values are slightly wrong. The errors sound very serious, but my tasks still return successfully.

EDIT

No thats not it. I had now 2 executions without any SQL errors, but the results were wrong.

EDIT

Also it looks like that ALL tasks either return the correct values or the wrong values. It can never happen that TASK A returns a wrong value and TASK B a correct. If the values are wrong, than all tasks return a wrong value.

A very dirty fix would be to hardcode a variable of one of the tasks, execute it at first and simply check wether the value is correct. If not re-submit the form.

EDIT

I think I can now say where the problem is. It has something to do with the connection to the external MySQL DB. Its either the cache or the isolation_level or the way I use the session (db_session) or something similar.

Before every task I have tried now different approaches, which all influenced the behaviour on heroku:

#db_session.close()
#db_session.commit()
#db_session.execute('SET TRANSACTION READ ONLY')

For example db_session.execute('SET TRANSACTION READ ONLY') worked on localhost but shows an error on heroku.

I also tried to alter the connection itself with 'isolation_level="READ UNCOMMITTED'. I saw some changes on heroku, but it didn't solved it.

Basically I need the correct configuration. For the connection to the MySQL DB I only need to READ/GET the values, I will never INSERT or DELETE or UPDATE something.

I would still like to know why the behaviour is different (localhost VS. heroku).

After some more testing I am certain that the workers should not reuse the same db_session, also it seems that only tasks, which use db_session in the query can return wrong results:

For example the query above uses db_session.query(...). It has a chance to return a wrong value.

An other task I have uses: Users.query... instead of db_session.query(Users). It seems that it always returns a correct value.

Is there really a difference here? I always thought its simply a different syntax.



from Python mysql sqlalchemy different results on localhost and server (heroku) | Look at last EDIT

Connect to Azure analysis services from python

I have Azure analysis service instance, with tabular model, I need to query the data by DAX or MDX from python script.

I got a connection string from Azure that look's like this:

Provider=MSOLAP;Data Source=asazure://eastus.asazure.windows.net/mymodel;Initial Catalog=mycatalog;User ID=myuser@mail.com;Password=mypass;Persist Security Info=True;Impersonation Level=Impersonate

I tried to connect to that connection string with pyodbc:

import pyodbc

connection_str = "Provider=MSOLAP;Data Source=asazure://eastus.asazure.windows.net/mymodel;" \
                 "Initial Catalog=mycatalog;User ID=myuser@mail.com;Password=mypass;" \
                 "Persist Security Info=True;Impersonation Level=Impersonate"

my_connection = pyodbc.connect(connection_str)

I got this error:

Traceback (most recent call last):
  File "C:/workspace/test.py", line 7, in <module>
    my_connection = pyodbc.connect(connection_str)
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

Process finished with exit code 1



from Connect to Azure analysis services from python

Thursday 29 November 2018

Include header when chunks are fetched with code splitting

I've used code splitting to seprate restricted parts of my app into different chunks. This is working great so far, now I would like to ensure that the files themselves don't get served unless authenticated. I was thinking of using ngx_http_auth_request_module

http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request

Which allows to send a sub-request before serving certain files. How can I ensure that certain headers are always send as part of the HTTP request when React wants to fetch the necessary chunks?



from Include header when chunks are fetched with code splitting

Multiuser / multigame interaction

I'm about to create a multi-user game, I've been looking for something similar and what I've seen is that Kahoot does exactly what I want, I want a room that to join you need a Pin, so User1 can put the pin to join that room and User2 can put the pin to join that room too, and if you look at the room you'll see that there're two guys inside, ok, then I'm wondering also how to send those events, for instance, start the game, next deal, etc and how to update the scores according what users have replied or did.

The thing is is there any framework that could help me to realize it?

I've thought about for instance admin has logged in with his/her acc and he has a button to Start the "game", next "deal" and then the apps should receive the "starting game" and "next deal", but I'm wondering how could I do this.



from Multiuser / multigame interaction

How to attach an object's function to a Dio.js event?

The Dio.js GitHub page

The goal is to render dom elements and attach an event that is in the same object as the render function

When the webpage loads, I call an init function that render some divs and attach a click event to a function in the same object.

var thecheckbox = (function() {
  function x() {}

  x.prototype.isActivated = false // True when the user click the checkbox
  x.prototype.init = function() {
    let bodydiv = document.createElement('div')
    document.body.appendChild(bodydiv)


    d.render(this.render, bodydiv)
  }
  x.prototype.init = function() {
    let mybody = document.createElement('div')
    document.body.appendChild(mybody)


    d.render(this.render, protekBody)
  }
  x.prototype.activate = function() {
    console.log('Activate')
    var _this = this
    if (!_this.isActivated) {
      _this.isActivated = true
      var checkbox = document.getElementsByClassName('checkbox')[0]
      checkbox.getElementsByClassName(
        'checkbox2'
      )[0].style.display = 'block'

    }
  }
  x.prototype.render = function() {
    var _this = this
    return d.h(
      'div',
      { class: 'normal light' },
      d.h(
        'div',
        {
          class: 'content'
        },
        d.h(
          'div',
          {
            class: 'inline-block',
            onClick: this.activate // <<<---------
          },

        ),
        d.h(
          'div',
          { class: 'inline-block' },
          d.h(
            'div',
            { class: 'center' },
            d.h('div', { class: 'label center' }, strings.checkme)
          )
        )
      )
    )
  }

  return new x()
})()

// Initialize
_addEvent(document, 'ready', function() {
  thecheckbox.init()
})

I talked to the owner of the repo here (https://github.com/thysultan/dio.js/issues/85) and it still doesn't work as he explained.

I need to be able to access the object's properties outside the scope of Dio but attach an event to a dio dom element.

I tried converting the object to a regular object (not instantiated) and call d.render(d.h(thecheckbox), mydiv) but it doesn't works.



from How to attach an object's function to a Dio.js event?

Google sheets APIv4 comment data to pandas df, not values

I'm getting the notes for ranges A1:E7 of a sheet. There are notes in B1, E1, D4 and B7.

result = gsheets.service.spreadsheets().get(spreadsheetId=key, fields="sheets/data/rowData/values/note").execute()
data=result['sheets'][0]['data'][0]

produces the following dictionary:

{u'rowData': [
        {u'values': [{}, {u'note': u'B1 notes'}, {}, {}, {u'note': u'E1 notes'}]},
        {}, 
        {}, 
        {u'values': [{}, {}, {}, {u'note': u'D4 notes'}]},
        {}, 
        {}, 
        {u'values': [{}, {u'note': u'B7 notes'}]}
        ]
}

Now how do I get this into a 7x5 dataframe that mimics the range A1:E7? I want to use '' for the blank cells.



from Google sheets APIv4 comment data to pandas df, not values

How to bypass certificate verification in HTTPs based APIs using ionic 3 application (iOS and Android)?

We are developing ionic framework based application. While calling HTTP based APIs it is working correctly, but while accessing HTTPs based APIs it fails.

Here are the details: - APIs are running on Java Apache server validating certificate for certain domain addresses - There was an error with the request: Or else it ends up into error block (Angular / ionic httpclient) with : err.Status: "0 error"

Trials: We are able to access the same HTTPS certificate enabled APIs in below two ways (But only on local machine browser, not on device builds)

  • If running chrome with --disable-web-security mode (Change in CORS plugin)
  • If assigning ipaddress to .companyname.com domain in hosts file. Then it got verified with certificate and able to run the app.

As this two approaches can be done over desktop machine, and not sure how can we use such bypass mechanism on mobile app side.

Even if it asks the user for permission to bypass certificate then also it should be ok to us. But it should get connected to APIs and fetch data.

How to overcome this error over mobile applications build using ionic framework?



from How to bypass certificate verification in HTTPs based APIs using ionic 3 application (iOS and Android)?

Tensorflow to Keras: import graph def error on Keras model

I have a Tensorflow code for classifying images which I want to convert to Keras code. But I'm having trouble with the higher level API not having all codes which I desire. The problem which I have been stuck at is:

#net = get_vgg_model() <- got tf.VGG16 model
net = tf.keras.applications.VGG16()


g1 = tf.Graph()
with tf.Session(graph=g1, config=config) as sess, g1.device('/cpu:0'):
    tf.import_graph_def(net['graph_def'], name='vgg')

this code gives the error:

Traceback (most recent call last):
  File "app.py", line 16, in <module>
    from modules.xvision import Xvision
    File "/app/modules/xvision.py", line 84, in <module>
       tf.import_graph_def(net['graph_def'], name='vgg')
   TypeError: 'Model' object has no attribute '__getitem__'

Could someone help me with this graph?



from Tensorflow to Keras: import graph def error on Keras model

How to create a Lint check to ensure an Activity/Fragment is attached?

I am trying to create a custom Lint check so that particular annotated methods have to first ensure that the fragment/activity is attached/visible before doing any work.

E.g.

class MyFragment extends Fragment {

    @CheckIsActive
    void lint_fail() {
        // This would throw a lint warning
    }

    @CheckIsActive
    void lint_succeed() {
        if(isAdded()) {
            // This wouldn't throw a lint warning
        }
    }

}

To do this, I have created an IssueRegistry, the @CheckIsActive annotation and the following custom Detector class.

public class CheckActiveDetector extends Detector implements Detector.UastScanner {

    private static final String CHECK_ACTIVE_ANNOTATION = Constants.ANNOTATIONS_PREFIX + "CheckIsActive";

    private static final Implementation IMPLEMENTATION = new Implementation(
            CheckActiveDetector.class,
            Scope.JAVA_FILE_SCOPE);

    public static final Issue ISSUE = Issue.create(
            "CheckActive",
            "Method should check if the activity/fragment is active",
            "This method should ensure the Activity/Fragment is active before continuing",
            Category.CORRECTNESS,
            9,
            Severity.WARNING,
            IMPLEMENTATION
    );


    public CheckActiveDetector() {}

    @Nullable
    @Override
    public List<Class<? extends UElement>> getApplicableUastTypes() {
        return Collections.<Class<? extends UElement>>singletonList(UMethod.class);
    }

    @Nullable
    @Override
    public UElementHandler createUastHandler(@NotNull final JavaContext context) {
        return new UElementHandler() {
            @Override
            public void visitMethod(@NotNull UMethod node) {


                UExpression body = node.getUastBody();
                if(body != null && node.findAnnotation(CHECK_ACTIVE_ANNOTATION) != null) {

                    String methodName = node.getName();
                    String message = "Overriding method should call `isAdded()"
                            + methodName + "`";
                    Location location = context.getLocation(node);
                    context.report(ISSUE, node, location, message);

                }
            }
        };
    }
}

I have struggled to work out how to progress from the state I am in now, which is (I believe) entering a method and correctly checking if it was annotated. I am not sure with the detector methods, how to

  1. Check if the containing class extends Activity / Fragment
  2. Check if isAdded() for Fragment or isDestroyed() for Activity was called

Does anyone have any idea how to carry on from this or know where any of this is documented? It seems Google is not using the latest lint version within their source (e.g. CallSuper source) so that has not been too much help.

Thanks



from How to create a Lint check to ensure an Activity/Fragment is attached?

Index pytorch 4d tensor by values in 2d tensor

I have two pytorch tensors:

  • X with shape (A, B, C, D)
  • I with shape (A, B)

Values in I are integers in range [0, C).


What is the most efficient way to get tensor Y with shape (A, B, D), such that:

Y[i][j][k] = X[i][j][ I[i][j] ][k]



from Index pytorch 4d tensor by values in 2d tensor

How to setup codec, samplerate and bitrate on an audio blob in javascript?

I just created a blob:

const audioBlob = new Blob(audioChunks, { 'type' : 'audio/wav; codecs=0' });

and sent it to the backend in base64 format. I saved this into a file named "test.wav" using the following code:

await writeFile('./temp/test.wav', Buffer.from(filename.replace('data:audio/wav; codecs=0;base64,', ''), 'base64'), 'base64');

On the output "test.wav" file, I get the codec as opus, bitrate=N/A and sample rate=48000. I want to change these values to codec=wav, bitrate=256kbps and sample rate=16000. How to achieve it in node(or angular)?

Here is a link for my frontend code.



from How to setup codec, samplerate and bitrate on an audio blob in javascript?

How to setup codec, samplerate and bitrate on an audio blob in javascript?

I just created a blob:

const audioBlob = new Blob(audioChunks, { 'type' : 'audio/wav; codecs=0' });

and sent it to the backend in base64 format. I saved this into a file named "test.wav" using the following code:

await writeFile('./temp/test.wav', Buffer.from(filename.replace('data:audio/wav; codecs=0;base64,', ''), 'base64'), 'base64');

On the output "test.wav" file, I get the codec as opus, bitrate=N/A and sample rate=48000. I want to change these values to codec=wav, bitrate=256kbps and sample rate=16000. How to achieve it in node(or angular)?

Here is a link for my frontend code.



from How to setup codec, samplerate and bitrate on an audio blob in javascript?

Node.js Sandbox For Running Untrusted User Submitted Code

I’m trying to source a node.js sandbox capable of running untrusted user submitted code.


There are a couple of posts regarding this but they are all old. I’m hoping an up to date post will help.
(2011) How to run user-submitted scripts securely in a node.js sandbox?
(2012) How to run untrusted code serverside?
(2013) Safely sandbox and execute user submitted JavaScript?


Through the other posts and researching this I’ve found the following sandboxes and exploits:
(Jailed) https://github.com/asvd/jailed
(Jailed Exploit) https://github.com/asvd/jailed/issues/33

(Sandbox) https://github.com/gf3/sandbox
(Sandbox Exploit) https://github.com/gf3/sandbox/issues/50

(Sandcastle) https://github.com/bcoe/sandcastle
(Sandcastle Exploit) https://github.com/bcoe/sandcastle/issues/70

(Node’s VM) https://nodejs.org/api/vm.html#vm_vm_runinthiscontext_code_options
(In documentation) Note: The vm module is not a security mechanism. Do not use it to run untrusted code.

(VM2) https://github.com/patriksimek/vm2
(VM2 Exploit) https://github.com/patriksimek/vm2/issues/76


Does anyone know of a node.js sandbox with no known exploits?



from Node.js Sandbox For Running Untrusted User Submitted Code

Install by default, "optional" dependencies in Python (setuptools)

Is there a way to specify optional dependencies for a Python package that should be installed by default from pip but for which an install should not be considered a failure if they cannot be installed?

I know that I can specify install_requires so that the packages will be installed for the 90% of users using OSes that can easily install certain optional dependencies, and I also know I can specify extra_require to specify that users can declare they want a full install to get these features, but I haven't found a way to make a default pip install try to install the packages but not complain if they cannot be installed.

(The particular package I'd like to update the setuptools and setup.py for is called music21 for which 95% of the tools can be run without matplotlib, IPython, scipy, pygame, some obscure audio tools etc. but the package gains extra abilities and speed if these packages are installed, and I'd prefer to let people have these abilities by default but not report errors if they cannot be installed)



from Install by default, "optional" dependencies in Python (setuptools)

How to wrap column header in ag-grid using angular

I have some columns which has four words i.e Pre Trading Follow Up, Post Trading Follow Up and some of them having three words. I tried the below css to wrap the text to multiple lines.

::ng-deep .ag-theme-material .ag-header-cell-label .ag-header-cell-text{
  white-space: normal;
  overflow-wrap: break-word;
}

HTML

<ag-grid-angular class="ag-theme-material" [rowData]="rowData" [columnDefs]="columnDefs" [overlayLoadingTemplate]="overlayLoadingTemplate" [domLayout]="domLayout" [enableSorting]="true" (gridReady)="onGridReady($event)" (gridOptions)="gridOptions" >
  </ag-grid-angular>

but the column header remains the same. I wanted to wrap the column header text to multiple lines. Is there anyway to do this?

Note: I can able to wrap the content using cellStyle: {'white-space': 'normal'}

{headerName: 'headername', field: 'headerfield', autoHeight:true, width: 100, cellStyle: {'white-space': 'normal'}},

But I wanted to wrap the header.



from How to wrap column header in ag-grid using angular

How to wrap column header in ag-grid using angular

I have some columns which has four words i.e Pre Trading Follow Up, Post Trading Follow Up and some of them having three words. I tried the below css to wrap the text to multiple lines.

::ng-deep .ag-theme-material .ag-header-cell-label .ag-header-cell-text{
  white-space: normal;
  overflow-wrap: break-word;
}

HTML

<ag-grid-angular class="ag-theme-material" [rowData]="rowData" [columnDefs]="columnDefs" [overlayLoadingTemplate]="overlayLoadingTemplate" [domLayout]="domLayout" [enableSorting]="true" (gridReady)="onGridReady($event)" (gridOptions)="gridOptions" >
  </ag-grid-angular>

but the column header remains the same. I wanted to wrap the column header text to multiple lines. Is there anyway to do this?

Note: I can able to wrap the content using cellStyle: {'white-space': 'normal'}

{headerName: 'headername', field: 'headerfield', autoHeight:true, width: 100, cellStyle: {'white-space': 'normal'}},

But I wanted to wrap the header.



from How to wrap column header in ag-grid using angular

Code Coverage on React with Puppeteer + Istanbul

I have an app created with create-react-app and some UI tests written in Jest + Istanbul.

I want to get code coverage of these UI tests. I like to keep using jest as I already use it for unit-tests.

I'd like not to eject create-react-app if at all possible. But I'm open to it if there is no other choice.

What I've tried so far:

in package.json

"scripts": {
  "uitest": "react-scripts test --env=jsdom --verbose --testMatch='**/*.ui-test.{js}'",
}

if I run npm run uitest -- --coverage

attempt 1 failure

^ I think in above scenario it only captures the tests and not the actual App.

How do I fix this?


Other failed attempts:

1) How to cover React jsx files in Istanbul? - Don't apply as I'm using create-react-app

2) https://github.com/facebook/create-react-app/issues/3257 - apparently this feature was suggested but was rejected.

3) https://github.com/istanbuljs/puppeteer-to-istanbul/issues/18 - There is a library called puppeteer-to-istanbul but it doesn't support source maps. (See the link for issue)

4) I also looked at the book Node.js Web Development - Fourth Edition on safaribooks - I found a useful guide for Puppeteer but it doesn't seem to cover, code coverage.

5) Book Hands-On Continuous Integration and Delivery on safaribooks - has a section on Puppeteer + Jest testing, doesn't say anything about code coverage.

6) I tried puppeteer-to-istanbul -> We can calculate code coverage for bundle this way, it doesn't support source-maps.

7) Attempted Enselic's suggestion but couldn't get it working. It seems to crash on push method inside custom preset when trying to push babel-plugin-istanbul.



from Code Coverage on React with Puppeteer + Istanbul

Datatable checkbox issues

View:

<?php 
    $attributes = array('class' => 'form-horizontal', 'id' => 'Form');
    echo form_open($loginRedirect2,$attributes);
?>

<div class="stock_report" id="table_stock"> 

    <div class="stock_report" id="table_stock_print"> 
        <table id="order-listing" class="table">
            <thead>
                <tr class="bg-light">
                    <th><input type="checkbox" name="selectAll" id="selectAll" class="form-control" data-to-table="tasks" value=1></th>
                    <th>Code</th>
                    <
                </tr>
            </thead>
            <tbody class="reportData">
                <?php
                    if(is_array($employees)){
                    foreach($employees as $employee){
                ?>

                <tr>
                    <td class="a-center "><input type="checkbox" name="selectall[]" class="form-control" value="<?php echo $employee['employeeId']; ?>"/></td>
                    <td><?php echo $employee['Code'];?></td> 

                </tr>
                <?php
                    }
                    }else{
                ?>
                <?php
                    }   
                ?>
            </tbody>
            <tfoot>
                <tr class="bg-light">
                    <th><input type="checkbox" name="selectAll" id="selectAll" class="form-control" data-to-table="tasks" value=1></th>
                    <th>Code</th>

                </tr>
            </tfoot>
        </table>
    </div>
</div>
<div class="shift_category form-group">

    <button type="submit" class="btn btn-primary">Submit</button>
</div>
<?php echo form_close();?>

Script:

$(document).ready(function() {
        var oTable = $('#order-listing').dataTable( {
            initComplete: function () {
                this.api().columns().every( function () {
                    var column = this;
                    var select = $('<select><option value=""></option></select>')
                        .appendTo( $(column.footer()).empty() )
                        .on( 'change', function () {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );

                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        } );

                    column.data().unique().sort().each( function ( d, j ) {
                        select.append( '<option value="'+d+'">'+d+'</option>' )
                    } );
                } );
            },
            columnDefs: [ {
                orderable: false,
                className: 'select-checkbox',
                targets:   0
            } ],
            select: {
                style:    'multi',
                selector: 'td:first-child'
            },
            lengthMenu: [[20,50, 100, -1], [20, 50, 100, "All"]],
            pageLength: 20 
         } );
        var allPages = oTable.fnGetNodes();

        $('body').on('click', '#selectAll', function () {
            if ($(this).hasClass('allChecked')) {
                $('input[type="checkbox"]', allPages).prop('checked', false);
            } else {
                $('input[type="checkbox"]', allPages).prop('checked', true);
            }
            $(this).toggleClass('allChecked');
        });




    } );

Here is my datatable view and script.I added a checkbox to this datatable.But the problem is selectall option of checkbox is not properly working.Here this is a modal view.First time when i click the selectall button it is not working.When I press the escape button ,then open the modal,the selectall checkbox box click is working.How to solve this issue.



from Datatable checkbox issues

Exclude file from compilation during karma test runs

I am using angular-cli with Karma, and I need to exclude a particular file from being compiled when running unit tests.

The file in question is referenced in the error below, where it cannot be compiled due to a module not being present it relies on.

enter image description here

This file is used by other projects where the module will be present and so compiles fine, its just in this particular project it does not need compilation but still needs to be exported.

I have been trying to use the excludes option in the compiler options but I have not been able to get it to be ignored.

My angular-cli.json file has an entry like so:

"testTsconfig": "tsconfig.spec.json"

And in the tsconfig.spec.json I have added an excludes property specifying the path of the file to exclude:

"exclude": [
        "**/o3-test-harness.class.ts"
    ]

But it's not making any difference.

Should this be possible? Thanks



from Exclude file from compilation during karma test runs

React Native 0.57.x large images low quality

Swift: View freezing when dismissing VC?

I have a basic camera app similar to snapchats, when a user takes a picture they go to the preview and can see the image. When they are done they can press a button wich will dissmiss the VC an dgo back to the camera. This works fine, however when a user takes a video then previews it, then when they press the cancel button, dissmissing the VC, the View where they can take pictures becomes frozen.

To fix this issue I had originaly done a segue instead of a dissmiss. However I found this to make the cancel functionality very slow. SO my question is how can I resolve this freezing problem?

Below is how I currently transition out of my previewVC:

@IBAction func cancelButton(_ sender: UIButton) {
    dismiss(animated: false, completion: nil)
    //deletes video data
    self.playerQueue?.removeAllItems()
}

Bellow can be found the previewVC where Vids and photos are displayed

    class PreviewViewController: UIViewController {

    @IBOutlet weak var mediaView: UIImageView!

    var image: UIImage!

    //To hide status bar:
    //    var statusBarHidden : Bool?

    override func viewDidLoad() {
        super.viewDidLoad()

        print(self.image)
        mediaView.image = self.image

        //bellow is for vid

        if videoURL != nil {
            print("videoURL", videoURL)

            playerItem1 = AVPlayerItem(url: videoURL as URL)
            print(playerItem1, "playerItem1")

            playerQueue = AVQueuePlayer(playerItem: playerItem1)
            print(playerQueue, "player queue")

            playerLayer = AVPlayerLayer(player: playerQueue)
            print(playerLayer, "playerLayer")

            playerLooper = AVPlayerLooper(player: playerQueue, templateItem: playerItem1)
            print(playerLooper, "player looper")

            playerLayer.frame = view.bounds
            playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            print(mediaView, "yruewioq")
            mediaView.layer.insertSublayer(playerLayer, at: 0)

            view.layoutIfNeeded()
            self.playerQueue?.play()
        }
    }


    //TO SAVE:
    @IBAction func saveButton(_ sender: UIButton) {
        if videoURL == nil {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            dismiss(animated: false, completion: nil)
        }
    }

    //TO CANCEL:
    @IBAction func cancelButton(_ sender: UIButton) {
    dismiss(animated: false, completion: nil)
    }

    //receives url video value from VideoViewController
    var videoURL: URL!

    private var playerQueue: AVQueuePlayer!
    private var playerItem1: AVPlayerItem!
    private var playerLooper: AVPlayerLooper!
    private var playerLayer: AVPlayerLayer!        

}

Bellow is my viewDidLoad() in teh mainVC

    override func viewDidLoad() {
    super.viewDidLoad()
    print("67423814700000000")
    //INTEGRATION nov 24 (putting nside if espcially is inTEGRAIO)
    if setupInputOutput() {
        print("in this gfgf")
        setupCaptureSession()
        setupDevice()
        //setupInputOutput()
        //            setupPreviewLayer()
        startRunningCaptureSession()
    }
    setupPreviewLayer()


    //INTEGRATED below nov 24 START =-=-=-=-=-
    //for button ---||||||||
    cameraButton.isUserInteractionEnabled = true

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
    tapGesture.numberOfTapsRequired = 1
    cameraButton.addGestureRecognizer(tapGesture)

    let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
    longGesture.minimumPressDuration = 0.15
    //longGesture.allowableMovement = 100

    //this functionality below may be imp?
    //        longGesture.delaysTouchesBegan
    cameraButton.addGestureRecognizer(longGesture)

    camPreview.addSubview(cameraButton)
    //INTEGRATED below nov 24 END =-=-=-=-=-

}



from Swift: View freezing when dismissing VC?

Not reading all characters after seek

I'm trying to make a program that inserts log entries into a text file. The issue I'm having is that I read through the file line by line for a specific line and want to write before the line. Python correctly reads the line I'm looking for, however, when I seek to go back to the previous position, it does not read the entire line anymore. I checked the offset and it's exactly the same but for some reason the entire line isn't getting read.

def fileWriter():
    immediateTrigger = 0
    returnTrigger = 0;
    with open('C:\\testData.txt', 'r+') as file:
        for line in iter(file.readline, ''):
            #line = file.readline()
            if 'Beginning of text entries' in line:
                print('arrived at text entries')
                print(file.tell())
                print(line)
                immediateTrigger = 1
                file_pos = file.tell()
            while not line.strip() and immediateTrigger == 1:
                #print('here')
                prev_pos = file.tell()
                print(str(prev_pos) + 'before')
                newLine = file.readline()
                print(newLine)
                if 'Text Entry 25' in newLine:
                    file.seek(prev_pos)
                    print(str(file.tell()) + 'after')
                    print(file.readline()')
                    immediateTrigger = 0

The output I would get is:

arrived at text entries
Text Entry 1: The 1st revision
(random entries...)
36800 before
Text Entry 25: The 25th revision
36800 after
try 25: The 25th revision

Why does it cut off like this?



from Not reading all characters after seek

PHP - Create a PDF Trimbox

I'm using FPDF to create PDF files. But I need the file to have trimbox settings. How to do that.

The trimbox needs to be 210mm x 297mm and the file has cropmarks of 7mm so the actual size of the file is bigger... 214mm x 311mm

I found PDFLib but there is no budget to buy this server-side software.



from PHP - Create a PDF Trimbox

How to make 2 clients connect each other directly, after having both connected a meeting-point server?

I'm writing a toy meeting-point/relay server listening on port 5555 for two clients "A" and "B".

It works like this: every byte received by the server from the firstly-connected client A will be sent to the secondly-connected client B, even if they are not in the same network, and even if A and B don't know their respective IP:

A -----------> server <----------- B     # they both connect the server first
A --"hello"--> server                    # A sends a message to server
               server --"hello"--> B     # the server sends the message to B

This code is currently working:

# server.py
import socket, time
from threading import Thread
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('', 5555))
socket.listen(5)
buf = ''
i = 0

def handler(client, i):
    global buf
    print 'Hello!', client, i 
    if i == 0:  # client A, who sends data to server
        while True:
            req = client.recv(1000)
            buf = str(req).strip()  # removes end of line 
            print 'Received from Client A: %s' % buf
    elif i == 1:  # client B, who receives data sent to server by client A
        while True:
            if buf != '':
                client.send(buf)
                buf = ''
            time.sleep(0.1)

while True:  # very simple concurrency: accept new clients and create a Thread for each one
    client, address = socket.accept()
    print "{} connected".format(address)
    Thread(target=handler, args=(client, i)).start()
    i += 1

and you can test it by launching it on a server, and do two netcat connections to it: nc <SERVER_IP> 5555.

Now in the particular case where these two clients are in the same local network (example: using the same home router), this will be displayed on server when the 2 clients will connect to the server on port 5555:

('203.0.113.0', 50340) connected  # client A, router translated port to 50340
('203.0.113.0', 52750) connected  # same public IP, client B, router translated port to 52750

How can I then pass the information to client A and B that they can talk directly to each other without making the bytes transit via the server?

(in general and especially in the case where they are in the same local network)



from How to make 2 clients connect each other directly, after having both connected a meeting-point server?

Google Analytics, Server-Side Tracking & Bot Filter

When submitting an event, using the Google Analytics Measurement Protocol... GA is classifying the events as bot traffic. I can determine this by configuring two views in GA, one with bot filtering on, and one with bot filtering disabled. The events show up consistently in the view with bot filtering disabled.

We do not want to disable the bot filter in our primary view, as this would include a ton of unnecessary bot traffic.

What about this code is tripping up the bot filter?

payload = {
    'v': 1,
    't': 'event',
    'tid': tracking_id,
    'ec': category,
    'ea': action,
    'el': label
}

if value and type(value) is int:
    payload['ev'] = value

if user_id:
    payload['uid'] = user_id
else:
    payload['cid'] = str(uuid4())

  requests.post(
      'https://www.google-analytics.com/collect',
      data=payload,
      headers=requests.utils.default_headers()
  )



from Google Analytics, Server-Side Tracking & Bot Filter

Wednesday 28 November 2018

Filtering based on custom warning categories

In addition to pre-existing warning categories, users can define their own warning classes, such as in the code below:

$ cat mwe.py 
#!/usr/bin/env python3.5

import warnings
import pprint

class ObnoxiousWarning(UserWarning):
    pass

for i in range(3):
    print(i)
    warnings.warn("I don't like this.", ObnoxiousWarning)

When invoking Python, the -W flag controls how to filter warnings. But when I try to get it to ignore my freshly minted warning category, I'm told the filter is ignored:

$ python3.5 -W ignore::ObnoxiousWarning ./mwe.py
Invalid -W option ignored: unknown warning category: 'ObnoxiousWarning'
0
./mwe.py:11: ObnoxiousWarning: I don't like this.
  warnings.warn("I don't like this.", ObnoxiousWarning)
1
2

How can I use the commandline to insert a filter for custom warning categories?



from Filtering based on custom warning categories

NullPointerException: int android.widget.Editor$SelectionModifierCursorController.getMinTouchOffset()

It's a very strange Xiaomi device's OS exception. Even if I do have logs available from Fabric, the stack trace doesn't refer any of my code.

A crash details are below as reported in crashalytics(Fabric),

  • 21K crashes

  • All crashes on Xiaomi devices

  • Crashes on Android OS version 6, 7 and 8

Crash Log:

# OS Version: 8.1.0
# Device: Redmi Note 5 pro
# RAM Free: 30.1%
# Disk Free: 74.2%

#0. Crashed: main
       at android.widget.Editor.touchPositionIsInSelection(Editor.java:1084)
       at android.widget.Editor.performLongClick(Editor.java:1205)
       at android.widget.TextView.performLongClick(TextView.java:10908)
       at android.view.View.performLongClick(View.java:6360)
       at android.view.View$CheckForLongPress.run(View.java:24768)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:171)
       at android.app.ActivityThread.main(ActivityThread.java:6606)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:518)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

--

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.Editor$SelectionModifierCursorController.getMinTouchOffset()' on a null object reference
       at android.widget.Editor.touchPositionIsInSelection(Editor.java:1084)
       at android.widget.Editor.performLongClick(Editor.java:1205)
       at android.widget.TextView.performLongClick(TextView.java:10908)
       at android.view.View.performLongClick(View.java:6360)
       at android.view.View$CheckForLongPress.run(View.java:24768)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:171)
       at android.app.ActivityThread.main(ActivityThread.java:6606)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:518)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

#0. Crashed: main
       at android.widget.Editor.touchPositionIsInSelection(Editor.java:1084)
       at android.widget.Editor.performLongClick(Editor.java:1205)
       at android.widget.TextView.performLongClick(TextView.java:10908)
       at android.view.View.performLongClick(View.java:6360)
       at android.view.View$CheckForLongPress.run(View.java:24768)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:171)
       at android.app.ActivityThread.main(ActivityThread.java:6606)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:518)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

Similar Reference:

https://issuetracker.google.com/issues/37127697

java.lang.NullPointerException with Nougat

Also asked on Xiaomi official forum http://en.miui.com/forum.php?mod=viewthread&tid=4595164

Please do provide any working solution as soon as possible. As users must not be happy with these crashes.

Thanks in advance.



from NullPointerException: int android.widget.Editor$SelectionModifierCursorController.getMinTouchOffset()