Wednesday, 31 July 2019

Convert query builder conditions to MongoDB operations including nested array of subdocuments

I am building an application in Angular 8 on the client side and NodeJS 12 with MongoDB 4 / Mongoose 5 on the server side.

I have a query generated by the Angular2 query builder module. The Angular query builder object is sent to the server.

I have a server-side controller function that converts the Angular query object to MongoDB operations. This is working perfectly for generating queries for top-level properties such as "RecordID" and "RecordType". As required, this is also working for nested and/or conditions. However, I need to also support querying a nested array of subdocuments (the "Items" array in the example schema).

Here is the example schema I am trying to query:

{
  RecordID: 123,
  RecordType: "Item",
  Items: [
    {
      Title: "Example Title 1",
      Description: "A description 1"
    },
    {
      Title: "Example 2",
      Description: "A description 2"
    },
    {
      Title: "A title 3",
      Description: "A description 3"
    },
  ]
}

Here's an example of the query builder output with nested and/or conditions (working correctly):

{ "condition": "or", "rules": [ { "field": "RecordID", "operator": "=", "value": 1 }, { "condition": "and", "rules": [ { "field": "RecordType", "operator": "=", "value": "Item" } ] } ] }

Here's the query builder output after it has been converted to MongoDB operations (working correctly):

{ '$expr': { '$or': [ { '$eq': [ '$RecordID', 1 ] }, { '$and': [ { '$eq': [ '$RecordType', 'Item' ] } ] } ] }}

Here is the NodeJS query conversion function that converts the angular query object to mongodb operators. As mentioned it works for top level properties but does not to query nested array subdocuments.

Query conversion function:

const conditions = { "and": "$and", "or": "$or" };
const operators = { "=": "$eq", "!=": "$ne", "<": "$lt", "<=": "$lte", ">": "$gt", ">=": "$gte" };

const mapRule = rule => ({
    [operators[rule.operator]]: [ "$"+rule.field, rule.value ]
});

const mapRuleSet = ruleSet => {
    return {
        [conditions[ruleSet.condition]]: ruleSet.rules.map(
            rule => rule.operator ? mapRule(rule) : mapRuleSet(rule)
        )
    }
};

let mongoDbQuery = { $expr: mapRuleSet(q) };
console.log(mongoDbQuery);

Issue: This works great for top-level properties such as RecordID and RecordType. However, the problem is this does not work for querying the Items nested arrays of sub-documents.

Apparently, to query properties in nested arrays of subdocuments, the $elemMatch operator must be used, based on this related question. However, in my case, the $expr is necessary to build the nested and/or conditions so I can't simply switch to $elemMatch.

QUESTION: How can I adapt the "query conversion function" to also support nested arrays of subdocuments? Is there a way to get the $expr to work? I still need to be able to have the nested and/or conditions as shown above.

UPDATE:

Here is an example Angular query builder with the nested "Items" array of subdocuments. In this example, the results should match RecordType equals "Item" AND Items.Title equals "Example Title 1" OR Items.Title contains "Example".

Angular query builder with nested array of objects

Here is the query generated by the builder:

{"condition":"and","rules":[{"field":"RecordType","operator":"=","value":"Item"},{"condition":"or","rules":[{"field":"Items.Title","operator":"=","value":"Example Title 1"},{"field":"Items.Title","operator":"contains","value":"Example"}]}]}



from Convert query builder conditions to MongoDB operations including nested array of subdocuments

Change multiple elements colour based on background colour

I have a fixed menu which consists of multiple elements. I am trying to find a way to have all these elements change colour depending on the background colour.

The elements are a

#page::before,
.logo-scroll

both of these elements have a white border (no fill)

The links of the main navigation .main-navigation and their borders are white

The logo which is white. I also have a black version.

My site is made up of 3 section colours, black, white and yellow.

I would like the items to switch to black when the background sections are either yellow or white.

The website is very much a work in progress but you can see it here: https://www.sheree-new.shereewalker.com

I have tried this for the logo

https://eduardoboucas.com/blog/2017/09/25/svg-clip-path-logo-colour.html

but could not get it to work. I tried mix-blend mode for the elements but it makes the lines blue when on the yellow. I tried to do mix-blend-mode and THEN use the desaturate or greyscale filter but with no luck.

This is perhaps too much to tackle in one question but I thought perhaps there was a plugin that handled this in Wordpress?

The header which contains the left and right nav elements:

<div class="logo-scroll">
        <div class="scroll-text">
            <a href="/home"><img width="53px" height="260px" src="/wp-content/uploads/2019/07/sheree-walker-web-design-edinburgh-vertical-01.svg"/></a>
        </div>
    </div>  

    <header id="masthead" class="site-header">
        <nav id="site-navigation" class="main-navigation">
            <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'sheree_walker' ); ?></button>
            <?php
            wp_nav_menu( array(
                'theme_location' => 'menu-1',
                'menu_id'        => 'primary-menu',
            ) );
            ?>
        </nav><!-- #site-navigation -->
    </header><!-- #masthead -->

The CSS

header#masthead {
    height: calc(100vh - 60px);
    width: 75px;
    position: fixed;
    float: right;
    right: 30px;
    top:30px;
}

#site-navigation {
    transform: rotate(90deg);
    transform-origin: top left;
    position: relative;
    right: -75px;
    width: calc(100vh - 60px);
}

.main-navigation li {
    float: left;
    position: relative;
    text-align: center;
    width: 33.33%;
    padding: 23px 20px 21px 20px;
    font-size: 23px;
    font-family: 'NeurialGrotesk';
}

.main-navigation li {
    border-bottom: 2px solid white;
}

.main-navigation li:nth-child(n+1) {
    border-right: 2px solid white;
}

.main-navigation a {
    color: white;
    letter-spacing: .5px;
}

#page::before {
    content: "";
    position: fixed;
    top: 30px;
    bottom: 30px;
    left: 30px;
    right: 30px;
    border: 2px solid white;
    pointer-events: none;
}

.logo-scroll {
    position: fixed;
    left: 30px;
    top: 30px;
    bottom: 30px;
    border: 2px solid white;
    width: 75px;
}

.scroll-text {
    position: fixed;
}

All the sections have classes of either yellow or white - the default background is black.

Any help or advice on a suitable plugin would be great.

**Edit - something like this would be perfect if it applied to background colours

https://github.com/kennethcachia/background-check

I have also just tried this which sort of works but also generates a background colour at random

contrast();

function contrast() {

    var R, G, B, C, L;

    $( "main-navigation a" ).each(function() {

        R = (Math.floor(Math.random() * 256));
        G = (Math.floor(Math.random() * 256));
        B = (Math.floor(Math.random() * 256));

        $( this ).css( 'background-color', 'rgb(' + R + ',' + G + ',' + B + ')' );

        C = [ R/255, G/255, B/255 ];

        for ( var i = 0; i < C.length; ++i ) {

            if ( C[i] <= 0.03928 ) {

                C[i] = C[i] / 12.92

            } else {

                C[i] = Math.pow( ( C[i] + 0.055 ) / 1.055, 2.4);

            }

        }

        L = 0.2126 * C[0] + 0.7152 * C[1] + 0.0722 * C[2];

        if ( L > 0.179 ) {

            $( this ).css( 'color', 'black' );

        } else {

            $( this ).css( 'color', 'white' );

        }

    });

}



from Change multiple elements colour based on background colour

How to deal with React Native animated.timing in same child components

parrent Component:

routes.forEach((data, index) => {
  content.push(<Item key={index} offset={688} route={route} />)
})

Item Component:

scrollAnimate (toValue) {
  const { offset } = this.props;

  Animated.timing(
    this.state.xTranslate,
    {
      toValue,
      duration: 20000,
      easing: Easing.linear,
      useNativeDriver: true
    }
  ).start((e) => {
    if (e.finished) {
      const newState = {xTranslate: new Animated.Value(offset)}
      this.setState(newState, () => { this.scrollAnimate(toValue) })
    }
  });
}

I want every Item Component loop animate separate, but the fact is all ItemComponents animation end and then all Item Component start the animation together, how to fix it ?



from How to deal with React Native animated.timing in same child components

Scatter plot two feature vector set in same figure

I want to plot two feature vector in scatter plot in same figure. I am doing PCA analysis from MNIST.

Current Feature Vector lets call it Elements has 784 rows.

print Elements.shape
(784,)

I want to plot Elements[-20] and Elements[-19] scatter plot in same figure and want to achieve something like below.

I am struggling to add both elements into same plot with different color.

plt.scatter(X[-20], X[-19], c= 'r') yields only one color and no distinction of scattered value.

As hightlighted below someof my data sets are overlapping and hence below solution from SO doesnt work. SO solution

enter image description here



from Scatter plot two feature vector set in same figure

How to use firebase auth and Cloud Firestore from different components as a single firebase App

I am trying to use firebase in my React project to provide the auth and database functionalities.

In my App.js I have

import app from "firebase/app";
import "firebase/auth";
app.initializeApp(firebaseConfig);

In my other components called <Component /> rendered by App.js I have this to initialize the database

import app from "firebase/app";
import "firebase/firestore";
const db = app.firestore();

However this time I got this error

Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

So I tried to put app.initializeApp(firebaseConfig); in this component too but I got a new error again to tell me I instantiated twice.

Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).

So one workaround I came up with is to create a context at App.js and right after app.initializeApp(firebaseConfig); I created the database by const db = app.firestore(); and pass the value to the context and let the <Component /> to consume. However I don't know if this is a good solution or not.

My question is different from How to check if a Firebase App is already initialized on Android for one reason. I am not trying to connect to a second Firebase App as it was for that question. There is only one Firebase App for my entire project, to provide two services: auth and database.

I tried the solution from that question to use in <Component />

if (!app.apps.length) {
  app.initializeApp(firebaseConfig);
}

const db = app.firestore();

but it didn't work it still gives me Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). error



from How to use firebase auth and Cloud Firestore from different components as a single firebase App

Tensorflow & Keras can't load .ckpt save

So I am using the ModelCheckpoint callback to save the best epoch of a model I am training. It saves with no errors, but when I try to load it, I get the error:

2019-07-27 22:58:04.713951: W tensorflow/core/util/tensor_slice_reader.cc:95] Could not open C:\Users\Riley\PycharmProjects\myNN\cp.ckpt: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?

I have tried using the absolute/full path, but no luck. I'm sure I could use EarlyStopping, but I'd still like to understand why I am getting the error. Here is my code:

from __future__ import absolute_import, division, print_function

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
import datetime
import statistics

(train_images, train_labels), (test_images, test_labels) = np.load("dataset.npy", allow_pickle=True)

train_images = train_images / 255
test_images = test_images / 255

train_labels = list(map(float, train_labels))
test_labels = list(map(float, test_labels))
train_labels = [i/10 for i in train_labels]
test_labels = [i/10 for i in test_labels]

'''
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(128, 128)),
    keras.layers.Dense(64, activation=tf.nn.relu),
    keras.layers.Dense(1)
  ])

'''

start_time = datetime.datetime.now()

model = keras.Sequential([
    keras.layers.Conv2D(32, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=(128, 128, 1)),
    keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
    keras.layers.Dropout(0.2),
    keras.layers.Conv2D(64, (5, 5), activation='relu'),
    keras.layers.MaxPooling2D(pool_size=(2, 2)),
    keras.layers.Dropout(0.2),
    keras.layers.Flatten(),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(1000, activation='relu'),
    keras.layers.Dense(1)

])

model.compile(loss='mean_absolute_error',
    optimizer=keras.optimizers.SGD(lr=0.01),
    metrics=['mean_absolute_error', 'mean_squared_error'])

train_images = train_images.reshape(328, 128, 128, 1)
test_images = test_images.reshape(82, 128, 128, 1)

model.fit(train_images, train_labels, epochs=100, callbacks=[keras.callbacks.ModelCheckpoint("cp.ckpt", monitor='mean_absolute_error', save_best_only=True, verbose=1)])

model.load_weights("cp.ckpt")

predictions = model.predict(test_images)

totalDifference = 0
for i in range(82):
    print("%s: %s" % (test_labels[i] * 10, predictions[i] * 10))
    totalDifference += abs(test_labels[i] - predictions[i])

avgDifference = totalDifference / 8.2

print("\n%s\n" % avgDifference)
print("Time Elapsed:")
print(datetime.datetime.now() - start_time)



from Tensorflow & Keras can't load .ckpt save

PHP Java bridge exception - protocol error

I am running the PHP-Java bridge server (apache-tomcat). Sometimes I get an intermittent error. It's working when I restart the tomcat server from /opt/apache-tomcat-8.5.43/bin directory by ./shutdown.sh and startup.sh.

25-Jul-2019 13:53:52.766 SEVERE [http-nio-8080-exec-8] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [PhpCGIServlet] in context with path [/JavaBridge] threw exception
    php.java.fastcgi.ConnectionException
            at php.java.fastcgi.FCGIInputStream.read(FCGIInputStream.java:31)
            at php.java.fastcgi.FCGIHeaderParser.parseBody(FCGIHeaderParser.java:82)
            at php.java.servlet.fastcgi.FastCGIServlet.doExecute(FastCGIServlet.java:442)
            at php.java.servlet.fastcgi.FastCGIServlet.execute(FastCGIServlet.java:468)
            at php.java.servlet.fastcgi.FastCGIServlet.handle(FastCGIServlet.java:479)
            at php.java.servlet.fastcgi.FastCGIServlet.doGet(FastCGIServlet.java:507)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at php.java.servlet.PhpCGIFilter.doFilter(PhpCGIFilter.java:126)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
            at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
            at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
            at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
            at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
            at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:748)
    Caused by: java.io.IOException: Protocol error
            at php.java.fastcgi.FCGIInputStream.doRead(FCGIInputStream.java:56)
            at php.java.fastcgi.FCGIInputStream.read(FCGIInputStream.java:29)

Dockerfile:

FROM ubuntu:16.04

MAINTAINER Alexey Nurgaliev <atnurgaliev@gmail.com>

ENV DEBIAN_FRONTEND=noninteractive

ENV JAVA_BRIDGE_URL="https://sourceforge.net/projects/php-java-bridge/files/Binary%20package/php-java-bridge_7.1.3/php-java-bridge_7.1.3_documentation.zip/download"

ENV JAYBIRD_URL="https://github.com/FirebirdSQL/jaybird/releases/download/v2.2.13/Jaybird-2.2.13-JDK_1.8.zip"
ENV JAYBIRD_FILE_NAME="jaybird-full-2.2.13.jar"

ENV POSTGRESQL_URL="https://jdbc.postgresql.org/download/postgresql-9.4.1212.jar"
ENV POSTGRESQL_FILE_NAME="postgresql-9.4.1212.jar"

ENV TOMCAT_VERSION="8.5.43"
ENV TOMCAT_URL="http://apache-mirror.rbc.ru/pub/apache/tomcat/tomcat-8/v8.5.43/bin/apache-tomcat-8.5.43.tar.gz"
ENV TOMCAT_DIR="/opt/apache-tomcat-${TOMCAT_VERSION}"
ENV TOMCAT_LIB_DIR="${TOMCAT_DIR}/webapps/JavaBridge/WEB-INF/lib"

RUN apt-get update -y && \
    apt-get upgrade -y && \
    apt-get install -y unzip wget php-cgi openjdk-8-jre-headless locales && \
    apt-get install -y nano && \
    apt-get install -y curl wget && \
    locale-gen --lang ru_RU.UTF-8

RUN cd /opt &&\

    wget -O "tomcat.tar.gz" "${TOMCAT_URL}" &&\
    tar -xf "tomcat.tar.gz" &&\
    rm "tomcat.tar.gz" &&\

    wget -O "JavaBridge.zip" "${JAVA_BRIDGE_URL}" &&\
    unzip "JavaBridge.zip" -d "JavaBridge" &&\
    unzip -o "JavaBridge/JavaBridge.war" -d "${TOMCAT_DIR}/webapps/JavaBridge" &&\
    rm -R JavaBridge &&\
    rm JavaBridge.zip &&\

    wget -O "jaybird.zip" "${JAYBIRD_URL}" &&\
    unzip "jaybird.zip" -d "jaybird" &&\
    cp "jaybird/${JAYBIRD_FILE_NAME}" "${TOMCAT_LIB_DIR}" &&\
    rm -R "jaybird" &&\

    wget "${POSTGRESQL_URL}" &&\
    cp "${POSTGRESQL_FILE_NAME}" "${TOMCAT_LIB_DIR}" &&\
    rm "${POSTGRESQL_FILE_NAME}"

EXPOSE 8080

CMD LANG=ru_RU.UTF-8 "${TOMCAT_DIR}/bin/catalina.sh" run

enter image description here



from PHP Java bridge exception - protocol error

Angular Animation IE - Why is my animation moving the whole page and not the specified element?

I have an animation which works well in Chrome but not in IE/Edge. I want to slide a panel in from outside the browser window into view and then once the exit button or <div> which covers the rest of the page is clicked, the panel will animate off the screen and out of view.

When the panel animates off the screen in IE, it seems to work fine. For some reason though, when the panel comes into view, the animation triggers on the entire page and not the specified element (which just appears with no animation). This is very strange considering the panel is absolutely positioned and simply uses the right CSS property when coming into view; it shouldn't be affecting anything else.

EDIT:

I found the reason why this is happening. It's because I am animating on the position property which is triggering a repaint of the DOM element repeatedly. As a result, the animation doesn't run as well as expected in IE. It is recommended that animations are performed on the transform property with translateX() as it's value.

I have changed my code to reflect this, however a new error has been introduced - the whole page is transformed and not the specific element on Internet Explorer.

View demonstrations below:

Chrome (works fine; animation is smooth): Chrome Demonstration

IE (bug; entire page is moved): IE Demonstration

Code: side-bar-component.ts:

animations: [
    trigger('animateInOutTrigger', [
      transition(':enter', [
        style({ transform: 'translateX(0%)' }),
        animate('0.3s', style({ transform: 'translateX(-100%)' }))
      ]),
      transition(':leave', [
        animate('0.3s', style({ transform: 'translateX(0%)' }))
      ])
    ]),
    trigger('fadeScrim', [
      transition(':enter', [
        style({ transform: 'opacity: 0' }),
        animate('0.3s', style({ opacity: '1' }))
      ]),
      transition(':leave', [
        animate('0.3s', style({ opacity: '0' }))
      ]),
    ]),

side-bar-component.html:

<div id="btn-scrim" *ngIf="windowWidth >= 768 && open" class="scrim" (click)="onCloseSideBar()" @fadeScrim></div>
<div *ngIf="windowWidth >= 768 && open" class="sidebar-wrapper">
  <div @animateInOutTrigger class="container">
    <div class="header">
      <span class="text">Claim Details</span>
      <span id="btn-close-sidebar-desktop" (click)="onCloseSideBar()">X</span>
    </div>
    <div class="claims claims-padding">
      <p>some text</p>
      <p>some more text</p>
  </div>
</div>

side-bar-component.scss:

.sidebar-wrapper {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  transform: translateX(100%);
  z-index: 2;
}

.container {
  height: 100%;
  position: absolute;
  top: 0;
  box-sizing: border-box;
  background-color: white;
  box-shadow: 0 8px 10px -5px rgba(0, 0, 0, 0.2), 0 6px 30px 5px rgba(0, 0, 0, 0.12), 0 16px 24px 2px rgba(0, 0, 0, 0.14);
  z-index: 2;
  display: flex;
  flex-direction: column;
  transform: translateX(-100%);
}

.scrim {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, .32);
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
}

.header {
  height: 56px;
  background-color: #333333;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  color: white;
  position: relative;
  z-index: 2;
}

.text {
  font-size: 16px;
  font-weight: 500;
}

.claims {
  height: 100%;
  overflow-y: scroll;
  -ms-overflow-style: none;
  box-sizing: border-box;
  flex: 1;
}

.claims-padding {
  padding-bottom: 25vh;
}

STACKBLITZ RECREATION: https://stackblitz.com/edit/angular-ven7eu

I've tried:

  • Using state to control the transition instead of using :enter and :leave
  • Performing the same functionality without the Angular animations library and purely with CSS conditional classes

Other information:

  • Angular Core 8.0.0
  • Angular Animations 8.0.0 (I've tried downgrading to older versions and upgrading to latest minor and patch versions)

Why is this bug happening in Internet Explorer?



from Angular Animation IE - Why is my animation moving the whole page and not the specified element?

Flutter flavor for iOS gives SharedPreference error on run

Issue faced while trying to run flavors for iOS using Build Schemas

 /Labs/Workspace/Flutter/camp-flutter/ios/Runner/GeneratedPluginRegistrant.m:6:9: fatal error:
    'shared_preferences/SharedPreferencesPlugin.h' file not found
    #import <shared_preferences/SharedPreferencesPlugin.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.

Flutter Doctor output

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.7.8+hotfix.4, on Mac OS X 10.14.5 18F132, locale en-IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
[✓] iOS tools - develop for iOS devices
[✓] Android Studio (version 3.4)
[✓] VS Code (version 1.36.1)
[✓] Connected device (1 available)

• No issues found!

Additional Information

We are using flavors and schemes for iOS build and using below command to run applications

flutter run --flavor abcd --target lib/main/abcd_main.dart



from Flutter flavor for iOS gives SharedPreference error on run

Zoom and Mask using Glide

I'm just looking to see if anyone can point me in the right direction to learning how to accomplish this using Glide...

  • We have a page with content.

  • In easy reading mode, I want to center and zoom on the first block of text content and mask the rest

  • When 'next' is clicked, I want to move to the next block of text content, recenter and rezoom

  • When 'back' is clicked, I want to move to the previous block of text content, recenter and rezoom

  • the mask will always been rectangular but the size will constantly change to fit the content

I've put a couple of simple images below to show what I mean. We're currently doing this with an imageview and 4 black views that we position but it's very janky and prone to misalignments. Can we accomplish this in Glide?

Thanks all!

"Full Page" View "Easy Reading" View



from Zoom and Mask using Glide

How to switch audio track in .mkv file on Chromecast (iOS)

I found that we can add mediaTracks for external audio and subtitles. And activate it with setActiveTrackIDs.

But how I can change current audio track from english to different language? Any code example? Infuse player in store somehow can do this.



from How to switch audio track in .mkv file on Chromecast (iOS)

How do I change where an image is when it is following my pointer?

So I have the code (see below). The orange line is meant to follow my mouse, however I want to change the position that the line sits under my mouse's pointer. Right now, it seems that the mouse pointer is centered right on the line. I want the line to be offset to the left a bit so that the mouse pointer's tip is centered on the line (roughly).

What I have tried doing is in the CSS, adding a "left" attribute and giving it 5px, however nothing, mainly because I think left is already being attributed in the code below.

Any help is greatly appreciated!

$(document).mousemove(function(e){
    $("#image").css({left:e.pageX})});
#image{
position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img id="image" src="https://cdn3.imggmi.com/uploads/2019/7/24/5274c06660578c6f2b538d23ff87b7e9-full.png"/>


from How do I change where an image is when it is following my pointer?

BLE Connection getting lost after app is closed

I'm developing native BLE android app where I need to constantly remain connected with BLE device. Along with BLE, I also need to track GPS all the time until user doesn't logout. Here are my concerns

  1. Can we keep multiple service in foreground? In my case it has to be BLE and Location Tracking.

  2. I have seen that service getting killed though it is started using StartForeground in service onCreate. Is there any solution that can help me to keep my service alive all the time?

  3. I'm using START_STICKY in onStartCommand, though it gets killed in the background after long time.

  4. I'm writing characterstic using BluetoothGatt to send command to BLE device, I have multiple command to execute, is there any way I can know which command was executed from the response or I need to use flag variable to track the command request?

Please provide suggestions as I'm new to BLE feature.



from BLE Connection getting lost after app is closed

ngFor + ngModel: How can I unshift values to the array I am iterating?

I have an array of elements which the user can not only edit, but also add and delete complete array elements. This works nicely, unless I attempt to add a value to the beginning of the array (e.g. using unshift).

Here is a test demonstrating my problem:

import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';


@Component({
    template: `
        <form>
            <div *ngFor="let item of values; let index = index">
                <input [name]="'elem' + index" [(ngModel)]="item.value">
            </div>
        </form>`
})
class TestComponent {
    values: {value: string}[] = [{value: 'a'}, {value: 'b'}];
}

fdescribe('ngFor/Model', () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;
    let element: HTMLDivElement;

    beforeEach(async () => {
        TestBed.configureTestingModule({
            imports: [FormsModule],
            declarations: [TestComponent]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        element = fixture.nativeElement;

        fixture.detectChanges();
        await fixture.whenStable();
    });

    function getAllValues() {
        return Array.from(element.querySelectorAll('input')).map(elem => elem.value);
    }

    it('should display all values', async () => {
        // evaluation
        expect(getAllValues()).toEqual(['a', 'b']);
    });

    it('should display all values after push', async () => {
        // execution
        component.values.push({value: 'c'});
        fixture.detectChanges();
        await fixture.whenStable();

        // evaluation
        expect(getAllValues()).toEqual(['a', 'b', 'c']);
    });

    it('should display all values after unshift', async () => {
        // execution
        component.values.unshift({value: 'z'});
        fixture.detectChanges();
        await fixture.whenStable();

        // evaluation
        console.log(JSON.stringify(getAllValues())); // Logs '["z","z","b"]'
        expect(getAllValues()).toEqual(['z', 'a', 'b']);
    });
});

The first two tests pass just fine. However the third test fails. In the third test I attempt to prepend "z" to my inputs, which is successful, however the second input also shows "z", which it should not.

(Note that hundreds of similar questions exist on the web, but in the other cases people were just not having unique name-attributes and they are also just appending, not prepending).

Why is this happening and what can I do about it?



from ngFor + ngModel: How can I unshift values to the array I am iterating?

"no such column" SQL error from Android Room and multiple @Embedded fields on POJO

I have a nested POJO structure that should represent a single Game having multiple Rounds and each Round has a single Topic associated with it:

class GameWithRounds {
    @Embedded
    var game: Game? = null

    @Relation(
        parentColumn = "id",
        entityColumn = "gameId",
        entity = RoundRoom::class
    )
    var rounds: List<RoundWithTopic>? = null
}

class RoundWithTopic(
    @Embedded
    var round: RoundRoom,

    @Embedded(prefix = "topic_")
    var topic: Topic
)

The embedded annotation on Topic specifies a prefix because there are clashing id properties.

The Room Query that can fetch those classes is:

@Query("SELECT Topic.id as topic_id, Topic.name as topic_name, (...), RoundRoom.* FROM RoundRoom INNER JOIN Topic ON RoundRoom.topicId = Topic.id")
    abstract fun findRoundsWithTopics(): List<RoundWithTopic>

However, building the project gives me Room errors:

There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such column: topic_id)

Even though when I induce a warning about which fields are actually present, this is what Room tells me:

Columns returned by the query: topic_id, topic_name, topic_description, topic_language, topic_keywords, topic_sourceUrls, topic_furtherUrls, topic_questions, order, gameId, topicId, status, id. Fields in cz.melkamar.sklapecka.model.RoundWithTopic: order, gameId, topicId, status, id, topic_id, topic_name, topic_description, topic_language, topic_keywords, topic_sourceUrls, topic_furtherUrls, topic_questions, topic_image.

The topic_id column is there in the query result! Why am I getting this error?


For completeness, this is the entities:

@Entity
data class Game(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,

    @Embedded
    val gameConfigurationEmbed: GameConfigurationEmbed
)

@Entity(
    foreignKeys = [
        ForeignKey(
            entity = Game::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("gameId"),
            onDelete = ForeignKey.CASCADE
        ),
        ForeignKey(
            entity = Topic::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("topicId"),
            onDelete = ForeignKey.CASCADE
        )
    ]
)
@TypeConverters(RoomConverters::class)
data class RoundRoom(
    val order: Int,
    var gameId: Long,
    val topicId: String,
    var status: RoundStatus = RoundStatus.CREATED,

    @PrimaryKey(autoGenerate = true)
    val id: Long = 0
) {
    enum class RoundStatus {
        CREATED, UPCOMING, IN_PROGRESS, FINISHED
    }
}

@Entity
data class Topic(
    @PrimaryKey val id: String,
    val name: String,
    val description: String,
    val language: String,
    val keywords: List<String>,
    val sourceUrls: List<String>,
    val furtherUrls: List<String>,
    val questions: List<String>,
    val image: ByteArray?
)



from "no such column" SQL error from Android Room and multiple @Embedded fields on POJO

How to publish the key in PEM format and serve the key with the content-type "text/plain" using php?

"I'm working with Google AMP cache. First, I generate a pair key (private-key.pem/public-key.pub) using PHP. I've used the below code:

<?php 


$pkGenerate = openssl_pkey_new(array(
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA
));


openssl_pkey_export($pkGenerate,$pkGeneratePrivate); 


$pkGenerateDetails = openssl_pkey_get_details($pkGenerate);
$pkGeneratePublic = $pkGenerateDetails['key'];

openssl_pkey_free($pkGenerate);

$pkImport = openssl_pkey_get_private($pkGeneratePrivate); 

$pkImportDetails = openssl_pkey_get_details($pkImport); 
$pkImportPublic = $pkImportDetails['key'];

file_put_contents('private-key.pem', $pkGeneratePrivate); 
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/.well-known/amphtml/apikey.pub', $pkImportPublic); 


then verify the signature and make AMP google cache URL with below code:

function urlsafe_b64encode($string) {
    return str_replace(array('+','/','='),array('-','_',''), base64_encode($string));
}

$timestamp=time();
$ampBaseUrl = "https://www-example-com.cdn.ampproject.org";
$signatureUrl = '/update-cache/c/s/example.com/google-seo-articles/ten-signs-your-seo-company-is-not-a-shark/?amp_action=flush&amp_ts='.$timestamp;

// opening the private key
$pkeyid = openssl_pkey_get_private("file://private-key.pem");
// generating the signature
openssl_sign($signatureUrl, $signature, $pkeyid, OPENSSL_ALGO_SHA256);
openssl_free_key($pkeyid);
// urlsafe base64 encoding
$signature = urlsafe_b64encode($signature);
// final url for updating
$ampUrl = $ampBaseUrl.$signatureUrl."&amp_url_signature=".$signature;
$ampUrl = str_replace("&", "&amp", $ampUrl);
echo $ampUrl."\n";


output :

https://www-example-com.cdn.ampproject.org/update-cache/c/s/example.com/google-seo-articles/ten-signs-your-seo-company-is-not-a-shark/?amp_action=flush&amp_ts=1564374402&amp_url_signature=Wtnae4vEz5cn0El8bKBh6xLSiqhy2YmMEwyp3tbR5OzD7Ym4-MCE926p1IuJBMSUjmoaRZpBHDvvG-sdgtTQijYpHJ9QiNRvR4w_b92ZeeInQ5qxVW93gZzVq6ODlwPP8aphkT6635ny9bgHWblQTz0Np0XA9my-roVaRqAPRH1NgBRyQFcJAoLNhBITy4ta94mn4qModJRVCwjPxich_N1ZLLXgPtp4KBZl2sYWTnROhJ-OujFDHA-2E7_DT-hMte7WjP_lBQLffkmwCTTTI2lrXaYwzSWx9MJYDqmnC1o0rGH3PW4y6R6xQ2jRVK9vaNSQTixVylBmMQFPbzVKVQ


When I checking the output with browser google return Error 403 and Invalid public key due to ingestion error: Invalid Content

I've researched about Error 403 and I think my issue with the content-type public key.

The Google AMP cache guideline wrote

You must publish the key in PEM format and serve the key with the content-type "text/plain". 

I've checked my content-type public key with below curl

curl -H 'Accept-Encoding: gzip' -i https://www.example.com/.well-known/amphtml/apikey.pub


Output:

HTTP/1.1 200 OK
Date: Mon, 29 Jul 2019 04:38:58 GMT
Content-Type: application/x-mspublisher
Content-Length: 451
Connection: keep-alive
Set-Cookie: __cfduid=dc3c0780a997f6ddf625019d3cf579a991564375138; expires=Tue, 28-Jul-20 04:38:58 GMT; path=/; domain=.example.com;HttpOnly
Last-Modified: Sun, 28 Jul 2019 17:48:39 GMT
Accept-Ranges: bytes
Vary: User-Agent
X-Turbo-Charged-By: LiteSpeed
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 4fdc68069ff5e0fa-IAD


it shows Content-Type: application/x-mspublisher !

So, I want to change Content-Type: application/x-mspublisher to plain/text.

Please correct me if I am wrong.

thanks in advance.



from How to publish the key in PEM format and serve the key with the content-type "text/plain" using php?

View Android webview network requests that occurred on page load in Chrome devtools

If you have a webview open in Android, you can inspect it in Chrome devtools. However, I can't open the devtools first, then open the webview to log network requests that occur on page load. Is there a way to log network requests that occur as soon as the webview loads?

Also, refreshing the page behaves differently from the initial load because the page modifies the URL.



from View Android webview network requests that occurred on page load in Chrome devtools

Is there a way to combine Webpack modules to decrease file size?

I'm using CSS modules, so a lot of the modules Webpack generates look like this:

    124: function(t, e, n) {
        t.exports = {
            textarea: "TextareaStyles__textarea"
        }
    },

Then, it's used in React:

return t(r, {
    onInput: o(this, "str"),
    class: a.a.textarea
})

It'll be smaller if Webpack combined the CSS module and React component into a single module. Then, Uglify/Terser can probably just make it inline:

return t(r, {
    onInput: o(this, "str"),
    class: "TextareaStyles__textarea"
})

Is this possible?



from Is there a way to combine Webpack modules to decrease file size?

How to have absolute import paths in a library project?

I have a library with a workspace containing two projects, one for the library itself and one for a test application.

├── projects
    ├── midi-app
    └── midi-lib

In the workspace tsconfig.json file I configured some @app and @lib paths:

"paths": {
  "@app/*": ["projects/midi-app/src/app/*"],
  "@lib/*": ["projects/midi-lib/src/lib/*"],
  "midi-lib": [
    "dist/midi-lib"
  ],
  "midi-lib/*": [
    "dist/midi-lib/*"
  ]
}

There is a projects/midi-lib/tsconfig.lib.json file which extends on the above tsconfig.json file:

"extends": "../../tsconfig.json",

There is a public-api.ts file which contains:

export * from './lib/midi-lib.module';

I can use this library with the test application just fine.

But when I try using it in another client application, in another workspace, imported as a Node module, I get many errors on the unknown paths Can't resolve '@lib/...'

How to express the library paths so that they are exposed in a client application ? Or how to translate the library paths when packaging the library ?

As a side question, I wonder why the extends is not done the other way around. Why is it not the tsconfig.json file that extends on the projects/midi-lib/tsconfig.lib.json file ?

Here is how I package and then use the library:

To package the library, add the following scripts in the scripts array of the parent package.json file

"copy-license": "cp ./LICENSE.md ./dist/midi-lib",
"copy-readme": "cp ./README.md ./dist/midi-lib",
"copy-files": "npm run copy-license && npm run copy-readme",
"build-lib": "ng build midi-lib",
"npm-pack": "cd dist/midi-lib && npm pack",
"package": "npm run build-lib && npm run copy-files && npm run npm-pack",

and run the command: npm run package

then install the dependency

npm install ../midi-lib/dist/midi-lib/midi-lib-0.0.1.tgz

and import the module in the application module In the app.module.ts file have:

import { MidiLibModule } from 'midi-lib';
@NgModule({
  imports: [
    MidiLibModule

finally insert the component in a template

<midi-midi-lib></midi-midi-lib>

When the library is installed in a client application, it has lots of .d.ts files in the node_modules/midi-lib directories:

├── bundles
├── esm2015
│   └── lib
│       ├── device
│       ├── keyboard
│       ├── model
│       │   ├── measure
│       │   └── note
│       │       ├── duration
│       │       └── pitch
│       ├── service
│       ├── sheet
│       ├── soundtrack
│       ├── store
│       ├── synth
│       └── upload
├── esm5
│   └── lib
│       ├── device
│       ├── keyboard
│       ├── model
│       │   ├── measure
│       │   └── note
│       │       ├── duration
│       │       └── pitch
│       ├── service
│       ├── sheet
│       ├── soundtrack
│       ├── store
│       ├── synth
│       └── upload
├── fesm2015
├── fesm5
└── lib
    ├── device
    ├── keyboard
    ├── model
    │   ├── measure
    │   └── note
    │       ├── duration
    │       └── pitch
    ├── service
    ├── sheet
    ├── soundtrack
    ├── store
    ├── synth
    └── upload

Like this one lib/service/melody.service.d.ts file

import { SoundtrackStore } from '@lib/store/soundtrack-store';
import { ParseService } from '@lib/service/parse.service';
import { CommonService } from './common.service';
export declare class MelodyService {
    private soundtrackStore;
    private parseService;
    private commonService;
    constructor(soundtrackStore: SoundtrackStore, parseService: ParseService, commonService: CommonService);
    addSomeMelodies(): void;
    private addSoundtrack;
    private generateNotes;
}

As can be seen, it contains references to the @lib path mapping, which is not known in the client application.

I also tried to use the baseUrl property as a work around, but that didn't help either, as when installing the library, this baseUrl value was not specified.

Why is packaging the library with the command npm run package not resolving the paths mappings ?



from How to have absolute import paths in a library project?

Opening text messaging app with attachment

I'm trying to start an Intent from a Unity app that will launch the text messaging app with an attachment.

I have been able to open the text messaging app but the attachment does not load properly, throwing the following exception:

'Could not determine type of file:///storage/emulated/0/Android/data/com.torpedoesaway.memematch/files/Gifit2MemeFiles/gifit2meme-2019-09-7-09-39-54.gif java.io.IOException: java.lang.RuntimeException: setDataSource failed: status = 0x80000000'

Note that I have also tried loading other images, such as pngs and jpgs, all throwing the same error.

This is my code:

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:" + recipient));
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, attachment);

if (intent.resolveActivity(activity.getPackageManager()) != null) {
   activity.startActivity(intent);
}

I tried playing around with the intent action as well as the setData/setType calls and in one instance I am able to open the chooser, select the messaging app and then the attachment is loaded properly. However, I want to open the text messaging app directly with the attachment working.

Thanks in advance for the help!

Edit:

How I'm making the call from Unity:

AndroidJavaClass Uri = new AndroidJavaClass("android.net.Uri");
        AndroidJavaObject uri = Uri.CallStatic<AndroidJavaObject>("parse", path);

        unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        pluginClass = new AndroidJavaObject("com.torpedosaway.giftomessage.Gif2Message");
        pluginClass.Call(
            "ComposeMmsMessage",
            "53876045",
            "message",
            uri,
            unityClass.GetStatic<AndroidJavaObject>("currentActivity"));



from Opening text messaging app with attachment

Dagger can not find classes generated by other annotation processor

I have written a simple Annotation Processor (just for fun) that will generate some boilerplate code that I have been writing in my previous project. It actually generates a module like following by collecting annotations on Activity classes

@Module
abstract class ActivityInjectorModule {
  @ContributesAndroidInjector
  abstract fun providesMain2Activity(): Main2Activity

  @ContributesAndroidInjector
  abstract fun providesMainActivity(): MainActivity
}

However, when I run it with dagger, dagger can't seem to find classes generated by my annotation processor. Although, class is generated and present in generated directory, I can use it in my source code but on compilation, dagger produces the following exception. Any expert suggestion?

error: cannot find symbol
@dagger.Component(modules = {dagger.android.AndroidInjectionModule.class, com.mallaudin.daggietest.di.AppModule.class, ActivityInjectorModule.class})
                                                                                                                       ^
  symbol: class ActivityInjectorModule

This is the main app component.

@Singleton
@Component(
    modules = [
        AndroidInjectionModule::class,
        AppModule::class,
        ActivityInjectorModule::class
    ]
)
interface AppComponent : AndroidInjector<App> {


    @Component.Builder
    interface Builder {

        fun addContext(@BindsInstance ctx: Context): Builder

        fun build(): AppComponent
    }
}

ActivityInjectorModule class is generated by annotation processor and exists in the generated directory.

Application class

class App : DaggerApplication() {
    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder().addContext(this).build()
    }
}

Everything works perfectly, if I create the generated class myself. Somehow on compile time, dagger is unable to find the class when generated by my annotation processor.



from Dagger can not find classes generated by other annotation processor

Set default header for each page by css?

I working with my project for printing some documents.There I met some problem in set header for each print pages ! I want to print the html table that have so many tr ,its separated to two pages when print.Therefore,I want to set thead as header element for each print page.So help me !!

<style type="text/css">
table {
  border: 1px solid #eee;
  width: 100%;
  color : green;
}
th,td {
    border: 1px solid red;
    width: 50px;
    height: 50px;
}
@media print {
body * {visibility: hidden;}
#printable * {visibility: visible;}
#printable th {

    top: 0;
}
}
</style>
<div id="printable">
<span><center>Print Example</center></span>
<table>
    <thead>
        <tr><th>Name</th>
            <th>Salary</th>
            <th>Phone</th>
        </tr>
    </thead>
    <tbody>
        <tr><td>David</td>
            <td>3828</td>
            <td>83939</td>
        </tr>
        <tr><td>Jone</td>
            <td>39393</td>
            <td>0202022</td>
        </tr>
        <tr><td>Smith</td>
            <td>39000383929</td>
            <td>0101010101</td>
        </tr>
        <tr><td>Sheee</td>
            <td>3483939</td>
            <td>111111</td>
        </tr>
        <tr><td>David</td>
            <td>3828</td>
            <td>83939</td>
        </tr>
        <tr><td>David</td>
            <td>3828</td>
            <td>83939</td>
        </tr>
        <tr><td>David</td>
            <td>3828</td>
            <td>83939</td>
        </tr>
        <tr><td>David</td>
            <td>3828</td>
            <td>83939</td>
        </tr>
        <tr><td>Jone</td>
            <td>39393</td>
            <td>0202022</td>
        </tr>
        <tr><td>Smith</td>
            <td>39000383929</td>
            <td>0101010101</td>
        </tr><tr><td>Jone</td>
            <td>39393</td>
            <td>0202022</td>
        </tr>
        <tr><td>Smith</td>
            <td>39000383929</td>
            <td>0101010101</td>
        </tr><tr><td>Jone</td>
            <td>39393</td>
            <td>0202022</td>
        </tr>
        <tr><td>Smith</td>
            <td>39000383929</td>
            <td>0101010101</td>
        </tr><tr><td>Jone</td>
            <td>39393</td>
            <td>0202022</td>
        </tr>
        <tr><td>Smith</td>
            <td>39000383929</td>
            <td>0101010101</td>
        </tr><tr><td>Jone</td>
            <td>39393</td>
            <td>0202022</td>
        </tr>
        <tr><td>Smith</td>
            <td>39000383929</td>
            <td>0101010101</td>
        </tr>
    </tbody>
 </table>
</div>

Here I also want thead to page 2 when print.(Running on Chrome)

enter image description here



from Set default header for each page by css?

How to insert one to many with Knex.js and Bookshelf.js (ExpressJS/Postgress)

I'm trying to create a record on two tables when a user registers.

user.js

const db = require('../database');

const User = db.Model.extend({
  tableName: 'login_user',
  hasSecurePassword: true,
  hasTimestamps: true,
  team : () =>{
    return this.hasMany('Team', 'owner_id');
  }
});

module.exports = User;

team.js

const db = require('../database');

const Team = db.Model.extend({
  tableName: 'team_master',
  hasTimestamps: true,
  user: () => {
    return this.belongsTo('User', 'owner_id');
  },
});

module.exports = Team;

knex migration file

exports.up = function (knex, Promise) {
  return knex.schema.createTable('login_user', t => {
    t.increments('id').unsigned().primary();
    t.string('email').notNull();
    t.string('password_digest').notNull();
    t.string('fName').notNull();
    t.string('lName').notNull();
    t.timestamp('created_at').defaultTo(knex.fn.now())
    t.timestamp('updated_at').defaultTo(knex.fn.now())
  })
  .createTable('team_master', t => {
    t.increments('id').unsigned().primary();
    t.integer('owner_id').references('id').inTable('login_user');
    t.string('teamName').notNull();
    t.timestamp('created_at').defaultTo(knex.fn.now())
    t.timestamp('updated_at').defaultTo(knex.fn.now())
  });
};

exports.down = function (knex, Promise) {
  return knex.schema.dropTable('login_user').dropTable('team_master');
};

My insert code looks like the following

const user = new User({
    email: req.body.email,
    password: req.body.password,
    fName: req.body.fName,
    lName: req.body.fName,
    //teamName: req.body.teamName,
  });

  user.save().then(() => {
    res.send('User Created');
  });

So in this case what I want to do is insert teamName into the team_master table with the newly created unique user ID inserted into the owner_id in team_master table.

Can someone point me in the right direction around this? Thank you.



from How to insert one to many with Knex.js and Bookshelf.js (ExpressJS/Postgress)

Drag and Drop interfering with scroll Angular 7 CDK [ionic] [angular]

I have an ionic app, which is built in angular, and thus has angular cdk drag and drop in it to rearrange a list. Drag and drop works great, however, on mobile, I cannot scroll at all. I believe the drag and drop gestures are eating up my scroll gestures.

I've attempted to set the cdkDragStartDelay to 5000 (milliseconds):

<cu-task-row
  cdkDrag
  [cdkDragData]="task"
  [cdkDragStartDelay]="5000"

It does delay the drag, but I still cannot scroll.

Is it possible to scroll and have drag and drop implemented in mobile using Angular cdk?



from Drag and Drop interfering with scroll Angular 7 CDK [ionic] [angular]

Drag and Drop interfering with scroll Angular 7 CDK [ionic] [angular]

I have an ionic app, which is built in angular, and thus has angular cdk drag and drop in it to rearrange a list. Drag and drop works great, however, on mobile, I cannot scroll at all. I believe the drag and drop gestures are eating up my scroll gestures.

I've attempted to set the cdkDragStartDelay to 5000 (milliseconds):

<cu-task-row
  cdkDrag
  [cdkDragData]="task"
  [cdkDragStartDelay]="5000"

It does delay the drag, but I still cannot scroll.

Is it possible to scroll and have drag and drop implemented in mobile using Angular cdk?



from Drag and Drop interfering with scroll Angular 7 CDK [ionic] [angular]

Drag and Drop interfering with scroll Angular 7 CDK [ionic] [angular]

I have an ionic app, which is built in angular, and thus has angular cdk drag and drop in it to rearrange a list. Drag and drop works great, however, on mobile, I cannot scroll at all. I believe the drag and drop gestures are eating up my scroll gestures.

I've attempted to set the cdkDragStartDelay to 5000 (milliseconds):

<cu-task-row
  cdkDrag
  [cdkDragData]="task"
  [cdkDragStartDelay]="5000"

It does delay the drag, but I still cannot scroll.

Is it possible to scroll and have drag and drop implemented in mobile using Angular cdk?



from Drag and Drop interfering with scroll Angular 7 CDK [ionic] [angular]

Can't scrape the links of different companies from a website using requests

I'm trying to get the links of different companies from a webpage but the script I've tried with throws the error below. In chrome dev tools I could see that I can get the ids of different companies using post http requests. However, if I can get the ids then I will be able to make use of this link 'https://angel.co/startups/{}' adding id's in string format to make a full-fledged company link.

Webpage link

I've tried with:

import requests

link = 'https://angel.co/company_filters/search_data'
base = 'https://angel.co/startups/{}'

payload={'sort':'signal','page':'2'}

r = requests.post(link,data=payload,headers={
    'x-requested-with':'XMLHttpRequest'
    'User-Agent":"Mozilla/5.0'
    })
print(r.json())

The above script throws the following error:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

How can I get the links of different companies from the aforementioned site using requests?



from Can't scrape the links of different companies from a website using requests

What is the Maximum image dimensions supported in desktop Chrome?

This can be very broad, but let me just narrow it down. Assume that

  • Browser: Chrome Latest (Desktop)
  • Hardware: Windows Standard PC with default Intel Graphics card
  • Ram: 8GB
  • Processor: i7 @ 3.40 GHz

What is the maximum Width x Height I can support ?

If I try to put a 27150 x 20950 image into an <img> tag Chrome crashes.

So I want to know what the maximum width, height of an Image I can support.

Note: I have gone thru this post but its 8 years old

Edit 1: I am able to load a 160 Mb 4000 x 4000 px file so file size isnt a problem the 27150 x 20950 image is just 7 Mb. Compression isn't an option for me.



from What is the Maximum image dimensions supported in desktop Chrome?

Tuesday, 30 July 2019

Continuously update string in python curses

Trying to learn curses, I wrote this script that lets the user input two numbers, then outputs their sum and their difference:

import curses

screen = curses.initscr()
screen.refresh()

height = 4
width = 25
abwindow =  curses.newwin(height, width, int(0.15*int(curses.LINES)), int(curses.COLS/2) - width)
abwindow.addstr(1, 2, "a is : ")
abwindow.addstr(2, 2, "b is : ")

abwindow.border()
abwindow.refresh()

sumdiffwindow = curses.newwin(height, width, int(0.15*int(curses.LINES)), int(curses.COLS/2))
sumdiffwindow.addstr(1, 2, "a + b is : ")
sumdiffwindow.addstr(2, 2, "a - b is : ")

sumdiffwindow.border()
sumdiffwindow.refresh()

atocheck = abwindow.getstr(1, 10, 7)
btocheck = abwindow.getstr(2, 10, 7)

try:
    a = float(atocheck)
    b = float(btocheck)
    sum = a + b
    diff = a - b
    sumdiffwindow.addstr(1, 14, "%g" %(sum))
    sumdiffwindow.addstr(2, 14, "%g" %(diff))
except ValueError:
    sumdiffwindow.addstr(1, 14, "nan")
    sumdiffwindow.addstr(2, 14, "nan")

sumdiffwindow.refresh()
curses.curs_set(0)

while True:
    curses.noecho()
    c = screen.getch(1, 1)
    if c == ord('q') or c == ord('Q'):
        break

curses.endwin()

Once the two numbers are inputed, (if they are numbers) it calculates the sum and difference, and then it idles until the user presses 'q' to go back to the terminal. How can I change it so that I can update a and b as much as I want (using the keyboard up and down arrows to navigate between the two input boxes), while continuously displaying their current sum and difference?



from Continuously update string in python curses

d3 returns error `e is not a function` while passing nest data to d3.stack

The following code is throwing the error e is not a function from D3:

var stack = d3.stack()
    .offset("zero")
    .keys(Object.keys(data[0]))(nest);

The below images show the error in detail:

This is the error when I run it.

error is taking to d3.min.js

Formatted code in browser

This is the error when I run it, the error appears in d3.min.js. How do I fix this?



from d3 returns error `e is not a function` while passing nest data to d3.stack

Div sliding down menu

Well, this is actually a complicated problem, the default behavior of a header is simple, it gets in front of everything, however I want to put a div that will overlap it, putting a blur on the page, my goal is for the header to be behind of this div.

.body{
min-height: 2000px;
}

.overlay{
    background-color: rgba(126, 246, 53, 0.50);
    z-index: 1050;
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0;
}

.overlayDiv{
    background: white;
    z-index: 1051;
    margin-top: 100px;
    position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<nav class="navbar fixed-top navbar-light bg-light">
  <a class="navbar-brand" href="#">Header</a>
</nav>
  
<div class="body">

<div class="overlayDiv col-8 offset-2">
  <h1>That's divs on top of the page</h1>
</div>

<div class="overlay"></div>
  </div>

As you can see in the example, overlayDiv is above the overlay, which is what I want, but it goes over the menu, what I want is for the menu to be over it even being opaque, would that be possible?

Edit:

I would like to do something rather complicated, I will explain otherwise to try to clarify.

The top div has to go under the header when it gets there, and fade in behind it partially.

so it looks like it's entering the page just below the header, I thought of going to cut the height of her, but the content is not getting the way desired, example: cutting the text



from Div sliding down menu

Installed Xdebug but I cant find it in phpinfo

I've installed Xdebug but cant find it in phpinfo() output.

I am operating according to https://xdebug.org/wizard.php:

Tailored Installation Instructions Summary

Xdebug installed: no
Server API: FPM/FastCGI
Windows: no
Zend Server: no
PHP Version: 7.2.14-1
Zend API nr: 320170718
PHP API nr: 20170718
Debug Build: no
Thread Safe Build: no
OPcache Loaded: no
Configuration File Path: /etc/php/7.2/fpm
Configuration File: /etc/php/7.2/fpm/php.ini
Extensions directory: /usr/lib/php/20170718

Instructions

Download xdebug-2.7.0.tgz
Install the pre-requisites for compiling PHP extensions.
On your Ubuntu system, install them with: apt-get install php-dev autoconf automake
Unpack the downloaded file with tar -xvzf xdebug-2.7.0.tgz
Run: cd xdebug-2.7.0

Run: phpize (See the FAQ if you don't have phpize).

As part of its output it should show:

Configuring for:
...
Zend Module Api No:      20170718
Zend Extension Api No:   320170718

If it does not, you are using the wrong phpize. Please follow this FAQ entry and skip the next step.
Run: ./configure
Run: make
Run: cp modules/xdebug.so /usr/lib/php/20170718
Edit /etc/php/7.2/fpm/php.ini and add the line
zend_extension = /usr/lib/php/20170718/xdebug.so
Restart the webserver

restart php and nginx, it still doesn't work.

When I execute php -m|grep xdebug it returns:

Failed loading /usr/lib/php/20180731/xdebug.so: /usr/lib/php/2017/xdebug.so: undefined symbol: zend_post_startup_cb

I don't know what's the zend_post_startup_cb; I can't find any information in website.



from Installed Xdebug but I cant find it in phpinfo

How do I change names programmatically to tell apart UIViews in Xcode visual debugger?

How do I rename views in Xcode visual debugger? It's a sea of UIViews so it's nearly impossible to tell which uiview a constraint is for.

UIViewControllers show titles while for UIViews unless it's a derived class it's UIView. How do you tell them apart?

Case to the point

enter image description here



from How do I change names programmatically to tell apart UIViews in Xcode visual debugger?

GeoDjango: Finding objects in radius

I'm currently trying to get a list of points contained within a radius but I can't get it working. Here is the code of my view so far:

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import Distance

class AreaInfoViewSet(viewsets.ViewSet):
    queryset = models.AreaInfoRequest.objects.all()
    serializer_class = serializers.AreaInfoRequestRequestSerializer

    def list(self, request):
        center_point = 'POINT(48.80033 2.49175)'
        radius = "50.0"

        data = {"center_point": center_point, "radius": radius, "source_ip": utils.get_client_ip(request)}
        serializer = serializers.AreaInfoRequestRequestSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # Contains an object with field "from_location"="SRID=4326;POINT (48.80029 2.49157)"
        objs = models.PointsResult.objects.all()

        float_radius = serializer.data["radius"]
        center_point = serializer.data["center_point"] # Point object

        res = models.PointsResult.objects.filter(from_location__distance_lte=(
            center_point, Distance({"meter": float_radius})))
        # Here the res doesn't contain the unique object in the db even if it's within the radius

        return Response(res)

Any idea why it's not working? Thank you



from GeoDjango: Finding objects in radius

How to unit test form validation in Aurelia

I am trying to implement some unit tests on a form to see if the validation rules are working as expected.

from this page : https://github.com/aurelia/testing/issues/63

I found this implementation : https://github.com/aurelia/validation/blob/master/test/validate-binding-behavior.ts

and I tried to implement it in my project

login.spec.js

import {bootstrap} from 'aurelia-bootstrapper';
import {StageComponent} from 'aurelia-testing';
import {PLATFORM} from 'aurelia-pal';
import { configure, blur, change } from './shared';
import { Login } from './login';


describe('ValidateBindingBehavior', () => {
    it('sets validateTrigger', (done) => {
        const component = StageComponent
            .withResources(PLATFORM.moduleName('features/account/login/login'))
            .inView('<login></login>')
            .boundTo({});
        component.bootstrap(configure);
        let viewModel;
        const renderer = { render: jasmine.createSpy() };
        component.create(bootstrap)
            // grab some references.
            .then(() => {
            viewModel = component.viewModel;
            viewModel.controller.addRenderer(renderer);
        })

            .then(() => expect(viewModel.controller.errors.length).toBe(0))
            .then(() => blur(viewModel.firstName))
            .then(() => expect(viewModel.controller.errors.length).toBe(1))
            .then(() => component.dispose())
            .then(done);
    });
});

login.js

import { inject, NewInstance } from 'aurelia-dependency-injection';
import {  ValidationController } from 'aurelia-validation';
import { User } from './login.model';

@inject(NewInstance.of(ValidationController), User)
export class Login {
  constructor(controller, user) {
    this.controller = controller;
    this.firstName = '';
    this.lastName = '';
    this.userName = '';
    this.showForm = true;
    this.user = user;
  }
};


login.model.js

import {ValidationRules} from 'aurelia-validation';

export class User {
    firstName = '';
    lastName = '';
    userName = '';

    constructor() {
      ValidationRules
        .ensure('firstName')
        .required()  
        .ensure('lastName')
        .required()
        .minLength(10)
        .ensure('userName')
        .required()
        .on(this);
    }
  }

shared.js

import {DOM, PLATFORM} from 'aurelia-pal';

export function configure(aurelia) {
    return aurelia.use
    .standardConfiguration()
    .plugin(PLATFORM.moduleName('aurelia-validation'))
}
export function blur(element) {
    element.dispatchEvent(DOM.createCustomEvent('blur', {}));
    return new Promise(resolve => setTimeout(resolve));
}
export function change(element, value) {
    element.value = value;
    element.dispatchEvent(DOM.createCustomEvent('change', { bubbles: true }));
    return new Promise(resolve => setTimeout(resolve));
}

and here is a piece of html markup :

    <div>
      <input ref="firstName" type="text" value.bind="user.firstName & validateOnBlur"
        validation-errors.bind="firstNameErrors">
      <label style="display: block;color:red" repeat.for="errorInfo of firstNameErrors">
        ${errorInfo.error.message}
      </label>
    </div>
    <div>

in the spec, when I blur the element I expect to get one error, but "controller.errors" is always an empty array. and I get this for the failed message :

Error: Expected 0 to be 1.

UPDATE:

I tried to validate manually, so I added this in my spec :

.then(()=> 
        viewModel.controller.validate({object: viewModel.user, propertyName: 'firstName' })

)

and it works fine, but the blur and change functions don't trigger validation.



from How to unit test form validation in Aurelia

VsCode intelliSense Problem with Sequelize.Model

I have some problems with intelliSense with class Sequelize.Model A lot of methods from Model doesn't linked with IS in vscode after set property Sequelize.Model

With default class

With @property jsdoc Sequelize.Model


 /**
  * @typedef DB
  * 
  * @property {Sequelize} sequelize
  * @property {Sequelize.Model} User
  * @property {Sequelize.Model} Product
  */

/**
 * @type {DB}
 */
const db = {
    ...models,
    sequelize
};
db.User.



from VsCode intelliSense Problem with Sequelize.Model

Why are breakpoints in Visual Code treated differently depending on how the file was opened?

A breakpoint in my Mocha test works when set in one tab, but not in another.

I figured out that if you do File->Open, then the full path appears in the tab, and breakpoints work. (Second item in screenshot.)

Two different access paths

But if you open it from the Explorer or Find views (first item in screenshot above), which is a more natural way to access a file, the full path does not appear, and breakpoints all become Unverified (gray) during execution.

How can I avoid this while still opening files in the normal way?



from Why are breakpoints in Visual Code treated differently depending on how the file was opened?

Error:

How to find the most likely sequences of hidden states for a Hidden Markov Model

The Viterbi algorithm finds the most likely sequence of hidden states in a Hidden Markov Model. I am currently using the following awesome code by hhquark.

import numpy as np


def viterbi_path(prior, transmat, obslik, scaled=True, ret_loglik=False):
    '''Finds the most-probable (Viterbi) path through the HMM state trellis
    Notation:
        Z[t] := Observation at time t
        Q[t] := Hidden state at time t
    Inputs:
        prior: np.array(num_hid)
            prior[i] := Pr(Q[0] == i)
        transmat: np.ndarray((num_hid,num_hid))
            transmat[i,j] := Pr(Q[t+1] == j | Q[t] == i)
        obslik: np.ndarray((num_hid,num_obs))
            obslik[i,t] := Pr(Z[t] | Q[t] == i)
        scaled: bool
            whether or not to normalize the probability trellis along the way
            doing so prevents underflow by repeated multiplications of probabilities
        ret_loglik: bool
            whether or not to return the log-likelihood of the best path
    Outputs:
        path: np.array(num_obs)
            path[t] := Q[t]
    '''
    num_hid = obslik.shape[0] # number of hidden states
    num_obs = obslik.shape[1] # number of observations (not observation *states*)

    # trellis_prob[i,t] := Pr((best sequence of length t-1 goes to state i), Z[1:(t+1)])
    trellis_prob = np.zeros((num_hid,num_obs))
    # trellis_state[i,t] := best predecessor state given that we ended up in state i at t
    trellis_state = np.zeros((num_hid,num_obs), dtype=int) # int because its elements will be used as indicies
    path = np.zeros(num_obs, dtype=int) # int because its elements will be used as indicies

    trellis_prob[:,0] = prior * obslik[:,0] # element-wise mult
    if scaled:
        scale = np.ones(num_obs) # only instantiated if necessary to save memory
        scale[0] = 1.0 / np.sum(trellis_prob[:,0])
        trellis_prob[:,0] *= scale[0]

    trellis_state[:,0] = 0 # arbitrary value since t == 0 has no predecessor
    for t in xrange(1, num_obs):
        for j in xrange(num_hid):
            trans_probs = trellis_prob[:,t-1] * transmat[:,j] # element-wise mult
            trellis_state[j,t] = trans_probs.argmax()
            trellis_prob[j,t] = trans_probs[trellis_state[j,t]] # max of trans_probs
            trellis_prob[j,t] *= obslik[j,t]
        if scaled:
            scale[t] = 1.0 / np.sum(trellis_prob[:,t])
            trellis_prob[:,t] *= scale[t]

    path[-1] = trellis_prob[:,-1].argmax()
    for t in range(num_obs-2, -1, -1):
        path[t] = trellis_state[(path[t+1]), t+1]

    if not ret_loglik:
        return path
    else:
        if scaled:
            loglik = -np.sum(np.log(scale))
        else:
            p = trellis_prob[path[-1],-1]
            loglik = np.log(p)
        return path, loglik


if __name__=='__main__':
    # Assume there are 3 observation states, 2 hidden states, and 5 observations
    priors = np.array([0.5, 0.5])
    transmat = np.array([
        [0.75, 0.25],
        [0.32, 0.68]])
    emmat = np.array([
        [0.8, 0.1, 0.1],
        [0.1, 0.2, 0.7]])
    observations = np.array([0, 1, 2, 1, 0], dtype=int)
    obslik = np.array([emmat[:,z] for z in observations]).T
    print viterbi_path(priors, transmat, obslik)                                #=> [0 1 1 1 0]
    print viterbi_path(priors, transmat, obslik, scaled=False)                  #=> [0 1 1 1 0]
    print viterbi_path(priors, transmat, obslik, ret_loglik=True)               #=> (array([0, 1, 1, 1, 0]), -7.776472586614755)
    print viterbi_path(priors, transmat, obslik, scaled=False, ret_loglik=True) #=> (array([0, 1, 1, 1, 0]), -8.0120386579275227)

However, what I really need is not just the most likely sequence, but the top k most likely sequences of hidden states.

How can this code be modified to give the top k most likely sequences?



from How to find the most likely sequences of hidden states for a Hidden Markov Model

Crash on UICollectionViewCell with JWVideoView - Swift

A ViewController has a UICollectionView. One of the cells contains JWVideoView. The app is frequently crashing on prepareForReuse in this cell.

There is no valuable info in the log. So I am having trouble figuring out the reason for the crash.

import UIKit

class VideoArticleElementCollectionViewCell: UICollectionViewCell {

    // MARK: - Properties

    public var imageURL: String? { didSet { videoView?.imageURL = imageURL } }
    public var videoId: String? { didSet { videoView?.videoId = videoId } }

    @IBOutlet private var videoView: JWVideoView?

    // MARK: - Reuse

    override func prepareForReuse() {
        super.prepareForReuse() // Crashing here! (Thread 1: EXC_BAD_ACCESS (code=1, address=0x7e8))

        videoView?.stopPlayingVideo()
    }

    deinit {

        videoView?.stopPlayingVideo()
    }
}








import UIKit

class JWVideoView: UIView, JWPlayerDelegate {

    // MARK: Properties

    public var imageURL: String?
    public var videoId: String? { didSet { setupPlayer() } }

    private var jwPlayer: JWPlayerController?
    private let jwPlayerURL = "https://content.jwplatform.com/manifests/"
    private var didPause = false

    // MARK: - Initialization

    override init(frame: CGRect) {

        super.init(frame: frame)
        setup()
    }

    convenience init() {

        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        setup()
    }

    // MARK: - Setup

    private func setup() {}

    private func setupPlayer() {



            guard let videoId = self.videoId else { return }

            let playerURL = jwPlayerURL + videoId + ".m3u8"

            let configuration: JWConfig = JWConfig(contentURL: playerURL)
            configuration.controls = true
            configuration.autostart = true
//            configuration.premiumSkin = JWPremiumSkinGlow
            configuration.image = imageURL

            jwPlayer = JWPlayerController(config: configuration)

            if let player = jwPlayer {

                player.forceFullScreenOnLandscape = true
                player.forceLandscapeOnFullScreen = true
                player.view?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
                player.view?.frame = bounds
                player.delegate = self
                player.volume = 0.0
                if let view = player.view { addSubview(view) }
            }

    }

    // MARK: - Orientation

    private func enableAllOrientation(enable: Bool) {

        if let delegate = UIApplication.shared.delegate as? AppDelegate {

//            delegate.shouldEnableLandscape = enable
        }
    }

    // MARK: API

    public func stopPlayingVideo() {

        enableAllOrientation(enable: false)

        if jwPlayer != nil {

            jwPlayer!.stop()
        }
    }

    // MARK: - JWPlayerDelegate

    internal func onFullscreen(_ status: Bool) {

        if status == false {

            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }
    }

    internal func onPlayAttempt() {

        if jwPlayer != nil {

            enableAllOrientation(enable: true)


        }
    }

    internal func onPlay(_ oldValue: String) {

        if didPause {

            didPause = false
        }
    }

    internal func onPause(_ oldValue: String) {

        didPause = true

    }

    internal func onComplete() {

    }

}



from Crash on UICollectionViewCell with JWVideoView - Swift

Error: OAuth2Credentials instance does not support refreshing the access token. How to create a AccessToken instance with token value string?

I am working on streaming speech to text by using Google Speech to Text service on Android. Here is official sample repository. The sample runs successfully. But Alternatively, you should get the access token on the server side, and supply client app with it.

So I set up a server and create RESTful api for app to get the access token. {"token":"1234567890sdertyuikjhgfghjk....."}

And also use api: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={token} to get the token info:

{
 "issued_to": "102073270616313859663",
 "audience": "102073270616313859663",
 "scope": "https://www.googleapis.com/auth/cloud-platform",
 "expires_in": 3600,
 "access_type": "offline"
}

Then create a AccessToken instance: AccessToken token = new AccessToken(tokenValue, expiresIn);

But following error:

07-04 20:14:07.395 3023-3067/com.google.cloud.android.speech E/SpeechService: Error calling the API.
io.grpc.StatusRuntimeException: UNKNOWN
    at io.grpc.Status.asRuntimeException(Status.java:543)
    at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:395)
    at io.grpc.ClientInterceptors$CheckedForwardingClientCall.start(ClientInterceptors.java:202)
    at io.grpc.stub.ClientCalls.startCall(ClientCalls.java:276)
    at io.grpc.stub.ClientCalls.asyncStreamingRequestCall(ClientCalls.java:266)
    at io.grpc.stub.ClientCalls.asyncBidiStreamingCall(ClientCalls.java:106)
    at com.google.cloud.speech.v1.SpeechGrpc$SpeechStub.streamingRecognize(SpeechGrpc.java:217)
    at com.google.cloud.android.speech.SpeechService.startRecognizing(SpeechService.java:264)
    at com.google.cloud.android.speech.MainActivity$1.onVoiceStart(MainActivity.java:62)
    at com.google.cloud.android.speech.VoiceRecorder$ProcessVoice.run(VoiceRecorder.java:199)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: java.lang.IllegalStateException: OAuth2Credentials instance does not support refreshing the access token. An instance with a new access token should be used, or a derived type that supports refreshing.
    at com.google.auth.oauth2.OAuth2Credentials.refreshAccessToken(OAuth2Credentials.java:208)
    at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:175)
    at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:161)
    at com.google.cloud.android.speech.SpeechService$GoogleCredentialsInterceptor.getRequestMetadata(SpeechService.java:532)
    at com.google.cloud.android.speech.SpeechService$GoogleCredentialsInterceptor.access$900(SpeechService.java:450)
    at com.google.cloud.android.speech.SpeechService$GoogleCredentialsInterceptor$1.checkedStart(SpeechService.java:474)
    at io.grpc.ClientInterceptors$CheckedForwardingClientCall.start(ClientInterceptors.java:194)
    at io.grpc.stub.ClientCalls.startCall(ClientCalls.java:276) 
    at io.grpc.stub.ClientCalls.asyncStreamingRequestCall(ClientCalls.java:266) 
    at io.grpc.stub.ClientCalls.asyncBidiStreamingCall(ClientCalls.java:106) 
    at com.google.cloud.speech.v1.SpeechGrpc$SpeechStub.streamingRecognize(SpeechGrpc.java:217) 
    at com.google.cloud.android.speech.SpeechService.startRecognizing(SpeechService.java:264) 
    at com.google.cloud.android.speech.MainActivity$1.onVoiceStart(MainActivity.java:62) 
    at com.google.cloud.android.speech.VoiceRecorder$ProcessVoice.run(VoiceRecorder.java:199) 
    at java.lang.Thread.run(Thread.java:764) 

I could use the sample code:

 final InputStream stream = getResources().openRawResource(R.raw.credential);
 final GoogleCredentials credentials = 
 GoogleCredentials.fromStream(stream).createScoped(SCOPE);
 final AccessToken token = credentials.refreshAccessToken();

and get a working Token, and get its token value by using getTokenValue() and get it expiration time by getExpirationTime. Then create a Token instance: AccessToken token = new AccessToken(tokenValue, expiresIn); to return a AccessToken instance. But it will cause the same error.

So my question is that how to create an working AccessToken instance when I get the token value string and the expiration time.



from Error: OAuth2Credentials instance does not support refreshing the access token. How to create a AccessToken instance with token value string?

How can I know when UNUserNotificationCenter's removeAllPendingNotificationRequests() has completed?

The iOS docs say that UNUserNotificationCenter's `removeAllPendingNotificationRequests() is asynchronous.

What I want to do is this:

  1. Call removeAllPendingNotificationRequests() to get rid of all my scheduled notifications

  2. Schedule a bunch of new notifications, some of which may or may not have the same IDs as what was there previously

But since the documentation says that the method is asynchronously running on another thread (and there is no completion callback parameter) I'm worried that sometimes, depending on the vagaries of threads and timing and whatnot, that step #1 will still be going as I am creating things in step 2 and therefore it will also kill some of the new notifications I'm making.

This kind of stuff is a little tricky to test manually, since it depends on timing. So I'm curious is anyone knows if this is something I should be worried about or not...



from How can I know when UNUserNotificationCenter's removeAllPendingNotificationRequests() has completed?

How to change language of Fingerprint Popup in Ionic4?

I'm using cordova-plugin-fingerprint-aio plugin in my ionic4 project.

I want to display fingerprint popup content in different language depend upon our app langauge.

This plugin support multi-language support but want to know that how to use it for both Android and iOS?



from How to change language of Fingerprint Popup in Ionic4?

Parsing fields in django-import-export before importing

I am using django-import-export package to expect a csv file containing a location's name and its longitude and latitude.

I want to parse the longitude and latitude field from the csv to convert them into django.contrib.gis.geos.Point object so that I can input it to my Location model's geom field.

# models.py
from django.contrib.gis.db import models
class Location(models.Model):
    name = models.CharField(max_length=200)
    geom = models.PointField(null=True, blank=True)

    def __str__(self):
        return self.name

# admin.py
from .models import Location
from import_export import resources
from import_export.admin import ImportExportModelAdmin

class LocationResource(resources.ModelResource):
    geom = Field()
    latitude = Field()
    longitude = Field()

    class Meta:
        model = Location
        fields = ('id','name', 'latitude', 'longitude')
        exclude = ('geom')
        export_order = ('id', 'name', 'latitude', 'longitude')

    def dehydrate_geom(self, data):
        return Point(data.longitude, data.longitude)

class LocationAdmin(ImportExportModelAdmin):
    resource_class = LocationResource

admin.site.register(Location, LocationAdmin)

This is how far I got but to no success. Must have:

Location(name='name', geom=Point(longitude, latitude))

CSV file: locations.csv

id,name,longitude,latitude
1,Naga,120.18,18.20



from Parsing fields in django-import-export before importing

Detect devices running MDM (mobile device management)

I have a feature to pop up an app update prompt dialog in old app versions (the version is controlled via Firebase Remote Config).

However, turns out a lot (but not most) of my customers use MDM to lock down their phone, in which case the end users cannot directly update the app.

I'm using the normal detection of intent.resolveActivity(packageManager) to check if the play store activity can be started before showing the dialog. But that check passes - the Play Store is there, but updates are blocked.

I want to disable the update prompt for these end users.

Is there a way to detect MDMs? Or at least a way to detect that app updates have been blocked?



from Detect devices running MDM (mobile device management)