Monday 31 August 2020

Bug when trying to make use of .includes

I'm experiencing the following Bug when I'm trying to define what to return inside the request from axios.

This is my code:

async fetchTask() {
        const token = await AsyncStorage.getItem('access');
        const access = 'Bearer ' + token;
        axios.get(`https://example.com/api/auth/tasl/${this.props.navigation.getParam('id')}`, {
            headers: {
                'Authorization': access,
            }
        })
            .then(res => {
                const id = res.data.id;
                this.setState({ userid: id });
                this.setState({ subject: res.data.subject })
                this.setState({ task: res.data.task })
                this.setState({ image: res.data.task.image })
                this.setState({ progresses: res.data.progresses })
                this.setState({ dueDate: res.data.task.duedate })
                this.setState({ progressValue: res.data.progressValue })
                this.setState({ loading: false });
                if (res.data.task.completed == 1) {
                    this.setState({ isCompleted: true });
                }
                if(this.state.image.includes('http')){
                    converted = this.state.image;
                } else {
                    converted = `https://example.com/storage/${this.state.image}`;
                }
            }).catch(error => {
                this.props.navigation.goBack()
            })
    }

Why is this happening? The image is changed once I click any button.

<Image
   style=
   source=
/>


from Bug when trying to make use of .includes

Differences between ways to dynamically instantiate a web component

There are several ways a web component can "come to life".

Are there notable differences between the three options below?

Option 1:

const foo = document.createElement('foo-element');
document.body.appendChild(foo);

Option 2:

const div = document.createElement('div');
div.innerHTML = '<foo-element></foo-element>'
const foo = div.firstElementChild;
document.body.appendChild(foo);

Option 3:

const foo = new FooElement;
document.body.appendChild(foo);

I wrote some Unit Tests based on a Karma/Mocha stack, and created my instances with option 3.

Is this sufficient, that means, can I rely on the components having identical state/behaviour using either method, or is it necessary to repeat all my tests with all different options of instantiating applied?

One of my web components fails to be instantiated using document.createElement because of an error:

VM977:1 Uncaught DOMException: Failed to construct 'CustomElement':
The result must not have attributes
at <anonymous>:1:10

The fact that the same component can be instantiated with no problems using new tells me that, behind the curtain, there must be notable differences especially between new FooElement and document.createElement('foo-element').

I can write three general tests to test all three ways of instantiating, for sure, but is this enough?

Or should all of my existing tests be run with all 3 options of instantiating?

Or asked differently:

Is every instance exactly the same after instantiating? (assuming there is no error)



from Differences between ways to dynamically instantiate a web component

Find the "center" of some histograms with EMD as the distance metric

Given some histograms of the same number of buckets, I need to find the "center" of those histograms. The "center" is a histogram such that the sum of Earth Mover's Distances to it from all other histograms is the minimum.

Simple arithmetic mean cannot find the "center", here is an example.

I need to calculate the "center" of millions of histograms, so how can I find the "center" efficiently. If no fast algorithm exists, is there any good approximate ?



from Find the "center" of some histograms with EMD as the distance metric

How are blobs removed in RelStorage pack?

This question is related to How to pack blobstorage with Plone and RelStorage

Using zodb database with RelStorage and sqlite as its backend I am trying to remove unused blobs. Currently db.pack does not remove the blobs from disc. The minimum working example below demonstrates this behavior:

import logging
import numpy as np
import os
import persistent
from persistent.list import PersistentList
import shutil
import time
from ZODB import config, blob

connectionString = """
%import relstorage
<zodb main>
<relstorage>
blob-dir ./blob
keep-history false
cache-local-mb 0
<sqlite3>
    data-dir .
</sqlite3>
</relstorage>
</zodb>
"""


class Data(persistent.Persistent):
    def __init__(self, data):
        super().__init__()

        self.children = PersistentList()

        self.data = blob.Blob()
        with self.data.open("w") as f:
            np.save(f, data)


def main():
    logging.basicConfig(level=logging.INFO)
    # Initial cleanup
    for f in os.listdir("."):
        if f.endswith("sqlite3"):
            os.remove(f)

    if os.path.exists("blob"):
        shutil.rmtree("blob", True)

    # Initializing database
    db = config.databaseFromString(connectionString)
    with db.transaction() as conn:
        root = Data(np.arange(10))
        conn.root.Root = root

        child = Data(np.arange(10))
        root.children.append(child)

    # Removing child reference from root
    with db.transaction() as conn:
        conn.root.Root.children.pop()

    db.close()

    print("blob directory:", [[os.path.join(rootDir, f) for f in files] for rootDir, _, files in os.walk("blob") if files])
    db = config.databaseFromString(connectionString)
    db.pack(time.time() + 1)
    db.close()
    print("blob directory:", [[os.path.join(rootDir, f) for f in files] for rootDir, _, files in os.walk("blob") if files])


if __name__ == "__main__":
    main()

The example above does the following:

  1. Remove any previous database in the current directory along with the blob directory.
  2. Create a database/storage from scratch adding two objects (root and child), while child is referenced by root and perform a transaction.
  3. Remove the linkage from root to child and perform a transaction.
  4. Close the database/storage
  5. Open the database/storage and perform db.pack for one second in the future.

The output of the minimum working example is the following:

INFO:ZODB.blob:(23376) Blob directory '<some path>/blob/' does not exist. Created new directory.
INFO:ZODB.blob:(23376) Blob temporary directory './blob/tmp' does not exist. Created new directory.
blob directory: [['blob/.layout'], ['blob/3/.lock', 'blob/3/0.03da352c4c5d8877.blob'], ['blob/6/.lock', 'blob/6/0.03da352c4c5d8877.blob']]
INFO:relstorage.storage.pack:pack: beginning pre-pack
INFO:relstorage.storage.pack:Analyzing transactions committed Thu Aug 27 11:48:17 2020 or before (TID 277592791412927078)
INFO:relstorage.adapters.packundo:pre_pack: filling the pack_object table
INFO:relstorage.adapters.packundo:pre_pack: Filled the pack_object table
INFO:relstorage.adapters.packundo:pre_pack: analyzing references from 7 object(s) (memory delta: 256.00 KB)
INFO:relstorage.adapters.packundo:pre_pack: objects analyzed: 7/7
INFO:relstorage.adapters.packundo:pre_pack: downloading pack_object and object_ref.
INFO:relstorage.adapters.packundo:pre_pack: traversing the object graph to find reachable objects.
INFO:relstorage.adapters.packundo:pre_pack: marking objects reachable: 4
INFO:relstorage.adapters.packundo:pre_pack: finished successfully
INFO:relstorage.storage.pack:pack: pre-pack complete
INFO:relstorage.adapters.packundo:pack: will remove 3 object(s)
INFO:relstorage.adapters.packundo:pack: cleaning up
INFO:relstorage.adapters.packundo:pack: finished successfully
blob directory: [['blob/.layout'], ['blob/3/.lock', 'blob/3/0.03da352c4c5d8877.blob'], ['blob/6/.lock', 'blob/6/0.03da352c4c5d8877.blob']]

As you can see db.pack does remove 3 objects "will remove 3 object(s)" but the blobs in the file system are unchanged.

In the unit tests of RelStorage it appears that they do test if the blobs are removed from the file system (see here), but in the script above it does not work.

What am I doing wrong? Any hint/link/help is appreciated.



from How are blobs removed in RelStorage pack?

Chrome Extension: Extension context invalidated when getting URL

I'm retrieving some images from one of my chrome extension folders to the website DOM and everytime I reload the extension I'm getting a 'Extension Context Invalidated' error. Same thing happens when I do a 'chrome.storage.local.set'.

Doing some research I have realized that this error has to do with the facts well explained on this answer but since I'm not messaging between my content script and the background.js I wonder why this happens.

This is the part of my script (injected via chrome.tabs.executeScript in the popup.js) where I'm getting the error, I'm basically injecting images from one of my extension folders to the website DOM:

  for (let k = 0; k < incomingChatTags.length; k++) {
    let normalHolderTag = $(incomingChatTags[k]).text().toLowerCase();
    switch (normalHolderTag) {
      case "vip":
        $(incomingChatTags[k]).addClass("ce-vip");
        priorityVal += 300;
        break;
      case "rg":
        $(incomingChatTags[k]).addClass("ce-rg");
        priorityVal += 240;
        break;
      case "accountclosure":
        $(incomingChatTags[k]).addClass("ce-accountclosure");
        priorityVal += 200;
        break;
      case "21com":
        let logo21 = chrome.extension.getURL("/images/21_thumb.png");
        $(incomingChatTags[k]).html('<img src="' + logo21 + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "caxino":
        //the console shows the error here and not before....¿why? 
        let logoCaxino = chrome.extension.getURL(
          "/images/caxino_thumb.png"
        );
        $(incomingChatTags[k]).html('<img src="' + logoCaxino + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "justspin":
        let logoJustSpin = chrome.extension.getURL(
          "/images/wildz_thumb.png"
        );
        $(incomingChatTags[k]).html('<img src="' + logoJustSpin + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "neonvegas":
        let logoNeonVegas = chrome.extension.getURL(
          "/images/neonVegas_thumb.jpg"
        );
        $(incomingChatTags[k]).html('<img src="' + logoNeonVegas + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "nitrocasino":
        let logoNitroCasino = chrome.extension.getURL(
          "/images/nitroCasino_thumb.jpg"
        );
        $(incomingChatTags[k]).html(
          '<img src="' + logoNitroCasino + '" />'
        );
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "snabbis":
        let logoSnabbis = chrome.extension.getURL(
          "/images/snabbis_thumb.png"
        );
        $(incomingChatTags[k]).html('<img src="' + logoSnabbis + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "sb.bet":
        let logoSB = chrome.extension.getURL("/images/sb_thumb.png");
        $(incomingChatTags[k]).html('<img src="' + logoSB + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "wildz":
        let logoWildz = chrome.extension.getURL("/images/wildz_thumb.png");
        $(incomingChatTags[k]).html('<img src="' + logoWildz + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
      case "wishmaker":
        let logoWishMaker = chrome.extension.getURL(
          "/images/wishmaker_thumb.png"
        );
        $(incomingChatTags[k]).html('<img src="' + logoWishMaker + '" />');
        $(incomingChatTags[k]).addClass("ce-tag-logo");
        break;
    }
    $(incomingChat).attr("data-priority", priorityVal);
    $(incomingChat).find(".numbers_cell").text(priorityVal);
  }


from Chrome Extension: Extension context invalidated when getting URL

Build typescript vue apps with only babel?

How can I transpile and build my typescript vue app with only babel? I used the vue-cli-service extensively but reached a point where I just need a minimal setup, without webpack or anything.

My .babelrc

{
    "presets": ["babel-preset-typescript-vue"],
    "plugins": ["@babel/plugin-transform-typescript"]
}

My package.json dependencies:

"devDependencies": {
    "@babel/cli": "^7.10.5",
    "@babel/plugin-transform-typescript": "^7.11.0",
    "@babel/preset-env": "^7.11.0",
    "babel-loader": "^8.1.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-typescript-vue": "^1.1.1",
    "typescript": "~3.9.3",
    "vue-template-compiler": "^2.6.11"
},
"dependencies": {
    "vue": "^2.6.12",
    "vue-class-component": "^7.2.3",
    "vue-property-decorator": "^8.4.2",
    "vuex": "^3.5.1"
}

My entry main.ts file:

import Vue from 'vue'
import Vuex from 'vuex';
import App from './App.vue'

Vue.config.productionTip = false;
Vue.use(Vuex);
    
new Vue({render: h => h(App)}).$mount('#app');

My App.vue

<script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';

    @Component
    class App extends Vue {}

    export default App;
</script>
    
<template>
    <div class="foobar">Babel worked</div>
</template>

My build script:

babel src/main.ts --out-dir build


from Build typescript vue apps with only babel?

Quickbooks webhooks works locally with ngrok but not working on production

I've went through all the troubleshooting steps they provide here. My endpoint is accessible, ssl passes the tests. Webhooks work when I'm testing on my local environment using ngrok but it does not work on staging and production servers hosted on aws and managed on laravel forge. The webhooks post request simply does not hit the server.

I contacted the Quickbooks support about this several times. Their response is, they get a timeout - StatusCode 41 when they post the notification to my endpoint. And they say that the network is restricting traffic in some way. Also contacted forge support and they said they wont help for application related issues.

I tried disabling the firewall with ufw, reviewed all the logs but I don't see any way how the server is restricting the traffic. I retried several times changing the webhooks URL on sandbox and no luck.

Any help would be greatly appreciated.



from Quickbooks webhooks works locally with ngrok but not working on production

Multer and express-validator creating problem in validation

I am submitting a form with an image. Using the below code.

router.post("/", upload.upload('image').single('categoryLogo'), categoryRules.categoryCreationRules(), validate, categoryController.createCategory);

It is working fine, but is some validation comes then still image is saving in disk. so what I tried is :

router.post("/", categoryRules.categoryCreationRules(), validate,upload.upload('image').single('categoryLogo'), categoryController.createCategory);

But in this express validator getting blank body so it throws validation error very time. What should I do for it, I search on google but I did not found any helpful info I am new in the node.

Rules code:

const categoryCreationRules = () => {

    return [
        check('name')
            .isLength({ min: 1 })
            .trim()
            .withMessage("Category name is required."),
        check('name').custom((name)=>{
             return CategoryModel.findOne({name: name}).collation({locale:'en',strength: 2})
                    .then(category=>{
                        if(category){
                            return Promise.reject(category.name+" category already exsist.");
                        }
                    })
        }),    
        check('name')
            .isLength({max: 100})
            .trim()
            .withMessage("Category name should not exceed more then 100 characters."),
        check('description')
            .isLength({max: 255})
            .trim()
            .withMessage("Category description should not exceed more then 255 characters.")
    ];
}


from Multer and express-validator creating problem in validation

Detecting when input is not being used for Python SoundDevice/PortAudio on Linux

I am using Python's sounddevice library (which runs PortAudio underneath) to record audio on Linux (Raspbian Buster desktop), but it appears that more than one instance of my script will cause an error PaErrorcode -9985 which I believe is due to PortAudio (or the OS?) not allowing multiple programs to access an audio input at the same time.

I am a noob but read about Try blocks and encapsulated the part of my code that uses sounddevice in a Try block where it keeps retrying until the error code is no longer given. However, it seems that sounddevice will not recognize the input is free even after it becomes free. For example, running sounddevice.default.device on the 2nd instance will produce [-1,3] instead of the first instance's [0,0] even after the first instance closes. Weirdly there are usually only two devices:

1st instance sounddevice.query_devices() result:

* 0 sysdefault, ALSA (128 in, 128 out)
  1 dmix, ALSA (0 in, 2 out)

2nd instance's result:

  0 snd_rpi_hifiberry_dacplusadcpro: HiFiBerry DAC+ADC Pro HiFi multicodec-0 (hw:0,0), ALSA (0 in, 2 out)
  1 sysdefault, ALSA (0 in, 128 out)
  2 dmix, ALSA (0 in, 2 out)
< 3 default, ALSA (0 in, 2 out)

In addition to the Try block like this, I also tried reimporting sounddevice and rechecking but that also did not work. I haven't been able to find any solution from searching the error code, reading the documentation for sounddevice or portaudio. I also looked into a pidfile but that won't help if I can't get sounddevice to re-recognize the proper inputs.

Overall, I am trying to figure out how to get sound device to recognize that the input is free and to use it.



from Detecting when input is not being used for Python SoundDevice/PortAudio on Linux

How to make customized stepSize for each horizontal bar in Chart.js graph

I have implemented a graph with four horizontal bars. Last one has nearly 35k records so the stepSize automatically is 2250. The first bar has only 20 records.

First bar's 20 records are not showing any color as the numbers are less at compare to stepSize 2250.

This is my code

scales: {
    xAxes: [
      {
        ticks: {
          beginAtZero: true,
          stepSize: 50,

        },
        stacked: true
      }
    ],
    yAxes: [
      {
        ticks: {
          fontSize: 12
        },
        stacked: true
      }
    ]
  },
  
animation: {
onComplete: function() {
  var chartInstance = this.chart;
  var ctx = chartInstance.ctx;
  ctx.textAlign = "left";
  ctx.fillStyle = "#fff";    
    //draw total count
    charData.datasets[0].data.forEach(function(data, index) {
    var total = this.data.datasets[0].data[index];
    var meta = chartInstance.controller.getDatasetMeta(0);
    var posX = meta.data[index]._model.x;
    var posY = meta.data[index]._model.y;
    ctx.fillStyle = "black";
    if(total.toString().length>=5)
    ctx.fillText(total, posX -40, posY + 2);
    else if(total==0)
    ctx.fillText(total, posX -4, posY + 4);
    else
    ctx.fillText(total, posX - 10, posY + 4);

  }, this);
}

This is output

enter image description here

How can I fix this issue?



from How to make customized stepSize for each horizontal bar in Chart.js graph

Upgrading to Angular 10 breaks ExcelJs

I have just upgraded my application from the last version of 9 to angular 10 using ng update. I know there are significant changes, and in the most part it has upgraded well, however I am currently getting an error from exceljs:

"export 'Workbook' (imported as 'Excel') was not found in 'exceljs/dist/exceljs'

Prior to the upgrade, it was using exceljs version 2.0.1. Now it is using exceljs 4.0.1. (It is one version prior to the latest version, because there is an error preventing compiling in the latest version due to an option argument being marked as required. That shouldn't matter.)

The import statement is as follows:

import * as Excel from "exceljs/dist/exceljs";

The code itself is pretty typical for exceljs. I have a service that provides data: HttpResponse and I load it into the workbook so that I can extract some of the columns.

this.myService.getMySpreadsheet().subscribe((data: HttpResponse<Blob>) => {
      new Response(data.body).arrayBuffer().then(arrayBuffer => {
        const wb: Excel.Workbook = new Excel.Workbook();
        wb.xlsx.load(arrayBuffer).then(() => {

          const ws1 = wb.getWorksheet("My Worksheet");

But it can't even get to that code now, because the angular compilation is broken.

Any idea how I can fix that problem? Is there some sort of backward compatibility flag that I need to add?



from Upgrading to Angular 10 breaks ExcelJs

Can't make use of dont_filter=true within a spider in the right way to avoid some unwanted activity

I've created a spider to parse the link from different container from some identical site's (supplied by text file) landing page and then use the link to get the title from it's inner page. Few links have next page button which the spider handles accordingly.

The spider does parse the content but falls into an infinite loop caused by the dont_filter=True parameter. If I don't use that parameter, the spider doesn't reuse some links that were failed to produce desired response in the first place.

I've used this parameter dont_filter=True in three places.

  1. In _retry() method within middlewares
  2. In the last line within the parse() method
  3. In the last line within the parse_content() method

spider that I've created:

import os
import scrapy
import urllib
from bs4 import BeautifulSoup
from scrapy.crawler import CrawlerProcess


class YelpSpider(scrapy.Spider):
    name = "yelpspidescript"

    with open("all_urls.txt") as f:
        start_urls = f.readlines()
   
    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url,callback=self.parse,meta={"lead_link":url})

    def parse(self,response):
        if response.meta.get("lead_link"):
            lead_link = response.meta.get("lead_link")
        elif response.meta.get("redirect_urls"):
            lead_link = response.meta.get("redirect_urls")[0]

        soup = BeautifulSoup(response.text, 'lxml')
        if soup.select("[class*='hoverable'] h4 a[href^='/biz/'][name]"):
            for item in soup.select("[class*='hoverable'] h4 a[href^='/biz/'][name]"):
                lead_link = response.urljoin(item.get("href"))
                yield scrapy.Request(lead_link,meta={"lead_link":lead_link},callback=self.parse_content)

            next_page = soup.select_one("a[class*='next-link'][href^='/search?']")
            if next_page:
                link = response.urljoin(next_page.get("href"))
                yield scrapy.Request(link,meta={"lead_link":link},callback=self.parse)

        else:
            yield scrapy.Request(lead_link,meta={"lead_link":lead_link},callback=self.parse,dont_filter=True)
            
    def parse_content(self,response):
        if response.meta.get("lead_link"):
            lead_link = response.meta.get("lead_link")
        elif response.meta.get("redirect_urls"):
            lead_link = response.meta.get("redirect_urls")[0]

        soup = BeautifulSoup(response.text, 'lxml')

        if soup.select_one("h1[class*='heading--inline__']"):
            try:
                name = soup.select_one("h1[class*='heading--inline__']").get_text(strip=True)
            except AttributeError: name = ""
            print(name)

        else:
            yield scrapy.Request(lead_link,meta={"lead_link":lead_link},callback=self.parse_content,dont_filter=True)
            

if __name__ == "__main__":
    c = CrawlerProcess({
        'USER_AGENT':'Mozilla/5.0',
        'LOG_LEVEL':'ERROR',
    })
    c.crawl(YelpSpider)
    c.start()

middlewares:

from fake_useragent import UserAgent


RETRY_HTTP_CODES = [500, 502, 503, 504, 408, 403, 401, 400, 404, 408]

class yelp_custom_Middleware(object):
    ua = UserAgent() 

    def process_request(self, request, spider):
        request.headers['User-Agent'] = self.ua.random

    def process_exception(self, request, exception, spider):
        return self._retry(request, exception, spider)

    def _retry(self, request, reason, spider):
        retryreq = request.copy()
        retryreq.dont_filter = True
        return retryreq

    def process_response(self, request, response, spider):
        if request.meta.get('dont_retry', False):
            return response
        if response.status in RETRY_HTTP_CODES:
            reason = response_status_message(response.status)
            return self._retry(request, reason, spider) or response
        return response

How can I let the spider not to fall into an infinite loop?

EDIT: I thought to include few of the urls I'm trying with which are within all_urls.txt file in case it helps identify the issue better.



from Can't make use of dont_filter=true within a spider in the right way to avoid some unwanted activity

Iterating two dataframes and providing minimum rank on multiple condition

I want to iterate through two dataframes, one being large (with multiple columns and non null cols value) and one being small (with some common cols and null value in it).

The large dataframe is actual customer data with all attributes and other one is ranking data. I am trying to stamp minimum rank to all customer comparing it with ranking data.

The Lager dataframe look like this -

CUST_ID,DTL1,DTL2,DTLS3,AGE_BAND,SCORE,STATE,ATTR_1,ATTR_2,ATTR_3
1,xx,xx,xx,A1,S1,MH,1,1,6
2,xx,xx,xx,A1,S2,MH,1,2,7
3,xx,xx,xx,A2,S3,GJ,2,2,7
4,xx,xx,xx,A3,S1,RJ,1,2,6
5,xx,xx,xx,A2,S1,GJ,2,1,6
6,xx,xx,xx,A3,S3,RJ,1,2,7

and the ranking data -

Rank,AGE_BAND,SCORE,STATE,ATTR_1,ATTR_2
1,A1,S1,MH,Null,Null
2,A1,Null,MH,Null,1
3,Null,S1,GJ,Null,1
4,Null,S1,GJ,2,Null

Here, If we see, then cust_1 satisfy for both the rank- 1 and 2, but we would go for minimum i.e. 1. Same goes for Cust_5, rank 3.

I tried creating a nested for loop; the outer loop iterating through the large dataframe and the inner loop iterating through the small dataframe however I am having difficulties.

I'm looking for a way to identify that the "col_name" and "value" in my small dataframe that matches my large dataframe when not null and then assigning minimum rank to it.

I am trying to write some thing like below:

for cust in Data_Cust.iterrows():       
    for rank in Data_rank.iterrows():       #if we can eliminate columns where its value are null for individual rank
        if rank.col_name == cust.col_name && rank.col_value == cust.value  ##something from which we can match col/val name with col/value name of both dfs
        
            #create a list and appended all eligible ranks
            #selecting minimun rank at the end
            #appending list and min rank in Data_cust 


from Iterating two dataframes and providing minimum rank on multiple condition

How to compare two LiveData whether they are equal in Android Studio?

I have two LiveData, aMVoice1, and aMVoice2.

I hope to check if they are equal.

I know I need to use observe to get the value of a LiveData.

so I think isEqual = (mDetailViewModel.aMVoice1.value==mDetailViewMode2.aMVoice1.value ) is wrong.

But I think there are some problems with fun observeVoice(), how can I fix it?

class FragmentDetail : Fragment() {

    private lateinit var binding: LayoutDetailBinding
 
    private val mDetailViewModel by lazy {
       ...
    }

    var isEqual=false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        ...
        binding.lifecycleOwner = this.viewLifecycleOwner
        binding.aDetailViewModel=mDetailViewModel

        isEqual = (mDetailViewModel.aMVoice1.value==mDetailViewMode2.aMVoice1.value ) // I don't think it's correct.

        observeVoice()
        return binding.root
    }

    fun observeVoice() {
        mDetailViewModel.aMVoice1.observe(viewLifecycleOwner){value1->
           isEqual = (value1==mDetailViewModel.aMVoice2.value)  // mDetailViewModel.aMVoice2.value maybe null
        }
    }

}


class DetailViewModel(private val mDBVoiceRepository: DBVoiceRepository, private val voiceId1:Int,private val voiceId2:Int) : ViewModel() {
   val aMVoice1=mDBVoiceRepository.getVoiceById(voiceId1)
   val aMVoice2=mDBVoiceRepository.getVoiceById(voiceId2)
}

class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    fun getVoiceById(id:Int)=mDBVoiceDao.getVoiceById(id)
}


@Dao
interface DBVoiceDao{
   @Query("SELECT * FROM voice_table where id=:id")
   fun getVoiceById(id:Int):LiveData<MVoice>
}

data class MVoice(
    @PrimaryKey (autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0,
    var name:          String = "",
    var path:          String = ""
)

Added Content

Is it Ok for the following code?

fun observeVoice() {
    mDetailViewModel.aMVoice1.observe(viewLifecycleOwner){value1->
       mDetailViewModel.aMVoice2.observe(viewLifecycleOwner){value2->
             isEqual = (value1==value2)
       }
    }
 }


from How to compare two LiveData whether they are equal in Android Studio?

Please accept all necessary Android SDK licenses

Setting up a React Native development environment on Windows for the first time, I create a new React Native project, cd into it, and run react-native run-android. I receive the error:

info Starting JS server... The system cannot find the path specified. info Launching emulator... error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds. warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.

error Failed to install the app. Please accept all necessary Android SDK licenses using Android SDK Manager: "$ANDROID_HOME/tools/bin/sdkmanager --licenses". Run CLI with --verbose flag for more details. Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

I've tried:

  • Go to Configure>SDK Manager in your Android Studio. Select SDK Tools tab and install Google Play Licensing Library
  • Open Android Studio, then click the gear icon (Configure). Press the SDK Manager option. Three tabs should be displayed, press the SDK Tools tab. After that, make sure that Android SDK Build-Tools, Android SDK Platform-Tools and Android SDK Tools are updated. Check them and press Apply.
  • Installing v28 of Android SDK and opened a Pixel 2 VD running v28.
  • Run Powershell C:\users\steve\appdata\local\Android\Sdk\tools\bin> ./sdkmanager.bat --licenses. I receive the error:

Warning: File C:\Users\steve\ .android\repositories.cfg could not be loaded. All SDK package licenses accepted.======] 100% Computing updates...

I've created a blank C:\Users\steve\ .android\repositories.cfg file, and started an Android emulator through Android Studio, but receive the same error.



from Please accept all necessary Android SDK licenses

record audio with exact timestamps

I want to record raw audio on an android wear device, and exactly synchronize it with other sensor data, such as the accelerometer. To record raw audio, there is AudioRecord, but how can I determine the exact timestamp for a part of the audio stream?

I get chunks of the audio data by calling AudioRecord.read() in a loop, but how can I tell when a specific frame was recorded?

I can see three ways to determine a timestamp, and all of them seem wrong to me:

  1. Get the current system time before or after calling AudioRecord.startRecording(), by calling SystemClock.elapsedRealtimeNanos(), and then calculate the time of each chunk based on the sample rate and frame size. But according to my tests there is a significant delay, until the recording actually starts. The time would also get out of sync whenever some frames are lost, e.g. when processing is stalled for a moment.

  2. Get the current system time before or after AudioRecord.read(). But that is probably not the time that this data was recorded, that could have happened a bit earlier. And if no data is available yet, read() will block and the timestamp taken before will be totally wrong.

  3. AudioRecord.getTimestamp() gives the time of the frame that is currently recording. But that is not necessarily the frame that I am currently reading, I could be a couple frames behind, or I could have missed some frames.

This would leave me with 6 probably wrong timestamps, shown in the code below. Is any of those even close to accurate?

recorder = new AudioRecord(...)

// timeBeforeStart =  SystemClock.elapsedRealtimeNanos()
recorder.startRecording()
// timeAfterStart =  SystemClock.elapsedRealtimeNanos()

...

// timeBeforeRead =  SystemClock.elapsedRealtimeNanos()
// recorder.getTimestamp(frameTimeBeforeRead, AudioTimestamp.TIMEBASE_BOOTTIME)
recorder.read(myArray, 0, mySize);
// recorder.getTimestamp(frameTimeAfterRead, AudioTimestamp.TIMEBASE_BOOTTIME)
// timeAfterRead =  SystemClock.elapsedRealtimeNanos()

Which of these would be the most accurate way to determine the timestamp corresponding to the data in the byte array?

Is there a different method for retrieving raw audio data with accurate timestamps?



from record audio with exact timestamps

How to fix refused to display url in a frame because it set x frame options to deny in webkitgtk python

Im building a simple web browser with Python, Gtk, and WebKitGtk. When trying to load youtube, i receive this error message:

console message: about:blank @0: Refused to display 'https://accounts.google.com/ServiceLogin?continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Ddesktop%26feature%3Dpassive%26hl%3Den%26next%3D%252Fsignin_passive&hl=en&passive=true&service=youtube&uilel=3' in a frame because it set 'X-Frame-Options' to 'DENY'.

my code (from a tutorial on webkitgtk):

import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit', '3.0')
from gi.repository import Gtk, WebKit

class Main:
    def __init__(self):
        self.win = Gtk.Window()
        self.win.set_position(Gtk.WindowPosition.CENTER)
        self.win.set_title('window')
        self.win.set_default_size(1200, 800)

        self.btn_grid = Gtk.Grid()

        self.btn_grid.set_column_spacing(10)
        self.reload_button = Gtk.Button('Reload')
        self.reload_button.connect('clicked', self.reload_window)
        self.btn_grid.attach(self.reload_button, 0, 0, 1, 1)

        self.url_entry = Gtk.Entry()
        self.url_entry.set_hexpand(True)
        self.url_entry.connect('activate', self.display_url)
        self.btn_grid.attach(self.url_entry, 1, 0, 1, 1)

        self.go_btn = Gtk.Button('Go')
        self.go_btn.connect('clicked', self.display_url)
        self.btn_grid.attach(self.go_btn, 2, 0, 1, 1)

        self.main_box = Gtk.VBox()
        self.main_box.pack_start(self.btn_grid, False, False, 0)
        self.win.add(self.main_box)

        self.webview = WebKit.WebView()
        self.webview.connect('title-changed', self.title_update)
        self.webview.load_uri("https://google.com")


        self.scroll_area = Gtk.ScrolledWindow()
        self.scroll_area.add(self.webview)
        self.main_box.pack_start(self.scroll_area, True, True, 0)
        self.win.connect('destroy', Gtk.main_quit)

    def title_update(self, webview, frame, title):
        self.win.set_title(f'window - {title}')

    def display_url(self, event):
        url = self.url_entry.get_text()
        if url == '':
            pass
        else:
            if "://" not in url:
                url = f'https://{url}'
            self.webview.load_uri(url)
            self.webview.grab_focus()

    def reload_window(self):
        self.webview.reload()


    def w_open(self):
        self.win.show_all()

main_window = Main()
main_window.w_open()
Gtk.main()

How could i fix this problem? YouTube loads fine on other web browsers.



from How to fix refused to display url in a frame because it set x frame options to deny in webkitgtk python

How to catch signals from a unknown USB OTG device?

I have a USB OTG device which acts like a mouse, bought in china with not much more information about the used controller. When I connect it to my android there is a mouse cursor and the device has 5 hard buttons (left, right, up, down, enter). I want to programm the buttons for my app to performe specific tasks. So I need to read the input signals and overwrite them.

I found out the vendor (0x04D9) and product id (0x2519) and the controller name Lenovo Calliope USB Keyboard. But no idea about the used chip, it's covert.

How can I catch the signals?

It doesn't work with the methods onKeyDown or dispatchKeyEvent.

Side question, if I connect the device the first time the app crash but I can reopen it and it works fine... any idea?

Update: I bought the USB OTG device in china so I have not much information about the used controller. I found out that they use a 'Lenovo Calliope USB Keyboard' Controller with HID\VID_04D9&PID_2519&REV_0001.

Update 2: the code from Fatih Şennik works for other usb devices. So I have an hardware issue? But the controller does what he is supposed to do...



from How to catch signals from a unknown USB OTG device?

sklearn : scaling x (data) and y (target) using both Pipeline and TransformedTargetRegressor

I'd like to use both Pipeline and TransformedTargetRegressor to handle all the scaling (on data and target) : is this possible to mix Pipeline and TransformedTargetRegressor ? How to get results out of TransformedTargetRegressor ?

$ cat test_ttr.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from sklearn.datasets import make_regression
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.pipeline import Pipeline
from sklearn.compose import TransformedTargetRegressor

def main():
    x, y = make_regression()

    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

    model = linear_model.Ridge(alpha=1)

    pipe = Pipeline([('scale', preprocessing.StandardScaler()), ('model', model)])
    treg = TransformedTargetRegressor(regressor=pipe, transformer=preprocessing.MinMaxScaler())

    treg.fit(x_train, y_train)

    print(pipe.get_params()['model__alpha']) # OK !
    print(treg.get_params()['regressor__model__coef']) # KO ?!

if __name__ == '__main__':
    main()

But can't get results (coefs for instance) out of TransformedTargetRegressor

1
Traceback (most recent call last):
  File ".\test_ttr.py", line 26, in <module>
    main()
  File ".\test_ttr.py", line 23, in main
    print(treg.get_params()['regressor__model__coef']) # KO ?!
TypeError: 'TransformedTargetRegressor' object is not subscriptable


from sklearn : scaling x (data) and y (target) using both Pipeline and TransformedTargetRegressor

face-api and tensorflow.js not working in browser

I'm trying to run this example in the browser

https://justadudewhohacks.github.io/face-api.js/docs/index.html#getting-started-browser

Specifically this code here

<!DOCTYPE html>
<html>
<head>
  <script src="assets/face-api.js"></script>
  <script src="assets/commons.js"></script>
  <script src="assets/faceDetectionControls.js"></script>
  <link rel="stylesheet" href="assets/styles.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.css">
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</head>
<body>
  <div id="navbar"></div>
  <div class="center-content page-container">

    <div class="progress" id="loader">
      <div class="indeterminate"></div>
    </div>
    <div style="position: relative" class="margin">
      <video onloadedmetadata="onPlay(this)" id="inputVideo" autoplay muted playsinline></video>
      <canvas id="overlay" />
    </div>

    <div class="row side-by-side">

      <!-- face_detector_selection_control -->
      <div id="face_detector_selection_control" class="row input-field" style="margin-right: 20px;">
        <select id="selectFaceDetector">
          <option value="ssd_mobilenetv1">SSD Mobilenet V1</option>
          <option value="tiny_face_detector">Tiny Face Detector</option>
        </select>
        <label>Select Face Detector</label>
      </div>
      <!-- face_detector_selection_control -->

      <!-- check boxes -->
      <div class="row" style="width: 220px;">
        <input type="checkbox" id="hideBoundingBoxesCheckbox" onchange="onChangeHideBoundingBoxes(event)" />
        <label for="hideBoundingBoxesCheckbox">Hide Bounding Boxes</label>
      </div>
      <!-- check boxes -->

      <!-- fps_meter -->
      <div id="fps_meter" class="row side-by-side">
        <div>
          <label for="time">Time:</label>
          <input disabled value="-" id="time" type="text" class="bold">
          <label for="fps">Estimated Fps:</label>
          <input disabled value="-" id="fps" type="text" class="bold">
        </div>
      </div>
      <!-- fps_meter -->

    </div>


    <!-- ssd_mobilenetv1_controls -->
    <span id="ssd_mobilenetv1_controls">
      <div class="row side-by-side">
        <div class="row">
          <label for="minConfidence">Min Confidence:</label>
          <input disabled value="0.5" id="minConfidence" type="text" class="bold">
        </div>
        <button
          class="waves-effect waves-light btn"
          onclick="onDecreaseMinConfidence()"
        >
          <i class="material-icons left">-</i>
        </button>
        <button
          class="waves-effect waves-light btn"
          onclick="onIncreaseMinConfidence()"
        >
          <i class="material-icons left">+</i>
        </button>
      </div>
    </span>
    <!-- ssd_mobilenetv1_controls -->

    <!-- tiny_face_detector_controls -->
    <span id="tiny_face_detector_controls">
      <div class="row side-by-side">
        <div class="row input-field" style="margin-right: 20px;">
          <select id="inputSize">
            <option value="" disabled selected>Input Size:</option>
            <option value="128">128 x 128</option>
            <option value="160">160 x 160</option>
            <option value="224">224 x 224</option>
            <option value="320">320 x 320</option>
            <option value="416">416 x 416</option>
            <option value="512">512 x 512</option>
            <option value="608">608 x 608</option>
          </select>
          <label>Input Size</label>
        </div>
        <div class="row">
          <label for="scoreThreshold">Score Threshold:</label>
          <input disabled value="0.5" id="scoreThreshold" type="text" class="bold">
        </div>
        <button
          class="waves-effect waves-light btn"
          onclick="onDecreaseScoreThreshold()"
        >
          <i class="material-icons left">-</i>
        </button>
        <button
          class="waves-effect waves-light btn"
          onclick="onIncreaseScoreThreshold()"
        >
          <i class="material-icons left">+</i>
        </button>
      </div>
    </span>
    <!-- tiny_face_detector_controls -->

  </body>

  <script>
    let forwardTimes = []
    let withBoxes = true

    function onChangeHideBoundingBoxes(e) {
      withBoxes = !$(e.target).prop('checked')
    }

    function updateTimeStats(timeInMs) {
      forwardTimes = [timeInMs].concat(forwardTimes).slice(0, 30)
      const avgTimeInMs = forwardTimes.reduce((total, t) => total + t) / forwardTimes.length
      $('#time').val(`${Math.round(avgTimeInMs)} ms`)
      $('#fps').val(`${faceapi.utils.round(1000 / avgTimeInMs)}`)
    }

    async function onPlay() {
      const videoEl = $('#inputVideo').get(0)

      if(videoEl.paused || videoEl.ended || !isFaceDetectionModelLoaded())
        return setTimeout(() => onPlay())


      const options = getFaceDetectorOptions()

      const ts = Date.now()

      const result = await faceapi.detectSingleFace(videoEl, options).withFaceExpressions()

      updateTimeStats(Date.now() - ts)

      if (result) {
        const canvas = $('#overlay').get(0)
        const dims = faceapi.matchDimensions(canvas, videoEl, true)

        const resizedResult = faceapi.resizeResults(result, dims)
        const minConfidence = 0.05
        if (withBoxes) {
          faceapi.draw.drawDetections(canvas, resizedResult)
        }
        faceapi.draw.drawFaceExpressions(canvas, resizedResult, minConfidence)
      }

      setTimeout(() => onPlay())
    }

    async function run() {
      // load face detection and face expression recognition models
      await changeFaceDetector(TINY_FACE_DETECTOR)
      await faceapi.loadFaceExpressionModel('/')
      changeInputSize(224)

      // try to access users webcam and stream the images
      // to the video element
      const stream = await navigator.mediaDevices.getUserMedia({ video: {} })
      const videoEl = $('#inputVideo').get(0)
      videoEl.srcObject = stream
    }

    function updateResults() {}

    $(document).ready(function() {
      renderNavBar('#navbar', 'webcam_face_expression_recognition')
      initFaceDetectionControls()
      run()
    })
  </script>
</body>
</html>

Unfortunately this is not working ( I have loaded the associated libraries into assets, i.e., https://github.com/justadudewhohacks/face-api.js/tree/master/dist and moving the other files from this example here

https://github.com/justadudewhohacks/face-api.js/tree/master/examples/examples-browser

What am i doing wrong? I am loading this on a page on my site here

https://moodmap.app/webcamFaceExpressionRecognition.html in case you want to see what's happening in the browser.

Based on changes below,

Here is the node server where I am setting where things are held - is it possible to just change this instead? As it is coming up with a separate issue with the shard needed in the model as well now when making the changes suggested below.

Thanks!

const config = require('../../config');

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, { wsEngine: 'ws' });
const mysql = require('mysql');
const expressSession = require('express-session');
const ExpressMysqlSessionStore = require('express-mysql-session')(expressSession);
const sharedsession = require('express-socket.io-session');
const path = require('path');

const utils = require('./utils');

// remove from header "X-Powered-By: Express"
app.disable('x-powered-by');

server.listen(config.serverParams.port, config.serverParams.address, () => {
    console.log(`Server running at http://${server.address().address}:${server.address().port}`);
});

/* DATABASE */
global.db = mysql.createConnection(config.db);
db.connect();
/* DATABASE */

/* SESSION */
const sessionStore = new ExpressMysqlSessionStore(config.sessionStore, db);
const session = expressSession({
    ...config.session,
    store: sessionStore,
});
app.use(session);
/* SESSION */

app.use(express.static(config.frontendDir));
app.use(express.static(path.join(__dirname, './src/assets')))
app.use(express.static(path.join(__dirname, './src/assets/weights')))

app.use((req,res,next)=>{
    //can reaplce * with website we want to allow access
    res.header('Access-Control-Allow-Origin', '*');
  next();
  });

app.get([
    '/signup',
    '/stats',
    '/pay',
], (req, res) => res.sendFile(path.join(`${config.frontendDir}${req.path}.html`)));

io.use(sharedsession(session, {
    autoSave: true
}));

io.on('connection', socket => {

    socket.use((packet, next) => {
        if (packet[0]) {
            console.log('METHOD:', packet[0]);
            const sessionData = socket.handshake.session.user;
            const noSessionNeed = [ 'login', 'signup', 'checkAuth' ].includes(packet[0]);
            let error;
            if ( ! sessionData && ! noSessionNeed) error = { code: -1, message: 'You need to login in extension!' };
            if (error) return next(new Error(JSON.stringify(error)));
            else next();
        }
    });

    const auth = require('./auth')(socket);
    socket.on('checkAuth', auth.checkAuth);
    socket.on('login', auth.login);
    socket.on('signup', auth.signup);
    socket.on('logout', auth.logout);

    const users = require('./users')(socket);
    socket.on('users.get', users.get);

    const sentiment = require('./sentiment')(socket);
    socket.on('sentiment.get', sentiment.get);
    socket.on('sentiment.set', sentiment.set);

    socket.on('disconnect', () => {

    });

});

Reason being still getting an error for some reason as below,?

fetchOrThrow.ts:11 Uncaught (in promise) Error: failed to fetch: (404) , from url: https://moodmap.app/assets/tiny_face_detector_model-weights_manifest.json
    at fetchOrThrow.ts:11
    at step (drawContour.ts:28)
    at Object.next (drawContour.ts:28)
    at fulfilled (drawContour.ts:28)
(anonymous) @   fetchOrThrow.ts:11
step    @   drawContour.ts:28
(anonymous) @   drawContour.ts:28
fulfilled   @   drawContour.ts:28
async function (async)      
run @   webcamFaceExpressionRecognition.html:142
(anonymous) @   webcamFaceExpressionRecognition.html:158
j   @   jquery-2.1.1.min.js:2
fireWith    @   jquery-2.1.1.min.js:2
ready   @   jquery-2.1.1.min.js:2
I   @   jquery-2.1.1.min.js:2

Thanks in advance!



from face-api and tensorflow.js not working in browser

DeepDiff among Rows

i have this data frame

import pandas as pd
from deepdiff import DeepDiff
df = pd.DataFrame({'col_new': ['a','b','c,d','d'],
                   'col_old': ['a','e','d','d'],
                   'col_val': [True,False,False,True]})
print(df)
  col_new col_old  col_val
0       a       a     True
1       b       e    False
2     c,d       d    False
3       d       d     True

i want to replace every False value with the DeepDiff of that row i tried this

df['col_val'] = df['col_val'].where(df['col_val'],DeepDiff(df['col_old'],df['col_new'])['values_changed'])

expected this

  col_new col_old                                            col_val
0       a       a                                               True
1       b       e  {'root': {'new_value': 'b', 'old_value': 'e'...
2     c,d       d  {'root': {'new_value': 'c,d', 'old_value': 'd...
3       d       d                                               True

but got this

  col_new col_old                                            col_val
0       a       a                                               True
1       b       e  {'root[1]': {'new_value': 'b', 'old_value': 'e...
2     c,d       d  {'root[1]': {'new_value': 'b', 'old_value': 'e...
3       d       d                                               True

Edit: I'd like to thank jezrael for his perfect answer.

But what if there are 10 or 20 columns, should I just type the same code over and over?



from DeepDiff among Rows

Android App Crashes on Physical Device But Not Emulator: "Parcel: dup() failed in Parcel::read [...] error: Too many open files"

I'm trying to turn an old phone into a networked security camera, since crime has increased dramatically in my area during all these riots (and I don't want to rely on someone else's app to control access to my private moments).

I'm chunking-and-sending, so the camera records video for a number of seconds, stops, encodes the binary of the captured file into Base64, then shoots it off to a home server via POST request, all in an endless loop. The server unwraps + decodes + saves it as the original binary "MP4" onto its own disk (TODO: fun post-processing for motion detection).

Using a variety of virtual devices at (and around) my target phone's OS version & screen size, this all works for extended periods of time. I've used 60-second chunks for 15+ minutes, plus 6-second chunks for over an hour. I consistently receive the goofy virtual room videos the emulator produces onto my server.

But on the Samsung Galaxy S5 running Android 6.0.1 that dreams of becoming a security camera, it usually takes 2 or 3 videos being sent before the app crashes... except when your resolution is set too high, then you run into a different symptom.

Symptom #0: Crashing at the End of a Chunk

E/Parcel: dup() failed in Parcel::read, i is 1, fds[i] is -1, fd_count is 2, error: Too many open files

E/Surface: dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: -22

W/Adreno-EGLSUB: DequeueBuffer:721: dequeue native buffer fail: Invalid argument, buffer=0x0, handle=0x0

W/Adreno-EGL: <qeglDrvAPI_eglSwapBuffers:3800>: EGL_BAD_SURFACE

Followed immediately by this second error:

E/CameraDeviceGLThread-1: Received exception on GL render thread:

java.lang.IllegalStateException: swapBuffers: EGL error: 0x300d

Then finally, once the chunk time is up and the camera goes to record again, the final error occurs to crash the entire app:

I/CameraDeviceState: Legacy camera service transitioning to state ERROR

E/AndroidRuntime: FATAL EXCEPTION: CameraThread

Process: com.example.roselawncam, PID: 14639

android.hardware.camera2.CameraAccessException: The camera device has encountered a serious error

Symptom #1: Crashing in the Middle of a Chunk Because You Went Too 🌈High-Res🌈 For Your Own Good

These warnings make it clear that resource strain causes this symptom. They occur as the app crashes, with higher resolutions causing sooner crashes. I clocked these bad boys at:

  • 1920x1080 (30 FPS): 5 seconds
  • 1280x720 (30 FPS): 9 seconds
  • 800x480 (30 FPS): 15 seconds

Times were similar for both the front and back cameras. At lower resolutions, you start running into Symptom #0 unless you bump your chunk time way up. Anyway:

W/Adreno-GSL: <gsl_ldd_control:475>: ioctl fd 28 code 0xc01c0915 (IOCTL_KGSL_MAP_USER_MEM) failed: errno 12 Out of memory

W/Adreno-EGLSUB: SyncBackBuffer:3130: failed to map the memory for fd=281 offs=0

E/Adreno-EGLSUB: SyncBackBuffer:3131: SyncBackBuffer: FATAL ERROR : (null)

A/Adreno-GSL: Exiting the process com.example.roselawncam from function SyncBackBuffer and line 3131

A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 19618 (CameraDeviceGLT)

And finally, the pertinent Kotlin pieces:

private fun createRecorder(surface: Surface) = MediaRecorder().apply {
        setAudioSource(MediaRecorder.AudioSource.MIC)
        setVideoSource(MediaRecorder.VideoSource.SURFACE)
        setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
        setOutputFile(outputFile.absolutePath)
        setVideoEncodingBitRate(RECORDER_VIDEO_BITRATE)
        if (args_fps > 0) setVideoFrameRate(args_fps)
        setVideoSize(args_width, args_height)
        setVideoEncoder(MediaRecorder.VideoEncoder.H264)
        setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        setInputSurface(surface)
}

private fun recordIt(cameraManager: CameraManager, cameraThread: HandlerThread) {
    val cameraHandler = Handler(cameraThread.looper)
    val stateCallback: CameraDevice.StateCallback = object: CameraDevice.StateCallback() {
        override fun onOpened(camera: CameraDevice) {
            camera.createCaptureSession(
                listOf<Surface>(recorderSurface),
                object : CameraCaptureSession.StateCallback() {
                    override fun onConfigured(session: CameraCaptureSession) {
                        val recTimeSeconds = findViewById<TextView>(R.id.recTimeSeconds)
                        val chunkTimeMilliseconds = recTimeSeconds.text.toString().toLong() * 1000

                        // Boolean "stopREC" (e.g. "Stop Recording") is false at this point
                        while (!stopREC) {
                            // // // This loop should run forever, but crashes after a few times // // //
                            val recorder: MediaRecorder by lazy { createRecorder(recorderSurface) }
                            val recordRequest: CaptureRequest by lazy {
                                session.device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {
                                    addTarget(recorderSurface)
                                    set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, Range(args_fps, args_fps))
                                }.build()
                            }
                            session.setRepeatingRequest(recordRequest, null, cameraHandler)
                            recorder.apply { prepare(); start() }
                            Thread.sleep(chunkTimeMilliseconds)
                            recorder.apply { stop(); release() }
    
                            // Send the video file across the network in JSON via POST request:
                            val params = HashMap<String, String>()
                            params["videodata"] = convertToBase64(outputFile)
                            val jsonObject = JSONObject(params as Map<*, *>)
                            val request = JsonObjectRequest(Request.Method.POST, url, jsonObject, null, null)
                            queue.add(request)
                            // // // End of loop that should've ran forever, but crashes occasionally instead  // // //
                        }
                        camera.close()
                    }
                    override fun onConfigureFailed(session: CameraCaptureSession) {}
                }, 
                cameraHandler
            )
        }
        override fun onDisconnected(camera: CameraDevice) { recorder.stop(); recorder.release() }
        override fun onError(camera: CameraDevice, error:Int) { camera.close() }
    }
    cameraManager.openCamera(args_cameraId, stateCallback, cameraHandler)
}


from Android App Crashes on Physical Device But Not Emulator: "Parcel: dup() failed in Parcel::read [...] error: Too many open files"

Sorting contours based on precedence in Python, OpenCV

I am trying to sort contours based on their arrivals, left-to-right and top-to-bottom just like how you write anything. From, top and left and then whichever comes accordingly.

This is what and how I have achieved up to now:

def get_contour_precedence(contour, cols):
    tolerance_factor = 61
    origin = cv2.boundingRect(contour)
    return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]


image = cv2.imread("C:/Users/XXXX/PycharmProjects/OCR/raw_dataset/23.png", 0)

ret, thresh1 = cv2.threshold(image, 130, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

contours, h = cv2.findContours(thresh1.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# perform edge detection, find contours in the edge map, and sort the
# resulting contours from left-to-right
contours.sort(key=lambda x: get_contour_precedence(x, thresh1.shape[1]))

# initialize the list of contour bounding boxes and associated
# characters that we'll be OCR'ing
chars = []
inc = 0
# loop over the contours
for c in contours:
    inc += 1

    # compute the bounding box of the contour
    (x, y, w, h) = cv2.boundingRect(c)

    label = str(inc)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
    cv2.putText(image, label, (x - 2, y - 2),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    print('x=', x)
    print('y=', y)
    print('x+w=', x + w)
    print('y+h=', y + h)
    crop_img = image[y + 2:y + h - 1, x + 2:x + w - 1]
    name = os.path.join("bounding boxes", 'Image_%d.png' % (
        inc))
    cv2.imshow("cropped", crop_img)
    print(name)
    crop_img = Image.fromarray(crop_img)
    crop_img.save(name)
    cv2.waitKey(0)

cv2.imshow('mat', image)
cv2.waitKey(0)

Input Image :

Input image

Output Image 1:

Output Image 1(WOrking)

Input Image 2 :

Image Input 2

Output for Image 2:

Output Image 2

Input Image 3:

Input Image 3

Output Image 3:

Output Image 3

As you can see the 1,2,3,4 is not what I was expecting it to be each image, as displayed in the Image Number 3.

How do I adjust this to make it work or even write a custom function?

NOTE: I have multiple images of the same input image provided in my question. The content is the same but they have variations in the text so the tolerance factor is not working for each one of them. Manually adjusting it would not be a good idea.



from Sorting contours based on precedence in Python, OpenCV

Debug php using VS Code: Unable to attach to browser

I have installed xdebug following the instructions from here: http://xdebug.org/wizard

enter image description here

I have also installed Debugger for Chrome extension

enter image description here

Now I choose my index.php file and start the debugger, but I get the following error:

enter image description here

This is the content of lunch.json

enter image description here

This is the config that I have added to php.ini

xdebug.remote_enable = 1
xdebug.remote_autostart = 1
zend_extension = /usr/lib/php/20170718/xdebug.so

Update:

I have added xdebug.remote_log=/tmp/xdebug.log to php.ini and this is the error that I get:

[3569] I: Connecting to configured address/port: localhost:9000.
[3569] W: Creating socket for 'localhost:9000', poll success, but error: Operation now in progress (29).
[3569] E: Could not connect to client. :-(


from Debug php using VS Code: Unable to attach to browser

Change Poetry colors in output

When running Poetry, I get some nice colores like these:

enter image description here

However, some colors are just unreadable, like the dark blue from poetry check. I found this issue and apparently this is a terminal problem, but I have no idea where Poetry is getting these colors and how I can change them. I have a custom ~/.dircolors file that applies to ls and other commands. How can I do the same for Poetry output?



from Change Poetry colors in output

React Native: RNIap.getPurchaseHistory().then does not execute either of it's resolve or it's reject functions

The project is at this Github Repository. The file with the code is at components/Soundboard.js


This code was working previously, but now it looks like the promise is running forever. If I uncomment all the commented lines below and call the function askForPurchase() the only things printed to the console are

  • an object that looks like "_40": 0, "_55": {"_40": 0, "_55": null, "_65": 0, "_72": null}, "_65": 3, "_72": null} for the line console.log(RNIap.getPurchaseHistory())
  • and then the word end.

The buyProduct() function also is no longer functioning properly.

const buyProduct = function(){
    RNIap.requestPurchase("1985162691", false).then(purchase => {
        store.dispatch(setPurchases(purchase))
    }).catch((error) => {
        console.log(error.message);
    })
}

const askForPurchase = function(){
    if (!store.getState().purchase){
        //console.log(RNIap.getPurchaseHistory())
        RNIap.getPurchaseHistory().then(purchase => {
            //console.log(`test1`)
            store.dispatch(setPurchases(purchase))
            if (purchase.length == 0){
                //console.log(`test if`)
                buyProduct()
            }else{
                //console.log(`test else`)
                RNIap.getAvailablePurchases()
            }
        }, reason => {
            console.log(reason)
        })
        //console.log(`end`)
    }
}

This code was working a few months ago and I even pulled a commit(1b9cb81f229680e173ce910892dddedc632c1651, comment: "Made the seal pic more cartoony") from that time to test out. After pulling this commit, I deleted my node_modules and pods, and cleaned my build folder, but the askForPurchase() and buyProduct() functions no longer work in that commit either.

I am testing this on a real iPhone SE running ios 13.6.1


If needed I can create a sandbox account for IAP, but it doesn't seem like I'll need to



from React Native: RNIap.getPurchaseHistory().then does not execute either of it's resolve or it's reject functions

Sunday 30 August 2020

DraftJs: Replace an entity using its entity key

I'm creating a rich text editor using draftjs and can't find any ressources to help me in my problem.

Please first have look to the codesandbox.

You can see a text that contains a link (testtest in red). If you click on it you will see some infos of the link in the table:

| 🔗 link src         | http://localhost:8080/testtest |
| 📝 link text        | testtest                       |
| 🔑 link Entity key  | ab5a7c6d...                    |

I get the current link key (🔑) thanks to my getCurrentLinkKey helper:

const getCurrentLinkKey = (
  editorState: EditorState,
  contentState?: ContentState
): string => {
  if (contentState === undefined) {
    contentState = editorState.getCurrentContent();
  }

  const startKey = editorState.getSelection().getStartKey();
  const startOffset = editorState.getSelection().getStartOffset();
  const blockWithLinkAtBeginning = contentState.getBlockForKey(startKey);

  return blockWithLinkAtBeginning.getEntityAt(startOffset);
};

Then with this key I can get the link Entity using getCurrentLinkEntity helper:

const getCurrentLinkEntity = (
  editorState: EditorState
): EntityInstance | null => {
  const contentState = editorState.getCurrentContent();
  const linkKey = getCurrentLinkKey(editorState, contentState);

  if (linkKey) {
    return contentState.getEntity(linkKey);
  }

  return null;
};

Using the link Entity I can finally get the src and text value:

getCurrentLinkEntity(editorState).getData().url   // 🔗
getCurrentLinkEntity(editorState).getData().text  // 📝

You can see at the bottom a button Insert link. If you select the entire link testtest and click on this button, the link will be replaced.

This feature is handled by the insertLink helper:

const insertLink = (
  link: string,
  text: string,
  editorState: EditorState,
  setEditorState: (editorState: EditorState) => void
): void => {
  const contentStateWithEntity = editorState
    .getCurrentContent()
    .createEntity("LINK", "MUTABLE", { url: link, text });

  const entityKey = contentStateWithEntity.getLastCreatedEntityKey();

  const contentState = Modifier.replaceText(
    editorState.getCurrentContent(),
    editorState.getSelection(),
    text,
    editorState.getCurrentInlineStyle(),
    entityKey
  );

  const newEditorState = EditorState.set(editorState, {
    currentContent: contentStateWithEntity
  });
  const newEditorStateWithLink = RichUtils.toggleLink(
    newEditorState,
    newEditorState.getSelection(),
    entityKey
  );

  setEditorState(
    EditorState.push(newEditorStateWithLink, contentState, "insert-characters")
  );
};

But this function will just replace your selected text by the google link. What I want is, if you are on a link and click the button, then the entire link should be updated. So I created the replaceLink helper:

const replaceLink = (
  link: string,
  text: string,
  editorState: EditorState,
  setEditorState: (editorState: EditorState) => void
): void => {
  const contentStateWithEntity = editorState
    .getCurrentContent()
    .createEntity("LINK", "MUTABLE", { url: link, text });

  const entityKey = contentStateWithEntity.getLastCreatedEntityKey();

  const newEditorState = EditorState.set(editorState, {
    currentContent: contentStateWithEntity
  });

  const contentState = newEditorState
    .getCurrentContent()
    .replaceEntityData(getCurrentLinkKey(editorState), { entityKey });

  const newEditorStateWithLink = RichUtils.toggleLink(
    newEditorState,
    newEditorState.getSelection(),
    entityKey
  );

  setEditorState(
    EditorState.push(newEditorStateWithLink, contentState, "insert-characters")
  );
};

But sadly, if I click on the Replace link button (that trigger replaceLink helper), the link is not updated but src and text are empty:

| 🔗 link src         |             |
| 📝 link text        |             |
| 🔑 link Entity key  | a1e34047... |

So as someone an idea how I can replace the link Entity using it's entity key?



from DraftJs: Replace an entity using its entity key

Check and enable AutoBackUp to google drive from inside android app

Is it possible to check if a user has enabled googles auto backup feature from inside an app and give them the option to switch it on or off? If so could someone please provide a blueprint of how to implement this feature as the google documentation is not providing any clarity on this matter.



from Check and enable AutoBackUp to google drive from inside android app

When update Plotly marker size, I want to preserve graph padding

Initial marker size is 16. first marker sie

When I update marker size to 30, then graph layout's padding change too. enter image description here

Try below codepn.

Codepen

var myPlot = document.getElementById('myDiv'),
    x = [1, 2, 3, 4, 5, 6],
    y = [1, 2, 3, 2, 3, 4],
    colors = ['#00000','#00000','#00000',
              '#00000','#00000','#00000'],
    data = [{x:x, y:y, type:'scatter',
             mode:'markers', marker:{size:16, color:colors}}],
    layout = {
        hovermode:'closest',
        title:'Click on a Point to Change Color<br>Double Click (anywhere) to Change it Back'
     };

Plotly.newPlot('myDiv', data, layout);

myPlot.on('plotly_click', function(data){
  var pn='',
      tn='',
      colors=[];
  for(var i=0; i < data.points.length; i++){
    pn = data.points[i].pointNumber;
    tn = data.points[i].curveNumber;
    colors = data.points[i].data.marker.color;
  };
  colors[pn] = '#C54C82';
    
  var update = {'marker':{color: colors, size:30}};
  Plotly.restyle('myDiv', update, [tn]);
});

Can I preserve graph layout with only marker size change?



from When update Plotly marker size, I want to preserve graph padding

Using passlib can register the password but can't verify it again getting error

I am using passlib to store the password in my sqlite database. I am not getting error while storing the new password(registration). But when I try to login with the same user I am getting this error 'TypeError: hash must be unicode or bytes, not sqlalchemy.orm.attributes.InstrumentedAttribute'.

My script

**models.py**
class Login(db.Model,UserMixin):
    "Creates username and password"
    id = db.Column(db.Integer,primary_key=True,nullable=False)
    username = db.Column(db.String,nullable=False)
    password = db.Column(db.String,nullable=False)
    email = db.Column(db.String,nullable=False)

    def __repr__(self):
        return f"Login('{self.id}','{self.username}','{self.password}','{self.email}')"

**routes.py**
from myfolder.security import encrypt_password,check_encrypted_password
def login():
   
    if request.method == 'POST':
        username = request.form.get('username')
        password1 = request.form.get('password')
        data = {'username':username}
        #fetch the email id of the user whose logged in
        user_email_id = Login.query.filter(Login.username==username).values(Login.email,Login.password)
        for logged_user in user_email_id:
            logged_email_id = logged_user.email
            hashed = logged_user.password
        session['logged_user'] = logged_email_id
        completion = validate(username)
        if completion ==False:
            error = 'error.'
        else:
            password_check = check_encrypted_password(password1,Login.password)
            if password_check ==False:
                error = 'error.'
            else:
                user = Login()
                user.name=username
                user.password=password
                login_user(user)
                error = 'Success'
        api_response = {'data':data,'error':error}
        return jsonify(api_response)

I have created new file called security.py

from passlib.context import CryptContext

pwd_context = CryptContext(
    schemes=["pbkdf2_sha256"],
    default="pbkdf2_sha256",
    pbkdf2_sha256__default_rounds=30000
)


def encrypt_password(password):
    return pwd_context.encrypt(password)


def check_encrypted_password(password, hashed):
    return pwd_context.verify(password, hashed)

In the login method I tried different ways but nothing is working.I tried passing the password here. password_check = check_encrypted_password(password1,password) But I am getting this error

raise ValueError("hash could not be identified")
ValueError: hash could not be identified

How should I verify my password and login?



from Using passlib can register the password but can't verify it again getting error

xcodebuild archive failure: picking the wrong SDK?

I'm using fastlane to release an app. The simplified version of xcodebuild command to build the app is this:

xcodebuild -workspace App.xcworkspace -scheme App 
           -configuration Release -sdk iphoneos13.6 
           -destination 'generic/platform=iOS' clean archive

This fails giving (adding a sample):

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/cdefs.h:807:2: error: Unsupported architecture
#error Unsupported architecture
 ^
In file included from /Users/sudeepkumar/Zendrive/mobile-apps/ios/copilot/Pods/glog/src/symbolize.cc:55:
In file included from /Users/sudeepkumar/Zendrive/mobile-apps/ios/copilot/Pods/glog/src/utilities.h:73:
In file included from /Users/sudeepkumar/Zendrive/mobile-apps/ios/copilot/Pods/glog/src/base/mutex.h:141:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/pthread.h:55:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_types.h:27:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/_types.h:33:
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/machine/_types.h:34:2: error: architecture not supported
#error architecture not supported
 ^

I see that it's picking the MacOSX.sdk, I would expect it to pick iPhoneOS sdk present in Xcode directory. Is this the reason for failure? Or something else?

xcrun output:

» xcrun --show-sdk-platform-path
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform

» xcrun --sdk iphoneos --show-sdk-platform-path
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform


from xcodebuild archive failure: picking the wrong SDK?

How to forward click event to Launcher app?

I have a widget placed programatically on the Home screen, and I made it possible for the user to drag it to the place he wishes. I have added an OnTouchListener to the view to get motion events (so that I can remember view position on screen for next time), and it fires wherever I click on the Home screen, even when this is outside of my view.

What I would like to achieve is to forward the MotionEvent.ACTION_UP to the Launcher app so that, if user clicked on an app icon, that app will be launched. Or alternatively, NOT to receive this event when clicked outside of my view. Here's what I have done:

 LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 inflatedViewWidget = inflater.inflate(R.layout.mtc_appwidget, null);

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                        0,
                        PixelFormat.TRANSLUCENT);
final WindowManager wm = (WindowManager) context.getSystemService(WINDOW_SERVICE);
wm.addView(inflatedViewWidget, params);

OnTouchListener:

inflatedViewWidget.setClickable(true);
inflatedViewWidget.setOnTouchListener(new View.OnTouchListener() {
       public boolean onTouch(View v, MotionEvent event) {

                        int action = event.getAction();
                        switch (action) {
                            case MotionEvent.ACTION_UP:
                                //how to forward event to Launcher app?
                                break;


from How to forward click event to Launcher app?

Angular route to server but apply token headers through interceptor

In my Angular routing, I want to add a route for serving authenticated files from the backend:

{ path: 'files/:id/:name', pathMatch: 'full', ??? }

I already have an HTTP interceptor which adds the token headers to other requests. What I want to achieve is simply that the (existing) interceptor adds the token headers, then passes the request on to the server.

(The server will then validate the authentication headers and e.g. return an image. The response will have no additional headers, the result will just be a plain image. Example: "files/1337/logo.svg".)

I don't need a component for that, do I? How can I achieve that in the simplest way?

Thanks for your help!



from Angular route to server but apply token headers through interceptor

Vizualizing speed of movement with color scale for location in Python

i have 3 main values (longitude, latitude and speed). Using Folium library i can map the location with lon and lat degree. but now i want also put the velocity with color scale. for example if the speed is between 0-20 the that part of line is red, if speed is between 20-60 the yellow, if the speed is higher than 60 then the line is green. is it possible to do it in python? Can anybody help me with this? my current code is:

my_map = folium.Map(location=[ave_lat, ave_long], zoom_start=14) 
folium.PolyLine(points, color="blue", weight=2.5, opacity=1).add_to(my_map)
my_map

"points" here is lon and lat pairs. but i have also speed column in my csv. my output is like this. Can anybody help me with this? Thanks! enter image description here

but i want to add speed column for data visualising to get something like this enter image description here



from Vizualizing speed of movement with color scale for location in Python

Issues when using Angular Datatables as a shared component

I am using the Datatable as a component so that I can use it in all the templates I have. I have the following files :

table.component.ts

import * as _ from "lodash";
import { Observable, Subject, merge } from 'rxjs';
import { Component, OnInit, ViewChild, Renderer2, Input, Output, EventEmitter, ContentChild, ElementRef } from "@angular/core";

import { DataTableDirective } from "angular-datatables";
import { TableActionEvent } from "../../types/table/table.actions";

@Component({
    selector: "common-table",
    templateUrl: "./table.component.html",
    styleUrls: ["./table.component.scss"],
})
export class TableComponent implements OnInit {

    public dtOptions: DataTables.Settings = {};
    public dtTrigger: Subject<any> = new Subject();
    public _data: Array<any>;
    public _settings: any;
    public _loading: boolean;

    @ViewChild(DataTableDirective, { static: false }) private datatableElement: DataTableDirective;

    /**
    *  Grid data with pagination meta
    */

    @Input()

    set data(data: any) {
        if (data) {
            this._data = data;
        }
    }

    get data(): any {
        return this._data;
    }

    /**
    *  Grid data with pagination meta
    */

    @Input()

    set settings(data: any) {
        if (data) {
            this._settings = data;
        }
    }

    get settings(): any {
        return this._settings;
    }

    @Input()

    set loading(loading: boolean) {
        this._loading = loading;
        setTimeout(() => {
            $('#releaseDatatable').DataTable().destroy();
            this.dtTrigger.next();
        }, 100);
    }

    get loading(): boolean {
        return this._loading;
    }


    @Output() public event: EventEmitter<TableActionEvent<any>> = new EventEmitter<TableActionEvent<any>>();

    /**
     * DashboardComponent constructor
     */
    constructor(
        private renderer: Renderer2,
        private elem: ElementRef
    ) { }

    /**
     * @memberof DashboardComponent
     */
    public ngOnInit(): void {
        this.dtOptions = {
            info: false,
            order: []
        };
    }

    /**
     *
    */
    cellRender(render, row) {
        if (_.isString(render)) {
            return render;
        }

        if (_.isFunction(render)) {
            return render(row);
        }
    }
   
    /**
     * @param $event
     */
    public search($event) {
        const term = $event.target.value;
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
            dtInstance.search(term).draw();
        });
    }

    /**
   * On Table Action
   *
   * @param {string} action
   * @param {T} row
   * @param {number} index
   *
   * @memberof AdminGridComponent
   */
    public onAction(action: string, row: any): void {
        const tableActionItem: any = {
            action: action,
            row: row
        };

        this.event.emit(tableActionItem);
    }

    rerender() {
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
            dtInstance.destroy();
            this.dtTrigger.next();
        });
    }

    ngAfterViewInit(): void {
        this.dtTrigger.next();
    }
    ngOnDestroy(): void {
        // Do not forget to unsubscribe the event
        this.dtTrigger.unsubscribe();
      }
}

and the template file table.component.html is like the following:

<div class="ma-datatables">
    <form>
        <div class="d-flex align-items-center app-login_input-layout">
            <input class="form-control app-login_input-style rm-release_search-bar" type="search" id="release-search"
                placeholder="Search here..." (keyup)=search($event)>
            <i class="material-icons rm-release_search-icon">search</i>
        </div>
    </form>
    <div class="table-responsive">
        <div *ngIf="!loading">
            <table class="table animate__animated animate__fadeIn" id="releaseDatatable" datatable
                [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
                <thead>
                    <tr>
                        <th *ngFor="let header of settings.columns"></th>
                        <th *ngIf="settings.actions">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let release of data">
                        <ng-container *ngFor="let column of settings.columns">
                            <td class="rm-release_table-cell" [style.width]=column.width>
                                <div>
                                    <p *ngIf="column.dataType !='html'" class="rm-release_data-id">
                                        
                                    </p>
                                    <span *ngIf="column.dataType =='html'">
                                        <div innerHTML=""></div>
                                    </span>
                                </div>
                            </td>
                        </ng-container>
                        <td class="rm-release_table-cell" *ngIf="settings.actions">
                            <div>
                                <a id="release-action" href="javascript:void(0)" (click)="openAction($event)">
                                    <i class="material-icons">more_vert</i>
                                </a>
                                <div class="rm-release_action-layout hidden" #actionSlide
                                    id="release-">
                                    <div class="rm-release_action-container animate__animated" #actionContainer>
                                        <div
                                            class="d-flex align-items-center justify-content-between rm-release_action-header">
                                            <a class="rm-release_action-close" href="javascript:void(0)"
                                                (click)="closeAction($event)">
                                                <i class="material-icons">close</i>
                                            </a>
                                        </div>
                                        <div class="rm-release_action-item-layout">
                                            <div class="rm-release_action-item-layout">
                                                <ng-container *ngIf="release.permitted_actions;else actionMenu">
                                                    <ng-container *ngFor="let action of settings.actions">
                                                        <div *ngIf="release.permitted_actions.includes(action.action)"
                                                            class="d-flex align-items-center rm-release_action-item"
                                                            (click)="onAction(action.action, release)">
                                                            <i class="material-icons"></i>
                                                            <p></p>
                                                        </div>
                                                    </ng-container>
                                                </ng-container>
                                                <ng-template #actionMenu>
                                                    <ng-container *ngFor="let action of settings.actions">
                                                        <div class="d-flex align-items-center rm-release_action-item"
                                                            (click)="onAction(action.action, release)">
                                                            <i class="material-icons"></i>
                                                            <p></p>
                                                        </div>
                                                    </ng-container>
                                                </ng-template>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

    </div>
</div>

and I am using this component as shown below:

  <common-table [data]="items" [settings]="settings" [loading]="isLoading"
      (event)="onGridEvent($event)">
  </common-table>

Now I am facing multiple issues here :

  1. It is showing No data available in table sometimes, but when the page is refreshed, it will be gone.

  2. Sometimes, it is showing DataTables warning: table id=releaseDatatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3"

It will be very much helpful if someone can help me to fix this issues. I am using the Angular Datatables package.



from Issues when using Angular Datatables as a shared component