Saturday, 30 April 2022

Unable to run armeabi-v7a on Android Studio emulator

I need to be able to create a virtual device in Android Studio, which allows me to test my app on old Android systems such as Lollipop or Marshmallow, but it looks like I am unable to do it.

The only ARM images I see available are the "armeabi-v7a", and every time I create a new device and try to launch it, I get the error "The emulator process for AVS [device name] has terminated" as shown in the shot below:

Emulator Error

Everything seems to be in place inside the SKD Tools panel as you can see below:

enter image description here

And everything works fine with arm64-v8a images.

For your information, I am using Android Studio for Mac version Bumblebee 2021.1.1 Patch 3 which should be the latest one:

enter image description here



from Unable to run armeabi-v7a on Android Studio emulator

Can't cast okHTTP response as JSON

I am using okhttp 4.9.0 to make API requests, but seems that can't get the response body as JSONOBJECT. This is my code:

client.newCall(request).enqueue(object : Callback {

            override fun onFailure(call: Call, e: IOException) {
                Log.d("respuesta","fallida")
            }
            override fun onResponse(call: Call, response: Response)
            {
                val codigoRespuesta: Int = response.code
                if(codigoRespuesta == 401) //Quiere decir que hubo un error al autentificar
                {
                    pantalla.cerrarSesion("Auth error")
                }
                Log.d("Response", response.body!!.string())
                val respuesta: JSONObject = JSONObject(response.body?.string())

                pantalla.procesarResultado(respuesta)
            }
        })

I get the following error:

E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher

    Process: com.ximhai.vekcheckin, PID: 22096
    java.lang.IllegalStateException: closed
        at okio.RealBufferedSource.select(RealBufferedSource.kt:218)
        at okhttp3.internal.Util.readBomAsCharset(Util.kt:258)
        at okhttp3.ResponseBody.string(ResponseBody.kt:187)
        at com.ximhai.vekcheckin.apiRetro$revisarBoleto$1.onResponse(apiRetro.kt:79)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

On the debug "Log.d("Response", response.body!!.string())" I get:

D/Response: {"resultado":0,"error":"Ticket not found"}

Which means that the API call is actually responding a JSON string.

Now, if I copy the response string and hard code it in the JSON Object like:

val respuesta: JSONObject = JSONObject("{\"resultado\":0,\"error\":\"Ticket not found\"}")

The code works perfectly. (backslashes added automatically by Android Studio when pasting the string).

I have tried:

val respuesta: JSONObject = JSONObject(response.body!!.string()) -> Same result

val respuesta: JSONObject = JSONObject(response.body?.toString()) -> Same result

val respuesta: JSONObject = JSONObject(response.body!!.toString()) -> Same result

val respuesta: JSONObject = JSONObject(response.body().string()) -> Build error: Using 'body(): ResponseBody?' is an error. moved to val

As an extra information: The API is supposed to be responging with Header: Content-type -> application/json

    $newResponse = $response->withHeader('Content-type', 'application/json');


from Can't cast okHTTP response as JSON

When can I stop using AppCompat or Support libraries?

I'm building an app with minSdkVersion 23. Can I stop using support libraries like androidx.appcompat:appcompat and stuff like AppCompatActivity?

I assume it would reduce app size and avoid unused code. Or am I missing something?

At which SDK version do we draw the line?



from When can I stop using AppCompat or Support libraries?

How to use BootstrapVue's layout and grid system to arrange these checkboxes?

I have a BootstrapVue table like this;

enter image description here

Here's the code for the table;

window.onload = () => {
  new Vue({
    el: '#app',
    computed: {
      visibleFields() {
        return this.fields.filter(field => field.visible)
      }
    },
    data() {
      return {
        items: [
          { id: 1, first: 'Mike', last: 'Kristensen', age: 16 },
          { id: 2, first: 'Peter', last: 'Madsen', age: 52 },
          { id: 3, first: 'Mads', last: 'Mikkelsen', age: 76 },
          { id: 4, first: 'Mikkel', last: 'Hansen', age: 34 },
        ],
        fields: [
          { key: 'id', label: 'ID', visible: true },
          { key: 'first', label: 'First Name', visible: true },
          { key: 'last', label: 'Last Name', visible: true },
          { key: 'age', label: 'Age', visible: true },
        ]
      }
    }
  })
}

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.2.2/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.2.2/dist/bootstrap-vue.min.js"></script>

<div id='app'>
<b-checkbox
    :disabled="visibleFields.length == 1 && field.visible"
    v-for="field in fields" 
    :key="field.key" 
    v-model="field.visible" 
    inline
  >
    
  </b-checkbox>
  <br /><br />
  <b-table :items="items" :fields="visibleFields" bordered>
  </b-table>
</div>

I want to use BootstrapVue layout and grid system to arrange the checkboxes.

https://bootstrap-vue.org/docs/components/layout

I want the checkboxes to be placed using BootstrapVue's layout and grid system as shown below;

<b-container class="bv-example-row">
  <b-row class="justify-content-md-center">
    <b-col col lg="12">1 of 3</b-col>
    <b-col cols="12" md="auto">Variable width content</b-col>
    <b-col col lg="2">3 of 3</b-col>
    <b-col col lg="14">3 of 3</b-col>
  </b-row>
</b-container>

What complicates matters is the html code for the checkbox which contains v-for. See below;

<b-checkbox
    :disabled="visibleFields.length == 1 && field.visible"
    v-for="field in fields" 
    :key="field.key" 
    v-model="field.visible" 
    inline
  >
    
  </b-checkbox>

I am using vue v2.6, BootstrapVue.



from How to use BootstrapVue's layout and grid system to arrange these checkboxes?

python setuptools setup.cfg: Including main- and subpackages in the build dir

I would like to create a pip package for my python software using a setup.cfg file. My program is currently structured as following:

mypkg
├── setup.cfg
└── src
    ├── subpkg
    │   └── __init__.py
    ├── __init__.py
    └── file_1.py
    ...

so far, using the setuptools find_packages() function allowed me to add my main package as well as the subpackage to my build package. When using a setup.cfg file however, I am not able to include both in my package anymore. The documentation shows that subpackages can be included by adding the option

[options]
packages = find:
package_dir =
    =src

[options.packages.find]
where = src
include = *

But this only includes the subpackage files and not the main package files in my case. Is there a way for me to include all my files while still making use of a setup.cfg setup file?



from python setuptools setup.cfg: Including main- and subpackages in the build dir

Custom edge detection for React tooltip causes page to "flash" occasionally

So I created simple edge detection for a tooltip that is part of a charting library. I can't use tooltips that already have implemented edge detection (like MUI tooltip) because the charting software only allows HTML tooltips, so I was left to create a React component that has edge detection for RIGHT side of screen only. Since the tooltip always opens to the right, I just have to take care of the right side.

So when the hover is close to the edge, the tooltip checks how close it is to the edge, then I use CSS offset to place the tooltip at a point away from the right side of the screen.

The component looks like this:

export const MyTooltip = ({ children }) => {

  useEffect(() => {
    const container =
      document.getElementById('tooltip');

    if (container) {
      const x = container.getBoundingClientRect().x;

      if (x > window.outerWidth - 200) {
    container.style.left = 'auto';
        container.style.right = '0';
        container.style.transform = `translateX(${
          window.outerWidth - x - 40
        }px)`;
      }
    }
  }, []);

  return (
    <TooltipStyle>
      <div id="tooltip" className="custom-tooltip">
        {children}
      </div>
    </TooltipStyle>
  );
};

TooltipStyle is a styled component that has CSS for the .custom-tooltip class for the background, padding, etc. 200px is the width of the tooltip in all instances and 40px is the padding.

The problem: Occasionally, when the tooltip renders in the DOM, the page "flashes" for a split second. It's very unsightly. I know it's because of the code in the useEffect hook that actually sets the offset of the tooltip, but I'm not certain about what a good solution would be.

Any help is much appreciated! Thanks.



from Custom edge detection for React tooltip causes page to "flash" occasionally

Friday, 29 April 2022

Angular Material table filtering out all results when input is initially blank, will work after typing into input Only

So my table works really well, except that it shows no data until either a row is clicked or the filter is used. I am unsure as to what is going on here, not sure what I am doing wrong.

I just want all data to initially load visibly into the table.

HTML:

<div fxLayoutAlign="center center">
    <button mat-mini-fab color="accent" style="margin-right: 20px">
      <mat-icon class="add-course-btn" (click)="stalkUser()">person_add_alt_1</mat-icon>
    </button>
      <mat-form-field fxFlex="40%">
        <input matInput (keyup)="doFilter($event)" placeholder="Ex. Username" #input>
      </mat-form-field>
    </div>
    
    <ng-container *ngIf="usersUserStalking.length > 0 && isLoading == false">
      <mat-table [dataSource]="dataSource" matSort>
        <ng-container matColumnDef="userName">
            <mat-header-cell *matHeaderCellDef mat-sort-header id="nameField">Name</mat-header-cell>
            <mat-cell *matCellDef="let element"><span style="cursor:pointer" (click)="navigateProfile(element.tag)"><img mat-card-avatar src="" class="friends-avatar-photo"> </span></mat-cell>
          </ng-container>
        
          <ng-container matColumnDef="userTag">
            <mat-header-cell *matHeaderCellDef mat-sort-header fxHide.xs>Tag</mat-header-cell>
            <mat-cell *matCellDef="let element" fxHide.xs></mat-cell>
          </ng-container>
    
          <ng-container matColumnDef="userRank">
            <mat-header-cell *matHeaderCellDef mat-sort-header fxHide.xs>Rank</mat-header-cell>
            <mat-cell *matCellDef="let element" fxHide.xs></mat-cell>
          </ng-container>
        
          <ng-container matColumnDef="factionName" >
            <mat-header-cell *matHeaderCellDef mat-sort-header fxHide.xs>Faction</mat-header-cell>
            <mat-cell *matCellDef="let element" fxHide.xs><span style="cursor:pointer" (click)="navigateProfile(element.tag)"></span></mat-cell>
          </ng-container>

          <ng-container matColumnDef="stalking" >
            <mat-header-cell *matHeaderCellDef>Stalking</mat-header-cell>
            <mat-cell *matCellDef="let element"><button mat-stroked-button class="hover-class" color="primary"><span>Stalking</span></button></mat-cell>
          </ng-container>
        
          <!-- Row shown when there is no matching data. -->
          <tr class="mat-row" *matNoDataRow>
            <td class="mat-cell" colspan="4">No data matching the filter ""</td>
          </tr>
        
          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
      </mat-table>
      
      <mat-paginator #paginator 
                    [pageSizeOptions]="[5, 10, 25, 100]">
      </mat-paginator>
    </ng-container>

    <!-- Show if user is stalking no one -->
    <ng-container *ngIf="usersUserStalking.length <= 0 && isLoading == false">
      <div fxLayoutAlign="center center">
        <h1>You are Stalking no one, use the yellow button above to stalk whoever you want!</h1>
      </div>
    </ng-container>
    <ng-container *ngIf="isLoading">
      <div class="spinner-container" fxLayoutAlign="center center">
        <mat-spinner></mat-spinner>
      </div>
    </ng-container>

Typscript:

import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Observable } from 'rxjs';
import { User } from 'src/app/auth/user.model';
import { UserService } from 'src/app/auth/user.service';
import { Router } from '@angular/router';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-stalking',
  templateUrl: './stalking.component.html',
  styleUrls: ['./stalking.component.css']
})
export class FollowingComponent implements OnInit {
  @Input() userUID: string;
  userId: string;

  displayedColumns = ["userName", "userTag", "userRank", "factionName", "stalking"];
  dataSource = new MatTableDataSource<User>();
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  //User Array
  userArray$: Observable<unknown[]| null>;
  usersUserStalking: User[] = []
  //loading
  isLoading: boolean = false;

  constructor(private user: UserService,
              private db: AngularFirestore,
              private router: Router) {}

  async ngOnInit() {
   await this.onReadCollection(this.userUID)
  }

  async onReadCollection(userUID: string){
    this.isLoading = true;
    this.db.collection(`users/${userUID}/stalking`).get()
        .pipe(
          finalize(() => {
            this.isLoading = false;
            this.dataSource.sort = this.sort;
            this.dataSource.paginator = this.paginator;
            console.log(this.usersUserStalking)
            this.dataSource.data = this.usersUserStalking; // update dataScource
            console.log(this.dataSource.data)
          })
        )
        .subscribe(snaps => {
         snaps.forEach(snap => {
            this.user.findUserbyUID(snap.id).subscribe(user => {
              this.usersUserStalking.push(<User>user)
            })
         })
     })
    
 }

 

  async getFriendsForProfile(){
    this.userId = this.user.getUserUID();
  }

  ngAfterViewInit() {
    // this.dataSource.sort = this.sort;
    // this.dataSource.paginator = this.paginator;
    // this.dataSource.data = this.usersUserStalking
  }

  doFilter(event: Event | null) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  navigateProfile(userTag){
    this.router.navigate(['/profile', userTag])    
  }

}

I have my filter set up like this:

html:

      <mat-form-field fxFlex="40%">
        <input matInput (keyup)="doFilter($event)" placeholder="Ex. Username" #input>
      </mat-form-field>

Typescript:

  doFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

I feel like I copied the angular material tables exactly like how it is done in the examples shown here: https://material.angular.io/components/table/examples

Edit 1: I updated my code and get on initial user to be visible now, but still generally have the same issue, I only see all users in the table after using the filter and clearing the filter.



from Angular Material table filtering out all results when input is initially blank, will work after typing into input Only

Python & Selenium: How to get values generated by JavaScript

I use Selenium in Python for scraping. I can't get values though these values are displayed on the browser.

So I checked the HTML source code, then I found that there are no values in HTML as below.

HTML

<div id="pos-list-body" class="list-body">

</div>

But there are values when I checked developer tool in chrome.

DevTools

<div id="pos-list-body" class="list-body">
    <div class="list-body-row" id="pos-row-1">
        <div class="pos-list-col-1">
            <input class="list-checkbox" type="checkbox" value="1">
        </div>
        <div class="detail-data pos-list-col-2">
            1
        </div>
        <div class="detail-data pos-list-col-3">
            a
        </div>
        ...
    </div>
    <div class="list-body-row" id="pos-row-2">
        <div class="pos-list-col-1">
            <input class="list-checkbox" type="checkbox" value="2">
        </div>
        <div class="detail-data pos-list-col-2">
            2
        </div>
        <div class="detail-data pos-list-col-3">
            b
        </div>
        ...
    </div>
    ...
</div>

It seems that these values generated by JavaScript or something.

There is no iframe in sorce code.

How can I get these values with python?

It would be appreciated if you could give me some hint.



from Python & Selenium: How to get values generated by JavaScript

return multiple function from parse function in node js / javascript

const parsers = new Map();

parsers._get = parsers.get;
parsers.get = function (key) {
  if (this.has(key)) return this._get(key);
  return () =>
    console.warn(`Parser not implemented for: ${JSON.stringify(key)}`);
};

parsers.set("document", parseDocument);
parsers.set("paragraph", parseParagraph);
parsers.set("text", parseText);
parsers.set("hr", parseHR);
parsers.set("heading-4", parseH4);
parsers.set("heading-6", parseH6);
parsers.set("block", parseBlock);

function convert(obj) {
  return [parsers.get(obj.nodeType)(obj)];
}

function parseDocument(obj) {
  let type = "doc";
  let attrs = { dirty: true };
  let children = [];

  obj.content.forEach((e) => children.push(parsers.get(e.nodeType)(e)));
  return { type, children, attrs };
}

function parseParagraph(obj) {
  let type = "p";
  let attrs = { dirty: true };
  let children = [];

  obj.content.forEach((e) => children.push(parsers.get(e.nodeType)(e)));
  return { type, children, attrs };
}

function parseText(obj) {
  const result = {};
  result.text = obj.value;
  obj.marks.forEach((e) => (result[e.type] = true));
  return result;
}

function parseHR(obj) {
  let type = "hr";
  let attrs = { dirty: true };
  let children = [];
  return { type, attrs, children };
}

function parseH4(obj) {
  let type = "h4";
  let attrs = { dirty: true };
  let children = [];
  obj.content.forEach((e) => children.push(parsers.get(e.nodeType)(e)));
  children = children.map((c) => c.children).flat();
  return { type, attrs, children };
}

function parseH6(obj) {
  let type = "h6";
  let attrs = { dirty: true };
  let children = [];
  obj.content.forEach((e) => children.push(parsers.get(e.nodeType)(e)));
  children = children.map((c) => c.children).flat();
  return { type, attrs, children };
}

function parseBlock(obj) {
  let jsonObject = {
    MVJlVePWr6: {
      e_id: "MVJlVePWr6",
      name_placeholder: "news_item",
      alternative_tags: ["da", "es"],
    },
    gevhdjsx: {
      e_id: "gevhdjsx",
      name_placeholder: "changes_item",
      alternative_tags: ["da"],
    },
  };
  let type, attrs, children;
  for (
    i = 0;
    jsonObject[obj.data.target.sys.id].alternative_tags.length > i;
    i++
  ) {
    for (const alt of jsonObject[obj.data.target.sys.id].alternative_tags) {
      type = "block";
      attrs = { dirty: true };
      children = {};
      if (obj.data.target.sys.id in jsonObject) {
        children = {
          type: "primary",
          name: `${alt}_name_we_got`,
          other_name: alt,
          employees: "intern",
        };
      }
      return { type, attrs, children };
    }
  }
}

let result = convert(getSrcData());
console.log("Converted object: ", result);

function getSrcData() {
  return {
    nodeType: "document",
    data: {},
    content: [
      {
        nodeType: "paragraph",
        content: [
          {
            nodeType: "text",
            value: "dummy testing bold",
            marks: [
              {
                type: "bold",
              },
            ],
            data: {},
          },
        ],
        data: {},
      },
      {
        nodeType: "hr",
        content: [],
        data: {},
      },
      {
        nodeType: "paragraph",
        content: [
          {
            nodeType: "text",
            value: "",
            marks: [],
            data: {},
          },
        ],
        data: {},
      },
      {
        nodeType: "heading-4",
        content: [
          {
            nodeType: "text",
            value: "heading 4",
            marks: [
              {
                type: "bold",
              },
            ],
            data: {},
          },
        ],
        data: {},
      },
      {
        nodeType: "heading-6",
        content: [
          {
            nodeType: "text",
            value: "heading 6",
            marks: [
              {
                type: "italic",
              },
            ],
            data: {},
          },
        ],
        data: {},
      },
      {
        nodeType: "hr",
        content: [],
        data: {},
      },
      {
        nodeType: "block",
        content: [],
        data: {
          target: {
            sys: {
              id: "MVJlVePWr6",
              type: "Link",
              linkType: "Block",
            },
          },
        },
      },
    ],
  };
}

I have wrote this code and I am getting expected output the problem is I want to send multiple data from one function that is from parseBlock but I can only retrun one value which is first da but I can't return other en value

as I check and printed console.log() so I am getting multiple values but when I am returning the value I am getting the single value

as my expected output is like this from parseBlock but in above output I am getting single value from parseBlock

      {
        "type": "block",
        "attrs": {
          "dirty": true
        },
        "children": {
          "type": "primary",
          "name": "da_name_we_got",
          "other_name": "da",
          "employees": "intern"
        }
      },
      {
        "type": "block",
        "attrs": {
          "dirty": true
        },
        "children": {
          "type": "primary",
          "name": "es_name_we_got",
          "other_name": "es",
          "employees": "intern"
        }
      }

but this is not I am getting and I don't know where I am doing wrong to return the multiple values from one function



from return multiple function from parse function in node js / javascript

How to get a better approximation of a thick bezier curve?

Let's say I already have a bezier curve approximated by many straight lines (the bezier array in the code), and I would like to draw it with a series of rectangles. I have the following code below that does exactly this:

// don't change this array
const bezier = [{x:167.00,y:40.00},{x:154.37,y:42.09},{x:143.09,y:44.48},{x:133.08,y:47.15},{x:124.26,y:50.09},{x:116.55,y:53.27},{x:109.87,y:56.68},{x:104.15,y:60.31},{x:99.32,y:64.14},{x:95.28,y:68.15},{x:91.97,y:72.34},{x:89.31,y:76.67},{x:87.22,y:81.14},{x:85.63,y:85.74},{x:84.44,y:90.43},{x:83.60,y:95.22},{x:83.02,y:100.08},{x:82.63,y:105.00},{x:82.33,y:109.96},{x:82.07,y:114.94},{x:81.76,y:119.94},{x:81.33,y:124.93},{x:80.69,y:129.89},{x:79.77,y:134.82},{x:78.49,y:139.70},{x:76.78,y:144.50},{x:74.55,y:149.22},{x:71.74,y:153.84},{x:68.25,y:158.34},{x:64.03,y:162.71},{x:58.97,y:166.93},{x:53.02,y:170.98},{x:46.10,y:174.86},{x:38.11,y:178.54},{x:29.00,y:182.00}];

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

const thickness = 35;

function rotateCanvas(x, y, a) {
  ctx.translate(x, y);
  ctx.rotate(a);
  ctx.translate(-x, -y);
}

function drawRectangle(rX, rY, rW, rH, rA, color) {
  ctx.beginPath();
  rotateCanvas(rX + rW / 2, rY + rH / 2, rA);
  ctx.rect(rX, rY, rW, rH);
  rotateCanvas(rX + rW / 2, rY + rH / 2, -rA);
  ctx.fill();
}

function calcRectFromLine(x1, y1, x2, y2) {
  const dx = x2 - x1;
  const dy = y2 - y1;
  const mag = Math.sqrt(dx * dx + dy * dy);
  const angle = Math.atan2(dy, dx);

  return { 
    x: (x1 + x2) / 2 - mag / 2,
    y: (y1 + y2) / 2 - thickness / 2,
    w: mag,
    h: thickness,
    a: angle
  };
}

function calculateRectangles() {
  const result = [];

  for (let i = 1; i < bezier.length; i++) {
    const prev = bezier[i - 1];
    const curr = bezier[i];

    result.push(calcRectFromLine(prev.x, prev.y, curr.x, curr.y));
  }

  return result;
}

const rectangles = calculateRectangles();

for (let r of rectangles) {
  drawRectangle(r.x, r.y, r.w, r.h, r.a);
}
<canvas width="400" height="400"></canvas>

If you run the snippet you'll see that the curve is not fully thick, and the fact that it is a series of rectangles is very obvious.

If you change the thickness parameter from 35 to a lower number and re-run it, it looks fine. It's only when it's very thick does this occur.

The code currently takes the bezier array, and creates a series of rotated rectangles and then renders them.

Is there any way to modify the calculateRectangles function to return a better approximation of the curve? Ideally it would still return a list of rectangles rotated around their center, but when rendered it would look more like the curve, and less like a list of rectangles.

The only idea I could think of is to somehow return twice as many rectangles from calculateRectangles, where each one is inverted from the previous one, such that both sides of the line are filled in, and while I think that might work, it unfortunately has the side-effect of returning twice as many rectangles, which is undesirable and I would to avoid it if possible.



from How to get a better approximation of a thick bezier curve?

pip install -r requirements.txt not installing libraries in vs code virtual environement

I have created virtual environment in VS code. When i am doing the command pip install -r requirements.txt. enter image description here

Still the vs code says no such module found. However, if i individually do pip install and it works like a charm. why ? My requirements.txt file are

Flask==1.1.2
joblib==1.0.1
keras==2.6.0
matplotlib==3.3.4
numpy==1.21.2
pandas==1.3.3
requests==2.25.1
scikit_learn==1.0.2
seaborn==0.11.1
xgboost==1.5.1
utils==1.0.1
jellyfish==0.8.9
langdetect==1.0.9
nltk==3.6.1
spacy==3.2.0
textblob==0.17.1
vaderSentiment==3.3.2
ipython==7.30.1
gapminder==0.1
mlxtend==0.19.0
networkx==2.5
squarify==0.4.3
pandas-profiling==3.1.0
plotly==5.3.1
scikit_image==0.18.1
scipy==1.7.1
nbformat
squarify==0.4.3
gapminder==0.1
tensorflow==2.7
ipywidgets


from pip install -r requirements.txt not installing libraries in vs code virtual environement

How to get all fuzzy matching substrings between two strings in python?

Say I have three example strings

text1 = "Patient has checked in for abdominal pain which started 3 days ago. Patient was prescribed idx 20 mg every 4 hours."
text2 = "The time of discomfort was 3 days ago."
text3 = "John was given a prescription of idx, 20mg to be given every four hours"

If I got all the matching substrings of text2 and text3 with text1, I would get

text1_text2_common = [
    '3 days ago.',
]

text2_text3_common = [
    'of',
]

text1_text3_common = [
    'was',
    'idx'
    'every'
    'hours'
]

What I am looking for is a fuzzy matching, using something like the Levenshtein distance [ https://ift.tt/5kYXErf ]. So even if the substrings are not exact, if they are similar enough for a criteria, it would get selected as a substring.

So ideally I am looking for something like

text1_text3_common_fuzzy = [
    'prescription of idx, 20mg to be given every four hours'
]


from How to get all fuzzy matching substrings between two strings in python?

Thursday, 28 April 2022

Error when importing '@tensorflow/tfjs' to use local model in Chrome extension

I tried to use tensorflow local model in my chrome extension. In contentScript:

import * as tf from '@tensorflow/tfjs';
const MODEL_URL = './model/model.json';
const model = tf.load_model(MODEL_URL);
model.run("text");

My manifest.json:

  "content_security_policy": {
    "extension_pages": "script-src 'self' http://localhost; object-src 'self';"
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_title": "My extension",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs", 
    "history", 
    "background", 
    "webNavigation", 
    "activeTab", 
    "storage"
  ],
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "run_at": "document_start",
      "js": [
        "contentScript.js"
      ]
    }
  ]

But I got error Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".

My package.json:

{
  "name": "my-extension",
  "version": "0.1.0",
  "description": "My Chrome Extension",
  "private": true,
  "scripts": {
    "watch": "webpack --mode=development --watch --config config/webpack.config.js",
    "build": "webpack --mode=production --config config/webpack.config.js"
  },
  "devDependencies": {
    "copy-webpack-plugin": "^6.4.1",
    "css-loader": "^4.3.0",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^0.10.1",
    "size-plugin": "^2.0.2",
    "webpack": "^4.46.0",
    "webpack-cli": "^3.3.12",
    "webpack-merge": "^5.8.0"
  },
  "dependencies": {
    "@tensorflow/tfjs": "^3.16.0",
    "@tensorflow/tfjs-node": "^3.16.0"
  }
}

What should be the proper way to using local model?



from Error when importing '@tensorflow/tfjs' to use local model in Chrome extension

Financial performance and risk analysis statistics from sample DataFrame

How do I output detailed financial performance and risk analysis statistics from this sample pandas DataFrame?

Can anyone show how this could be done with Quantstats, Pyfolio or another similar approach?

Code

start_amount = 100000

np.random.seed(8)
win_loss_df = pd.DataFrame(
    np.random.choice([1000, -1000], 543),
    index=pd.date_range("2020-01-01", "2022-01-30", freq="B"),
    columns=["win_loss_amount"]
)
win_loss_df["total_profit"] = win_loss_df.win_loss_amount.cumsum() + start_amount

Sample DataFrame

win_loss_df.head(10)

win_loss_amount total_profit
2020-01-01  -1000   99000
2020-01-02  1000    100000
2020-01-03  -1000   99000
2020-01-06  -1000   98000
2020-01-07  -1000   97000
2020-01-08  1000    98000
2020-01-09  1000    99000
2020-01-10  -1000   98000
2020-01-13  1000    99000
2020-01-14  -1000   98000

Desired output

I would like to see output including:

  • Annual return
  • Sharpe ratio
  • Max drawdown

I was hoping to use a library for this which would simplify the process and return data similar to a tear sheet.



from Financial performance and risk analysis statistics from sample DataFrame

Privacy policy link for Google Play

I am having trouble here, this is my first app and there is so much involved, I did not think it was this hard, currently I am stuck on adding a link to my app's PRIVACY POLICY my app is very simple.

It does not share any data but I do use Google Analytics, one more thing is that I do not have a website, so supposedly I had the privacy policy link where would I put it apart from a site I own?

Thanks.



from Privacy policy link for Google Play

recursion and ram flood: Starting a Gradle Daemon, 1 busy and 6 stopped Daemons could not be reused, use --status for details

I'm using this plugin https://github.com/mozilla/rust-android-gradle, which requires me to add

tasks.whenTaskAdded { task ->
    if ((task.name == 'javaPreCompileDebug' || task.name == 'javaPreCompileRelease')) {
        task.dependsOn 'cargoBuild'
    }
}

to my flutter project's build.gradle and when I do flutter build apk I get things like

Starting a Gradle Daemon, 18 busy Daemons could not be reused, use --status for details
Starting a Gradle Daemon, 19 busy Daemons could not be reused, use --status for details
...

and then it keeps starting a new one until my RAM floods and the computer crashes. If I comment that code, it builds.

Is there a way to debug more to see what is hapening? Looking at the system monitor, it's starting lots of java gradle daemons

This is part of the output of ./gradlew --info --stacktrace --debug assembleDebug

2022-04-24T17:14:45.981+0000 [QUIET] [system.out] > Configure project :
2022-04-24T17:14:45.981+0000 [QUIET] [system.out] Starting a Gradle Daemon, 2 busy and 23 stopped Daemons could not be reused, use --status for details
2022-04-24T17:14:51.958+0000 [LIFECYCLE] [org.gradle.cache.internal.DefaultFileLockManager] 
2022-04-24T17:14:51.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry.
2022-04-24T17:14:51.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired on daemon addresses registry.
2022-04-24T17:14:51.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
2022-04-24T17:14:51.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry.
2022-04-24T17:14:51.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired on daemon addresses registry.
2022-04-24T17:14:51.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
2022-04-24T17:14:46.015+0000 [LIFECYCLE] [org.gradle.internal.logging.progress.ProgressLoggerFactory] 
2022-04-24T17:14:46.015+0000 [LIFECYCLE] [org.gradle.internal.logging.progress.ProgressLoggerFactory] > Configure project :
2022-04-24T17:14:54.279+0000 [QUIET] [system.out] 
2022-04-24T17:14:54.279+0000 [QUIET] [system.out] > Configure project :
2022-04-24T17:14:54.279+0000 [QUIET] [system.out] Starting a Gradle Daemon, 3 busy and 23 stopped Daemons could not be reused, use --status for details
2022-04-24T17:15:01.958+0000 [LIFECYCLE] [org.gradle.cache.internal.DefaultFileLockManager] 
2022-04-24T17:15:01.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry.
2022-04-24T17:15:01.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired on daemon addresses registry.
2022-04-24T17:15:01.958+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
2022-04-24T17:15:01.959+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry.
2022-04-24T17:15:01.959+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired on daemon addresses registry.
2022-04-24T17:15:01.959+0000 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
2022-04-24T17:14:54.315+0000 [LIFECYCLE] [org.gradle.internal.logging.progress.ProgressLoggerFactory] 
2022-04-24T17:14:54.315+0000 [LIFECYCLE] [org.gradle.internal.logging.progress.ProgressLoggerFactory] > Configure project :
2022-04-24T17:15:02.379+0000 [QUIET] [system.out] 
2022-04-24T17:15:02.379+0000 [QUIET] [system.out] > Configure project :
2022-04-24T17:15:02.379+0000 [QUIET] [system.out] Starting a Gradle Daemon, 4 busy and 23 stopped Daemons could not be reused, use --status for details
2022-04-24T17:15:10.279+0000 [QUIET] [system.out] 
2022-04-24T17:15:10.279+0000 [QUIET] [system.out] > Configure project :
2022-04-24T17:15:10.279+0000 [QUIET] [system.out] Starting a Gradle Daemon, 5 busy and 23 stopped Daemons could not be reused, use --status for details

my build.gradle:

buildscript {
    ext.kotlin_version = '1.6.21'
    repositories {
        google()
        mavenCentral()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'org.mozilla.rust-android-gradle:plugin:0.9.2'
    }

gradle version:

distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip


from recursion and ram flood: Starting a Gradle Daemon, 1 busy and 6 stopped Daemons could not be reused, use --status for details

Wednesday, 27 April 2022

How to use JSX in data, computed, methods in VueJS SFC

I'm setting up an app for study. From React, I've known how to use JSX and when I'm writting in VueJS, I don't know how to use it here.

<template>
    <div>
        <h1></h1> <!--Work-->
        <h1></h1> <!--Not working-->
    </div>
</template>

<script>
    export default {
        name: "test",
        data() {
            return {
                message: "Hello, JSX!", // Work
                messageJSX: <span>Hello, JSX!</span>, // Not Working
            }
        }
    }
</script>

Now I got this error:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Vue'
    |     property '$options' -> object with constructor 'Object'
    |     property 'router' -> object with constructor 'VueRouter'
    --- property 'app' closes the circle"

Thank you.



from How to use JSX in data, computed, methods in VueJS SFC

Which android lifecycle methods are guaranteed to be called after a call to finish()?

I have an activity A with several execution branches that end with a call to finish(). Reading the documentation, my understanding is that this will result in onDestroy() being called at some point for activity A if and when finish() is called. Later on, activity A might be restarted by activity B.

However, I am observing that this isn't always what happens. In rare cases onDestroy() is not called before activity A is restarted by activity B following activity A calling finish(). This is especially true if activity B restarts activity A very soon after activity A calls finish(). This possibility matches with the lifecycle graph (see here).

My question is as follows. Suppose that Activity A is in the running state and calls finish(). Can any guarantee be made about activity A calling onPause() or onStop() before activity B restarts activity A (irrespective of how soon/late in the future the restart occurs)? Moreover, once Activity A restarts, is there any guarantee that onCreate(), onStart(), or onResume() will be called? Put another way, my question is if an activity is in the running state and finish() is called what are the possible paths through the lifecycle graph that activity may take to return to the running state?



from Which android lifecycle methods are guaranteed to be called after a call to finish()?

Tuesday, 26 April 2022

just installed Python, getting WinError 32 for any libraries I try to install

I just installed Python 3.10 on my work machine. I went to pip install pandas and got a Win32 error on a temp file within the AppData Temp Folder.I have tried with other libraries and same error. Tried to uninstall and reinstall and got the same error. Also, tried to run CMD as admin and no better.

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: C:\\Users\\user\\AppData\\Local\\Temp\\tmp1b78532k


from just installed Python, getting WinError 32 for any libraries I try to install

How to automate build using appcenter

I am using app-center as CI and CD for my application. I have to configure all the branches manually against which I need to build and distribute.

I want like if somebody create a feature branch from develop/master and push the code then appcenter start running automatically like circleci etc.

Is this not possible in appcenter ? and What does SSH mechanism means in CI and CD ?



from How to automate build using appcenter

Generate chart in table cell according to json values

I need to create a bar or column chart inside a table cell of each row.

i.e I need a graph to be populated for each category inside table cell.

JSON:

[
  {
    "Chocolate": [
      {
        "kisses": [
          {
            "2022": {
              "jan": 2000,
              "feb": 1200,
              "mar": 7000
            }
          },
          {
            "2021": {
              "jan": 2000,
              "feb": 1200,
              "mar": 7000
            }
          }
        ]
      },
      {
        "kitkat": [
          {
            "2022": {
              "jan": 1000,
              "feb": 3200,
              "mar": 4500
            }
          },
          {
            "2021": {
              "jan": 2000,
              "feb": 200,
              "mar": 7030
            }
          }
        ]
      }
    ]
  },
  {
    "Drinks": [
      {
        "Coco cola": [
          {
            "2022": {
              "jan": 2000,
              "feb": 1200,
              "mar": 7000
            }
          },
          {
            "2021": {
              "jan": 2200,
              "feb": 1200,
              "mar": 7100
            }
          }
        ]
      },
      {
        "Pepsi": [
          {
            "2022": {
              "jan": 1000,
              "feb": 3200,
              "mar": 4500
            }
          },
          {
            "2021": {
              "jan": 4550,
              "feb": 2100,
              "mar": 3430
            }
          }
        ]
      }
    ]
  }
]

I need to create a bar or column chart inside a table cell of each row.

google.charts.load('current', {
  packages: ['corechart', 'table']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Category');
  data.addColumn('number', 'Name');
  data.addColumn('string', 'Chart');
  data.addRows([
    ['Choclate', {v: 10000, f: 'Kisses'}, null],
    ['Drinks', {v: 12500, f: 'Pepsi'}, null],
    ['Food', {v: 7000, f: 'Pizza'}, null]
  ]);

  var table = new google.visualization.Table(document.getElementById('table_div'));

  google.visualization.events.addListener(table, 'ready', function () {
    // table body
    Array.prototype.forEach.call(table.getContainer().getElementsByTagName('tbody'), function(tableBody) {
      // table rows
      Array.prototype.forEach.call(tableBody.rows, function(tableRow, rowIndex) {
        // table cells
        Array.prototype.forEach.call(tableRow.cells, function(tableCell, cellIndex) {
          // determine if last cell
          if (cellIndex === (tableRow.cells.length - 1)) {
            // add chart continer
            var chartContainer = tableCell.appendChild(document.createElement('div'));
            chartContainer.className = 'chart';

            // build chart data table
            var dataChart = new google.visualization.DataTable();
            dataChart.addColumn('number', 'x');
            dataChart.addColumn('number', 'y');
            for (var i = 0; i <= rowIndex; i++) {
              dataChart.addRow([i, data.getValue(i, 1)]);
            }

            // draw chart
            var chart = new google.visualization.ColumnChart(chartContainer);
            chart.draw(dataChart, {
              chartArea: {
                left: 24,
                top: 16,
                right: 24,
                bottom: 16,
                height: '100%',
                width: '100%'
              },
              height: '100%',
              legend: 'none',
              pointSize: 6,
              width: '100%'
            });
          }
        });
      });
    });
  });

  table.draw(data, {showRowNumber: true, width: '60%', height: '70%'});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></div>

I Want JSON values to be populated in the graph w.r.t each category.

Sample output: https://i.stack.imgur.com/H973g.png

If unable to pivot row based on category. I need to try atlease each row.

Please suggest me how to achieve



from Generate chart in table cell according to json values

How stream a response from a Twisted server?

Issue

My problem is that I can't write a server that streams the response that my application sends back.
The response are not retrieved chunk by chunk, but from a single block when the iterator has finished iterating.

Approach

When I write the response with the write method of Request, it understands well that it is a chunk that we send.
I checked if there was a buffer size used by Twisted, but the message size check seems to be done in the doWrite.

After spending some time debugging, it seems that the reactor only reads and writes at the end.
If I understood correctly how a reactor works with Twisted, it writes and reads when the file descriptor is available.

What is a file descriptor in Twisted ?
Why is it not available after writing the response ?

Example

I have written a minimal script of what I would like my server to look like.
It's a "ASGI-like" server that runs an application, iterates over a function that returns a very large string:

# async_stream_server.py
import asyncio
from twisted.internet import asyncioreactor

twisted_loop = asyncio.new_event_loop()
asyncioreactor.install(twisted_loop)

import time
from sys import stdout

from twisted.web import http
from twisted.python.log import startLogging
from twisted.internet import reactor, endpoints

CHUNK_SIZE = 2**16


def async_partial(async_fn, *partial_args):
    async def wrapped(*args):
        return await async_fn(*partial_args, *args)
    return wrapped


def iterable_content():
    for _ in range(5):
        time.sleep(1)
        yield b"a" * CHUNK_SIZE


async def application(send):
    for part in iterable_content():
        await send(
            {
                "body": part,
                "more_body": True,
            }
        )
    await send({"more_body": False})


class Dummy(http.Request):
    def process(self):
        asyncio.ensure_future(
            application(send=async_partial(self.handle_reply)),
            loop=asyncio.get_event_loop()
        )

    async def handle_reply(self, message):
        http.Request.write(self, message.get("body", b""))
        if not message.get("more_body", False):
            http.Request.finish(self)
        print('HTTP response chunk')


class DummyFactory(http.HTTPFactory):
    def buildProtocol(self, addr):
        protocol = http.HTTPFactory.buildProtocol(self, addr)
        protocol.requestFactory = Dummy
        return protocol


startLogging(stdout)
endpoints.serverFromString(reactor, "tcp:1234").listen(DummyFactory())
asyncio.set_event_loop(reactor._asyncioEventloop)
reactor.run()

To execute this example:

  • in a terminal, run:
python async_stream_server.py
  • in another terminal, run:
curl http://localhost:1234/

You will have to wait a while before you see the whole message.

Details

$ python --version
Python 3.10.4
$ pip list
Package           Version Editable project location
----------------- ------- --------------------------------------------------
asgiref           3.5.0
Twisted           22.4.0


from How stream a response from a Twisted server?

Trying to build react native app for Android on Mac M1 - Error: No emulators found as an output of `emulator -list-avds`

I have installed Android Studio on my mac M1
I have added a virtual device in Android Studio using Device Manager
The app builds fine from inside Android Studio......however when I run npx react-native run-android from command line in VSCode, I get the error No emulators found as an output of emulator -list-avds

However when I navigate to emulator folder using cd ~/Library/Android/sdk/emulator and run command ./emulator -avd {AVD_NAME}, the emulator starts fine.....however even with the emulator running, the command npx react-native run-android still gives the error No emulators found as an output of emulator -list-avds



from Trying to build react native app for Android on Mac M1 - Error: No emulators found as an output of `emulator -list-avds`

Monday, 25 April 2022

How to convert an int to a hex string?

I want to take an integer (that will be <= 255), to a hex string representation

e.g.: I want to pass in 65 and get out '\x41', or 255 and get '\xff'.

I've tried doing this with the struct.pack('c',65), but that chokes on anything above 9 since it wants to take in a single character string.



from How to convert an int to a hex string?

Is it possible to disable the cursor from being recorded with getDisplayMedia()

I am recording my browser window using MediaStream and MediaRecorder.

But need to disable the mouse cursor from being recorded, so when I create my video track, i use the following code:

stream['input'] = await navigator.mediaDevices.getDisplayMedia({
    audio: true,
    video: {
    cursor: 'never',
    frameRate: 40,
}
});
console.log( stream['input'].getVideoTracks()[0].getSettings() );

However chrome, opera and edge console displays:

aspectRatio: 1.7777777777777777
cursor: "motion"
deviceId: "window:200730:1"
displaySurface: "window"
frameRate: 40
height: 1080
logicalSurface: true
resizeMode: "crop-and-scale"
width: 1920

But seem to ignore the setting, so the cursor is being recorded.

I can see the frameRate constraint is being set in my console, however I just cannot for the life of me seem to disable the cursor.

Yet, firefox doesn't record the cursor and shows this in the console

frameRate: 40
​height: 924
​width: 1263

Has anyone successfully managed to disable the cursor at all with Chrome, Edge and Opera?

i've even tried using

stream['input'].getVideoTracks()[0].applyConstraints( { 
video: { cursor: 'never', frameRate: 30 } 
} );

Which doesn't work :-(

Update: I can see from the chart here: https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints

that the cursor constraint is only supposed to be supported on opera. However the output from getSupportedConstraints() shows cursor is not supported after all.

Thanks



from Is it possible to disable the cursor from being recorded with getDisplayMedia()

React Native TypeScript WebSocket onerror Value of "this" must be of type Event

I'm trying to implement WebSocket support into my app by following React Native's own tutorial at https://reactnative.dev/docs/network#websocket-support.

Here is my code:

function initializeSocket(socket:WebSocket){
    socket.onopen = () => {
        store.dispatch(toggleWebsocketConnected(true));
    };
    socket.onclose = () => {
        store.dispatch(toggleWebsocketConnected(false));
    };
    socket.onerror = (e:any) => {
        console.log('websocket error', e);
        store.dispatch(toggleWebsocketConnected(false));
    };
    socket.onmessage = (e) => {
        processMessage(e);
    };
}

In onerror event handler (for now, ignore why error handler is called, this is not a "why can't I connect" question, but a TypeScript question) when it's triggered I'm getting a weird error at runtime:

TypeError [ERR_INVALID_THIS]: Value of "this" must be of type Event
    at new NodeError (/path/to/my/project/lib/internal/errors.js:371:5)
    at Event.[nodejs.util.inspect.custom] (/path/to/my/project/lib/internal/event_target.js:120:13)
    at formatValue (/path/to/my/project/lib/internal/util/inspect.js:763:19)
    at inspect (/path/to/my/project/lib/internal/util/inspect.js:340:10)
    at formatWithOptionsInternal (/path/to/my/project/lib/internal/util/inspect.js:2006:40)
    at formatWithOptions (/path/to/my/project/lib/internal/util/inspect.js:1888:10)
    at console.value (/path/to/my/project/lib/internal/console/constructor.js:323:14)
    at console.log (/path/to/my/project/lib/internal/console/constructor.js:359:61)
    at EventTarget.socket.onerror (/path/to/my/project/src/services/myproject/socket.ts:27:17)
    at EventTarget.dispatchEvent (/path/to/my/project/.vscode/.react/index.bundle:31193:27) {code: 'ERR_INVALID_THIS', stack: 'TypeError [ERR_INVALID_THIS]: Value of "this"…/myproject/.vscode/.react/index.bundle:31193:27)', message: 'Value of "this" must be of type Event', toString: Æ’, Symbol(kIsNodeError): true}

Vscode linter shows everything is fine though. When I hover over the onerror function it shows:

(property) WebSocket.onerror: ((this: WebSocket, ev: Event) => any) | null

Two input arguments. So eventhough Vscode isn't complaining about my initial code, I also tried to change it to the following:

 socket.onerror = (_:any, e:any) => {
    console.log('websocket error', e);
    store.dispatch(toggleWebsocketConnected(false));
 };

Now, Vscode linter shows an error:

Type '(_: any, e: any) => void' is not assignable to type '(this: WebSocket, ev: Event) => any'.ts(2322)

If I run the code regardless of the error, I don't get a runtime error, yet _ is now an actual event object and e is undefined:

enter image description here

What am I doing wrong? What is the correct form of doing it? I've stumbled upon a weird problem with this keyword in arguments and TypeScript before (see Why are rest parameters undefined in TypeScript?) which indeed turned to be a Babel bug, which is now merged and fixed long ago.

How can I get it to work correectly?

UPDATE: I've managed to "work around" by turning the arrow function into a function with a function keyword:

    socket.onerror = function(this:any, e:Event){
        console.log('websocket error', e);
        store.dispatch(toggleWebsocketConnected(false));
    };

It "works" now, though this is not an actual solution as I still can't use arrow functions, breaking my code style as I never use function keyword functions in code (other than top-level simple definitions) anywhere in the app.

No it doesn't, it seemed to step correctly yet actually threw an error again when I reached a line to console.log the event.



from React Native TypeScript WebSocket onerror Value of "this" must be of type Event

Django ORM: Get maximum value of a field with corresponding other fields values

I have this Table (Counters):

cell_id tftralacc tfnscan thtralacc thnscan date_time
13997 10 360 94 360 2022-02-22 00:00:00+01
13997 0 360 0 360 2022-02-22 01:00:00+01
13997 0 360 0 360 2022-02-22 02:00:00+01
13997 0 360 0 360 2022-02-22 03:00:00+01
13997 36 360 83 360 2022-02-22 04:00:00+01
13997 0 360 2 360 2022-02-22 05:00:00+01
13997 1 360 15 360 2022-02-22 06:00:00+01
13997 11 360 159 360 2022-02-22 07:00:00+01
13997 21 360 409 360 2022-02-22 08:00:00+01
13997 25 360 1282 360 2022-02-22 09:00:00+01
13997 20 360 1201 360 2022-02-22 10:00:00+01
13997 30 360 1381 360 2022-02-22 11:00:00+01
13997 42 360 924 360 2022-02-22 12:00:00+01
14000 1 360 36 360 2022-02-22 00:00:00+01
14000 0 360 0 360 2022-02-22 01:00:00+01
14000 1 360 0 360 2022-02-22 02:00:00+01
14000 0 360 2 360 2022-02-22 03:00:00+01
14000 0 360 0 360 2022-02-22 04:00:00+01
14000 0 360 12 360 2022-02-22 05:00:00+01
14000 3 360 4 360 2022-02-22 06:00:00+01
14000 24 360 123 360 2022-02-22 07:00:00+01
14000 31 360 374 360 2022-02-22 08:00:00+01
14000 18 360 620 360 2022-02-22 09:00:00+01
14000 38 360 1616 360 2022-02-22 10:00:00+01
14000 36 360 1410 360 2022-02-22 11:00:00+01
14000 24 360 957 360 2022-02-22 12:00:00+01

I want to get the specific date_time value of the maximum traffic (which is calculated based on the the fields tftralacc, tfnscan, thtralacc and thnscan) for every cell_id.

I've managed to get this maximum value for every cell_id by using the annotate() and group_by() functions of the Django's QuerySet API:

result = Counters.objects.filter(
    date_time__gte = date_start,
    date_time__lte = date_end
).annotate(
    # calculate the traffic for each row.
    traffic = Case(
        When(Q(tfnscan=0) or Q(thnscan=0), then=0),
        default = Round((F('tftralacc')*1.0/F('tfnscan')) + 
                        (F('thtralacc')*1.0/F('thnscan')), 2),
        output_field=FloatField()
    )
).order_by('cell_id').values(
    # Group by cell_id.
    'cell_id'
).order_by().annotate(
    # calculate the max traffic for the grouped Cells.
    max_traffic = Max('traffic')
)

The calculated traffic for every date_time is demonstrated here: enter image description here

My code successfully returns the maximum traffic for every cell_id:

cell_id max_traffic
13997 3.92
14000 4.59

But my goal is to get the Corresponding date_time value for every max value. like this:

cell_id max_traffic date_time
13997 3.92 2022-02-22 11:00:00+01
14000 4.59 2022-02-22 10:00:00+01

or

cell_id date_time
13997 2022-02-22 11:00:00+01
14000 2022-02-22 10:00:00+01

Because that max value is just a mean to get the date_time and not the goal.

Note: There is this question that describes my problem, but its answer refers to a work-around solution, which is not possible with my problem. SO Question



from Django ORM: Get maximum value of a field with corresponding other fields values

Moshi: How to provide adapter for PolymorphicJsonAdapterFactory.withFallbackJsonAdapter while configuring Moshi.Builder

I'm trying to use PolymorphicJsonAdapterFactory for JSON which provides different structure depending on type field, like below.

{
  "notifications": [
    {
      "type": "achievement",
      "title": "New Achievement!",
      "content": "You got new achievement Level 100! (100pt)"
      "metadata": {
        "category": "level",
        "id": "level100",
        "points": 100,
      }
    },
    {
      "type": "message",
      "name": "message",
      "content": "Cloud: hello, ~"
      "metadata": {
        "from": "Cloud",
        "content": "hello, ~ "
      }
    },
    {
      "type": "new", <--- e.g. this is unknown type for app
      "name": "something new",
      "content": "You are informed something about. Please check app://~",
      "deeplink": "app://~"
    }
  ]
}

Suppose our app already prepared for some known type, achievement and message. But there's a chance to add new type, in this case new. At this time, we want app to work with minimum properties title and content. In short, I want map that new type to Other fallback class.

data class Notifications(
    val notifications: List<Notification>
)

sealed class Notification {
    abstract val type: String
    abstract val title: String
    abstract val content: String
}

data class Achievement(
    override val type: String,
    override val title: String,
    override val content: String,
    val metadata: Metadata,
): Notification() {
    data class Metadata(
        val category: String,
        val id: String,
        val points: Int,
    )
}

data class Message(
    override val type: String,
    override val title: String,
    override val content: String,
    val metadata: Metadata,
): Notification() {
    data class Metadata(
        val from: String,
        val content: String,
    )
}

// Any unknown `type` goes here.
data class Other(
    override val type: String,
    override val title: String,
    override val content: String,
): Notification()

val moshi = Moshi.Builder()
    .add(
        PolymorphicJsonAdapterFactory.of(Notification::class.java, "type")
            .withSubtype(Achievement::class.java, "achievement")
            .withSubtype(Message::class.java, "message")
            .withFallbackJsonAdapter(...)
    )
    .addLast(KotlinJsonAdapterFactory())
    .build()

If moshi configuration and Notification is so simple like this, it is able to write .withFallbackJsonAdapter(object: Adapter()...).

But if we have some customization in Moshi.Builder, we may want to use adapter from configured moshi val adapter = moshi.adapter() so we can't write adapter inline. Then, I thought creating two moshi like this.

val moshiWithoutPoly = Moshi.Builder()
    // some other base configuration going here
    .build()

val moshi = moshiWithoutPoly.newBuilder()
    .add(
        PolymorphicJsonAdapterFactory.of(Notification::class.java, "type")
            .withSubtype(Achievement::class.java, "achievement")
            .withSubtype(Message::class.java, "message")
            .withFallbackJsonAdapter(moshiWithoutPoly.adapter(Other::class.java) as JsonAdapter<Any>)
    )
    .build()

Is it fine or is there more proper solution for this?
(Or I'm wondering if it is eligible for proposing new API like .withFallbackSubtype(Other::class.java) or .withFallbackAdapterFactory(factory) for such situation.)



from Moshi: How to provide adapter for PolymorphicJsonAdapterFactory.withFallbackJsonAdapter while configuring Moshi.Builder

http request does not get called when uploading the data to Firebase - firebase cloud function

Hello everyone I am trying to fetch the data from Binance than do a schedule function that uploads the data from the previous fetch to the Cloud FireStore , the schedule function is a function that gets called every minute and MUST call the fetch function update the object that contain the data and than I parse that object in order to upload the updated data.

The problem is that the function that fetches the data gets called just one time and that is it, the next minute after the function deploy the fetch data gets not called and I tried everything I found on stackoverflow and google but not luck.

Can anyone give me a hint thank you.

Code:

"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const https = require("https");
admin.initializeApp();
const database = admin.firestore();
let finalData = [];
const page = 1;
const fiat = "RON";
const tradeType = "SELL";
const asset = "USDT";
const payTypes = ["BCRBank"];
const baseObj = {
  page,
  rows: 20,
  publisherType: null,
  asset,
  tradeType,
  fiat,
  payTypes,
};
const stringData = JSON.stringify(baseObj);
const options = {
  hostname: "p2p.binance.com",
  port: 443,
  path: "/bapi/c2c/v2/friendly/c2c/adv/search",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Content-Length": stringData.length,
  },
};

finalData = [];
const req = https.request(options, (res) => {
  console.log("Entered the request call");
  let output = "";
  res.on("data", (d) => {
    output += d;
  });
  res.on("end", () => {
    try {
      const jsonOuput = JSON.parse(output);
      const allData = jsonOuput["data"];
      for (let i = 0; i < allData.length; i++) {
        let payTypesz = "";
        for (let y = 0; y < allData[i]["adv"]["tradeMethods"].length; y++) {
          payTypesz += allData[i]["adv"]["tradeMethods"][y]["payType"];
          if (y < allData[i]["adv"]["tradeMethods"].length - 1) {
            payTypesz += ", ";
          }
        }
        const obj = {
          tradeType: allData[i]["adv"]["tradeType"],
          asset: allData[i]["adv"]["asset"],
          fiatUnit: allData[i]["adv"]["fiatUnit"],
          price: allData[i]["adv"]["price"],
          surplusAmount: allData[i]["adv"]["surplusAmount"],
          maxSingleTransAmount: allData[i]["adv"]["maxSingleTransAmount"],
          minSingleTransAmount: allData[i]["adv"]["minSingleTransAmount"],
          nickName: allData[i]["advertiser"]["nickName"],
          monthOrderCount: allData[i]["advertiser"]["monthOrderCount"],
          monthFinishRate: allData[i]["advertiser"]["monthFinishRate"],
          advConfirmTime: allData[i]["advertiser"]["advConfirmTime"],
          payTypes: payTypesz,
          position: 0,
        };
        finalData.push(obj);
      }
      console.log(finalData);
    } catch (e) {
      console.log(e);
    }
  });
});

const fD =function fetchData(stringData) {
  console.log("I entered the FetchData");
  req.write(stringData);
};

exports.scheduledFunction = functions.pubsub
    .schedule("* * * * *")
    .onRun(async (context) => {
      console.log("I am doing it");
      fD(stringData);
      for (let i = 0; i < finalData.length; i++) {
        console.log("I did not entered here");
        console.log(finalData[i]["price"]);
        await database.collection("SebiBinanceSale").doc("BCR Bank")
            .collection("1").doc(i.toString())
            .set({
              "tradeType": finalData[i]["tradeType"],
              "asset": finalData[i]["asset"],
              "fiatUnit": finalData[i]["fiatUnit"],
              "price": finalData[i]["price"],
              "surplusAmount": finalData[i]["surplusAmount"],
              "maxSingleTransAmount": finalData[i]["maxSingleTransAmount"],
              "minSingleTransAmount": finalData[i]["minSingleTransAmount"],
              "nickName": finalData[i]["nickName"],
              "monthOrderCount": finalData[i]["monthOrderCount"],
              "monthFinishRate": finalData[i]["monthFinishRate"],
              "advConfirmTime": finalData[i]["advConfirmTime"],
              "payTypes": finalData[i]["payTypes"],
              "position": finalData[i]["position"],
            });
      }
      return console.log("Succes Upload of the data ");
    });


from http request does not get called when uploading the data to Firebase - firebase cloud function

Unable to run Flutter project on Android after update

I've been trying to get my Flutter project to run after upgrading it to 2.10.4 and it's been a headache from the start. The project runs fine on a browser, but I'm having difficulty running on an Android emulator. I think I'm at the last hurdle, but I'm stumped right now. I'm receiving this error when running on VS Code:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Failed to install the following SDK components:
      build-tools;30.0.2 Android SDK Build-Tools 30.0.2
  The SDK directory is not writable (C:\Program Files (x86)\Android\android-sdk)

Here's my Flutter Doctor:

PS D:\Documents\Flutter_Projects\glance> flutter doctor -v
[√] Flutter (Channel stable, 2.10.4, on Microsoft Windows [Version 10.0.19043.1586], locale en-US)
• Flutter version 2.10.4 at D:\Programs\flutter_windows_v1.2.1-stable\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision c860cba910 (3 weeks ago), 2022-03-25 00:23:12 -0500
• Engine revision 57d3bac3dd
• Dart version 2.16.2       
• DevTools version 2.9.2
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at C:\Program Files (x86)\Android\android-sdk
• Platform android-31, build-tools 30.0.3
• ANDROID_HOME = C:\Users\reff1\AppData\Local\Android\Sdk
• ANDROID_SDK_ROOT = C:\Users\reff1\AppData\Local\Android\Sdk
• Java binary at: D:\AndroidStudio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.11+9-b60-7590822)
X Android license status unknown.
  Run `flutter doctor --android-licenses` to accept the SDK licenses.
  See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.
[√] Chrome - develop for the web
• Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
  Download at https://visualstudio.microsoft.com/downloads/.
  Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.1)
• Android Studio at D:\AndroidStudio
• Flutter plugin can be installed from:
   https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
   https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.11+9-b60-7590822)
[!] Android Studio (version 4.1)
• Android Studio at D:\Programs\AndroidStudio
• Flutter plugin can be installed from:
   https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
   https://plugins.jetbrains.com/plugin/6351-dart
X Unable to determine bundled Java version.
• Try updating or re-installing Android Studio.
[√] VS Code, 64-bit edition (version 1.50.1)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension version 3.17.0
[√] Connected device (4 available)
• sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 12 (API 32) (emulator)
• Windows (desktop)            • windows       • windows-x64    • Microsoft Windows [Version 10.0.19043.1586]
• Chrome (web)                 • chrome        • web-javascript • Google Chrome 100.0.4896.88
• Edge (web)                   • edge          • web-javascript • Microsoft Edge 99.0.1150.46
[√] HTTP Host Availability
• All required HTTP hosts are available

Here's the part that keeps getting me. I'm seeing I need to run flutter doctor --android-licenses and this is what I get:

PS D:\Documents\Flutter_Projects\glance> flutter doctor --android-licenses

Error: Could not find or load main class Files

I have no clue where to go from here. Any help would be greatly appreciated here. Thank you in advance.



from Unable to run Flutter project on Android after update

Sunday, 24 April 2022

Click

I am writing a Greasemonkey script to interact with orders on Shipstation.com.

The script will select certain values in <select> and <input> elements of the order modal based on certain criteria.

Thus, the script must be able to interact with these elements.

However, I cannot figure out how to do so.

So far, I have tried to do the following and have been unable to trigger a click on the element:

  • Set the value of the element using JS .value
  • Set the value of the element using jQuery .val
  • Trigger a click event on the element using JS .click()
  • Trigger a click event on the element using this code:
function triggerMostButtons (jNode) {
    triggerMouseEvent (jNode, "mouseover");
    triggerMouseEvent (jNode, "mousedown");
    triggerMouseEvent (jNode, "mouseup");
    triggerMouseEvent (jNode, "click");
}

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

triggerMostButtons(jNode);

It appears that Shipstation is locking the value of <select> and <input> values.

Here are examples of the SO questions I have read to try and figure this out. I haven't been able to trigger a click on these elements using any of these approaches:

How else can I trigger a click on these elements?

Alternatively, how can I set the value of these fields using JS? Do I have to find the data model in the JS and edit the value directly? Or find a way to hijack the functions that are triggered when a user clicks on these elements?

enter image description here



from Click

kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')

I am using sealed class to handle api response. I am trying some code but getting some error of serialization. I tried this solution as well but it not working. Can you guys help me out on this problem. I am new in serialization field.

import kotlinx.serialization.Serializable

sealed class ApiResponse<out T : Any> {

    data class Success<out T : Any>(
        val data: T?
    ) : ApiResponse<T>()

    data class Error(
        val exception: Throwable? = null,
        val responseCode: Int = -1
    ) : ApiResponse<Nothing>()

    fun handleResult(onSuccess: ((responseData: T?) -> Unit)?,onError: ((error: Error) -> Unit)?) {
        when (this) {
            is Success -> {
                onSuccess?.invoke(this.data)
            }
            is Error -> {
                onError?.invoke(this)
            }
        }
    }
}

@Serializable
data class ErrorResponse(
    val errorCode: Int,
    val errorMessage: String
)

Api

import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import kotlinx.coroutines.flow.Flow
import kotlinx.serialization.Serializable

class KtorCountryApi(private val httpClient: HttpClient) {
    suspend fun getCart(): Flow<ApiResponse<KtorCountriesResponse>> {
        println("api call")
        return httpClient.get {
            url("https://shop-api.example-stg2.com/api/v1/address/country")
        }.body()
    }
}

@Serializable
data class KtorCountriesResponse(
    val items: List<KtorCountry>? = null
)

@Serializable
data class KtorCountry(
    val id: String? = null,
    val isCurrentCountry: Boolean? = null,
    var isoAlpha2Code: String? = null,
    var name: String? = null,
    var phonePrefix: String? = null,
    val usesPerAreaShipping: Boolean? = null
)

Client

actual fun httpClient(config: HttpClientConfig<*>.() -> Unit) = HttpClient(OkHttp) {
    config(this)
    install(Logging) {
        logger = Logger.SIMPLE
        level = LogLevel.BODY
    }
    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            ignoreUnknownKeys = true
            explicitNulls = false
        })
    }
    engine {
        config {
            retryOnConnectionFailure(true)
            connectTimeout(30, TimeUnit.SECONDS)
            readTimeout(40, TimeUnit.SECONDS)
        }
    }
    defaultRequest {
        header("Client-Version", Platform().versionCode)
    }
    install(Auth) {
        bearer {
            loadTokens {
                BearerTokens(tokenProvider.accessToken, "")
            }
            refreshTokens {
                val response =
                    client.post("https://example-stg2.com/api/v1/session/refresh") {
                        markAsRefreshTokenRequest()
                        contentType(ContentType.Application.Json)
                        setBody(KtorSessionCommand(tokenProvider.refreshToken))
                    }
                if (response.status == HttpStatusCode.Unauthorized) {
                    null
                } else {
                    val ktorLoginResponse = response.body<KtorLoginResponse>()
                    ktorLoginResponse.accessToken?.let { ktorAccessToken ->
                        ktorAccessToken.accessToken?.let { accessToken ->
                            ktorAccessToken.refreshToken?.let { refreshToken ->
                                BearerTokens(accessToken, refreshToken)
                            }
                        }
                    }
                }
            }
        }
    }
}

Error

2022-04-22 10:50:28.614 8365-8365/com.example.app.dev E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app.dev, PID: 8365
    kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')
    JSON input: .....pping":false,"phonePrefix":"263","isCurrentCountry":false}]}
        at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
        at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
        at kotlinx.serialization.json.internal.PolymorphicKt.throwSerializerNotFound(Polymorphic.kt:76)
        at kotlinx.serialization.json.internal.PolymorphicKt.decodeSerializableValuePolymorphic(Polymorphic.kt:66)
        at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeSerializableValue(StreamingJsonDecoder.kt:36)
        at kotlinx.serialization.json.Json.decodeFromString(Json.kt:100)
        at io.ktor.serialization.kotlinx.KotlinxSerializationConverter.deserialize(KotlinxSerializationConverter.kt:55)
        at io.ktor.client.plugins.contentnegotiation.ContentNegotiation$Plugin$install$2.invokeSuspend(ContentNegotiation.kt:135)
        at io.ktor.client.plugins.contentnegotiation.ContentNegotiation$Plugin$install$2.invoke(Unknown Source:13)
        at io.ktor.client.plugins.contentnegotiation.ContentNegotiation$Plugin$install$2.invoke(Unknown Source:6)
        at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
        at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
        at io.ktor.client.HttpClient$4.invokeSuspend(HttpClient.kt:170)
        at io.ktor.client.HttpClient$4.invoke(Unknown Source:11)
        at io.ktor.client.HttpClient$4.invoke(Unknown Source:6)
        at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
        at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
        at io.ktor.client.plugins.logging.Logging$setupResponseLogging$2.invokeSuspend(Logging.kt:167)
        at io.ktor.client.plugins.logging.Logging$setupResponseLogging$2.invoke(Unknown Source:11)
        at io.ktor.client.plugins.logging.Logging$setupResponseLogging$2.invoke(Unknown Source:6)
        at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
        at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
        at io.ktor.util.pipeline.SuspendFunctionGun.proceedWith(SuspendFunctionGun.kt:91)
        at io.ktor.client.plugins.HttpCallValidator$Companion$install$2.invokeSuspend(HttpCallValidator.kt:140)
        at io.ktor.client.plugins.HttpCallValidator$Companion$install$2.invoke(Unknown Source:13)
        at io.ktor.client.plugins.HttpCallValidator$Companion$install$2.invoke(Unknown Source:6)
        at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
        at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
        at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:101)
        at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
        at io.ktor.client.call.HttpClientCall.body(HttpClientCall.kt:87)
        at com.example.kotlinmultiplatformsharedmodule.KtorCountryApi.getCart(KtorCountryApi.kt:53)
        at com.example.kotlinmultiplatformsharedmodule.KtorCountryApi$getCart$1.invokeSuspend(Unknown Source:14)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

I am not understand what this error mean. Can someone explain me why do we need extra code for this error to solve.



from kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')

OneTimeWorkRequest (content observer) loses first picture after app is closed. Works OK for subsequent pictures

I am trying to implement reliable background listener on user media (e.g. if user takes a picture, I want to capture that, even if application is closed). I am using Android's WorkManager (OneTimeWorkRequest).

Everything works fine when application is at the foreground or in the background in the task bar. However when I close the application, doWork() doesn't gets called for the first picture that user is taking. Subsequent pictures, 2nd, 3rd and so on work just fine.

When app is closed, after first picture is taken, I can see plenty additional stuff in Logcat, almost like if Android rebuilt the app context, initialize some stuff, but actually doesn't run the doWork(), event gets lost.

Logs after first background event triggered:

...
2022-03-31 11:56:24.842 10616-10616/com.my.app I/s.app: The ClassLoaderContext is a special shared library.
2022-03-31 11:56:24.998 10616-10616/com.my.app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2022-03-31 11:56:24.998 10616-10616/com.my.app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2022-03-31 11:56:25.000 10616-10616/com.my.app D/WM-WrkMgrInitializer: Initializing WorkManager with default configuration.
2022-03-31 11:56:25.008 10616-10616/com.my.app I/TetheringManager: registerTetheringEventCallback:com.my.app
2022-03-31 11:56:26.793 10616-10632/com.my.app W/System: A resource failed to call close. 

I get the feeling that this issue has something related to WorkManager initialization. It seems it's not properly initialized during first event. It gets initialized on the go by default initializer, however it loses the event as doWork() isn't called properly.

Any idea why this might be and how to overcome this issue?

CODE EXAMPLE

https://github.com/tomekit/so_71691180

In order to reproduce:

  1. Open this in Android Studio, compile and install app on emulator.
  2. Open camera and take a photo, you should see: I/ContentURI: content://media/external/images/media/109 in LogCat.
  3. Close an app (swipe away) and make sure it's no longer available in taskbar.
  4. Take a photo. You will see no log is produced.
  5. Take another photo. Now you can see that logs are created correctly, meaning that doWork() gets executed. Any subsequent photo, creates log entry correctly.


from OneTimeWorkRequest (content observer) loses first picture after app is closed. Works OK for subsequent pictures

Bootstrap 5 Carousel Navigation Buttons Mapping issue

I made the following Bootstrap 5 Carousels in React. This generates as many carousels as many array items we have, with dynamically changing images.

My issue is that all Carousels navigation buttons point to the first Carousel slides and because of that all the Carousels buttons change the First Carousel's slides. The reason for this, I believe, is that the slide buttons point to the id 'carouselExampleIndicators', which handles only the first Carousel.

What is the best way to deal with this problem, and How to do it?

My plan is to solve this problem by making the id change dynamically, but I'm not sure how to do it.

const MyQUESTIONS = [
    {quest: Question1 , answer: Question1A },
    {quest: Question2 , answer: Question2A },
    {quest: Question3 , answer: Question3A },
    {quest: Question4 , answer: Question4A },
  ];



const Questions = () =>{
 return (
<>

//It maps through the array, creating x amount of carousels
{MyQUESTIONS.map((questionData) => {
  return (
<div className="row question__row">
<div id="carouselExampleIndicators" className="carousel carousel-dark slide question__carousel mb-5 mt-5 me-auto ms-auto" data-bs-ride="carousel">
  <div className="carousel-indicators">
    <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" className="active" aria-current="true" aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button>
  </div>
  <div classNamelass="carousel-inner">
    <div className="carousel-item active">
        <img className="d-block w-100" src={questionData.quest} alt="First slide" />
    </div>
    <div className="carousel-item">
  
        <img className="d-block w-100" src={questionData.answer} alt="Second slide" />
    </div>
  </div>
  <button className="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev">
    <span className="carousel-control-prev-icon" aria-hidden="true"></span>
    <span className="visually-hidden">Previous</span>
  </button>
  <button className="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next">
    <span className="carousel-control-next-icon" aria-hidden="true"></span>
    <span className="visually-hidden">Next</span>
  </button>
</div>
</div>

  );
})}

</>
 )
}

Carousels: enter image description here

enter image description here



from Bootstrap 5 Carousel Navigation Buttons Mapping issue