Tuesday, 30 November 2021

Harness is attempting to use a fixture that has already been destroyed

I have a trivial unit test that passes but throws the error, "Harness is attempting to use a fixture that has already been destroyed" when I run ng test --watch=false. Is this happening because I'm placing my component in <ng-template>? Does anyone know how to resolve this error?

MenuComponent Spec

describe("MenuComponent", () => {
    let testHostFixture: ComponentFixture<TestHostComponent>;
    let myMenuHarness: MenuHarness;

    beforeEach(
        waitForAsync(() => {
            TestBed.configureTestingModule({
                declarations: [...],
                imports: [...],
                providers: [...],
            }).compileComponents();
        })
    );

    beforeEach(async () => {
        testHostFixture = TestBed.createComponent(TestHostComponent);
        myMenuHarness = await TestbedHarnessEnvironment.harnessForFixture(
            testHostFixture,
            MenuHarness
        );
        testHostFixture.detectChanges();
    });

    describe("simple test", () => {
        it("should pass", async () => {
            await myMenuHarness.openMenu();
            expect(true);
        });
    });

    @Component({
        selector: `my-test-host-component`,
        template: `<kendo-grid ...>
            <ng-template kendoGridColumnMenuTemplate let-service="service">
                <app-my-menu [service]="service"></app-my-menu>
            </ng-template>
            <kendo-grid-column ... ></kendo-grid-column>
        </kendo-grid>`,
    })
    class TestHostComponent {
        @ViewChild(MenuComponent)
        public menu?: MenuComponent;
    }
});

MenuHarness

public async openColumnMenu() {
    const element = await this.queryColumnMenuButton();
    element?.click();
}

Output

Error: Harness is attempting to use a fixture that has already been destroyed.
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:720:23
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3:1)
    at _next (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:25:1)     
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:32:1
    at new ZoneAwarePromise (http://localhost:9877/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1340:1)
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:21:1
    at TestbedHarnessEnvironment.forceStabilize (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:717:28)
    at UnitTestElement._stabilize (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:751:56)
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:449:20, 'Error: Harness is attempting to use a fixture that has already been destroyed.
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:720:23
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3:1)
    at _next (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:25:1)     
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:32:1
    at new ZoneAwarePromise (http://localhost:9877/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1340:1)
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:21:1
    at TestbedHarnessEnvironment.forceStabilize (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:717:28)
    at UnitTestElement._stabilize (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:751:56)
    at http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/cdk/fesm2020/testing/testbed.mjs:449:20'


from Harness is attempting to use a fixture that has already been destroyed

How do I cleanly test equality of objects in Mypy without producing errors?

I have the following function:

import pandas as pd

def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
    return left == right

I get the following error when I run it through Mypy:

error: Returning Any from function declared to return "bool"

I believe this is because Mypy doesn't know about pd.Timestamp so treats it as Any. (Using the Mypy reveal_type function shows that Mypy treats left and right as Any.)

What is the correct way to deal with this to stop Mypy complaining?



from How do I cleanly test equality of objects in Mypy without producing errors?

Find parameters from the Vasicek model

I am given the following bond: enter image description here and need to fit the Vasicek model to this data.

My attempt is the following:

# ...  imports
years = np.array([1, 2, 3, 4, 7, 10])
pric = np.array([0, .93, .85, .78, .65, .55, .42])


X = sympy.symbols("a b sigma")
a, b, s = X
rt1_rt = np.diff(pric)
ab_rt = np.array([a*(b-r) for r in pric[1:] ])
term = rt1_rt - ab_rt

def normpdf(x, mean, sd):
    var = sd**2
    denom = (2*sym.pi*var)**.5
    num = sym.E**(-(x-mean)**2/(2*var))
    return num/denom

pdfs = np.array([sym.log(normpdf(x, 0, s)) for x in term])
func = 0
for el in pdfs:
    func += el
func = func.factor()
lmd = sym.lambdify(X, func)
def target_fun(params):
    return lmd(*params)
result = scipy.optimize.least_squares(target_fun, [10, 10, 10])

I don't think that it outputs correct solution.



from Find parameters from the Vasicek model

set expiration time for WebView cache in android

in the documentation of WebView's cachingMode, in the LOAD_DEFAULT's description says:

If the navigation type doesn't impose any specific behavior, use cached resources when they are available and not expired, otherwise load resources from the network.

how can I set expiration time for web view's caching in android client without needing to modify server-side configuration?

also I have checked out following useful links: link1, link2 and link3.



from set expiration time for WebView cache in android

How promises inside for loop are working?

In my program source code I have the following function (Promise concurrency limitation function, similar to pLimit):

async function promiseMapLimit(
  array,
  poolLimit,
  iteratorFn,
) {
  const ret = [];
  const executing = [];
  for (const item of array) {
    const p = Promise.resolve().then(() => iteratorFn(item, array));
    ret.push(p);

    if (poolLimit <= array.length) {
      const e = p.then(() => executing.splice(executing.indexOf(e), 1));
      executing.push(e);
      if (executing.length >= poolLimit) {
        await Promise.race(executing);
      }
    }
  }

  return Promise.all(ret);
}

It works properly, so if I passed it an array of numbers [1..99] and try to multiply it by 2 it will give the correct output [0..198].

const testArray = Array.from(Array(100).keys());

promiseMapLimit(testArray, 20, async (value) => value * 2).then((result) =>
  console.log(result)
);

Code sample - js playground.

But I can't understand its logic, during the debugging I noticed, that it adds promises in chunks of 20 and only after that goes further: enter image description here

For example, this block of code:

  for (const item of array) {
    const p = Promise.resolve().then(() => iteratorFn(item, array));
    ret.push(p);

will iterate over 20 items of an array (why not all 100???)

same here:

if (poolLimit <= array.length) {
      const e = p.then(() => executing.splice(executing.indexOf(e), 1));
      executing.push(e);

it will add only 20 items to the executing array and only after that step inside if (executing.length >= poolLimit) code block.

I'd be very grateful for the explanation of how this function works.



from How promises inside for loop are working?

window.addEventListener testing with jasmine

I have a question after searching for allot of hours i didn't find a right direction.

service in AngularJS:

public webViewMessage = new Subject<any>();

constructor(private windowService: WindowService) {
 const wndw = this.windowService.getWindow();
 wndw?.chrome?.webview?.addEventListener('message', (event) => {
  this.webViewMessage.next(event.data);
 });
}

it is using WebView to receive data.

I'm trying to implement some jasmine tests for this but how do we hook into the addEventListener 'message' since its being used on window how do we raise this? and is there a way to do this some-how we need to Mock the window?



from window.addEventListener testing with jasmine

Activity quickly flashes white before switching to dark / night theme

I've implemented a Dark / night mode switch in my App I copied the implementation from the Google I/O App.

I've created a ThemedActivityDelegate that can be included in ViewModels. The actual changing to light or dark is done using the Extension function: updateForTheme.

But I see the SettingsActivity briefly flashing white before it turns black. While I put the updateForTheme method before setContentView.

MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)
    updateForTheme(viewModel.currentTheme)

    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            launch {
                viewModel.theme.collect { theme ->
                    updateForTheme(theme)
                }
            }
        }
    }
}

Extensions.kt:

fun AppCompatActivity.updateForTheme(theme: Theme) = when (theme) {
    Theme.DARK -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
    Theme.LIGHT -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
    Theme.SYSTEM -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
    Theme.BATTERY_SAVER -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
}

SettingsActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    updateForTheme(Theme.DARK)
    setContentView(R.layout.activity_settings)
}


from Activity quickly flashes white before switching to dark / night theme

Automatically Update Python source code (imports)

We are refactoring our code base.

Old:

from a.b import foo_method

New:

from b.d import bar_method

Both methods (foo_method() and bar_method()) are the same. It just changed the name an the package.

Since above example is just one example of many ways a method can be imported, I don't think a simple regular expression can help here.

How to refactor the importing of a module with a command line tool?

A lot of source code lines need to be changed, so that an IDE does not help here.



from Automatically Update Python source code (imports)

Using biometrigs data to login in andorid app

I need to develop an android app that has an MFA authentication. In this app the user to log in needs first to insert his username and password and after us some biometric data(fingerprint, face, or iris) to confirm his identity. Now i trough to use something like Cognito for the login but honestly, I can't really understand how i should implement biometrics in cogito. Please can someones give me some suggestions?



from Using biometrigs data to login in andorid app

webview shows app splashscreen background in select dropdown option

My application base is ionic capacitor. We have created the below setAuthWebViewSettings for opening the webview with url.

@SuppressLint("SetJavaScriptEnabled")
    private void setAuthWebViewSettings(WebView webView) {
      webView.setWebViewClient(new mAuthWebViewClient());

      WebSettings webSettings = mAuthWebView.getSettings();
      webSettings.setJavaScriptEnabled(true);
      webSettings.setSupportZoom(false);

      webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

      webSettings.setAppCacheEnabled(false);
      webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
      webSettings.setDatabaseEnabled(true);
      webSettings.setDomStorageEnabled(true);
      
      if (BuildConfig.DEBUG) {
        WebView.setWebContentsDebuggingEnabled(true);
      }
    }

Below is my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.Enterprise.xxx.mAuthWebView">

<WebView
    tools:context="com.Enterprise.xxx.mAuthWebView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
 </androidx.coordinatorlayout.widget.CoordinatorLayout>

Below are the issues that I am facing in my webview:

  1. Select options shows capacitor default splash screen in the background (screenshot attached below)
  2. Date field implemented using date-fns plugin crashes the application

enter image description here

I have tried all the answers in below link, still no luck.

Webview isn't opening select html components (dropdown) when initiating it with application context

Webview not working with HTML select element

Thanks!



from webview shows app splashscreen background in select dropdown option

Leaflet: Get scaled bounding box by zoom level

I am trying to make a projection on how the next bounds will look like. Here is a plunkr: https://plnkr.co/edit/sk6NRh51WZA2vpWP

This is how I got it working, but it is not very efficient:

const originalMapElement = document.getElementById('map');
const lMap: any = L.map(originalMapElement);


// working but very inefficient
// ----------------------------
function getScaledBounds(center, zoom) {
  const fakeDiv = document.createElement("div");
  fakeDiv.style.display = "block";
  fakeDiv.style.visibility = "hidden";
  fakeDiv.style.width = originalMapElement.offsetWidth + "px";
  fakeDiv.style.height = originalMapElement.offsetHeight + "px";
  document.body.appendChild(fakeDiv);
  const fakeMap = L.map(fakeDiv);
  fakeMap.setView(center, zoom, { animate: false });
  return fakeMap.getBounds();
}

My two other programmatic approaches are very close and yield almost but not quite the same results as the first function above:

function getScaledBounds(center, zoom) {
  const centerPoint = lMap.project(center, zoom);
  const viewHalf = lMap.getSize().divideBy(2);
  const projectedBox = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf));
  return L.latLngBounds(
    lMap.unproject(projectedBox.getBottomLeft(), zoom),
    lMap.unproject(projectedBox.getTopRight(), zoom),
  );
}
function getScaledBounds(center, zoom) {
  const zoomFactor = Math.pow(2, zoom) * 2;
  const dw = originalMapElement.offsetWidth / zoomFactor;
  const dh = originalMapElement.offsetHeight / zoomFactor;
  const centerPoint = lMap.project(center, zoom);
  return L.latLngBounds(
    lMap.unproject(new Point(centerPoint.x - dw, centerPoint.y + dh, false), zoom),
    lMap.unproject(new Point(centerPoint.x + dw, centerPoint.y - dh, false), zoom),
  );
}

Does anybody have a solution for this problem? Or can someone explain why all of these yield different results, while they should return the same value in my understanding?



from Leaflet: Get scaled bounding box by zoom level

How to catch ERR_CERT_AUTHORITY_INVALID in javascript

The Web Application I am developing needs to fetch data from a number of different IOTs within the local network, e.g.,

const response = await fetch("https://192.168.0.245/api/auto/login", options);

Since it is an https connection, and each IOT carries a self-signed SSL cert, therefore, the fetch() above will throw an error "TypeError: Failed to fetch" (since the cert has not yet been accepted), and the application will show the following in the browser's console

OPTIONS https://192.168.0.245/api/auto/login net::ERR_CERT_AUTHORITY_INVALID

What I need is to be able to catch this error in javascript. Specifically I need to be able to catch different errors like ERR_CERT_AUTHORITY_INVALID, ERR_SSL_PROTOCOL_ERROR or ERR_CONNECITON_REFUSED... etc. so I can show different error messages accordingly.

Unfortunately the fetch() function always throw the same "TypeError: Failed to fetch" exception under all these three different errors above.

Is there anyway I can catch this specific ERR_CERT_AUTHORITY_INVALID exception?

Thank you.



from How to catch ERR_CERT_AUTHORITY_INVALID in javascript

What's the difference between Channel pypi and

How to merge multiple MODIS swaths into one plot in python?

I want to mosaic/merge multiple swaths of the MODIS dataset (MOD06_L2) using python. I used the example (http://hdfeos.org/zoo/MORE/LAADS/MOD/MOD04_L2_merge.py) to read multiple files and merge. But I am getting an error while doing so, how to correct this error?

I would like to know is there any better way than this, to merge/mosaic MODIS HDF files into one?

import os
import glob                                                                 
import matplotlib as mpl
import matplotlib.pyplot as plt
# import cartopy.crs as ccrs
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

# The first file in 3 swath files.
FILE_NAME = 'MOD06_L2.A2017126.0655.061.2019226193408.hdf'
GEO_FILE_NAME ='MOD06_L2.A2017126.0655.061.2019226193408.hdf'
DATAFIELD_NAME = 'Brightness_Temperature'

from pyhdf.SD import SD, SDC

i = 0

for file in list(glob.glob('MOD06*.hdf')):
    reader = open(file)
    hdf = SD(file, SDC.READ)
    # Read dataset.
    data2D = hdf.select(DATAFIELD_NAME)
    data = data2D[:,:].astype(np.double)
    hdf_geo = SD(GEO_FILE_NAME, SDC.READ)
    # Read geolocation dataset.
    lat = hdf_geo.select('Latitude')
    latitude = lat[:,:]
    lon = hdf_geo.select('Longitude')
    longitude = lon[:,:]
    # Retrieve attributes.
    attrs = data2D.attributes(full=1)
    lna=attrs["long_name"]
    long_name = lna[0]
    aoa=attrs["add_offset"]
    add_offset = aoa[0]
    fva=attrs["_FillValue"]
    _FillValue = fva[0]
    sfa=attrs["scale_factor"]
    scale_factor = sfa[0]
    vra=attrs["valid_range"]
    valid_min = vra[0][0]
    valid_max = vra[0][1]        
    ua=attrs["units"]
    units = ua[0]
    invalid = np.logical_or(data > valid_max,data < valid_min)
    invalid = np.logical_or(invalid, data == _FillValue)
    data[invalid] = np.nan
    data = (data - add_offset) * scale_factor 
    datam = np.ma.masked_array(data, np.isnan(data))
    if i == 0 :
        data_m = datam
        latitude_m = latitude
        longitude_m = longitude
    else:
        data_m = np.vstack([data_m, datam])
        latitude_m = np.vstack([latitude_m, latitude])
        longitude_m = np.vstack([longitude_m, longitude])
    i = i + 1
m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180)
m.drawcoastlines(linewidth=0.5)
m.drawparallels(np.arange(-90, 91, 45))
m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True])
sc = m.scatter(longitude_m, latitude_m, c=data_m, s=0.1, cmap=plt.cm.jet,
               edgecolors=None, linewidth=0)
cb = m.colorbar()
cb.set_label(units)


# Put title using the first file.
basename = os.path.basename(FILE_NAME)
plt.title('{0}\n{1}'.format(basename, DATAFIELD_NAME))
fig = plt.gcf()

# Save image.
pngfile = "{0}.py.png".format(basename)
fig.savefig(pngfile)

It showing an error

ValueError: 'c' argument has 4604040 elements, which is inconsistent with 'x' and 'y' with size 657720.



from How to merge multiple MODIS swaths into one plot in python?

Add drag resistance to MotionEvent when dragging upwards

I am using MotionEvent.ACTION_MOVE to drag a view up or down on the y axis. The dragging works perfectly, however, I would like to add some 'resistance' when the drag is UP.

Here is my progress thus far.

MotionEvent.ACTION_DOWN -> {

    downYValue = event.y

    rightDY = viewToDrag!!.y - event.rawY
}
MotionEvent.ACTION_MOVE -> {

    val displacement = ((event.rawY) + rightDY)

    println("DISPLACEMENT $displacement")

    val currentY = event.y
    if (downYValue > currentY) {
        println("up")
    }

    viewToDrag!!.animate().y(displacement).setDuration(0).start()
}

When the view is dragged either up or down, the drag speed is the same as the finger speed.

I would like for the UPWARD drag to drag much slower than your finger speed. The closet I got was detecting "up".

How can I add resistance to the upward drag speed?



from Add drag resistance to MotionEvent when dragging upwards

Monday, 29 November 2021

Avoid irrelevant files while debugging in Chrome not working

While debugging in Chrome I want to avoid jumping through content scripts and libraries, so I enabled ignoring such files in preferences as per documentation but it doesn't seem to work.

I've tried patterns, "ignore content scripts" checkbox, right-click on the file, etc. Weirdly enough it shows all the files I didn't want to go through, with the message that the file is in the ignore list:

enter image description here

How to effectively ignore those?



from Avoid irrelevant files while debugging in Chrome not working

Way to stop any previously playing sounds (base64) in javascript before playing next sound

I have a javascript function that plays a particular sound from base64 plain text. What I am looking for I think is quite simple, but I am not at all familiar with js, as I'm actually using js in R as part of a shiny app. I am simply looking for a way that when this function is called, it will cancel any previously playing sound from the same or a similar function that might already be playing:

shinyjs.soundmaker = function() {
  var snd = new Audio("data:audio/wav;base64,blablablabla");
  snd.play();
}

Any help would be great!



from Way to stop any previously playing sounds (base64) in javascript before playing next sound

Android App Links manual verification not working

I have an Android app whose targetSdkVersion : 30 and App Links are working as expected on my device running Android OS 11, but they are broken (web links don't open the app by default) on another device running Android OS 12 because of these changes. I should go to OS level settings and manually add (see my app screenshot) the links to make them open the app.

My App

There are some apps, for example gmail, that has verified links by default (see gmail screenshot) and I was trying to achieve the same thing for my app as well by following Android docs here. However when I try to review the verification results, I don't see the expected output (see terminal screenshot). I have waited few minutes before reviewing the verification results but nothing yet. May be I'm missing something and I need some help. Thank you.

Gmail

Terminal



from Android App Links manual verification not working

How to completely remove mobile browser long-press vibration?

I'm trying to completely remove the vibration that occurs on a long press of an element in a mobile browser.

Specifically, I have an image that I'm adding my own long-press functionality to, but the subtle short-vibrate that happens by default is interfering and I need to disable it.

I've successfully stopped the usual context menu from appearing by overriding it as follows:

window.oncontextmenu = function (event) {
  event.preventDefault();
  event.stopPropagation();
  return false;
};

I've also added CSS to stop highlights and text selection etc - but I haven't been able to figure out what's causing the default vibrate after a few hundred ms.

Is there another lifecycle event that's popped on a long-press in a mobile browser, in or around oncontextmenu?

Full plunker Example here, long-press on the image from a mobile browser (I'm using chrome on Android) to see what I mean: https://plnkr.co/edit/y1KVPltTzEhQeMWGMa1F?p=preview



from How to completely remove mobile browser long-press vibration?

Using pd.xlsxwriter to conditionally format an entire row based on a single cell in that row

I have the following code:

import pandas as pd
from datetime import datetime
 writer = pd.ExcelWriter(
        f"~/{datetime.today().strftime('%Y.%m.%d')} - Report.xlsx",
        engine="xlsxwriter",
        date_format="dd/mm/yyyy",
        datetime_format="dd/mm/yyyy",
    )
worksheet = writer.sheets["Sheet1"]
comma_format = workbook.add_format(
        {"num_format": "#,###;[Red](#,###);-", "bold": True}
    )
worksheet.conditional_format(
        "$A$2:$J$1000",
        {
            "type": "cell",
            "criteria": "containing",
            "value": '"Total"',
            "format": comma_format,
        },
    )

I would like to, whenever a row contains the word "Total" in any cell in the row, format the entire cell with comma_format.

The above script, however, only formats the cell containing "Total", not the entire row.

Any ideas on how I can fix this?

Many thanks,

Mike



from Using pd.xlsxwriter to conditionally format an entire row based on a single cell in that row

Amazon S3 Error: The request signature we calculated does not match the signature you provided. Check your key and signing method

I am trying to get an object from my bucket but I always get the "signature does not match" error. I got my signature generation function from AWS sample code so I am sure that this works. I also tested the upload function and it works. I am only having trouble with the get object function. I spent a huge amount of hours verifying all scenarios/answers in this post but nothing worked. So here I am seeking your help.

Am I missing something in the headers? Here is a sample canonical request that gets created:

GET
/index.html
    
host:<bucketname>.s3.amazonaws.com
x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-amz-date:20211127T120453Z
    
host;x-amz-content-sha256;x-amz-date
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

EDIT1:

I tried the AWS sample code by compiling it using javac, then ran it, the get object function works fine. But when added into my Android project, it does not work. To make sure that I copy the sample code as is, I generated its jar file and included the resulting jar file in my project. Still, same issue. This is frustrating. Argg!

EDIT2: Minimal reproducible example

  1. Download the sample code from the link above
  2. Add the code into your Android project except for com.amazonaws.services.s3.sample.RunAllSamples class.
  3. Add this call in one of your activities: GetS3ObjectSample.getS3Object(<bucketName>, <regionName>, <awsAccessKey>, <awsSecretKey>);


from Amazon S3 Error: The request signature we calculated does not match the signature you provided. Check your key and signing method

How do I call inside the layout activity_main(sw320dp)?

I want to call gray (sw320dp) layout file

Layout:- activity_main(sw320dp)

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main(sw320dp));
 }
}

enter image description here



from How do I call inside the layout activity_main(sw320dp)?

Pagination in TypeORM/NestJS

I have to introduce pagination in findAll() method. I really dont know how to do it. I tried but it is giving so many errors. I used findAndCount() method given by typeorm for that, But I am not sure how it will work.

As of now below method returning all the record. I need to return at a time 10 records. Please suggest what modification I need to do.

async findAll(queryCertificateDto: QueryCertificateDto,page=1):  Promise<PaginatedResult> {
    
    let { country, sponser } = queryCertificateDto;

    const query = this.certificateRepository.createQueryBuilder('certificate');

    if (sponser) {
        sponser = sponser.toUpperCase();
        query.andWhere('Upper(certificate.sponser)=:sponser', { sponser });
    }

    if (country) {
        country = country.toUpperCase();
        query.andWhere('Upper(certificate.country)=:country', { country });
    }      
    const  certificates = query.getMany();     
    return certificates;
}

this is PaginatedResult file.

 export class PaginatedResult {
        data: any[];
        meta: {
          total: number;
          page: number;
          last_page: number;
        };
      }
  

I tried changing code of findAll() but where clause is giving error. I am not sure how to handle query.getMany() in pagination.

 const take = query.take || 10
        const skip = query.skip || 0
       
      
        const [result, total] = await this.certificateRepository.findAndCount(
            {
                where: query.getMany(),   //this is giving error
                take:take,
                skip:skip
            }
        );
        return result;

I need to introduce pagination in this method. Any help will be really helpful.



from Pagination in TypeORM/NestJS

Getting synsets of custom hungarian wordnet dictionary with nltk

I am very new to NLP and I might be doing something wrong.

I would like to work with a hungarian text where I can get the synset/hyponym/hypernym of some selected words. I am working in python.

As Open Multilingual Wordnet does not have hungarian wordnet dictionary I have downloaded one from this github site: https://github.com/mmihaltz/huwn

As it is an xml file I have converted it to .tab with a converter available in other language folders.

So at this stage I created the '\nltk_data\corpora\omw\hun' library and placed my new wn-data-hun.tab inside this directory.

But unfortunately it is not working

After importing nltk and wordnet the wn.langs() command shows the 'hun' also as available language.

However trying: wn.lemmas('cane', lang='hun') command is showing an empty list. Trying with other languages (built in languages in open multilanguage wordnet), it works.

Could you pleaes help me or point me in the right direction in order to make it work?

Thank you in advance!



from Getting synsets of custom hungarian wordnet dictionary with nltk

positive and negative fraction to binary conversion

I am trying to convert positive and negative fractions to binary, I found the following approach online (https://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/) to convert positive fractions to binary and tried to extend it to support the negative fractions. I am trying to do the 2's complement on the fractional part. Any help is much appreciated.

# decimal to binary number

# Function to convert decimal to binary
# upto k-precision after decimal point
def decimalToBinary(num, k_prec) :

    binary = ""

    # Fetch the integral part of
    # decimal number
    Integral = int(num)

    # Fetch the fractional part
    # decimal number
    fractional = num - Integral

    # Conversion of integral part to
    # binary equivalent
    while (Integral) :
        
        rem = Integral % 2

        # Append 0 in binary
        binary += str(rem);

        Integral //= 2
    
    # Reverse string to get original
    # binary equivalent
    binary = binary[ : : -1]

    # Append point before conversion
    # of fractional part
    binary += '.'

    # Conversion of fractional part
    # to binary equivalent
    while (k_prec) :
        
        # Find next bit in fraction
        fractional *= 2
        fract_bit = int(fractional)

        if (fract_bit == 1) :
            
            fractional -= fract_bit
            binary += '1'
            
        else :
            binary += '0'

        k_prec -= 1

    if (num < 0): // if negative numbers do the two's complement
        binary = ~binary // struck here.
    else:
        binary = binary
    return binary

# Driver code
if __name__ == "__main__" :
    num_list=[1, 0, 0.924, -0.383]
    for i in num_list:
        print(i, decimalToBinary(i,8))
macky@test:~/test$ python frac_to_binary.py 
(1, '1.00000000')
(0, '.00000000')
(0.924, '.11101100')
Traceback (most recent call last):
  File "frac_to_binary.py", line 63, in <module>
    print(i, decimalToBinary(i,8))
  File "frac_to_binary.py", line 54, in decimalToBinary
    binary = ~binary
TypeError: bad operand type for unary ~: 'str'



from positive and negative fraction to binary conversion

axios : How exactly to preserve session after successful authorization and send with subsequent request

In this test case am sending an axios post request with userId and password to ExpressJS server running with passportjs local. Server respond with status code 200, and send appropriate header with set-cookie.

I need subsequent request to be treated as authorized request, for that tried following options, but none seems to be working. It getting rejected with status code 401.

First call with userid and password, responded with status 200

const userDoc = {
    userId: 'test-user-1',
    userName: 'Test User 1',
    emailId: 'test.user.1@abc.xom',
    password: 'test-password'
} ;

let resp

resp = await axios({method : 'post', url : 'http://localhost:4040/auth/local', data : {userId: userDoc.userId, password: userDoc.password },withCredentials: true   })

following options are used to send next request

  1. send cookies received as part of 1st request

     const headers = { headers : {Cookie: resp.headers['set-cookie'][0] } };
    
  2. send header as it is received as part of 1st request

     const headers = { headers : resp.headers};
    
  3. send withCredentials: true along with above headers.

Second call is made with either of above option

resp = await axios({method : 'post', url : 'http://localhost:4040/v1/master/account', data : accountDoc , headers, withCredentials: true})
  1. used httpAgent, keepAlive with axios instance
const axios = require('axios')
const http = require("http")
const httpAgent = new http.Agent({keepAlive : true , timeout :1000})
const instance = axios.create({httpAgent})

const resp1 = await instance({method : 'post', url : 'http://localhost:4040/auth/local', data : {userId: userDoc.userId, password: userDoc.password, } , withCredentials: true })

const resp2 = await instance({method : 'post', url : 'http://localhost:4040/v1/master/account', data : accountDoc , withCredentials: true })

Rejected with status code 401

--   Error: Request failed with status code 401
at createError (/home/Projects/FinAccounts2003/node_modules/axios/lib/core/createError.js:16:15)
at settle (/home/Projects/FinAccounts2003/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/home/Projects/FinAccounts2003/node_modules/axios/lib/adapters/http.js:269:11)
at IncomingMessage.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)

Server code is standard passport-js local code, which working well with browser.

It may be duplicate of some of the questions, solutions given are 1) withCredentials: true, already tried above 2) Authorization: Bearer ${token} - not applicable in this case, in passport js, cookie is directly set, and not getting token.



from axios : How exactly to preserve session after successful authorization and send with subsequent request

Android Paging 3 library PagingSource invalidation, causes the list to jump due to wrong refresh key (not using room)

Since I'm currently working on a Project with custom database (not Room), I'm testing whether we could use the Paging 3 library in the Project. However, I run into the issue, that if you make changes to the data and therefore invalidate the paging source, the recreation of the list is buggy and jumps to a different location. This is happening because the Refresh Key calculation seems to be wrong, which is most likely caused by the fact that the initial load loads three pages worth of data, but puts it into one page.

The default Paging Source looks like this:

    override fun getRefreshKey(state: PagingState<Int, CustomData>): Int? {
        // Try to find the page key of the closest page to anchorPosition, from
        // either the prevKey or the nextKey, but you need to handle nullability
        // here:
        //  * prevKey == null -> anchorPage is the first page.
        //  * nextKey == null -> anchorPage is the last page.
        //  * both prevKey and nextKey null -> anchorPage is the initial page, so
        //    just return null.
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CustomData> {
    var pagePosition = params.key ?: STARTING_PAGE_INDEX
    var loadSize = params.loadSize
    return try {
        val dataResult = dataRepository.getPagedData(
            pagePosition = pagePosition,
            loadSize = loadSize,
            pageSize = pageSize
        )
        val nextKey = if (dataResult.isEmpty() || dataResult.size < pageSize) {
            null
        } else {
            pagePosition + (loadSize / pageSize)
        }
        Log.i(
            "RoomFreePagingSource",
            "page $pagePosition with size $loadSize publish ${dataResult.size} routes"
        )
        return LoadResult.Page(
            data = dataResult,
            prevKey = if (pagePosition == STARTING_PAGE_INDEX) null else pagePosition - 1,
            nextKey = nextKey
        )

    } catch (exception: Exception) {
        LoadResult.Error(exception)
    }
}

The dataRepository.getPagedData() function simply accesses a in memory list and returns a subsection of the list, simulating the paged data. For completeness here is the implementation of this function:

fun getPagedData(pageSize:Int, loadSize:Int, pagePosition: Int): List<CustomData>{
    val startIndex = pagePosition * pageSize
    val endIndexExl =startIndex + loadSize
    return data.safeSubList(startIndex,endIndexExl).map { it.copy() }
}

private fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int) : List<T>{
    // only returns list with valid range, to not throw exception
    if(fromIndex>= this.size)
        return emptyList()
    val endIndex = if(toIndex> this.size) this.size else toIndex
    return subList(fromIndex,endIndex)
}

The main Problem I currently face is, that the getRefreshKey function doesn't return a correct refresh page key, which results in the wrong page being refreshed and the list jumping to the loaded page.

  • For example if you have 10 items per page.
  • The first page 0 contains 30 items
  • The next page would be 3 and contains 10 items.
  • If you don't scroll (only see the first 7 items) and invalidate then the anchorPosition will be 7 and the refresh key will be 2. (anchorPage.prevKey = null => anchorPage.nextKey = 3 => 3-1 is 2) However, at this point we would like to load page 0 not page 2.

Knowing the cause of the issue I tried to adapt the default implementation to resolve it and came up with a lot of different versions. The one below currently works best, but still causes the jumping from time to time. And also sometimes a part of the list flickers, which is probably caused when not enough items are fetched to fill the view port.

override fun getRefreshKey(state: PagingState<Int, CustomData>): Int? {
    return state.anchorPosition?.let { anchorPosition ->
        val closestPage = state.closestPageToPosition(anchorPosition)?.prevKey
            ?: STARTING_PAGE_INDEX
        val refKey = if(anchorPosition>(closestPage)*pageSize + pageSize)
            closestPage+1
        else
            closestPage

        Log.i(
            "RoomFreePagingSource",
            "getRefreshKey $refKey from anchorPosition $anchorPosition closestPage $closestPage"
        )
        refKey
    }
}

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CustomData> {
    var pagePosition = params.key ?: STARTING_PAGE_INDEX
    var loadSize = pageSize
    return try {
        when (params) {
            is LoadParams.Refresh -> {
                if (pagePosition > STARTING_PAGE_INDEX) {
                    loadSize *= 3
                } else if (pagePosition == STARTING_PAGE_INDEX) {
                    loadSize *= 2
                }
            }
            else -> {}
        }
        val dataResult = dataRepository.getPagedData(
            pagePosition = pagePosition,
            loadSize = loadSize,
            pageSize = pageSize
        )
        val nextKey = if (dataResult.isEmpty() || dataResult.size < pageSize) {
            null
        } else {
            pagePosition + (loadSize / pageSize)
        }
        Log.i(
            "RouteRepository",
            "page $pagePosition with size $loadSize publish ${dataResult.size} routes"
        )
        return LoadResult.Page(
            data = dataResult,
            prevKey = if (pagePosition == STARTING_PAGE_INDEX) null else pagePosition - 1,
            nextKey = nextKey
        )

    } catch (exception: Exception) {
        LoadResult.Error(exception)
    }
}

In theory I found that the best solution would be to just calculate the refresh PageKey like this anchorPosition/pageSize then load this page, the one before and after it. Hower, calculating the refresh key like this does not work since the anchorPosition isn't the actual position of the item in the list. After some invalidations, the anchor could be 5 even if you are currently looking at item 140 in the list.

So to sum it up:

How can I calculate the correct refresh page after invalidation when I don't use Room, but another data source, like in this sample case a in memory list which I access through getPagedData?



from Android Paging 3 library PagingSource invalidation, causes the list to jump due to wrong refresh key (not using room)

How can I delete just one parameter with urlsearchparams.delete()?

So I have an app which displays movies with Movie API and multiple buttons, which show movies of particular genre. So when I click on multiple of such buttons, they all add together in the query, like in the example below:

https://api.themoviedb.org/3/discover/movie?api_key={api_key}&sort_by=popularity.desc&with_genres=99&with_genres=80&with_genres=35

So when I click on one of those genre buttons second time, I want to remove particular genre from url. I tried to do it like this:

function genreChoose(e){
        let genres = {
            Action: 28,
            Adventure: 12,
            Animation: 16,
            Comedy: 35,
            Crime: 80,
            Documentary: 99,
            Drama: 18,
            Family: 10751,
            Fantasy: 14,
            History: 36,
            Horror: 27,
            Music: 10402,
            Mystery: 9648,
            Romance: 10749,
            Science_Fiction: 878,
            TV_Movie: 10770,
            Thriller: 53,
            War: 10752,
            Western: 37
        };
        let url = new URL(lastUrl);
        if(!e.target.classList.contains('active')){
            url.searchParams.append('with_genres', genres[e.target.innerText]);
        }else if(e.target.classList.contains('active')){
            e.target.classList.remove('active');
            url.searchParams.delete('with_genres', genres[e.target.innerText]);
            
        }
        
        fetchURL(url);
        console.log(url);
    }

So if a button is active and is clicked, it should remove 'active' class and also remove particular genre from the url, but instead, it becomes like this:

https://api.themoviedb.org/3/discover/movie?api_key={api_key}&sort_by=popularity.desc

So instead it just removes all 'with_genres' params, but I'm trying to find a way to delete just one of 'with_genres' parameter.

Edit: so I used T.J. Crowder's example, I added a function to remove value:

let url = new URL(lastUrl);
        params = new URLSearchParams(url.search.slice(1));
        console.log(params.toString());
        if(e.target.classList.contains('active')){
            removeValue(params, 'with_genres', genres[e.target.innerText]);
        }else if(!e.target.classList.contains('active')){
            url.searchParams.append('with_genres', genres[e.target.innerText]);
        }
        fetchURL(url);
    }

But it doesn't really remove anything, maybe I should implement it with promises?

Edit 2: So I added a snippet of code, it doesn't display movie blocks sadly, but you can see how url changes when I click genre buttons. So when I click on it, it adds a genre, but when I unclick it, it doesn't remove anything, tho it shows console.log that genre is removed, so I guess it has to do something with removeValue function, but I can't figure out what.

window.onload = function() {
  const API_KEY = 'api_key=73b31f15b44a93f52789c751c34a5d7d';
  const BASE_URL = 'https://api.themoviedb.org/3';
  const API_URL = '/discover/movie?' + API_KEY + '&sort_by=popularity.desc';
  const url = BASE_URL + API_URL;
  const movie_container = document.getElementById('movie_container');
  const prev = document.getElementById('prev');
  const next = document.getElementById('next');
  const ulTag = document.querySelectorAll('.numb');
  const liTag = document.querySelector('li');
  const genres = document.querySelectorAll('.genre');

  var lastUrl = '';
  fetchURL(url);
  
  trendingMovies = movies =>{
        movie_container.innerHTML = '';

        movies.forEach(movie => {
            img = IMG_URL + movie.poster_path;
            title = movie.title;

            const movieEl = document.createElement('div');
            movieEl.classList.add('movie');

            movieEl.innerHTML = 
            `<img src="${img}">
            <span class="movie_title">${title}</span>
                `
            movie_container.appendChild(movieEl);

        });
    }


  function fetchURL(url) {
    lastUrl = url;
    console.log(url);
    fetch(url)
      .then(res => res.json())
      .then(data => {
        trendingMovies(data.results);
        
      })
  }

  
  const removeValue = (params, key, valueToRemove) => {
        const values = params.getAll(key);
        if (values.length) {
            params.delete(key);
            console.log('param deleted', params.toString());
            for (const value of values) {
                if (value !== valueToRemove) {
                    params.append(key, value);
                    console.log('params appended:', params.toString());
                }
            }
        }
        return params; 
    };

    genres.forEach(el => el.addEventListener('click', (e) => {
            genreChoose(e);
            if(e.target.classList.contains('active')){
                e.target.classList.remove('active');
            }else if(!e.target.classList.contains('active')){
                e.target.classList.toggle('active');
            }
            
    }))


    function genreChoose(e){
        let genres = {
            Action: 28,
            Adventure: 12,
            Animation: 16,
            Comedy: 35,
            Crime: 80,
            Documentary: 99,
            Drama: 18,
            Family: 10751,
            Fantasy: 14,
            History: 36,
            Horror: 27,
            Music: 10402,
            Mystery: 9648,
            Romance: 10749,
            Science_Fiction: 878,
            TV_Movie: 10770,
            Thriller: 53,
            War: 10752,
            Western: 37
        };
        let url = new URL(lastUrl);
        params = new URLSearchParams(url.search.slice(1));
         if(e.currentTarget.classList.contains('active')){
            removeValue(params, 'with_genres', genres[e.target.innerText]); 
            console.log('remove genre');
        }else if(!e.target.classList.contains('active')){
            url.searchParams.append('with_genres', genres[e.target.innerText]);
            console.log('add genre');
        } 
        
        fetchURL(url);
    }
}
body {
  margin: 0;
  padding: 0;
  --primary-color: #39445a;
  --secondary-color: rgb(34, 24, 24);
  background-color: var(--primary-color);
}

.app {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100vh;
  background-color: var(--secondary-color);
}

.app h1 {
  font-family: "Montserrat", sans-serif;
  text-transform: uppercase;
  text-align: center;
  color: #39445a;
  font-size: 2em;
  font-weight: 900;
}

.movie_container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.movie {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  width: 200px;
  padding: 5px;
  margin: 5px 15px;
  background-color: #282c34;
  border-radius: 10px;
  font-family: "Montserrat", sans-serif;
}

.movie .movie_title {
  font-family: "Montserrat", sans-serif;
  text-transform: uppercase;
  color: #fff;
  font-size: 1em;
  font-weight: 900;
  text-align: center;
}

.genres {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin: 10px;
}

.genres .genre {
  color: rgba(0, 0, 0, 0.87);
  display: flex;
  align-items: center;
  text-transform: capitalize;
  cursor: pointer;
  background-color: #fff;
  line-height: 3px;
  border-radius: 10px;
  padding: 5px 15px;
  font-size: 0.850rem;
  margin: 2px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.genres .genre.active {
  color: #fff;
  background-color: #3f51b5;
}
<div class="app">
  <h1>discover movies</h1>
  <div class="genres">
    <div class="genre">action</div>
    <div class="genre">adventure</div>
    <div class="genre">animation</div>
    <div class="genre">comedy</div>
    <div class="genre">crime</div>
    <div class="genre">documentary</div>
    <div class="genre">drama</div>
    <div class="genre">family</div>
    <div class="genre">fantasy</div>
    <div class="genre">history</div>
    <div class="genre">horror</div>
    <div class="genre">music</div>
    <div class="genre">mystery</div>
    <div class="genre">romance</div>
    <div class="genre">science fiction</div>
    <div class="genre">TV movie</div>
    <div class="genre">thriller</div>
    <div class="genre">war</div>
    <div class="genre">western</div>
  </div>
  <div class="movie_container" id="movie_container">
    <div class="movie">
      <img src="img/dark_knight.jpg">
      <span class="movie_title">the dark knight</span>
    </div>
  </div>


from How can I delete just one parameter with urlsearchparams.delete()?

Summernote copy image

I haven't found anything about this anywhere. How can I copy a selected image into the clipboard? I have created a custom js that adds a button to the popover of the image which works fine but I'm stuck here:

$.extend($.summernote.plugins, {
        'imageCopy': function (context) {
            var self = this;
            var ui = $.summernote.ui,
            $editable = context.layoutInfo.editable,
            options = context.options,
            $editor = context.layoutInfo.editor,
            lang = options.langInfo,
            $note = context.layoutInfo.note;

            context.memo('button.imageCopy', function () {
                var button = ui.button({
                    contents: options.imageCopy.icon,
                    container: false,
                    tooltip: lang.imageCopy.tooltip,
                    click: function () {
                        var img = $($editable.data('target'));
                        console.log('copy image=' + img);
                    }
                });
                return button.render();
            });
        }
    });

So I don't really know how I can get the data from the currently selected image and put it into the clipboard.



from Summernote copy image

social authentication provider is not returning the user email

It is an architectural question rather than a technical one. Our web and mobile application are totally dependant upon social authentication and we are using social authentication providers such as Google, Facebook, and many others.

On successful user login, providers like Google and Facebook return the user's data with email and a unique id. We are storing that data in the database something like this.

+----+--------------------------------------------------------------+---------------+----------+
| id | socialId                                                     | email         | provider |
+----+--------------------------------------------------------------+---------------+----------+
| 1  | $2a$12$Qx.FVkgYkXqJGF4PyJ1kb.JlSDe9bV6TJFodpTx2eBsYxvqn6Gywa | a@example.com | Facebook |
+----+--------------------------------------------------------------+---------------+----------+
| 2  | $2a$12$N2fCTRxymPlcaID5oP617OJTXkrvKAHZ/taFJ.lePZddfW3E6U.Fe | b@example.com | Google   |
+----+--------------------------------------------------------------+---------------+----------+

All database fields are required and not nullable.

Note: We are also storing socialIds in a hash format for security reasons and storing email helps us to know whether the user is a new user or an old user and help to prevent duplicate records.

But there is a problem, there are some providers who are not returning user emails.

So it has become a problem to identify whether the user is new or old, it also creates the risk of duplicate rows.

What is the best way to solve this problem? Is it good to store IDs in raw form in the database?



from social authentication provider is not returning the user email

Android App Retrofit Web Service Request Intercept and Modify Using Burp Suit Attack Fix

In my Android App we are using retrofit web service for communication to server. Some Hacker intercept request and modify it using some tool Burp Suit.

Please help me to let me know how I stop Intercept Attack.



from Android App Retrofit Web Service Request Intercept and Modify Using Burp Suit Attack Fix

Is it feasible to often switching between redis and rabbitmq in celery?

In production we facing some unknown errors occuring in celery when we use redis as message broker. So we thought of migrate to rabbitmq until the errors get fixed. So that in future if there is any error in any one of them we can quickly switch between them. Is this idea feasible and is it possible to implement?

Thanks in advance



from Is it feasible to often switching between redis and rabbitmq in celery?

Handle Back button with Angular [Chrome]

I am creating a project using angular, In my application I need to handle back button event. Below is the code which is working fine apart from one scenario

Code:

this.location.subscribe(event => {
 //logout
});
history.pushState({}, '');

This code only works when user is perform some activity, if user just landed on page and click back button then this event is not captured. I tried all the ways but not works.



from Handle Back button with Angular [Chrome]

Max out CPU with parallel API calls to local endpoint using Python

Python 3.10

I've been tasked with proving I can max out the CPU of my Mac laptop (10 cores) by calling a local API endpoint which runs in a Java VM, as well as "measure and record throughput," all using Python. For parallelization, I have researched and decided to go with asyncio per this answer: https://stackoverflow.com/a/59385935/7191927

I plan to use htop to show all cores maxed out so that part I think I have covered. Where I'm getting tripped up is what I actually need to do in the code to max out the CPU.

This is what I have so far. This code is to call two local API endpoints (which each just process blocks of text and extract relevant terms):

import asyncio
from api import API, DocumentParameters, EndException


def background(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)
    return wrapped

@background
def get_word_results(data):
    api = API(url='http://localhost:8181/rest/words')     
    words_data = data        
    params = DocumentParameters()
    params["content"] = words_data 
    try:
        result = api.words(params)
    except EndException as exception:
        print(exception)
    return result

@background
def get_language_results(data):
    api = API(url='http://localhost:8181/rest/languages')     
    language_data = data        
    params = DocumentParameters()
    params["content"] = language_text_data 
    try:
        result = api.language(params)
    except EndException as exception:
        print(exception)
    return result

if __name__ == '__main__':
    filepath = "/Users/me/stuff.txt"
    with open(filepath, 'r') as file: 
        data = file.read()
    get_word_results(data)
    get_language_results(data)
    print('Done.')

This is where my Python knowledge/experience begins to wane.

So what would be the most efficient way to:

  1. Run this code continuously and at increasing thread counts in attempt to max out the CPU.
  2. Measure and record throughput, as per the requirement.

EDIT 1 - Bounty started. I need a solid solution for this - which maxes out CPU and gives some kind of output that shows this, as well as how many calls are being made and causing the max. Based on what Mr Miyagi says in the comments, it sound like multiprocessing is what I want, either instead of or in tandem with asyncio The winner will achieve with the lowest amount of lines of code.



from Max out CPU with parallel API calls to local endpoint using Python

Android App Links - exclude specific sub-directory

I am using Android App Links to take users to a specific screens directly in my app. I am following same approach as Rakuten, meaning the last path segment(lps) of the url is a valid domain, which lands user to a specific brand screen on my app.

https://www.rakuten.com/nike.com   (lps = nike.com)
https://www.rakuten.com/adidas.com   (lps = addidas.com)
https://www.rakuten.com/samsung.com   (lps = samsung.com)

Android Manifest Code

<data android:host="www.rakuten.com" android:scheme="https" android:pathPattern=".*..*"/>

The pathPattern = ".*..*" allows any domain in the url to open inside my app. All of the below links open Nike brand screen in my app.

https://www.rakuten.com/dir1/nike.com
https://www.rakuten.com/dir1/dir2/nike.com
https://www.rakuten.com/dir1/dir2/dir3/nike.com
https://www.rakuten.com/dir1/dir2/dir3/dir4/nike.com

CASE TO HANDLE:

if any url contains /browser/ (meaning subdirectory name = browser), I want to open that url in the browser and not inside my app.

https://www.rakuten.com/browser/nike.com (should open in browser and not in app)

Is there any possibility to do that?



from Android App Links - exclude specific sub-directory

Sunday, 28 November 2021

Globle module without import not working nestjs

I am trying to implement a global module in nest.js

I have created a service like below

export interface ConfigData {
    DB_NAME:        string;
}

@Injectable()
export class ConfigManager {
    private static _instance?: ConfigManager;
    public static configData:ConfigData | null;
    private constructor() {
        console.log(ConfigManager)
        if (ConfigManager._instance)
            ConfigManager._instance = this;
        else{
            ConfigManager._instance = new ConfigManager()
            ConfigManager.configData = <ConfigData|null><unknown>ConfigManager.fetchSecretData()
        }
    }
    private static async fetchSecretData():Promise<ConfigData|null>{
        // some data from db
    }
    // static get instance() {
    //     return ConfigManager._instance ?? (ConfigManager._instance = new ConfigManager());
    //     //return ConfigManager._instance ?? (ConfigManager._instance = ConfigManager.fetchSecretData()) //new ConfigManager());
    // }
    
}

configuration.module.ts

@Global()
@Module({
    providers: [ConfigManager],
    exports: [ConfigManager],
})
export class ConfigurationModule {}

and in app.module.ts added ConfigurationModule in imports.

Also adding private constructor on service unable it to add in module.ts file.

I am expecting that I should be able to configData anywhere without importing the ConfigManager. but it's not working...

ConfigManager is not available without import.



from Globle module without import not working nestjs

Trouble forming an autocompletion url using requests

When I visit this site and write any address, as in Taekwondo Mattighofen, Am Steinbach, Lochen am See, Austria in inputbox under ENTER A LOCATION, I can see this autocompletion url in dev tools which has parameters like this. The full form of that autocompleted url looks like this, which produces the value of latitude and longitude.

I've found success using the value of latitude and longitude taken manually from that above mentioned api within my following script to produce the end result, though.

import requests
from bs4 import BeautifulSoup

link = 'https://www.ktm.com/content/websites/ktm-com/middle-east/ae/en/dealer-search/jcr:content/root/responsivegrid_1_col/dealersearch.dealers.json'
params = {
    'latitude': '48.0075483',
    'longitude': '13.1848824',
    'country': '',
    'qualification': '',
    'distance': '50'
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
    res = s.get(link,params=params)
    print(res.json())

How can I produce such autocompletion url based on any address like Nachhilfe Mattighofen, Rosengasse, Mattighofen, Austria using a python script built upon requests?



from Trouble forming an autocompletion url using requests

Unity lighting goes bad when loading a scene via SceneManager

I'm trying to create a game with unity where you have to solve levels but can only see the shadows. Now if I try to play my scenes by doubleclicking they look like they should and have good lightning and shadows. But if I select them by the levelselector and load then with the scene manager The levels look dark and the lightning get bad. My script to load scene is easy: I just load the scene by the scene name e.g. with SceneManager.LoadScene(Level1); But every time I do that the lighting settings get bad.

My Quality settings: My Quality Settings

My Graphic settings Graphic settings

Scene after loading by doubbleclick: Scene after loading by doubbleclick

Same Scene after loading with SceneManager Same Scene after loading with SceneManager



from Unity lighting goes bad when loading a scene via SceneManager

using bootstrap 3.37 header dropdown menu and tranlsating jquery to knockoutJS

I was looking at this article to apply header menu with dropdowns in my mvc5 knockoutjs solution.

https://jdmdigital.co/news/codex/bootstrap-3-secondary-dropdown-menu/

The frontend it looks nice, and it is ok in my solution, however, I cant figure it out how to bind js section to work. Now when I click on my dropdown parent item, nothing happens, because the js code is not working.

here is my setup of the js (knockoutjs) file.

define(['durandal/system', 'plugins/router', 'durandal/services/logger', 'knockout', 'common', 'plugins/dialog', 'durandal/binder', 'fastclick'],
    function (system, router, logger, ko, common, dialog, binder, fs) {
        var shell = {
            activate: activate,
            router: router,
        };

        // Make Dropdown Submenus possible
        $('.dropdown-submenu a.dropdown-submenu-toggle').on("click", function (e) {
            $('.dropdown-submenu ul').removeAttr('style');
            $(this).next('ul').toggle();
            e.stopPropagation();
            e.preventDefault();
        });
        // Clear Submenu Dropdowns on hidden event
        $('#bs-navbar-collapse-1').on('hidden.bs.dropdown', function () {
            $('.navbar-nav .dropdown-submenu ul.dropdown-menu').removeAttr('style');
        });


        //...
        //...
        //OTHER INIT METHODS (not in the scope for this question)
        //#region Internal Methods
        function activate() {
            var result = registerRoutes();
            //setRouteGuard();
            if (window.cordova) {
                window.document.addEventListener("deviceready", function () {
                    shell.refreshUserData(true);
                    shell.changeLanguage();
                });
            } else {
                shell.refreshUserData(true);
                shell.changeLanguage();
            }
            shell.isLoading.subscribe(function (newValue) {
                //if something gone wrong
                if (newValue) {
                    setTimeout(function () {
                        //shell.isLoading(false);
                    }, 10000);
                }
            });

            if (router.activeInstruction().config.moduleId == "viewmodels/parentschedule") {
                if (shell.isAnonymousUser() == true) {
                    shell.isClient(false);
                    shell.isEmployee(false);
                }
                else {
                    shell.isClient(true);
                    shell.isEmployee(true);
                }
                //console.log("test");
            }

            return result;
        }


        function route(r, moduleId, name, visible, alwaysVisible, role, condition) {
            var self = this;
            self.route = r;
            self.moduleId = moduleId;
            self.title = name;
            self.visible = visible;
            self.nav = true;
            self.role = role;
            self.condition = condition;
            self.mouseover = ko.observable(false);
            self.onhover = function () {
                self.mouseover(!self.mouseover());
            };
            self.goToPage = function () {
                router.navigate(this.hash);
            };
            self.alwaysVisible = alwaysVisible;
            self.isTouched = ko.observable(false);
            self.setTouched = function () {
                self.isTouched(true);
                return true;
            }
            self.setUnTouched = function () {
                setTimeout(function () {
                    self.isTouched(false);
                }, 200);
                return true;
            }
            self.isActiveMenuItem = ko.computed(function () {
                return router.activeInstruction() &&
                    router.activeInstruction().fragment.indexOf(self.route) > -1
            });
            return self;
        }
        //#endregion
    });



from using bootstrap 3.37 header dropdown menu and tranlsating jquery to knockoutJS

Catch events from printer in Windows

The printer has a print queue where are documents prepared for printing that were sent to the printer from a few computers.

I'd like to write a code in Python that runs on the server and checks for printer events. Especially when the document has finished successfully printing, I'd like to catch this event and get information about the document

  • document name
  • number of pages
  • format (A4, A3, etc.)
  • was it colorful or black and white
  • time of finish printing

Could you help me bounce off?

I already studied this question but I can't figure out what I need from it.



from Catch events from printer in Windows

How do I change the theme in an AnyChart React tag cloud?

I am creating a tag cloud word cloud using the React library from AnyChart. How do I change the color theme of it? The answer found here doesn't seem to work:

import React from "react";
import ReactDOM from "react-dom";
import AnyChart from "anychart-react";
import anychart from "anychart";
anychart.theme("coffee");

var data = [
  { x: "learning", value: 80 },
  { x: "includes", value: 56 },
  { x: "lists", value: 44 },
  { x: "meaning", value: 40 },
  { x: "useful", value: 36 },
  { x: "different", value: 32 },
  { x: "grammar", value: 28 },
  { x: "teaching", value: 24 },
  { x: "example", value: 20 },
  { x: "thing", value: 12 }
];

// create a chart and set the data
var chart = anychart.tagCloud(data);
//chart.theme = anychart.palettes.coffee;

ReactDOM.render(
  <AnyChart width={800} height={600} instance={chart} title="Column chart" />,
  document.getElementById("root")
);

Full demo is here



from How do I change the theme in an AnyChart React tag cloud?

AngularFire getIdToken(true) not refreshing token

I have an angularfire authentication service which works absolutely fine - except it wont refresh the token.

My refresh code:

firebase.auth().currentUser.getIdToken(true).then((token: string) => {
    const newUser = { token: token }; // new user details in brief
    this.user.next(newUser);
});

calls the firebase service just fine and gives a response, but it only returns the current token and doesn't refresh the token - so it still logs out of the app after 1 hour.

I have read a multitude of issues regarding getIdToken but none which specifically address a token not refreshing.

I made a stackblitz: https://stackblitz.com/edit/angular-ivy-uvcdz7?file=src/app/app.component.ts so you can see the code in full (though it doesn't work for some reason, but also because I cant work out how to connect the project to firebase via SB)

edit

To help there are some other odd behaviours I dont expect, for example in my ngOnInit I have...

this.fAuth.onAuthStateChanged((state) => {
    console.log(state);
})

which does nothing when I log in or out - no message to say the state has changed. None of these functions which I expect to trigger when things change in the authentication seem to do anything.

edit 2

As added info, before I added the bounty I did a full and painful update of Angular and AngularFire, so now Angular is v13 and AngularFire is 7.2.0 to see if this would make any difference, but it did not, the getIdToken still provides no refresh of the token.



from AngularFire getIdToken(true) not refreshing token

How do I prefix my log messages with the current date and time?

I'm using Python 3.9 and Django 3.2. I have logging configured in my settings.py file

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}

When I do logging in one of my classes, I do it like so

import logging
...
class TransactionService:
    def __init__(self):
        self._logger = logging.getLogger(__name__)


    def my_method(self, arg1, arg2):
            ...
        self._logger.info("Doing some logging here.")
      

  

How do I configure my logger such that when the message is printed out, it is prefixed by the current date and time?



from How do I prefix my log messages with the current date and time?

Apex chart Charts order in Mixed chart

I'm currently using the library ApexChart and more particulary Vue apex chart combined with nuxt.

I'm building a dashboard and I'm trying to build a mixed chart composed of :

  • An area chart
  • A Bar chart
  • A line chart

The three charts are displaying in the following order (from back to front) : Area - Bar - Line

I'd like to change the order to get the bar chart to the back but i don't see how to do it.

What i've tried

I've tried to change the order of the series to put the bar chart last

series() {
  return [
    {
      name: 'My Line chart',
      type: 'line',
      data: this.capacityCalls
    },
    {
      name: 'My Area Chart',
      type: 'area',
      data: this.callsRealProd
    },
    {
      name: 'My Bar Chart',
      type: 'bar',
      data: this.callsToMake
    },
  ]
},


from Apex chart Charts order in Mixed chart

Android Instrumented tests with KodeIn

We have an Android app that is using compose for the view layer and we are using Kodein for all of our dependency injections.

I have a BaseApplication class which is DIAware:

class BaseApplication : Application(), DIAware {
    override val di: DI = DI.lazy {
        import(modules) // modules defined in respective packages
    }
}

I also have a MainActivity and a nav graph to manage navigation between the various composables.

Problem: How can I properly override these modules in my instrumented tests for MainActivity?

@RunWith(AndroidJUnit4::class)
class MainActivityTest {
    @get:Rule
    val composeTestRule = createAndroidComposeRule<MainActivity>()

    val moduleOverrides = DI.Module(allowSilentOverride = true) {
        // add bindings for fakes w/ allowOverride = true
    }
    
    @Before
    fun setup() {
        val application =
            ApplicationProvider.getApplicationContext() as BaseApplication

        // how can I override the BaseApplication modules for my test?
    }

}

I cant seem to find any clear language on the matter and feel like I am missing something very obvious. Any help would be very much appreciated.



from Android Instrumented tests with KodeIn

Upon restarting a Jupyter notebook, automatically run 1st/nth cell only (to load modules and other variables), ideally using a keyboard shortcut

In addition to loading required modules, in the first cell of the jupyter notebook, I usually load variables (e.g. metadata, tables etc.). So every time when I restart a jupyter notebook, I need to run the 1st cell of the notebook. I know this is not a big issue, but sometimes can be an annoyance. For example, if I would be working at the end of the notebook and need to restart it, I would have to scroll all the way up, run the first cell, and then scroll all the way back to resume the work.

I hope there is a way to automatically run 1st (or any n'th) cell of a jupyter notebook when it is restarted. I wonder if anybody knows if such a functionality exists.



from Upon restarting a Jupyter notebook, automatically run 1st/nth cell only (to load modules and other variables), ideally using a keyboard shortcut

Firebase server-timestamp differs from the correct time

I am trying to use firebase-server-timestamp to show the user when he/she send their order to us.

The problem I encounter is, that the server-timestamp is showing a wrong time (e.g: Current time is 12:30, but timestamp shows 12:15). How is that possible?

Android code

data class MyTimestampPOJO(
    val date: Timestamp = Timestamp.now(), // wrong, 15 minutes too early
)

Database screenshot (sending was at 12:50 and not 12:35)

enter image description here

I am testing this inside the firebase-emulator. The time on my phone is correct (even tho it does not matter, because the server-timestamp is independent to the phone-time, as it should be.)



from Firebase server-timestamp differs from the correct time

Android some EditText fields don't respond to long-press (API 30+ with layout_width 0dp)

I'm wondering if anyone else has experienced this strange bug. My layout is complicated but essentially it's rows of view holders with EditText fields.

It worked flawlessly until I updated my target SDK to API 30.

After targetting API 30, some of my EditText fields don't respond to "focus touch events" (the cursor handle doesn't show up, you can't long press, and you can't select any text). You can still type in the field and move the cursor by tapping. Again, some text fields work perfectly fine while others are affected by this bug.

enter image description here

^ The image is not of my app, just to show the cursor handler for understanding.

<!-- in constraint layout -->
<androidx.appcompat.widget.AppCompatEditText
    android:id="@+id/myTextField"
    android:layout_height="wrap_content"
    android:layout_width="0dp"
    app:layout_constraintHorizontal_weight="1"
    app:layout_constraintLeft_toRightOf="parent"
    app:layout_constraintRight_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"/>

<!-- in linear layout -->
<androidx.appcompat.widget.AppCompatEditText
    android:id="@+id/myTextField"
    android:layout_height="wrap_content"
    android:layout_width="0dp"
    android:layout_weight="1"/>

If I change the text fields width to wrap_content it works perfectly for all text fields, but that doesn't fit with my design. I need the text field to fill the available space.

I even tried manually setting the width to a random dp value and it still didn't work.

I've tested on < API 30 devices and it's totally fine.

Did I miss something? Why isn't this working on API 30+?

Is there another way to get the EditText field to fill the space?



from Android some EditText fields don't respond to long-press (API 30+ with layout_width 0dp)

Saturday, 27 November 2021

ffmpeg exited with code 1: Error reinitializing filters! Failed to inject frame into filter network: Invalid argument

Using video show npm i am creating a video from multiple images. initially there was an issue but then i downlaod and installed ffmpeg. Now another error occored.Thanks to every one in advance. this is my code.

   //create a video from multiple images 

var secondsToShowEachImage = 3
var finalVideoPath = '/outputImages/newvideo2.mp4'

// setup videoshow options
var videoOptions = {
  fps: 24,
  transition: false,
  videoBitrate: 1024 ,
  videoCodec: 'libx264', 
  size: '640x640',
  outputOptions: ['-pix_fmt yuv420p'],
  format: 'mp4' 
}
let path1= '/InputImages/abc.jpg';
let path2 = '/InputImages/xy.jpg'
let path3 = '/InputImages/ab.jpg'

// array of images to make the 'videoshow' from
var images = [
  {path: path1, loop: secondsToShowEachImage}, 
  {path: path2, loop: secondsToShowEachImage}
]
console.log('working --->')
 videoshow(images, videoOptions)
.save(finalVideoPath)
// console.log('hello world')
.on('start', function (command) { 

  console.log('encoding ' + finalVideoPath + ' with command ' + command) 
})
.on('error', function (err) {
   console.log('err' , err)
//   return Promise.reject(new Error(err)) 
})
.on('end', function (output) {
  // do stuff here when done
})

The error is

err Error: ffmpeg exited with code 1: Error reinitializing filters!
Failed to inject frame into filter network: Invalid argument
Error while processing the decoded data for stream #1:0
Conversion failed!

    at ChildProcess.<anonymous> (E:\Video-Editor-Practice\Nodees6video-editor\NewVideoEditor\node_modules\fluent-ffmpeg\lib\processor.js:182:22)


from ffmpeg exited with code 1: Error reinitializing filters! Failed to inject frame into filter network: Invalid argument

How to repeatedly (forever) animate a BottomNavigationView icon

I am familiar with BottomNavigationView's on-click one-shot animations. But I have a use case where I need to repeatedly animate BottomNavigationView's icon forever using an XML or vector. I have done enough research but couldn't find a place to start. Any help is really appreciated.



from How to repeatedly (forever) animate a BottomNavigationView icon

How to implement pagination with kotlin

Hello there recently I switch my project from java to kotlin and I'm a very beginner in kotlin, and I want to implement pagination in my recycler view

the recycler view contain images that are stored in firebase, what I want

Option 1 is that first when the fragment is created it loads 20 images and when the user reaches the last image (20) it loads the next 20 images in the recycler view

Option 2

(optional but wanted this kind of pagination in my app )

have you seen Pinterest and Instagram, if you just scroll normally you probably don't see the images are loading until if you scroll very fast, and then it shows the progress bar?

for eg: Pinterest

1: scroll normally or slow Link

2: scroll very fast Link

I want this kind of functionality if possible

what I think is going on in Instagram or Pinterest is for eg

They load probably 20 images at the start and when the user reaches the 10th image (still 10 images are remaining to be seen by the user) they just load the next 10 images so it just maintains the adapter with 20 images instead of reaching the end of the list to load the next images ( hence this would be an exception if user scrolls very fast)


Note: I just don't know what it is said pagination or something else and also not sure that what I said up are the technique used I'm just speculating

Code

Home_Fragment.kt

I only included the required code but if you want more references please tell me I will update the question btw the implemented pagination (don't know is it pagination or something else but it's not working)

val staggeredGridLayoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        postRecyclerView.layoutManager = staggeredGridLayoutManager
        postRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                visibleItemCount = staggeredGridLayoutManager.childCount
                totalItemCount = staggeredGridLayoutManager.itemCount
                val firstVisibleItems: IntArray? = null
                staggeredGridLayoutManager.findFirstVisibleItemPositions(firstVisibleItems)
                if (loading) {
                    if (totalItemCount > previousTotal) {
                        loading = false
                        previousTotal = totalItemCount
                    }
                }
                if (!loading && totalItemCount - visibleItemCount
                    <= firstVisibleItem + visibleThreshold
                ) {
                    data
                    loading = true
                }
            }
        })
        data
        //        setupFirebaseAuth();
        shimmerFrameLayout!!.startShimmer()
        mUploads = ArrayList()
        postsAdapter = PostAdapter_Home(requireContext(), mUploads)
        postRecyclerView.adapter = postsAdapter
        postRecyclerView.scrollToPosition(saved_position)
        //        postsAdapter.stateRestorationPolicy = PREVENT_WHEN_EMPTY;
        return view
    }
 private val data: Unit
        get() {
            databaseReference.addValueEventListener(object : ValueEventListener {
                @SuppressLint("NotifyDataSetChanged")
                override fun onDataChange(snapshot: DataSnapshot) {
                    if (snapshot.exists()) {
                        shimmerFrameLayout!!.stopShimmer()
                        shimmerFrameLayout!!.visibility = View.GONE
                        postRecyclerView.visibility = View.VISIBLE
                        mUploads!!.clear()
                        for (dataSnapshot in snapshot.children) {
                            val upload = dataSnapshot.getValue(Upload::class.java)!!
                            upload.setmKey(dataSnapshot.key)
                            mUploads!!.add(upload)
                        }
                    }
                    postsAdapter!!.setUploads(mUploads)
                    //notify the adapter
                    postsAdapter!!.notifyItemRangeInserted(0, mUploads!!.size)
                    loading = true
                }

                override fun onCancelled(error: DatabaseError) {
                    loading = true
                }
            })
        }

PostAdapter_Home.kt

class PostAdapter_Home(var mcontext: Context, var mUploads: MutableList<Upload?>?) :
    RecyclerView.Adapter<PostAdapter_Home.PostViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
        val view: View
        view = LayoutInflater.from(mcontext)
            .inflate(R.layout.post_item_container_home_ex, parent, false)
        return PostViewHolder(view)
    }

    override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
        val shimmer = ColorHighlightBuilder()
            .setBaseColor(Color.parseColor("#F3F3F3"))
            .setBaseAlpha(1f)
            .setHighlightColor(Color.parseColor("#E7E7E7"))
            .setHighlightAlpha(1f)
            .setDropoff(50f)
            .build()
        val shimmerDrawable = ShimmerDrawable()
        shimmerDrawable.setShimmer(shimmer)
        val uploadCurrent = mUploads?.get(position)
        Glide.with(mcontext)
            .load(uploadCurrent?.getmImageUrl())
            .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
            .placeholder(shimmerDrawable)
            .fitCenter()
            .into(holder.imageView)

    }

    
    override fun getItemCount(): Int {
        return mUploads?.size!!
    }

    //    public long getId() {
    //        return this.id;
    //    }
    //
    //    @Override
    //    public long getItemId(int position) {
    //        return mUploads.get(position).Id;
    //    }
    fun setUploads(uploads: MutableList<Upload?>?) {
        mUploads = uploads
    }

    class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ShapeableImageView

        init {
            imageView = itemView.findViewById(R.id.imagePostHome)
        }
    }
}

Upload.kt

package com.example.myappnotfinal.AdaptersAndMore

import com.google.firebase.database.Exclude

class Upload {
    private var mImageUrl: String? = null
    private var mKey: String? = null

    constructor() {}
    constructor(imageUrl: String?) {
        mImageUrl = imageUrl
    }

    fun getmImageUrl(): String? {
        return mImageUrl
    }

    fun setmImageUrl(mImageUrl: String?) {
        this.mImageUrl = mImageUrl
    }

    @Exclude
    fun getmKey(): String? {
        return mKey
    }

    @Exclude
    fun setmKey(Key: String?) {
        mKey = Key
    }
}


from How to implement pagination with kotlin