Monday 30 November 2020

Why does adding CDay() to DatetimeIndex include a weekend?

I am on pandas version 1.1.3.

Suppose I have the following index

import pandas as pd
from pandas.tseries.offsets import CDay

idx = pd.bdate_range("2010-02-03","2010-02-12") + pd.Timedelta('22H')

If I then add:

shifted_idx = idx + 0*CDay(offset=pd.Timedelta('4H'))

I would expect the timestamp in idx of 2010-05-05 22:00 to move to 2010-05-08 02:00 since CDay() has weekmask = ‘Mon Tue Wed Thu Fri’ by default.

However, we see in shifted_idx a timestamp 2010-02-06 02:00:00 which is on a Saturday and violates the weekmask?



from Why does adding CDay() to DatetimeIndex include a weekend?

Exception has been thrown by the target of an invocation in Xamarin

Here is the Code (Run this to see what's the problem) => https://github.com/x0axz/CustomRenderer

In my Xamarin App, there is a Custom Camera Renderer for Android, which is being called from ViewModel through MessagingCenter.Send<object>(this, "A");.

It's working fine. The only problem is that, on first page it takes Picture, but when I navigate to another page, where there is an other command, MessagingCenter.Send<object>(this, "A");, to take a Picture, but this time it returns an error Camera is being used after Camera.release() was called.

Below is the code for ViewModel and Camera Renderer.

FirstCameraViewModel.cs

private void FirstCamera(object sender, EventArgs e)
{
    try
    {
        MessagingCenter.Send<object>(this, "A");
    }
    catch
    {
        Console.WriteLine(error.InnerException.StackTrace);
        Console.WriteLine(error.InnerException.Message);
    }
    finally
    {
        timer_countdown = new Timer();
        timer_countdown.Interval = 1000;
        timer_countdown.Elapsed += OnTimedEvent;
        timer_countdown.Enabled = true;
        timer_countdown.AutoReset = true;
        timer_countdown.Start();
    }
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Seconds++;

    if (Seconds == 5)
    {
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await NavigationService.NavigateToAsync<SecondCameraViewModel>();
        });
    }
}

SecondCameraViewModel.cs, in this page it returns an error

private void SecondCamera(object sender, EventArgs e)
{
    try
    {
        MessagingCenter.Send<object>(this, "A");
    }
    catch
    {
        Console.WriteLine(error.InnerException.StackTrace);
        Console.WriteLine(error.InnerException.Message);
    }
    finally
    {
        timer_countdown = new Timer();
        timer_countdown.Interval = 1000;
        timer_countdown.Elapsed += OnTimedEvent;
        timer_countdown.Enabled = true;
        timer_countdown.AutoReset = true;
        timer_countdown.Start();
    }
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Seconds++;

    if (Seconds == 5)
    {
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await NavigationService.NavigateToAsync<IndexViewModel>();
        });
    }
}

UPDATE

CameraPreview.cs

public sealed class CameraPreview : ViewGroup, ISurfaceHolderCallback, Camera.IPictureCallback
{
    SurfaceView surfaceView;
    ISurfaceHolder holder;
    Camera.Size previewSize;
    IList<Camera.Size> supportedPreviewSizes;
    Camera camera;
    IWindowManager windowManager;

    public bool IsPreviewing { get; set; }

    public Camera Preview
    {
        get { return camera; }
        set
        {
            camera = value;
            if (camera != null)
            {
                supportedPreviewSizes = Preview.GetParameters().SupportedPreviewSizes;
                RequestLayout();
            }
        }
    }

    public CameraPreview(Context context)
        : base(context)
    {
        surfaceView = new SurfaceView(context);
        AddView(surfaceView);

        windowManager = Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();

        IsPreviewing = false;
        holder = surfaceView.Holder;
        holder.AddCallback(this);

        MessagingCenter.Subscribe<object>(this, "A", (e) =>
        {
            camera.TakePicture(null, null, this);
        });
    }

    protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = ResolveSize(SuggestedMinimumWidth, widthMeasureSpec);
        int height = ResolveSize(SuggestedMinimumHeight, heightMeasureSpec);
        SetMeasuredDimension(width, height);

        if (supportedPreviewSizes != null)
        {
            previewSize = GetOptimalPreviewSize(supportedPreviewSizes, width, height);
        }
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        var msw = MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly);
        var msh = MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly);

        surfaceView.Measure(msw, msh);
        surfaceView.Layout(0, 0, r - l, b - t);
    }

    public void SurfaceCreated(ISurfaceHolder holder)
    {
        try
        {
            if (Preview != null)
            {
                Preview.SetPreviewDisplay(holder);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"           ERROR: ", ex.Message);
        }
    }

    public void SurfaceDestroyed(ISurfaceHolder holder)
    {
        if (Preview != null)
        {
            Preview.StopPreview();
        }
    }

    public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int width, int height)
    {
        var parameters = Preview.GetParameters();
        parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
        RequestLayout();

        switch (windowManager.DefaultDisplay.Rotation)
        {
            case SurfaceOrientation.Rotation0:
                camera.SetDisplayOrientation(90);
                break;
            case SurfaceOrientation.Rotation90:
                camera.SetDisplayOrientation(0);
                break;
            case SurfaceOrientation.Rotation270:
                camera.SetDisplayOrientation(180);
                break;
        }

        Preview.SetParameters(parameters);
        Preview.StartPreview();
        IsPreviewing = true;
    }

    Camera.Size GetOptimalPreviewSize(IList<Camera.Size> sizes, int w, int h)
    {
        const double AspectTolerance = 0.1;
        double targetRatio = (double)w / h;

        if (sizes == null)
        {
            return null;
        }

        Camera.Size optimalSize = null;
        double minDiff = double.MaxValue;

        int targetHeight = h;
        foreach (Camera.Size size in sizes)
        {
            double ratio = (double)size.Width / size.Height;

            if (Math.Abs(ratio - targetRatio) > AspectTolerance)
                continue;
            if (Math.Abs(size.Height - targetHeight) < minDiff)
            {
                optimalSize = size;
                minDiff = Math.Abs(size.Height - targetHeight);
            }
        }

        if (optimalSize == null)
        {
            minDiff = double.MaxValue;
            foreach (Camera.Size size in sizes)
            {
                if (Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff = Math.Abs(size.Height - targetHeight);
                }
            }
        }

        return optimalSize;
    }

    public void OnPictureTaken(byte[] data, Camera camera)
    {
        camera.StopPreview();

        FileOutputStream outStream = null;
        File dataDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
        if (data != null)
        {
            try
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var s = ts.TotalMilliseconds;
                outStream = new FileOutputStream(dataDir + "/" + s + ".jpg");
                outStream.Write(data);

                outStream.Close();
            }
            catch (FileNotFoundException e)
            {
                System.Console.Out.WriteLine(e.Message);
            }
            catch (IOException ie)
            {
                System.Console.Out.WriteLine(ie.Message);
            }
        }
        camera.StartPreview();
    }
}

CameraPreviewRenderer.cs

public class CameraPreviewRenderer : ViewRenderer<Mobile.App.CameraPreview, CameraPreview>
{
    CameraPreview cameraPreview;

    public CameraPreviewRenderer(Context context) : base(context)
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Mobile.App.CameraPreview> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            // Unsubscribe
            cameraPreview.Click -= OnCameraPreviewClicked;
        }
        if (e.NewElement != null)
        {
            if (Control == null)
            {
                cameraPreview = new CameraPreview(Context);
                SetNativeControl(cameraPreview);
            }
            Control.Preview = Camera.Open((int)e.NewElement.Camera);

            // Subscribe
            cameraPreview.Click += OnCameraPreviewClicked;
        }
    }

    void OnCameraPreviewClicked(object sender, EventArgs e)
    {
        if (cameraPreview.IsPreviewing)
        {
            cameraPreview.Preview.StopPreview();
            cameraPreview.IsPreviewing = false;
        }
        else
        {
            cameraPreview.Preview.StartPreview();
            cameraPreview.IsPreviewing = true;
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            Control.Preview.Release();
        }
        base.Dispose(disposing);
    }
}


from Exception has been thrown by the target of an invocation in Xamarin

Accurately calculate Vehicle Speed (MPH) using Android GPS Location Latitude/Longitude

Im currently attempting to develop an Android Application that displays an accurate road speed for a vehicle in Mile Per Hour (MPH) using Location Latitude/Longitude from GPS.

I have the following code as my first attempt:-

private fun startLocationUpdates() {
    val locationRequest = LocationRequest.create()?.apply {
        interval = 1000
        fastestInterval = 500
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }

    fusedLocationClient.requestLocationUpdates(locationRequest, manufactureCallBack(), Looper.getMainLooper())
}

       @SuppressLint("SetTextI18n")
        override fun onLocationResult(locationResult: LocationResult) {
            locationResult.locations.forEach { location ->
                previousTimestamp = if (this@MainActivity::previousLocation.isInitialized) {
                    val dist: Double = HaversineAlgorithm.distanceMiles(previousLocation.latitude, previousLocation.longitude, location.latitude, location.longitude)

                    val currentTime = System.nanoTime()
                    val time_s: Double = (currentTime - previousTimestamp) / (1_000_000_000.0 * 60.0 * 60.0)

                    Timber.i("time_s = $time_s :: dist = $dist")

                    if (dist > 0.0 && time_s > 0.0) {
                        val speed_mps: Double = dist / time_s
                        Timber.i("${location.time} speed_mps = $speed_mps")
                        val speed_mph: Double = speed_mps * something
                        milesPerHourTV.text = "$speed_mph MPH"
                    }
                    currentTime
                } else {
                    System.nanoTime()
                }

                previousLocation = location
            }
        }

My Haversine calculation (Km) is as follows:-

fun distance(departureLatitude: Double, departureLongitude: Double, destinationLatitude: Double, destinationLongitude: Double): Double {
    val latitudeDelta = Math.toRadians(destinationLatitude - departureLatitude)
    val longitudeDelta = Math.toRadians(destinationLongitude - departureLongitude)
    val radiusDepartureLatitude = Math.toRadians(departureLatitude)
    val radiusDestinationLatitude = Math.toRadians(destinationLatitude)
    val a = sin(latitudeDelta / 2).pow(2.0) + sin(longitudeDelta / 2).pow(2.0) * cos(radiusDepartureLatitude) * cos(radiusDestinationLatitude)
    val c = 2 * asin(sqrt(a))
    return EARTH_RADIUS * c
}

to Miles :-

fun distanceMiles(departureLatitude: Double, departureLongitude: Double, destinationLatitude: Double, destinationLongitude: Double): Double {
    val distanceInKm = distance(departureLatitude, departureLongitude, destinationLatitude, destinationLongitude)
    return distanceInKm * 0.621371
}

As I only use two points in my calculations I expected "jittery" results however the figures I see are very odd.

I was thinking of employing Kotlin Flow to send my Location updates to an Averaging function to average out the locations and obtain a more accurate velocity value.

What approach could I take to obtain a more accurate velocity?

Have I made a mistake in my calculations?



from Accurately calculate Vehicle Speed (MPH) using Android GPS Location Latitude/Longitude

React hook form - Field Array inside Dialog (Material UI)

So i have a form that has custom fields that i add via Field Array from react-hook-form. And everything works but i added drag and drop for the property items (to reorder them) and now it would be a big mess to show all these many fields directly so i moved them in a Dialog.

Here are the pictures to get the idea what is easier to drag n drop... (the right one)

The problem is that field array values get "reset" after the modal closes (after i type those form values in edit modal), i guess it has something to do with re-rendering but i am not sure.

I tried to show the minimal code example here without d&d and other useless stuff...
But here is codesandbox playground with the full code

CreateCategoryForm.js

const defaultValues = {
  name: "",
  slug: "",
  description: "",
  properties: [] // field array
}

function CreateCategoryForm() {
  const methods = useForm({ defaultValues });
  const { handleSubmit, control, errors } = methods;
  const { fields, append, remove, swap } = useFieldArray({ name: "properties", control });

  const onSubmit = async (data) => {
    console.log("data: ", data);
  };

  return (
    <Container>
        <FormProvider {...methods}>
          <form onSubmit={handleSubmit(onSubmit)} noValidate>
            <FormTextField name="name" />
            <FormTextField name="slug" />
            <FormTextField name="description" />

            {fields.map((card, idx) => (
              <PropertyCard key={card.id} card={card} idx={idx} errors={errors} remove={remove} />
            ))}

            <Button onClick={() => append({ name: "", label: "", type: "text", filterable: true })}>
                Add Property
            </Button>

            <FormSubmitButton>
              Create Category
            </FormSubmitButton>
          </form>
        </FormProvider>
    </Container>
  );
}

PropertyCard.js

function PropertyCard({ card, errors, idx, remove }) {
  const [dialogOpen, setDialogOpen] = React.useState(false);

  const handleOpenDialog = () => {
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
  };
 
return (
    <div>
      Property {idx + 1}
      <IconButton onClick={() => handleOpenDialog()}>
        edit
      </IconButton>
      <IconButton onClick={() => remove(idx)}>
        X
      </IconButton>

      <Dialog
        fullScreen
        open={dialogOpen}
        onClose={handleCloseDialog}
      >
        <Container maxWidth="xs">
          <FormTextField
            name={`properties[${idx}].name`}
            label="Property Name"
          />
          <FormTextField
            name={`properties[${idx}].label`}
            label="Property Label"
          />
          <FormSelect
            name={`properties[${idx}].type`}
            label="Filter Type"
            options={[
              { label: "text", value: "text" },
              { label: "bool", value: "bool" }
            ]}
            defaultValue="text"
          />
          <FormSwitch
            name={`properties[${idx}].filterable`}
            label="Filterable"
            defaultValue={true}
          />
          <IconButton onClick={handleCloseDialog}>
              X
          </IconButton>
        </Container>
      </Dialog>
    </div>
  );  
}
  • it is not the FormProvider context that is the issue or my FormTextField components... i tried with normal input with ref and it didn't work also.
  • also happens with no drag and drop code


from React hook form - Field Array inside Dialog (Material UI)

Javascript Safari Push Notifications "Allowed" but are always put in "Deny" mode

After successfully certify my package with PHP and deliver it to Safari through endpoint /v1/pushPackages/web.com.mywebsite, the so expected popup appeared:

enter image description here

Three problems now happen:

  1. After pressing "Allow" nothing is triggered, the console is empty and should print "Device Token: ..." in the granted condition.
  2. After quit and reopen Safari, I went to Safari > Preferences > Websites > Notifications and my website has the value "Deny"!
  3. If I change the value from "Deny" to "Allow" it's not saved. Safari will put back to "Deny"

enter image description here

I can select the item an press the button "Remove", restart the Safari and my website will ask again for permissions, but the problem persists. My log files are empty, no error is thrown!

var checkSafariPermission = function (permissionData)
{
    if (permissionData.permission === 'default')
    {
        window.safari.pushNotification.requestPermission(
            'https://mywebsite.com',
            'web.com.mywebsite',
            {},
            checkSafariPermission
        );
    } else if (permissionData.permission === 'denied')
    {
        console.log('denied');
    } else if (permissionData.permission === 'granted')
    {
        // This is never triggered!
        console.log('Device token: ' + permissionData.deviceToken);
    }
};

var permissionData = window.safari.pushNotification.permission('web.com.mywebsite');
checkSafariPermission(permissionData);

I have the routes:

POST /v1/devices/{deviceToken}/registrations/web.com.mywebsite
DELETE /v1/devices/{deviceToken}/registrations/web.com.mywebsite

Ready to receive data, but I don't think Safari is yet requesting this routes.

The official documentation says the following:

Important: Make sure that your web server is using a real certificate issued from a Certificate Authority, not a self-signed certificate. If your certificate is self-signed, push notifications won’t reach your users.

Could this be the problem? Currently my website has an certificate called "Let's Encrypt Authority X3", with the bellow data, but I don't know if this is a self-signed certificate?

Common name: www.mywebsite.com
SANs: mail.mywebsite.com, mywebsite.com, webmail.mywebsite.com, www.mywebsite.com
Valid from November 10, 2020 to February 8, 2021
Serial Number: 046829bc4b1e9d71ed27b...
Signature Algorithm: sha256WithRSAEncryption
Issuer: Let's Encrypt Authority X3

UPDATE 1 - I just acquired & installed a certificate, the problem persists



from Javascript Safari Push Notifications "Allowed" but are always put in "Deny" mode

how to use django 3 with django-otp to send token sms using SMS service provider for user verification and redirecting to password reset form?

I have only been able to make the following changes in django code:

settings.py: added along with other apps added in

INSTALLED_APPS = [
 .....
    'django_otp',
    'django_otp.plugins.otp_totp',
]

In additions to other middleware configurations, added:

MIDDLEWARE = [
    'django_otp.middleware.OTPMiddleware',
]

urls.py:

from django_otp.admin import OTPAdminSite
from django_otp.plugins.otp_totp.models import TOTPDevice

admin_site = OTPAdmin(name='OTPAdmin')
admin_site.register(User)
admin_site.register(TOTPDevice)

urlpatterns = [
    path('admin/', admin_site.urls), #otp app
    path('dadmin/', admin.site.urls),
]

Then I ran: $ python3 manage.py migrate otp_totp --fake and runserver. Created a user and totp device. Scanned the qr code in google authenticator. Then tried logging in using the admin url to login for this new user. It asks for the token generated which I input, it says invalid token though user is authenticated. Seen other posts where the secret code needs to be converted to 32basecode etc, but don't know exactly and where to implement. What more code needs to be added to get this working? I will require detailed code and steps for my use case where i need to change the time for generating the code and send via sms using my service provider api and redirect to password reset form.

Using django 3.1, django-otp 1.0.2 My google authenticator works with my gmail account, so there is no clock time difference either.



from how to use django 3 with django-otp to send token sms using SMS service provider for user verification and redirecting to password reset form?

Correct way to communicate the result of a background thread to the Ui Thread in Android

This is one of the most confusing topics for me. So my question is, what is the correct way of communicate the result of background thread when this finish?.

Imagine I want to update some TextView with some information I just downloaded.There is 3 things I use when I need to perform background tasks:

AsyncTask

Very easy to use, this one has the onPostExecute() method that will return the result directly to the UiThread so I can use a callback interface or do whatever I want. I liked this class but it's deprecated.

ThreadPoolExecutor

This is what I actually use when need to perform background tasks and here comes my problem, the moment when I have to give the result to the UiThread. I have informed myself about Looper and Handler classes and about the mainLooper.

So, when I need to return some results I use the method runOnUiThread() that, as I have readed, just get the Looper of the Ui thread and post my Runnable to the queue.

Well this is working and I can communicate with the main thread but, I find it really ugly, and I am sure there is a more elegant way of doing it than populate all my code of "runOnUiThread()" methods. Also, if the background task need too much time, maybe the user already change of Activity or Fragment when the code inside runOnUiThread() runs what will cause Exceptions (I know using LiveData and MVVM pattern would solve this last problem but I am working in a legacy project and I can't refactor all the code so I am working with the clasical Activity mvc pattern)

So, there is another way of doing this? Could you give an example? I really searched a lot but didn't find anything...

Coroutines

I am actually working in a legacy project and I must use Java so can't use Kotlin coroutines, but I find them easy to use and so powerfull.

Any help would be appreciated!



from Correct way to communicate the result of a background thread to the Ui Thread in Android

Gradle exclude classes from aar

Im using lib Gson in my dependecies and im import a .aar with some classes from Gson that are imported to a project. When i build my project i keep getting duplicated classes, bcz its on my dependency and aar classes.

How i can exclude gson classes from aar?

I have been trying with:

  • exclude group: I think this is not work since is not a dependency from aar, but classes inside.
  • transitive true, same reason as before

Can i do it? or should i get other .aar with gson as dependecy?



from Gradle exclude classes from aar

Programmatically change input value in Facebook's editable div input area

I'm trying to write a Chrome Extension that needs to be able to insert a character at the cursor location in an input field.

It's very easy when the input is an actual HTMLInputElement (insertAtCaretInput borrowed from another stack answer):

function insertAtCaretInput(text) {
  text = text || '';
  if (document.selection) {
    // IE
    this.focus();
    var sel = document.selection.createRange();
    sel.text = text;
  } else if (this.selectionStart || this.selectionStart === 0) {
    // Others
    var startPos = this.selectionStart;
    var endPos = this.selectionEnd;
    this.value = this.value.substring(0, startPos) + text + this.value.substring(endPos, this.value.length);
    this.selectionStart = startPos + text.length;
    this.selectionEnd = startPos + text.length;
  } else {
    this.value += text;
  }
}

HTMLInputElement.prototype.insertAtCaret = insertAtCaretInput;

onKeyDown(e){
  ...
  targetElement = e.target;
  target.insertAtCaret(charToInsert);
  ...
}

But the moment an input is actually represented differently in the HTML structure (e.g. Facebook having a <div> with <span> elements showing up and consolidating at weird times) I can't figure out how to do it reliably. The new character disappears or changes position or the cursor jumps to unpredictable places the moment I start interacting with the input.

Example HTML structure for Facebook's (Chrome desktop page, new post or message input fields) editable <div> containing string Test :

<div data-offset-key="87o4u-0-0" class="_1mf _1mj">
  <span>
    <span data-offset-key="87o4u-0-0">
      <span data-text="true">Test
      </span>
    </span>
  </span>
  <span data-offset-key="87o4u-1-0">
    <span data-text="true"> 
    </span>
  </span>
</div>

Here's my most successful attempt so far. I extend the span element like so (insertTextAtCursor also borrowed from another answer):

function insertTextAtCursor(text) {
  let selection = window.getSelection();
  let range = selection.getRangeAt(0);
  range.deleteContents();
  let node = document.createTextNode(text);
  range.insertNode(node);

  for (let position = 0; position != text.length; position++) {
    selection.modify('move', 'right', 'character');
  }
}

HTMLSpanElement.prototype.insertAtCaret = insertTextAtCursor;

And since the element triggering key press events is a <div> that then holds <span> elements which then hold the text nodes with the actual input, I find the deepest <span> element and perform insertAtCaret on that element:

function findDeepestChild(parent) {
  var result = { depth: 0, element: parent };

  [].slice.call(parent.childNodes).forEach(function (child) {
    var childResult = findDeepestChild(child);
    if (childResult.depth + 1 > result.depth) {
      result = {
        depth: 1 + childResult.depth,
        element: childResult.element,
        parent: childResult.element.parentNode,
      };
    }
  });

  return result;
}

onKeyDown(e){
  ...
  targetElement = findDeepestChild(e.target).parent; // deepest child is a text node
  target.insertAtCaret(charToInsert);
  ...
}

The code above can successfully insert the character but then strange things happen when Facebook's behind-the-scenes framework tries to process the new value. I tried all kinds of tricks with repositioning the cursors and inserting <span> elements similar to what seems to be happening when Facebook manipulates the dom on inserts but in the end, all of it fails one way or another. I imagine it's because the state of the input area is held somewhere and is not synchronized with my modifications.

Do you think it's possible to do this reliably and if so, how? Ideally, the answer wouldn't be specific to Facebook but would also work on other pages that use other elements instead of HTMLInputElement as input fields but I understand that it might not be possible.



from Programmatically change input value in Facebook's editable div input area

How to count the number of consecutive days a value grows

I have the following df:

Date
2015-11-27    105.449997
2015-11-30    104.239998
2015-12-01    107.120003
2015-12-02    106.070000
2015-12-03    104.379997
                 ...    
2020-11-18    271.970001
2020-11-19    272.940002
2020-11-20    269.700012
2020-11-23    268.429993
2020-11-24    276.920013
Name: Close, Length: 1258, dtype: float64

What I am trying to do is find for how many days in a row has the Close closed lower than the previous day. Could you please advise how I can go about this?

For example: enter image description here

At this point it would say Close was lower for the last 3 days on Date

    Date          Close     Days
    10/30/2020  263.109985  0.0
    11/2/2020   261.359985  1.0
    11/3/2020   265.299988  0.0
    11/4/2020   287.380005  1.0
    11/5/2020   294.679993  0.0
    11/6/2020   293.410004  1.0
    11/9/2020   278.769989  0.0
    11/10/2020  272.429993  1.0
    11/11/2020  276.480011  0.0
    11/12/2020  275.079987  1.0
    11/13/2020  276.950012  0.0
    11/16/2020  278.959991  0.0
    11/17/2020  275.000000  1.0
    11/18/2020  271.970001  2.0
    11/19/2020  272.940002  0.0
    11/20/2020  278.000000  1.0
    11/23/2020  277.000000  2.0
    11/24/2020  276.920013  3.0

How can achieve this?



from How to count the number of consecutive days a value grows

How to validate multistep form in react

I have a multi-step form, which I am making using react, to work on validation I am using react-hook-form.

I have already achieved 90% of things just one thing I am facing the issue is getting the second form data which is dynamic.

What I am doing is

  • In my first form I have two fields when those are filled (validated) I am going to the next form
  • In my next form I have two input fields and on the add button user can add multiple rows of fields as well and these are working fine

issue

  • Now when I create new fields in the second form I want to validate them but not getting an idea how can I do that.

What I have done

In my main component, I am doing this for validation

const forms = [
  {
    fields: ['desig', 'dept'],
    component: () => (
      <Pro register={register} errors={errors} defaultValues={defaultValues} />
    ),
  },
  {
    fields: [
      `userInfo[0].fname`, // here I am facing issue if I am statically putting 0,1 then it is validating that perticular form
      `userInfo[0].sirname`,
    ],
    component: () => (
      <Basic
        register={register}
        errors={errors}
        defaultValues={defaultValues}
        inputHolder={inputHolder}
        deleteRow={deleteRow}
        addRow={addRow}
      />
    ),
  },
];

On click of submitting, I am doing this

const handleSubmit = (e) => {
  triggerValidation(forms[currentForm].fields).then((valid) => {
    if (valid) {
      console.log('whole form data - ', JSON.stringify(defaultValues));
    }
  });
};

and here i want data as like below if two data is added in form2

    {
  "fname": "dsteve",
  "sname": "smith",
  "userInfo": [
    {
      "desig": "ddd",
      "dept": "deptee"
    },
    {
      "desig": "ddd",
      "dept": "deptee"
    }
  ]
}

I have done everything but here only I have been stuck, I know where the issue is

Instead of this

fields: ["fname", "sname"],

I have to do like this

fields:[`userInfo[0].name, `userInfo[0].sname],

This 0-1 I have to make dynamic as per indexes, I don't know what I am missing

I tried mapping the fields with index through inputHolderbut it did not work

Edit / Update

If I am doing like this

fields:[`userInfo[0].name`,`userInfo[1].name`, `userInfo[0].sname`,`userInfo[1].sname],

So it is taking validation for two fields, but that is manually I am doming, if user creates more fields then that should take these fields dynamically.

Here is my code sandbox, which contains the full code

Here is my code sandbox



from How to validate multistep form in react

How to prevent page reload after submit button clicked for bootstrap modal and parsley.js validation?

I have bootstrap modal which open up a modal to allow user to enter the form and it works. I implemented parseley.js for the form validaton and it kinda works. The problem is when the validation passed, it reload the page (as you can see from below gif) which it not the behavior I expect. What I expect is to see the alert('ok') in validateForm().

enter image description here

This is how I define my form tag and submit button

<form id="myForm" data-parsley-validate="">
    <button class="btn btn-default" >Save</button>           
</form>

and this is my function to validate the form using Parsely.js. When all validation pass, I expect is to see the alert('ok') but it doesn't. Instead, it reload the page.

function validateForm() {
    $('#myForm').parsley().on('field:validated', function () {
        debugger
        var ok = $('.parsley-error').length === 0;
        $('.bs-callout-info').toggleClass('hidden', !ok);
        $('.bs-callout-warning').toggleClass('hidden', ok);
    })

        .on('form:submit', function () {
            debugger
            alert('ok') // I expect to reach here when pass validation pass but it doesn't
            postCustomer();
            return false; 
        });
}

and this is my bootstrap modal

$('#modalCustomerForm').on('shown.bs.modal', function () {
    debugger
    validateForm();
    return false;
})

If I add sample code below, there is no css class added by parsley. I suspect parsley is not loading. But then, the validation work. When I press Submit button, I can see red color error message at the bottom of the textbox.

<div class="bs-callout bs-callout-warning hidden">
    <h4>Oh snap!</h4>
    <p>This form seems to be invalid :(</p>
</div>

<div class="bs-callout bs-callout-info hidden">
    <h4>Yay!</h4>
    <p>Everything seems to be ok :)</p>
</div>

Further troubleshooting. If I add an id to the button and create button click event, it doesn't auto reload the page. But if I do so, parsley.js validation doesn't work.

<button class="btn btn-default" type="submit" id="formBtn">Save</button>

$('#formBtn').on("click", function (e) {
    debugger

    postCustomer();
    debugger
    e.preventDefault();
})

That's why I put my postCustomer() at here (below) in validateForm() but it doesn't work either:

.on('form:submit', function () {
    
    debugger
    alert('ok')
    postCustomer();
    return false; // Don't submit form for this demo
});


from How to prevent page reload after submit button clicked for bootstrap modal and parsley.js validation?

How to display PNG image in ARCore?

I want to display 2d png image in Arcore. I don’t want to use obj, .smf ,imgdb file, and 3D image. I have already referred many links but none of them showing how to display only 2d png image using Arcore.

https://github.com/google-ar/arcore-android-sdk

https://developers.google.com/ar/develop/java/quickstart



from How to display PNG image in ARCore?

Mongoose Pre and Post hook: stopping a query from execution

I am working on versioning changes for an application. I am making use of the mongoose pre-hook to alter the queries before processing according to the versioning requirements, I came across a situation where I need to do a separate query to check whether the other document exists and if it is I don't have to execute the current query as shown below,

schema.pre('find', { document: false, query: true }, async function (next) {
  const query = this.getQuery();
  const doc = await model.find(query).exec();
  if (!doc) {
    const liveVersion = { ...query, version: "default" };
    this.setQuery(liveVersion);
  } else {
    return doc;
  }
});

In the above find pre-hook, I am trying to

  • check the required doc exists in the DB using the find query and return if does exist and
  • if the document does not exist, I am executing the query by setting the default version based query.

The problem here is mongoose will execute the set query no matter what and the result its returning is also the one which I got for the this.setQuery, not the other DB query result(doc).

Is there a way to stop the default query execution in mongoose pre-hook?

Any help will be appreciated.



from Mongoose Pre and Post hook: stopping a query from execution

Ternary conditions to find expmod?

I am reading SICP in JS about a non-terminating example of ternary conditions:

function is_even(n) {
    return n % 2 === 0;
}

function expmod(base, exp, m) {
    const half_exp = expmod(base, exp / 2, m);
    return exp === 0 ? 1
           : is_even(exp) ? half_exp * half_exp % m
           : base * expmod(base, exp - 1, m) % m;
}

console.log(expmod(4, 3, 5))

It explains that:

This would make the function not just inefficient, but actually non-terminating! The problem is that the constant declaration appears outside the conditional expression, which means that it is executed even when the base case exp === 0 is met.

I just cannot get its idea, when exp === 0, it terminate with 1 but why half_exp executed?



from Ternary conditions to find expmod?

Android PhotoView - zoom to previous position (x y coordinates and scale)

I'm using https://github.com/chrisbanes/PhotoView so user can zoom the image and then draw some point.

There is also a function to delete this point. In this case I redraw whole bitmap:

matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
setImageBitmap(bmp);

But now I want to zoom image to previous position/coordinates.

This should work:

setScale(scale, focalX, focalY, false);

I know the scale but I need focalX, focalY.

How can I get it? Maybe I should somehow calculate it from the

getSuppMatrix(matrix);

But I'm not sure if it's possible and how.

Do you have some tips? Help?



from Android PhotoView - zoom to previous position (x y coordinates and scale)

Open KML/GPX files in appropriate external map app

My Flutter (Android and iOS) app generates KML or GPX files, which works as expected.

Now I want to add a button "Open file" which should open such a system dialog where the installed map apps (which can handle such formats) are listed to be chosen.

How can I open this dialog? How can I find the format-related apps and how can I send the file to these apps. I guess, there is a plugin for this, but couldn't find one. It must work on Android and iOS, nice-to have is web support.

I just saw open_file but I am not quite sure, if it works as expected because it doesn't list support for KML/GPX.

Thanks in advance!



from Open KML/GPX files in appropriate external map app

Match words in any order in Isotope (using input value)

I'm using Isotope.js with vanilla javascript.

Inside my items, I have put a div with a display:none to hide keywords for each item. For example, the item Orange has the keywords 'color' and 'fruit'. So if someone types in any of those three words into the input form (orange, color, or fruit) that item will be shown via Isotope.

Here is a jsfiddle showing my project.

What I'm wanting to do, is if someone were to type all three words into the input form in any order the item will show. Right now the item will only show if the keywords are typed in order. For example, typing in "fruit color" will show the item Orange, but "color fruit" will not.

Edit: This answer here does exactly what I'm trying to achieve. I applied it to a jQuery version of my project and worked perfectly. However, I'm having troubling rewriting it in vanilla JS. Any help is immensely appreciated.



from Match words in any order in Isotope (using input value)

How to convert googleapis/java-translate library to custom api rest request using google translation api v3 in an Android project

Before seeing conflicts when building a release for my app because of googleapis/java-translate library, I used these lines and it worked perfectly :

val translate: Translate = TranslateOptions.newBuilder().setApiKey(API_KEY).build().service
val translations = translate.translate(
     textsToTranslate,
     Translate.TranslateOption.sourceLanguage(sourceLanguage),
     Translate.TranslateOption.targetLanguage(targetLanguage)
)

Then, when building release, I had to add some extra code in app/build.gradle to make it works. But, I saw that my app grows from 10Mo to 15Mo. Expensive just for translating some texts..

So I decide to perform these translations by myself using the latest Google Translate Api v3 link

Perform a simple api rest request like this :

val jsonObjectResponse = JSONObject(translate(sourceLanguageCode = sourceLanguage, targetLanguageCode = targetLanguage, textsToTranslate).awaitString())
val translations = jsonObjectResponse.getJSONArray("translations").toArray { getJSONObject(it) }.map { it.getString("translatedText") }

where "translate" function is :

private fun translate(sourceLanguageCode: String, targetLanguageCode: String, textsToTranslate: List<String>): Request =
    Fuel.post(path = "https://translation.googleapis.com/v3/projects/$PROJECT_ID:translateText?key=$API_KEY")
        .header(Headers.ACCEPT to "application/json")
        .jsonBody(
            JSONObject().apply {
                put("contents", JSONArray().apply {
                    textsToTranslate.forEach { text -> put(text) }
                })
                put("sourceLanguageCode", sourceLanguageCode)
                put("targetLanguageCode", targetLanguageCode)
            }.toString()
        )

but it returns : "HTTP Exception 401 Unautorhorized". The link doesn't mention usage of API_KEY so I suppose it's related to..

Note : Fuel is just a HTTP networking library for Kotlin/Android to avoid boiler plate code.

To resume: the first one using googleapis/java-translate was working but the second (custom) doesn't work and returns : "HTTP Exception 401 Unautorhorized".

Where am I wrong ?

Extra note: I know I'm not restricting right now to the package name of the android app but here, I just want to make it works :)

Edit

  • jsonBody function add implicitly header "Content-Type" to "application/json"
  • If apiKey can't be use in v3, which other way can I use ? I already have firebase Crashlytics, it means I already have a google service to potentially handle a communication to a google service but there's way too much documentation going all over the place, it's just terrible, it makes me sick. Which library can I use to handle credential in android application without breaking my app for "Meta-*** conflict", etc. I'm confused and lost in this ocean of information.


from How to convert googleapis/java-translate library to custom api rest request using google translation api v3 in an Android project

raise AttributeError: Response content isn't text Scarpy proxy pool. How to solve?

Raises AttributeError: Response content isn't text. I am using scrapy_proxy_pool and scrapy_user_agents. I am trying to find each and every link of target website.

import scrapy

class LinksSpider(scrapy.Spider):

    name = 'links'
    allowed_domains = ['www.chotosite.com','chotosite.com']

    extracted_links = []

    def start_requests(self):
        start_urls = 'https://www.chotosite.com'
        yield scrapy.Request(url=start_urls, callback=self.extract_link)

    def extract_link(self, response):
        # eleminating images url from links
        str_response_content_type = str(response.headers.get('content-type'))
        if str_response_content_type == "b'text/html; charset=UTF-8'" :
            
            links = response.xpath("//a/@href").extract()

            for link in links:
                if "chotosite" in link and link not in self.extracted_links:
                    self.extracted_links.append(link)
                    yield scrapy.Request(url=link, callback=self.extract_link)

                    yield {
                        "links": link
                    }

Here is my settings.py file

BOT_NAME = 'chotosite'

SPIDER_MODULES = ['chotosite.spiders']
NEWSPIDER_MODULE = 'chotosite.spiders'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False
PROXY_POOL_ENABLED = True


DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
    'scrapy_user_agents.middlewares.RandomUserAgentMiddleware': 400,
    'scrapy_proxy_pool.middlewares.ProxyPoolMiddleware': 610,
    'scrapy_proxy_pool.middlewares.BanDetectionMiddleware': 620,
}

AUTOTHROTTLE_ENABLED = True

Here is the big console output in pastebin https://pastebin.com/tRbfvxdN

And here is the traceback:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
    result = g.send(result)
  File "/usr/lib/python3/dist-packages/scrapy/core/downloader/middleware.py", line 44, in process_request
    defer.returnValue((yield download_func(request=request, spider=spider)))
  File "/usr/lib/python3/dist-packages/twisted/internet/defer.py", line 1362, in returnValue
    raise _DefGen_Return(val)
twisted.internet.defer._DefGen_Return: <200 https://www.chotosite.com>
 
During handling of the above exception, another exception occurred:
 
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
    result = g.send(result)
  File "/usr/lib/python3/dist-packages/scrapy/core/downloader/middleware.py", line 53, in process_response
    response = yield method(request=request, response=response, spider=spider)
  File "/usr/local/lib/python3.8/dist-packages/scrapy_proxy_pool/middlewares.py", line 287, in process_response
    ban = is_ban(request, response)
  File "/usr/local/lib/python3.8/dist-packages/scrapy_proxy_pool/policy.py", line 15, in response_is_ban
    if self.BANNED_PATTERN.search(response.text):
  File "/usr/lib/python3/dist-packages/scrapy/http/response/__init__.py", line 93, in text
    raise AttributeError("Response content isn't text")
AttributeError: Response content isn't text

And this is what installed on my system

Scrapy       : 1.7.3
lxml         : 4.5.0.0
libxml2      : 2.9.10
cssselect    : 1.1.0
parsel       : 1.5.2
w3lib        : 1.21.0
Twisted      : 18.9.0
Python       : 3.8.5 (default, Jul 28 2020, 12:59:40) - [GCC 9.3.0]
pyOpenSSL    : 19.0.0 (OpenSSL 1.1.1f  31 Mar 2020)
cryptography : 2.8
Platform     : Linux-5.4.0-53-generic-x86_64-with-glibc2.29



from raise AttributeError: Response content isn't text Scarpy proxy pool. How to solve?

Video Spec to fluent-FFMPEG settings

Not sure how to translate this video spec into fluent-FFmpeg. please assist.


This is the only video I have that plays on my iPhone, and I would like to reuse the video's encoding to allow other videos I have, to be converted into the same video format. resulting in having my other videos playable via iPhone and iOS. (this also happens to play on android, I would like the recommended encoding settings to also work on android)

The video should also be streamable, I know theres a flag called +faststart but not sure how to use it.


enter image description here


here is my existing code

function convertWebmToMp4File(input, output) {
  return new Promise(
    function (resolve, reject) {
  ffmpeg(input)
    .outputOptions([
      // Which settings should I put here, each on their own line/entry <-- Important plz read
      '-c:v libx264',
      '-pix_fmt yuv420p',
      '-profile:v baseline',
      '-level 3.0',
      '-crf 22',
      '-preset veryslow',
      '-vf scale=1280:-2',
      '-c:a aac',
      '-strict experimental',
      '-movflags +faststart',
      '-threads 0',
    ])
    .on("end", function () {
      resolve(true);
    })
    .on("error", function (err) {
      reject(err);
    })
    .saveToFile(output);
  });
}

TIA



from Video Spec to fluent-FFMPEG settings

Wait for Windows file I/O to complete in Python

I have a set of system tests which fire up some processes, create files etc., then shut them all down and delete the files.

I am encountering two intermittent errors on the cleanup:

On a log file created by one of the processes:

    os.remove(log_path)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: <path_to_file>

When trying to delete the output directory with shutil.rmtree:

File "C:\Python27\lib\shutil.py", line 254, in rmtree
    os.rmdir(path)
WindowsError: [Error 145] The directory is not empty: 'C:\\TestTarget\\xxx'

Both errors go away if I insert a 2 second delay before the tidyup, so I think the problem is with the time Windows takes to release the files. Obviously I'd like to avoid putting in delays in my tests, is there a way to wait until the filesystem has caught up?



from Wait for Windows file I/O to complete in Python

Unity Android load local MP3 or WAV as AudioClip

I'm able to load audio using UnityWebRequestMultimedia.GetAudioClip in the Unity Editor with the following code but when I run it on Android I am unable to load any files from the user's device.

void Start() {
    audio = GetComponent<AudioSource>();
    string fullPath = Path.Combine("file://" + previewSong);
    StartCoroutine(GetAudioClip(fullPath));
}

IEnumerator GetAudioClip(string fullPath)
{
    using (var uwr = UnityWebRequestMultimedia.GetAudioClip(fullPath, AudioType.MPEG))
    {
        ((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true;

        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            debugSongPath2.text = uwr.error;
            yield break;
        }

        DownloadHandlerAudioClip dlHandler = (DownloadHandlerAudioClip)uwr.downloadHandler;

        if (dlHandler.isDone)
        {
            audio.clip = dlHandler.audioClip;

            if (audio.clip != null)
            {
                audio.clip = DownloadHandlerAudioClip.GetContent(uwr);

                Debug.Log("Playing song using Audio Source!");
            }
            else
            {
                Debug.Log("Couldn't find a valid AudioClip.");
            }
        }
        else
        {
            Debug.Log("The download process is not completely finished.");
        }
    }
}

The errors I experience vary depending on how I form the start of the URL.

Path.Combine("file:/" + previewSong);
malformed URL

Path.Combine("file://" + previewSong); 
http:/1.1 404 not found

Path.Combine("file:///" + previewSong);
unknown error

Path.Combine("file:////" + previewSong);
unknown error

When I output the URLs on my phone they look correct. Here's an example path:

file:///storage/emulated/0/Music/Deorro/Deorro - Five Hours.mp3

I was previously loading audio from this URL successfully with WWW.GetAudioClip but that's obsolete. This leads me to believe the URL is correct. I've tried building with and without Development Mode. Not sure what else to try. I'd like to get this working with UnityWebRequestMultimedia but if there is an alternative, more effective way of loading local files I'm open to it.



from Unity Android load local MP3 or WAV as AudioClip

Sunday 29 November 2020

Elasticsearch/dataflow - connection timeout after ~60 concurrent connection

We host elatsicsearch cluster on Elastic Cloud and call it from dataflow (GCP). Job works fine in dev but when we deploy to prod we're seeing lots of connection timeout on the client side.

Traceback (most recent call last):
  File "apache_beam/runners/common.py", line 1213, in apache_beam.runners.common.DoFnRunner.process
  File "apache_beam/runners/common.py", line 570, in apache_beam.runners.common.SimpleInvoker.invoke_process
  File "main.py", line 159, in process
  File "/usr/local/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 152, in _wrapped
    return func(*args, params=params, headers=headers, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/elasticsearch/client/__init__.py", line 1617, in search
    body=body,
  File "/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py", line 390, in perform_request
    raise e
  File "/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py", line 365, in perform_request
    timeout=timeout,
  File "/usr/local/lib/python3.7/site-packages/elasticsearch/connection/http_urllib3.py", line 258, in perform_request
    raise ConnectionError("N/A", str(e), e)
elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPSConnection object at 0x7fe5d04e5690>: Failed to establish a new connection: [Errno 110] Connection timed out) caused by: NewConnectionError(<urllib3.connection.HTTPSConnection object at 0x7fe5d04e5690>: Failed to establish a new connection: [Errno 110] Connection timed out)

I increased timeout setting in elasticsearch client to 300s like below but it didn't seem to help.

self.elasticsearch = Elasticsearch([es_host], http_auth=http_auth, timeout=300)

Looking at deployment at https://cloud.elastic.co/deployments//metrics CPU and memory usage are very low (below 10%) and search response time is also order of 200ms. What could be the bottleneck here and how we can we avoid such timeouts?

As seen in below log most of requests are failing with connection timeout while successful request receives response very quick:

enter image description here

I tried ssh into the VM where we experience the connection error. netstat showed there were about 60 ESTABLISHED connections to the elastic search IP address. When I curl from the VM to elasticsearch address I was able to reproduce timeout. I can curl fine to other URLs. Also I can curl fine to elasticsearch from my local so issue is only connection between VM and elasticsaerch server.

Does dataflow (compute engine) or ElasticSearch has limitation on number of concurrent connection? I could not find any information online.



from Elasticsearch/dataflow - connection timeout after ~60 concurrent connection

Redux middleware async function

I have a redux middleware that interacts with a rest api. I recently started rewriting some fetch functions using async/await.

For this to make the most sense for me, I would need the middleware function itself to be an async function so that I can use "await" and try/catch blocks on those other async functions I have created as opposed to having to use .then, .catch.

So far I have this:

const apiMiddleware = ({
  dispatch,
  getState
}) => next => async action => {
  switch (action.type) {
   //...
   }
  next(action);
};

Please note the use of async keyword before "action". So far this seems to be working as expected, I am able to await other async functions from that middleware. However, since I was not able to find documentation on this, I was wondering if what I did truly is valid.

Thank you



from Redux middleware async function

Cannot read property 'click' of undefined while using Java Script Executor in Selenium

I am getting an error:

Cannot read property 'click' of undefined

while trying to click a button using java script executor. I have tried many different approach to click the button using action classes, webdriverwait etc but none seems to work.Java Script is working in console but when i am using in my code i am unable to click the button and getting the mentioned error

The html dom looks as below:

<div>
    <a class="button button--new-resource" href="/admin/certificate_types/new">
        <img src="/assets/icon-add-user-e2a98953aa1855b15304eb16415b536ee92e579ce89f429bcdd062faa855e261.svg" alt="Icon add user"> New Certificate Type
    </a>
</div>

My selenium script is as below

JavascriptExecutor js=(JavascriptExecutor) driver;        
js.executeScript("var x= document.getElementsByClassName('button button--new-resource')[0];"+"x.click();");


from Cannot read property 'click' of undefined while using Java Script Executor in Selenium

Puppeteer goto with query parameters does not work

I am using Puppeteer page.goto(url) to to navigate to a page that ends with with .html?page=2

So a page I would call would look something like this:

https://mypage.com/some-category.html?page=2

Unfortunately the query params are ignored. When I call page.url() the return value is the page that I have called without the query params which looks like this:

https://mypage.com/some-category.html

Executing page.goto(url, { waitUntil: [anyhting] }) results in a timeout

Help would be greatly appreciated.



from Puppeteer goto with query parameters does not work

How to determine whether Vue component is destroyed due to hot reload?

I have a Vue component that manages heavy resources that are expensive to set up (namely, WebRTC PeerConnection with video streams). The component is designed in a way so these heavy resources are saved elsewhere and are preserved across module reloads. When component is reloaded (destroyed & created again) it checks for saved stream and just redeploys it without recreation.

This, however, implies that destroyed hook actualy does not destroy anything. Which is not expected behavior when user leaves the page and component is destroyed completely, not for reloading.

So the question is: how to tell whether the component is destroyed to be reloaded (and resources should be left intact) or because it is no longer needed (and resources should be closed)?

I use Nuxt, so webpack configuration and other low-level related things are managed by Nuxt itself. No changes to Nuxt config were made in this area.



from How to determine whether Vue component is destroyed due to hot reload?

Python library for hierarchical sets (or set operations on trees)

Let's imagine I have the following hierarchy/tree:

                Commit
             /     |    \
           /      Fix     \
         /       /   \      \
  Feature   CodeFix  DocFix  Refactoring

I want to be able to define sets where the elements are the leaves of this tree. The way to do it with standard python sets would be to list all the leaves to be included, e.g. {Feature, CodeFix, DocFix}. What I want is to use a shortcut and pass the entire sub-trees instead. For that, we need some abstraction level that handles that, let's say class HSet. With such class, it should be possible not only to create a set like this:HSet(Feature, BugFix, DocFix) but also like this: HSet(Feature, Fix). Both alternatives should yield the same object and represent the same set since Fix == CodeFix|DocFix according to the hierarchy.

Having such a shortcut would be especially beneficial if Fix had dozens of children. Having to create large sets in the code manually is exactly my use case. Except for set creation, I need also a shortcut for listing the elements in a set. For example, if a set contains all the leaves in the hierarchy, it could be represented by the root of the hierarchy, which would be {Commit} for the example provided above. Please see the examples that will hopefully illustrate the concept better.

>>> from somelibrary import HSet 

>>> commit = HSet.create_root_element("Commit")
>>> feature, fix, refactoring = commit.add_children("Feature", "Fix", "Refactoring")
>>> code_fix, doc_fix = fix.add_children("CodeFix", "DocFix")

>>> str(code_fix | doc_fix)
'{Fix}'
>>> str(code_fix | refactoring)
'{CodeFix|Refactoring}'
>>> str(feature | fix | refactoring)
'{Commit}'

>>> str(~ code_fix)
'{Feature|DocFix|Refactoring}'
>>> str(~ commit)
'{}'
>>> str(~ (feature | refactoring))
'{Fix}'

I am curious if there exists such somelibrary that implements this.

Update: Implementation

In the meantime, I wrote my implementation of the concept I was talking about. But I am always concerned about not reinventing the wheel. So, I would be grateful to pointers to existing data structures in the standard python library or custom libraries that can be used to fully/partially replace my code.

hset.py

from typing import List

from hset.tree import _Tree


class HSet:
    def __init__(self, subtrees: List[_Tree], domain: _Tree):
        self.subtrees = domain.collapse_subtrees(subtrees)
        self.domain = domain

    @classmethod
    def create_root_element(cls, label: str) -> 'HSet':
        tree = _Tree(label, None, [])
        return cls([tree], tree)

    def add_children(self, *labels: str) -> List['HSet']:
        if len(self.subtrees) != 1:
            raise ValueError(f"Cannot add children to this HSet since it has multiple root elements: {self}")
        if self.subtrees[0].children:
            raise ValueError(f"This HSet already has children.")

        trees = self.subtrees[0].add_children(*labels)
        return list(map(lambda t: self._create([t]), trees))

    def _create(self, subtrees: List[_Tree]) -> 'HSet':
        return HSet(subtrees, self.domain)

    def __str__(self):
        return '{' + "|".join(map(lambda x: x.label, self.subtrees)) + '}'

    def __invert__(self) -> 'HSet':
        return self._create(self.domain.complement(self.subtrees))

    def __or__(self, other: 'HSet') -> 'HSet':
        if self.domain != other.domain:
            raise ValueError("Cannot perform operations on HSets with different domains")

        return self._create(self.domain.collapse_subtrees(self.subtrees + other.subtrees))

tree.py

from dataclasses import dataclass
from typing import Optional, List


@dataclass
class _Tree:
    label: str
    parent: Optional['_Tree']
    children: List['_Tree']

    def add_children(self, *labels: str) -> List['_Tree']:
        children = [_Tree(label, self, []) for label in labels]
        self.children = children
        return children

    def collapse_subtrees(self, subtrees: List['_Tree']) -> List['_Tree']:
        if self in subtrees:
            return [self]
        elif not self.children:
            return []
        fully_covered = True
        res = []
        for child in self.children:
            collapsed_child = child.collapse_subtrees(subtrees)
            fully_covered &= (collapsed_child == [child])
            res.extend(collapsed_child)

        return [self] if fully_covered else res

    def complement(self, subtrees: List['_Tree']) -> List['_Tree']:
        if self in subtrees:
            return []
        elif not self.children:
            return [self]
        return [elem for lst in map(lambda x: x.complement(subtrees), self.children) for elem in lst]

Cheers, Hlib.



from Python library for hierarchical sets (or set operations on trees)

Python NEAT not learning further after a certain point

It seems that my program is trying to learn until a certain point, and then it's satisfied and stops improving and changing at all. With my testing it usually goes to a value of -5 at most, and then it remains there no matter how long I keep it running. The result set does not change either.

Just to keep track of it I made my own kind of logging thing to see which did best. The array of ones and zeroes is referring to how often the AI made a right choice (1), and how often the AI made a wrong choice (0).

My goal is to get the AI to repeat a pattern of going above 0.5 and then going below 0.5, not necessarily find the odd number. This was meant as just a little test to see if I could get an AI working properly with some basic data, before doing something a bit more advanced.

But unfortunately it's not working and I am not certain why.

The code:

import os
import neat

def main(genomes, config):
    networks = []
    ge = []
    choices = []

    for _, genome in genomes:
        network = neat.nn.FeedForwardNetwork.create(genome, config)
        networks.append(network)

        genome.fitness = 0
        ge.append(genome)

        choices.append([])

    for x in range(25):
        for i, genome in enumerate(ge):
            output = networks[i].activate([x])

            # print(str(x) + " - " + str(i) + " chose " + str(output[0]))
            if output[0] > 0.5:
                if x % 2 == 0:
                    ge[i].fitness += 1
                    choices[i].append(1)
                else:
                    ge[i].fitness -= 5
                    choices[i].append(0)
            else:
                if not x % 2 == 0:
                    ge[i].fitness += 1
                    choices[i].append(1)
                else:
                    ge[i].fitness -= 5
                    choices[i].append(0)
                    pass
            
            # Optional death function, if I use this there are no winners at any point.
            # if ge[i].fitness <= 20:
            #     ge[i].fitness -= 100
            #     ge.pop(i)
            #     choices.pop(i)
            #    networks.pop(i)
    if len(ge) > 0:
        fittest = -1
        fitness = -999999
        for i, genome in enumerate(ge):
            if ge[i].fitness > fitness:
                fittest = i
                fitness = ge[i].fitness

        print("Best: " + str(fittest) + " with fitness " + str(fitness))
        print(str(choices[fittest]))
    else:
        print("Done with no best.")

def run(config_path):
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet,
                                neat.DefaultStagnation, config_path)

    pop = neat.Population(config)

    #pop.add_reporter(neat.StdOutReporter(True))
    #stats = neat.StatisticsReporter()
    #pop.add_reporter(stats)

    winner = pop.run(main, 100)

if __name__ == "__main__":
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, "config-feedforward.txt")
    run(config_path)

The NEAT config:

[NEAT]
fitness_criterion     = max
fitness_threshold     = 100000
pop_size              = 5000
reset_on_extinction   = False

[DefaultGenome]
# node activation options
activation_default      = tanh
activation_mutate_rate  = 0.0
activation_options      = tanh

# node aggregation options
aggregation_default     = sum
aggregation_mutate_rate = 0.0
aggregation_options     = sum

# node bias options
bias_init_mean          = 0.0
bias_init_stdev         = 1.0
bias_max_value          = 30.0
bias_min_value          = -30.0
bias_mutate_power       = 0.5
bias_mutate_rate        = 0.7
bias_replace_rate       = 0.1

# genome compatibility options
compatibility_disjoint_coefficient = 1.0
compatibility_weight_coefficient   = 0.5

# connection add/remove rates
conn_add_prob           = 0.5
conn_delete_prob        = 0.5

# connection enable options
enabled_default         = True
enabled_mutate_rate     = 0.1

feed_forward            = True
initial_connection      = full

# node add/remove rates
node_add_prob           = 0.2
node_delete_prob        = 0.2

# network parameters
num_hidden              = 0
num_inputs              = 1
num_outputs             = 1

# node response options
response_init_mean      = 1.0
response_init_stdev     = 0.0
response_max_value      = 30.0
response_min_value      = -30.0
response_mutate_power   = 0.0
response_mutate_rate    = 0.0
response_replace_rate   = 0.0

# connection weight options
weight_init_mean        = 0.0
weight_init_stdev       = 1.0
weight_max_value        = 30
weight_min_value        = -30
weight_mutate_power     = 0.5
weight_mutate_rate      = 0.8
weight_replace_rate     = 0.1

[DefaultSpeciesSet]
compatibility_threshold = 3.0

[DefaultStagnation]
species_fitness_func = max
max_stagnation       = 20
species_elitism      = 2

[DefaultReproduction]
elitism            = 2
survival_threshold = 0.2


from Python NEAT not learning further after a certain point

How to change centered slide by clicking on desired slide in swiper.js?

I use swiper in centeredSlides mode and loop option is true. I want to when I click on a slide, that slide set as centered slide in swiper carousel. Swiper give me clicked slide index, but how to use it for change the centered slide?

These are my options:

  slidesPerView: 4.5,
  spaceBetween: 20,
  updateOnWindowResize: true,
  loop: true,
  grabCursor: true,
  centeredSlides: true,
  centeredSlidesBounds: true,
  initialSlide: 0,
  on: {
    click() {
      console.log(this.clickedIndex);
    },
  },


from How to change centered slide by clicking on desired slide in swiper.js?

How to use Firebase Cloud Messaging with NextJS API Routes

According to the Firebase Cloud Messaging docs on Setting up Javascript Client, it is required that you place a firebase-messaging-sw.js file in the root of your domain. In the NextJS examples with-firebase-cloud-messaging, the firebase-messaging-sw.js is configured using a custom server.

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.get('/service-worker.js', (req, res) => {
    app.serveStatic(req, res, './.next/service-worker.js')
  })

  const serviceWorkers = [
    {
      filename: 'service-worker.js',
      path: './.next/service-worker.js',
    },
    {
      filename: 'firebase-messaging-sw.js',
      path: './static/firebase-messaging-sw.js',
    },
  ]

  serviceWorkers.forEach(({ filename, path }) => {
    server.get(`/${filename}`, (req, res) => {
      app.serveStatic(req, res, path)
    })
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

My Application is already using API Routes, so do I need to also add a custom server, or is there a way this can be achieved with API Routes?



from How to use Firebase Cloud Messaging with NextJS API Routes

Magnifying glass that follows cursor for canvas

I'm working on a t-shirt designer for a client of mine and I made it using html5 canvas. The shirt designer is now finished but he requested I add a magnifying glass (something like this: http://mlens.musings.it/). I've found a lot of similar scripts out there, however, they all seem to have one thing in common they use a small and a large image. Using canvas, however, I have a different scenario and have been stumped on how I can add a magnifying glass to magnify where ever the cursor is on canvas.

Are there any scripts that exist that can get this done? or what other options would I have?



from Magnifying glass that follows cursor for canvas

Python requests https: code 403 without but code 200 when using BurpSuite

I'm currently trying to scrap retailmenot.com this is how my code looks so far:

import requests
from collections import OrderedDict

s = requests.session()

s.headers = OrderedDict()
s.headers["Connection"] = "close"
s.headers["Upgrade-Insecure-Requests"] = "1"
s.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
s.headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
s.headers["Sec-Fetch-Site"] = "none"
s.headers["Sec-Fetch-Mode"] = "navigate"
s.headers["Sec-Fetch-Dest"] = "document"
s.headers["Accept-Encoding"] = "gzip, deflate"
s.headers["Accept-Language"] = "en-GB,en-US;q=0.9,en;q=0.8"

s.get("https://www.retailmenot.com/sitemap/A")

When I use this code I instantly get redirected to a CloudFlare page. That said whenever I pass my traffic through burpsuite by replacing the last line of my code with this one:

s.get("https://www.retailmenot.com/sitemap/A", proxies = {"https":"https://127.0.0.1:8080"}, verify ="/Users/Downloads/cacert (1).pem")

I get straight to the website. I find this a bit strange and was wondering If anyone could possibly explain to me why this is happing and if there's a way to get similar results by using some different certificate (As in order to use the BurpSuite Certificate I need to keep the app open). Many thanks in advance!



from Python requests https: code 403 without but code 200 when using BurpSuite

How to send a progress of operation in a FastAPI app?

I have deployed a fastapi endpoint,

from fastapi import FastAPI, UploadFile
from typing import List

app = FastAPI()

@app.post('/work/test')
async def testing(files: List(UploadFile)):
    for i in files:
        .......
        # do a lot of operations on each file

        # after than I am just writing that processed data into mysql database
        # cur.execute(...)
        # cur.commit()
        .......
    
    # just returning "OK" to confirm data is written into mysql
    return {"response" : "OK"}

I can request output from the API endpoint and its working fine for me perfectly.

Now, the biggest challenge for me to know how much time it is taking for each iteration. Because in the UI part (those who are accessing my API endpoint) I want to help them show a progress bar (TIME TAKEN) for each iteration/file being processed.

Is there any possible way for me to achieve it? If so, please help me out on how can I proceed further?

Thank you.



from How to send a progress of operation in a FastAPI app?

How to list all root folder and shares on the Google Drive API v3 while paging and using order by?

I've seen a few questions about this but none cover my scenario.

Basically what I want is to use tokens to do paging and also list all folders and files in the root folder including shared files and folders.

This appears to be working, but once I add orderBy it doesn't work well. It works ok with sorting if I remove or sharedWithMe = true but once I add it it like the shared items aren't sorted.

What am I doing wrong?

This is my code (Kotlin and on Android):

val response =
 gDriveClient.files()
 .list()
 .setSpaces("drive")
 .setCorpora("user")
 .setFields("files(id, name, size, modifiedTime, mimeType, parents, quotaBytesUsed),nextPageToken")
 .setQ("('root' in parents or sharedWithMe = true) and trashed = false")
 .setOrderBy("folder,name")
 .setPageSize(params.loadSize)
 .setPageToken(token)


from How to list all root folder and shares on the Google Drive API v3 while paging and using order by?

How to use Firebase Cloud Messaging with NextJS API Routes

According to the Firebase Cloud Messaging docs on Setting up Javascript Client, it is required that you place a firebase-messaging-sw.js file in the root of your domain. In the NextJS examples with-firebase-cloud-messaging, the firebase-messaging-sw.js is configured using a custom server.

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.get('/service-worker.js', (req, res) => {
    app.serveStatic(req, res, './.next/service-worker.js')
  })

  const serviceWorkers = [
    {
      filename: 'service-worker.js',
      path: './.next/service-worker.js',
    },
    {
      filename: 'firebase-messaging-sw.js',
      path: './static/firebase-messaging-sw.js',
    },
  ]

  serviceWorkers.forEach(({ filename, path }) => {
    server.get(`/${filename}`, (req, res) => {
      app.serveStatic(req, res, path)
    })
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

My Application is already using API Routes, so do I need to also add a custom server, or is there a way this can be achieved with API Routes?



from How to use Firebase Cloud Messaging with NextJS API Routes

How to Concatenate 5 Images Out Of Multiple Images In a Folder

I have a folder which has multiple images lets say images names are----

AB_1.jpg, AB_2.jpg, AB_3.jpg, AB_4.jpg, AB_5.jpg, AB_6.jpg, AB_7.jpg, AB_8.jpg, BC_1.jpg, BC_2.jpg, BC_3.jpg, CA_1.jpg, CA_2.jpg

Here my objective is to concatenate all the images till _5 or less than _5 as one image....

So basically what I am saying is that--- AB_1.jpg, AB_2.jpg, AB_3.jpg, AB_4.jpg, AB_5.jpg

will get concatenated vertically and file name lets say will be AB_Concat.jpg

_6,_7,_8 are skipped because we want to concatenate only images till _5 as one....

Similarly,, BC_1.jpg, BC_2.jpg, BC_3.jpg

will get concatenated vertically and file name lets say will be BC_Concat.jpg as you can see here BC_3 is last one which is less than _5 so all will be concatenated vertically.....

So if anyone have any idea on how to achieve the same please help....

This question is not similar to the once where two images are concatenated since here we are concatenating images on the basis of value after underscore in a image....

This is something which I tried--- '''python

import cv2

import shutil

import numpy as np

import os

from PIL import Image

path = r"D:\split"

out = r"D:\concat_test"

os.makedirs(out,exist_ok=True)

imag_name =[]

imag_name1 = []

for img in os.listdir(path):

folder  = img.rsplit("_",1)[0]  

imag_name1.append((folder,img))

images = cv2.imread(os.path.join(path,img),0)

imag_name.append((folder,images))

to create a folder for multiple images contain same name

for image,name in zip(imag_name,imag_name1):

if image[0] == name[0]:

    folder_n = os.path.join(out,name[0])

    final_fldr = os.path.join(folder_n,name[1])

    os.makedirs(folder_n,exist_ok=True)

    cv2.imwrite(final_fldr,image[1])

to concatinate the images

for root,dirs,files in os.walk(out):

np_images = [cv2.imread(os.path.join(root,file),0) for file in files]

np_name = list(set([file.rsplit("_",1)[0] for file in files]))


if len(np_images) != 0:

    print(np_name)

    concat = cv2.vconcat(np_images)

    concatinated_images = os.path.join(out,"concatinated_images")

    os.makedirs(concatinated_images,exist_ok=True)

    cv2.imwrite(os.path.join(concatinated_images,*np_name)+".tif",concat)

#to remove the unwanted folder

for remove_folder in os.listdir(out):

if remove_folder != "concatinated_images":

    folders_to_remove = os.path.join(out,remove_folder)

    shutil.rmtree(folders_to_remove)

'''



from How to Concatenate 5 Images Out Of Multiple Images In a Folder

How to add a horizontal scroll indicator for Android TabLayout

I am looking to add a horizontal scroll view for an Android TabLayout.

The TabLayout has multiple tabs in it and is scrollable. Due to multiple tabs on it, some of them are not visible at the first glance. The users have to scroll to get to the tabs on the far right(which are usually hidden) and so those tabs are not getting user's attention.

The thought is to have a horizontal scroll indicator or an arrow indicating that there are more tabs to the right so the users can scroll to find/use them.

The design idea is to have a scrollIndicator and not have a tabIndicator. I found the following image from Google which is closer to the idea. enter image description here

Thanks in advance,



from How to add a horizontal scroll indicator for Android TabLayout

Classify if point is within specified area using threshold - python

The aim of this question is to obtain some advice. I've got a df that contains xy points. I want to remove these points if they are located within a polygon. This is exhibited as area below. The points will come and go from this area, so I only want to remove when they are definitively placed within there.

The central dilemma is I don't want to pass a strict rule here. Because the points are fluid, I'm hoping to incorporate flexibility. For instance, some points may pass through this area temporarily and shouldn't be removed. While other points are located within the area long enough that they should be removed.

The obvious approach is to pass some method of threshold here. Using df1 below, A is located within the area for 3 frames, while B is located within the area for 7 frames. If I pass a threshold of >5 frames, B should be removed for all frames within this area, while A shouldn't be impacted.

The issue is, it has to be consecutive frames. The points will come and go, so I only want to remove after 5 consecutive frames.

Are there any other approaches I should consider?

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import random

# general dataframe
df = pd.DataFrame(np.random.randint(-25,125,size=(500, 2)), columns=list('XY'))
labels = df['X'].apply(lambda x: random.choice(['A', 'B']) ) 
df['Label'] = labels
df['Time'] = range(1, len(df) + 1)

# edge cases
df1 = pd.DataFrame({
    'X' : [20,10,0,-5,-5,-5,0,10,20,30,20,10,0,-5,-5,-5,-5,-5,-5,-5],  
    'Y' : [50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50],                  
    'Label' : ['A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','B','B','B','B'], 
    'Time' : [501,502,503,504,505,506,507,508,509,510,501,502,503,504,505,506,507,508,509,510],                         
    })

fig, ax = plt.subplots()
ax.set_xlim(-50, 150)
ax.set_ylim(-50, 150)

# designated area
x = ([1.5,-0.5,-1.25,-0.5,1.5,-11,-11,1.5]) 
y = ([75,62.5,50,37.5,25,25,75,75])

line = plt.plot(x,y)
Oval_patch = mpl.patches.Ellipse((50,50), 100, 150, color = 'k', fill = False)
ax.add_patch(Oval_patch)

pts = df[['X','Y']]
mask = line[0].get_path().contains_points(pts)
df = df[~mask]

A_X = np.array(df1.groupby(['Time'])['X'].apply(list))
A_Y = np.array(df1.groupby(['Time'])['Y'].apply(list))

ax.scatter(A_X[0], A_Y[0], c = 'purple', alpha = 0.2)


from Classify if point is within specified area using threshold - python

When is a fragment not attatched to an activity but only a context?

At the docs for Fragment.getActivity() it says: Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.

But how can a fragment not be associated with an activity? I mean, don't I always need an activity to show anything in Android?



from When is a fragment not attatched to an activity but only a context?

Jetpack Compose model list becomes jumbled when adding new items

I have an issue with Jetpack compose displaying a model containing a ModelList of items. When new items are added, the order of the UI elements becomes incorrect.

Here's a very simple CounterModel containing a ModelList of ItemModels:

@Model
data class CounterModel(
    var counter: Int = 0,
    var name: String = "",
    val items: ModelList<ItemModel> = ModelList()
)

@Model
data class ItemModel(
    var name: String
)

The screen shows two card rows for each ItemModel: RowA and RowB. When I create this screen initialised with the following CounterModel:

val model = CounterModel()
model.name="hi"
model.items.add(ItemModel("Item 1"))
model.items.add(ItemModel("Item 2"))
CounterModelScreen(model)

...it displays as expected like this:

Item 1 Row A

Item 1 Row B

Item 2 Row A

Item 2 Row B

When I click my 'add' button, to insert a new ItemModel, I simply expect to see

Item 3 Row A

Item 3 Row B

At the bottom. But instead, the order is jumbled, and I see two rowAs then two rowBs:

Item 1 Row A

Item 1 Row B

Item 2 Row A

Item 3 Row A

Item 3 Row B

Item 2 Row B

I don't really understand how this is possible. The UI code is extremely simple: loop through the items and emit RowA and RowB for each one:

for (i in counterModel.items.indices) {
    RowA(counterModel, i)
    RowB(counterModel, i)
}

Using Android Studio 4.0C6

Here's the complete code:

@Composable
fun CounterModelScreen(counterModel: CounterModel) {
    Column {
        TopAppBar(title = {
            Text(
                text = "Counter Model"
            )
        })

        CounterHeader(counterModel)
        for (i in counterModel.items.indices) {
            RowA(counterModel, i)
            RowB(counterModel, i)
        }
        Button(
            text = "Add",
            onClick = {
                counterModel.items.add(ItemModel("Item " + (counterModel.items.size + 1)))
            })
    }
}

@Composable
fun CounterHeader(counterModel: CounterModel) {
    Text(text = counterModel.name)
}

@Composable
fun RowA(counterModel: CounterModel, index: Int) {
    Padding(padding = 8.dp) {
        Card(color = Color.White, shape = RoundedCornerShape(4.dp)) {
            Column(crossAxisSize = LayoutSize.Expand) {
                Text(
                    text = counterModel.items[index].name
                )
                Text(text = "Row A")
            }
        }
    }
}

@Composable
fun RowB(counterModel: CounterModel, index: Int) {
    Padding(padding = 8.dp) {
        Card(color = Color.Gray, shape = RoundedCornerShape(4.dp)) {
            Column(crossAxisSize = LayoutSize.Expand) {
                Text(
                    text = counterModel.items[index].name
                )
                Text(text = "Row B")
            }
        }
    }
}


from Jetpack Compose model list becomes jumbled when adding new items

Android app link not working after the application is made live in play store

I have implemented Android app links based on the below links.

https://developer.android.com/studio/write/app-link-indexing.html

https://developer.android.com/training/app-links

I have hosted assetlinks file into our domain https://ourdomain/.well-known/assetlinks.json And also I have verified this using https://developers.google.com/digital-asset-links/tools/generator and from android studio's App Links Assitant also. and got verified status from both the ways.

Now when I generate a signed build and tested it via google drive links. Android app link works as expected(on click of the link the application gets open without opening disambiguation dialog for android version 6.0 and above).

After uploading the same version to play store it's not working.

Below is the code used in the manifest file.

            <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="https"
                android:host="<ourdomain>" />
        </intent-filter>

EDIT: Android app link did work as expected for one day after uploading it to the play store. and started opening disambiguation dialog again on the second day. Any idea what could be the issue?

The same version from the play store gave me two different Statuses as Ask and Always on a different day.

enter image description here enter image description here

adb shell dumpsys package domain-preferred-apps

When I run the above command



from Android app link not working after the application is made live in play store