Tuesday 31 May 2022

Android: View Visibility set to View.VISIBLE but View is not Visible

In my app (general construction described below), I have a custom dialog, built of a bunch of views and a blur-background view.
There are two ways to open that dialog:

  1. Clicking a button inside the app triggers the method that opens this dialog.
  2. A notification is shown when the dialog can be opened, and in the notification, there's a button that opens the app and is also supposed to open the dialog (By calling a BroadcastReceiver that lives in the same fragment as the dialog, and in the BroadcastReceiver I call the method that opens the dialog).

The first method works - clicking the button opens the dialog when it's supposed to.
The second, however, opens the app but not the dialog (To clarify - opening the dialog means changing its views visibility to View.VISIBLE).

To check what goes wrong, I used a Toast message that shows the visibility of the dialog every time the method that opens the dialog gets called. The Toast message shows "VISIBLE", so that means the Views visibility is set to View.VISIBLE indeed - but the dialog is not shown, nor the blur-background.

General Construction: The app has multiple Fragments, stored inside a view pager, inside the MainActivity and the dialog lives in the main fragment.

Might Be Relevant: when clicking the notifications button, the app opens, but the notification panel stays fully opened. The Toast message shows behind the notification panel.

Why doesn't the dialog show?
And how can I fix it?



from Android: View Visibility set to View.VISIBLE but View is not Visible

Django Rest Framework import OpenAPI spec from other service to generate Schema

My system consists of multiple services that generate their own OpenAPI specifications. For one endpoint in my Django service I want the input schema to be of a type that is specified at another service, is there somehow a way to retrieve/import/reference to a type that is part of another service?

(Currently just using the schemas from DRF but thinking of using drf-spectacular)

In the end I want the services to dynamically generate full OpenAPI specs (and sometimes those can be based on each other)



from Django Rest Framework import OpenAPI spec from other service to generate Schema

How to rotate arrowheads in 3D quiver in matplotlib?

I'm trying to replicate the following plot using python and matplotlib. Plot I want to replicate However, the best I have been able to produce is the following My attempt

The main issue here is the not in-plane arrows heads, even if I am not satisfied with the quality of the plot in general. I've searched for a solution to use a 2D quiver in a 3D plot but I haven't found any useful information about how to do that. Do you know any other way to achieve in-plane arrowheads? In general, any suggestion on how to improve the quality of this plot would be welcomed.


import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

params = {
   'font.family' : 'serif',
   'mathtext.fontset': 'stix',
   'axes.labelsize': 13,
   'legend.fontsize': 8,
   'xtick.labelsize': 13,
   'ytick.labelsize': 13,
   'text.usetex': True,
   'figure.figsize': [10, 5]
   }


plt.rcParams.update(params)

plt.close('all')


x_ax = np.linspace(-10, 10, 24)
y_ax = np.linspace(-10, 10, 24)

x, y = np.meshgrid(x_ax, y_ax, indexing='ij')

r = np.sqrt(x**2 + y**2)

j_x = -y/r*(- np.exp(-np.abs(r)) + np.exp(-np.abs(r)/2) )*2
j_y = +x/r*(- np.exp(-np.abs(r)) + np.exp(-np.abs(r)/2) )*2

#c = np.arctan2(x, -y)
c = np.sqrt(j_x**2 + j_y**2)
c = (c.ravel() - c.min()) / c.ptp()
c = np.concatenate((c, np.repeat(c, 2)))
c = cm.jet(c)
#c = plt.cm.hsv(c)

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.quiver(x, y, 0, j_x, j_y, 0, colors=c, length=1.2, pivot='middle')


t = np.linspace(-10, 10, 200)

psi = 1 - np.exp(-np.abs(t))
b = np.exp(-t**2)
j_abs = np.abs(t)*np.exp(-t**2)*2
#j_abs = (- np.exp(-np.abs(t)) + np.exp(-np.abs(t)/2) )*2

ax.plot(t, psi, zs=0, zdir='y', label=r"$|\psi|$")
ax.plot(t, b, zs=0, zdir='y', label=r"$|\vec B|$")
ax.plot(t, j_abs, zs=0, zdir='y', label=r"$|\vec j|$")

ax.legend()

ax.set_proj_type('ortho')
ax.set_axis_off()

ax.set_zlim([-0.2, 1.4])
ax.view_init(elev=45, azim=90)
ax.dist=5
fig.savefig("vortex.pdf", bbox_inches="tight")



from How to rotate arrowheads in 3D quiver in matplotlib?

Duplicate keys detected: 'X'. This may cause an update error. in VueJS datatable search

In my laravel vue application I have following datatable with some filters in a vue component(department-user-list.vue).

<template>
    <div>
        <cs-card
            :cardButton="false"
            :title="`Team members`"
        >
            <template slot="header-action">
                <div class="inline-block mr-4" direction-from="top">
                    <open-overlay identifier="corporateInviteEmployeeToDepartmentModal">
                        <cs-button size="small" variant="secondary">
                            Invite team member
                        </cs-button>
                    </open-overlay>
                </div>
                <div class="inline-block" direction-from="top">
                    <cs-button @click="redirectToAssignation" size="small">
                        Assign team member
                    </cs-button>
                </div>
            </template>
            <Datatable
                v-model="selectedForAction"
                :data="dataset"
                :headers="headers"
                :is-loading="isLoading"
                :has-action-bar-column="true"
                :key-id="`id`"
                :search-panel="{placeholder: 'Search team member...'}"
                @change="handlePaginationChange"
                @paginate="loadDepartmentEmployees"
            >
                <!--Filter Slot-->
                <template v-slot:filters>
                    <!--Nationality filter-->
                    <div class="w-2/12 pl-4 h-auto">
                        <cs-multiple-select
                            v-model="nationalitiesFilter"
                            :options="countries"
                            key-id="id"
                            label="name"
                            name="nationality"
                            placeholder="Nationality"
                        >
                        </cs-multiple-select>
                    </div>
                    <!--Certificate Status filter-->
                    <div class="w-6/12 pl-4 h-auto">
                        <cs-multiple-select
                            v-model="certificateStatusFilter"
                            :options="certificateStatus"
                            name="certificateStatusFilter"
                            placeholder="Qualification status"
                            @input="loadDepartmentEmployees"
                        />
                    </div>
                    <!--Matrix Status filter-->
                    <div class="w-4/12 pl-4 h-auto">
                        <cs-multiple-select
                            v-model="matrixStatusFilter"
                            :options="matrixStatus"
                            key-id="value"
                            label="label"
                            name="matrixStatusFilter"
                            placeholder="Matrix status"
                            @input="loadDepartmentEmployees"
                        />
                    </div>
                     <!--Employee Type  filter-->
                        <div class="w-4/12 pl-4 h-auto">
                            <cs-multiple-select
                                v-model="selectedEmployeeTypes"
                                :options="employeeType"
                                key-id="value"
                                label="label"
                                name="selectedEmployeeTypes"
                                placeholder="Employee type"
                                @input="loadDepartmentEmployees"
                            >
                            </cs-multiple-select>
                        </div>
                </template>

                <!--Table Header-->
                <template v-slot:header.country="{ header}">
                    <span class="material-icons-outlined">language</span>
                </template>

                <!--Table Body-->
                <template v-slot:item.name="{ item }">
                    <div class="flex items-center cursor-pointer">
                        <div class="rounded-full w-8 h-8 mr-4 overflow-hidden">
                            <img :src="item.profile_image[0].url" alt=""
                                 class="w-full h-full object-cover">
                        </div>
                        <a :href="employeeDetailRoute(item)">
                            <span class="text-certstyle-titles font-bold leading-loose"></span>
                        </a>
                        <span
                            v-if="item.is_subcontractor && item.company_name"
                            :title="item.company_name"
                            class="text-certstyle-text-light bg-certstyle-background flex font-semibold cursor-help  text-xs rounded mx-2 py-1 px-2"
                        >
                            
                             <span v-if="item.company_name.length > 10">...</span>
                        </span>
                    </div>
                </template>
                <template v-slot:item.job_title="{ item }">
                    
                </template>
                <template v-slot:item.country="{ item }">
                <span v-if="item.country" class="font-normal">
                    <country-flag width="w-5" :country-code="item.country.country_code"></country-flag>
                </span>
                </template>
                <template v-slot:item.certificate_status="{ item }">
                    <div class="status--summary--component inline-block mr-2 relative"
                         @click="getValidityStatus(item.certificate_matrix) !== 'all valid' &&
                            getValidityStatus(item.certificate_matrix) !== '-'
                             ? openCertificatesModal(item) : null
                         ">
                        <label :class="getValidityStatusClass(item.certificate_matrix)" class="badge">
                            
                        </label>
                    </div>
                </template>
                <template v-slot:item.matrix_status="{ item }">
                    <div class="status--summary--component inline-block mr-2 relative"
                         @click="getMatrixStatus(item.certificate_matrix) === 'non compliant'
                            ? openCertificatesModal(item)
                            : null
                         ">
                        <label :class="getMatrixStatusClass(item.certificate_matrix)" class="badge">
                            
                        </label>
                    </div>
                </template>
                <template v-slot:actionItems="slotProps">
                    <DatatableActionbarItem
                        :slot-props="slotProps"
                        identifier="removeConfirmationModal"
                        label="Remove"
                        variant="danger"
                    />
                </template>
                <template v-slot:rowActionItems="slotProps">
                    <DatatableActionbarItem
                        icon=""
                        label="Contact details"
                        @click.native="openContactDetailsModal(slotProps.item)"
                        :slot-props="slotProps"
                    />
                </template>
            </Datatable>


            <modal-md
                v-if="selectedEmployee !== null"
                :options="{ useDefaultContentStyling: false }"
                      :identifier="`statusSummaryComponent`">
                <template slot="modal_title">
                    Qualifications
                    <span v-if="selectedEmployee !== null && selectedEmployee !== undefined">
                            
                        </span>
                </template>


                <div class="bg-white" slot="modal_content">
                    <div
                        class="flex items-center justify-between text-certstyle-text-light bg-white border-certstyle-border border-b text-sm py-2 px-10">
                        <cs-dashboard-table-header-item-unstyled :item="`statusSummaryCertificateTitle`">
                            <p>Qualification</p>
                        </cs-dashboard-table-header-item-unstyled>

                        <cs-dashboard-table-header-item-unstyled :item="`statusSummaryCertificateStatus`">
                            <p>Validity Status</p>
                        </cs-dashboard-table-header-item-unstyled>

                        <cs-dashboard-table-header-item-unstyled :item="`statusSummaryMatrixStatus`">
                            <p>Matrix Status</p>
                        </cs-dashboard-table-header-item-unstyled>

                    </div>

                    <!--Certificates-->
                    <div class="text-certstyle-titles">
                        <div v-for="certificate in selectedEmployee.certificate_matrix"
                             v-if="selectedEmployee.certificate_matrix.length > 0"
                             class="table--row flex items-center justify-between border-certstyle-border last:border-b-0 border-b px-10 py-4">
                            <!-- Title -->
                            <cs-dashboard-table-item-unstyled
                                class="w-1/2"
                                :item="`statusSummaryCertificateTitle`">
                                <p :title="certificate.title" class=" ">
                                    
                                </p>
                            </cs-dashboard-table-item-unstyled>

                            <cs-dashboard-table-item-unstyled class="w-32" :item="`statusSummaryCertificateStatus`">
                                <div class="flex items-center justify-start w-full">
                                    <!--Expired styling-->
                                    <label v-if="certificate.matrix_status === 0"
                                           class="badge badge-danger">
                                        -
                                    </label>

                                    <!--Expires styling-->
                                    <label v-if="certificate.matrix_status &&  certificate.expired === 1"
                                           class="badge badge-danger">
                                        expired
                                    </label>
                                    <!--Expires styling-->
                                    <label v-if="certificate.matrix_status &&  certificate.expire_soon === 1"
                                           class="badge badge-danger">
                                        expires soon
                                    </label>

                                    <!--Active styling-->
                                    <label
                                        v-if="certificate.matrix_status &&  certificate.expire_soon === 0 && certificate.expired === 0"
                                        class="badge badge-success">
                                        active
                                    </label>
                                </div>
                            </cs-dashboard-table-item-unstyled>

                            <cs-dashboard-table-item-unstyled
                                class="w-32"
                                :item="`statusSummaryMatrixStatus`">
                                <!--Active styling-->
                                <label v-if="certificate.matrix_status"
                                       class="badge badge-success">
                                    compliant
                                </label>
                                <label v-else
                                       class="badge badge-danger">
                                    non-compliant
                                </label>
                            </cs-dashboard-table-item-unstyled>
                        </div>
                        <div v-else
                             class="table--row flex items-center justify-between border-certstyle-border last:border-b-0 border-b px-10 py-4">
                            <cs-dashboard-table-item-unstyled
                                class="w-1/2"
                                :item="`statusSummaryCertificateTitle`">
                                No certificates found
                            </cs-dashboard-table-item-unstyled>
                            <cs-dashboard-table-item-unstyled class="w-32"
                                                              :item="`statusSummaryCertificateStatus`">
                            </cs-dashboard-table-item-unstyled>
                            <cs-dashboard-table-item-unstyled
                                class="w-32"
                                :item="`statusSummaryMatrixStatus`">
                            </cs-dashboard-table-item-unstyled>
                        </div>
                    </div>
                </div>
            </modal-md>
        </cs-card>

        <contact-details
            v-if="userToShowContactDetails"
            :user="userToShowContactDetails"
        />

        <add-employee-modal
            :countries="countries"
            :identifier="`addEmployeeModal`"
            :invite-modal-title="`Invite to department`"
            :suggestion-url="userSuggestionApiURL"
            :title="`Assign to ${department ? department.name: ''}`"
            @inviteEmployees="handleInvitedEmployees"
            @selectEmployee="addEmployeeToDepartment"
            @removeEmployee="handleRemoveEmployee"
        />

        <cs-confirmation-modal
            v-if="checkRole(['admin', 'planner'])"
            @proceed="handleRemoveEmployee"
            identifier="removeConfirmationModal">
            <div class="text-certstyle-titles font-normal" slot="content">
                Removing employees from this department can not be undo.
            </div>

            <div slot="cancelButton"
                 class="cursor-pointer hover:bg-certstyle-background border border-certstyle-border rounded px-6 py-2 text-certstyle-text-light mr-4">
                Cancel
            </div>

            <cs-button slot="proceedButton">
                Remove
            </cs-button>
        </cs-confirmation-modal>
    </div>

</template>

This list and the filters works fine but when I try to search a user by typing their names, it kept giving me following error,

Duplicate keys detected: '1025'. This may cause an update error.

found in

---> at resources/js/components/reusable/datatable/Datatable.vue at resources/js/components/reusable/csCard.vue at resources/js/components/dashboard/communities/department/one-departments/department-user-list.vue

But when I try to filter the list by some other param, they get filtered without any error.

I'm struggling to find what I'm doing wrong here....

UPDATE

following is my non-filtered json data for a single user

 {
      "id": 1038,
      "unique_id": "0a3938c1-07d5-3884-9df0-a8fe3201a3e5",
      "first_name": "Mango",
      "last_name": "F1",
      "job_title": null,
      "email": "mangoF1@gmail.com",
      "phone_number": null,
      "phone_country_calling_code": null,
      "country_id": null,
      "company_name": null,
      "is_subcontractor": 0,
      "current_jobtitle": "Deck Foreman",
      "department_jobtitle": "Rigging Engineers",
      "language": "en",
      "email_verified_at": "2022-04-12T12:47:55.000000Z",
      "gender": null,
      "state": null,
      "postal_code": null,
      "house_number": null,
      "street": null,
      "city": null,
      "date_of_birth": null,
      "city_of_birth": null,
      "emergency_number": null,
      "opt_in": null,
      "created_at": "2022-04-12T12:46:34.000000Z",
      "updated_at": "2022-04-12T12:47:55.000000Z",
      "emergency_number_country_calling_code": null,
      "deleted_at": null,
      "has_ip_restriction": 0,
      "address": null,
      "latitude": null,
      "longitude": null,
      "place_id": null,
      "bouwpas_worker_id": null,
      "bouwpas_certificate_id": null,
      "certificate_matrix": [
        {
          "id": 463,
          .....
        }
      ]
    },

Following is my controller function,

public function index($locale, Company $company, Department $department, Request $request)
    {
        $this->authorize('viewUsers', [Department::class, $company, $department]);

        $users = $department->usersWithSubcontractors()
            //            ->notApiUser()
            ->select(
                'users.id',
                'unique_id',
                'first_name',
                'last_name',
                'job_title',
                'email',
                'phone_number',
                'unique_id',
                'phone_country_calling_code',
                'country_id',
                'company_name',
                'is_subcontractor',
            )->addSelect([
                'current_jobtitle' => JobTitle::selectRaw('IFNULL(project_specific_job_titles.title, job_titles.title)')
                    ->join('project_track_records', 'project_track_records.user_id', 'users.id', 'inner')
                    ->join('project_specific_job_titles', 'project_track_records.project_specific_job_title_id', 'project_specific_job_titles.id', 'inner')
                    ->whereColumn('job_titles.id', 'project_specific_job_titles.job_title_id')
                    ->whereDate('project_track_records.start_date', '<=', Carbon::now())
                    ->whereDate('project_track_records.end_date', '>=', Carbon::now())
                    ->limit(1),
                'department_jobtitle' => JobTitle::selectRaw('title')->whereColumn('job_titles.id', 'department_user.job_title_id'),
            ])->when(request('q'), function ($q) {
                $q->where(function ($q) {
                    $q->whereRaw("CONCAT_WS(' ', `first_name`, `last_name`) like '%" . request('q') . "%'");
                });
            })->when($request->get('employeeType'), function ($q) use ($request) {
                $q->whereIn('users.is_subcontractor', $request->get('employeeType'));
            })->paginate(\request('per_page', config('repository.pagination.limit')));

        $users->load('country');
        $users->append(['profile_image']);
        $users->makeVisible(['unique_id']);

        $users->map(fn ($item) => $item->certificate_matrix = (new GetCertificationMatrixQueryAction())->execute($item->id, $department->id));

        if ($request->filled('certificateStatus')) {
            $valid = in_array('valid', $request->get('certificateStatus'));
            $expire_soon = in_array('expire soon', $request->get('certificateStatus'));
            $expired = in_array('expired', $request->get('certificateStatus'));

            if ($valid) $users->setCollection($users->filter(fn ($item) => $item->certificate_matrix->filter(fn ($certificate) => $certificate->matrix_status && !$certificate->expire_soon && !$certificate->expired)->count() === $item->certificate_matrix->count())->values());
            if ($expire_soon && !$expired) $users->setCollection($users->filter(fn ($item) => $item->certificate_matrix->filter(fn ($certificate) => $certificate->matrix_status && $certificate->expire_soon)->count() > 0)->values());
            if ($expired && !$expire_soon) $users->setCollection($users->filter(fn ($item) => $item->certificate_matrix->filter(fn ($certificate) => $certificate->matrix_status && $certificate->expired)->count() > 0)->values());
        }

        if ($request->filled('matrixStatus')) {
            $compliant = in_array('compliant', $request->get('matrixStatus'));
            $non_compliant = in_array('non-compliant', $request->get('matrixStatus'));

            if ($non_compliant && !$compliant)
                $users->setCollection($users->filter(fn ($item) => $item->certificate_matrix->filter(fn ($certificate) => $certificate->matrix_status === 0 || $certificate->expire_soon || !$certificate->expired)->count() > 0)->values());

            if ($compliant && !$non_compliant)
                $users->setCollection($users->filter(fn ($item) => $item->certificate_matrix->filter(fn ($certificate) => $certificate->matrix_status && !$certificate->expire_soon && !$certificate->expired)->count() == $item->certificate_matrix->count())->values());
        }
        return response()->json($users);
    }


from Duplicate keys detected: 'X'. This may cause an update error. in VueJS datatable search

Remove uneven vertical and horizontal lines from an image using cv2 Python

The objective is to remove uneven vertical and horizontal lines from an images using cv2 Python.

Currently, I am using these two code block to remove the horizontal and vertical lines.

Remove vertical and horizontal line

nimg_v=gray.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 40))
detLines = cv2.morphologyEx(nimg_v, cv2.MORPH_OPEN, kernel, iterations=2) #
nimg_v[(detLines !=0)]=0

# Remove horizontal lines
nimg_h=nimg_v.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40,30))
detLines = cv2.morphologyEx(nimg_h, cv2.MORPH_OPEN, kernel, iterations=1)
nimg_h[(detLines !=0)]=0

Despite adjusting the Size of the structuring element, but I am still unable to remove most of the lines while maintaining the text N1,DG,and BJ.

The full code is

import cv2
import numpy as np
from matplotlib import pyplot as plt

dpath='so_images/dummy_image.jpg'

im = cv2.imread(dpath)
# Rough estimation the starting point of text region
y,x=50,700

# Rough estimation where the end of text region
y_end, x_end=1500,1350
white_bg = 255*np.ones_like(im)
white_bg[y:y+(y_end-y), x:x+(x_end-x)] =im[y:y+(y_end-y), x:x+(x_end-x)]
gray=cv2.cvtColor(white_bg, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
dilate = cv2.dilate(gray, kernel, iterations = 2)
idx = (dilate==255)
gray[idx]=0

## Remove vertical and horizontal line

nimg_v=gray.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 40))
detLines = cv2.morphologyEx(nimg_v, cv2.MORPH_OPEN, kernel, iterations=2) #
nimg_v[(detLines !=0)]=0

# Remove horizontal lines
nimg_h=nimg_v.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40,30))
detLines = cv2.morphologyEx(nimg_h, cv2.MORPH_OPEN, kernel, iterations=1)
nimg_h[(detLines !=0)]=0



img_sm=nimg_h.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2,2))
dilate = cv2.dilate(img_sm, kernel, iterations = 4)

img_sm[(dilate !=0)]=255


img_cont=img_sm.copy()
schunk_small=800
schunk_big=50000
cnts = cv2.findContours(img_cont, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if (area < schunk_small) | (area>schunk_big):
        cv2.drawContours(img_cont, [c], -1, (0, 0, 0), -1)

plt.imshow(img_cont)
plt.show()

The original input image

enter image description here

Which produce

enter image description here

But, notice, there are still vertical and horizontal lines in the image. Most of these lines are not a perfect straight.

I intend to clear the all the lines and having an output, ideally something as below.

enter image description here

In addition, I also try using HoughLinesP and filter based on the slope <1 as below. However, I am still unable to remove the lines.

edges = cv2.Laplacian(img_cont,cv2.CV_8UC1) # Laplacian Edge Detection

lines = cv2.HoughLinesP(
    edges, # Input edge image
    1, # Distance resolution in pixels
    np.pi/180, # Angle resolution in radians
    threshold=100, # Min number of votes for valid line
    minLineLength=5, # Min allowed length of line
    maxLineGap=10 # Max allowed gap between line for joining them
)

lines_list = []

for points in lines:
    x1,y1,x2,y2=points[0]
    slope = ((y2-y1) / (x2-x1)) if (x2-x1) != 0 else np.inf
    if slope <= 1:
        cv2.line(img_cont,(x1,y1),(x2,y2),(255,255,255),1)

Remark:

Since this is for OCR application, I am particularly interested to remove the vertical and horizontal lines below the text BJ. This is because, the OCR system unable to recognize the text if there is horizontal lines below the BJ

The Google Colab notebook to run the cleaning can be found from this link



from Remove uneven vertical and horizontal lines from an image using cv2 Python

Osmdroid offline zip files (tiles) maps does not load on android 10 and 11 devices

I'm working with osmdroid map in offline mode. I have downloaded tiles using Global mapper and zip tiles are keep in download folder(/sdcard/Download). But on Accessing it getting below error in ArchiveFileFactory of osmdroid. It is Occurring in Android 10 and above.. Given storage access permission also.

ArchiveFileFactory class. Getting Error on highlighted line,

enter image description here

Getting Error On Access Zip File:

Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.osmdroid.tileprovider.modules.ZipFileArchive.toString()

Below is the code:

Permissions using enter image description here

and build.gradle config is as below

enter image description here

Osm Library:

enter image description here

Tried Both Permissions :

1.Intent.ACTION_OPEN_DOCUMENT_TREE

2.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION

enter image description here

Fetching Offline Map

    File f = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS) + "/map_file.zip");
    if (f.exists()) {
        String name = f.getName().toLowerCase();
        name = name.substring(name.lastIndexOf(".") + 1);
        if (ArchiveFileFactory.isFileExtensionRegistered(name)) {
            try {
                OfflineTileProvider tileProvider = new OfflineTileProvider(new SimpleRegisterReceiver(getActivity()),
                        new File[]{f});
                mMap.setTileProvider(tileProvider);
                String source;
                IArchiveFile[] archives = tileProvider.getArchives();
                if (archives.length > 0) {
                    String mapSrc = Preference.getMapSrc(getContext());
                    if (TextUtils.isEmpty(mapSrc)) {
                        Set<String> tileSources = archives[0].getTileSources();
                        if (!tileSources.isEmpty()) {
                            source = tileSources.iterator().next();
                            Preference.setMapSrc(getContext(), source);
                            mMap.setTileSource(FileBasedTileSource.getSource(source));
                        } else {
                            mMap.setUseDataConnection(true);
                            mMap.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
                        }
                    } else {
                        mMap.setTileSource(FileBasedTileSource.getSource(mapSrc));
                    }
                } else {
                    mMap.setUseDataConnection(true);
                    mMap.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
                    return Constant.MAP_ASSETS_KML;
                }
                clearData();
                return Constant.MAP_ASSETS_KML;

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    return Constant.MAP_ASSETS_KML;
}


from Osmdroid offline zip files (tiles) maps does not load on android 10 and 11 devices

Hermitian transformation frequencies? (hypothetical function numpy.fft.hfftfreq)

For a normal FFT, Numpy implements the method fftfreq(n,d), which provides the frequencies of the FFT right away. However, for the Hermitian transformation hfft, the companion function hfftfreq is missing. What would be the returned values of the function hfftfreq(n,d), if it existed?

Sources:

numpy.fft.fftfreq: https://numpy.org/doc/stable/reference/generated/numpy.fft.fftfreq.html

Discrete Fourier Transform (numpy.fft): https://numpy.org/doc/stable/reference/routines.fft.html



from Hermitian transformation frequencies? (hypothetical function numpy.fft.hfftfreq)

Monday 30 May 2022

How can I get a screenshot on Wayland with pure Python?

As of the latest Pillow version (9.1.0), the grab() function to get a screenshot only works on X11 and not Wayland. When I disable Wayland, it works fine.

How can I get screenshot on Wayland with pure Python? Ideally the solution doesn't involve relying on other libraries.

Is this even possible for an app to get a full screenshot (including the windows of other apps) given Wayland's security model? Using scrot to get a screenshot results in a completely black image (similar to the issue here). However, gnome-screenshot works just fine so I know this is possible.



from How can I get a screenshot on Wayland with pure Python?

Compile a JSX string to a component on the fly

I've got a React application, in which I need to display an HTML Popup with some dynamic content generated by the server. This content also contains some JSX markup which I want to be rendered into real components.

<MyButton onClick={displayInfo}/>

...

async displayInfo() {
    let text = await fetch(...)  

    console.log(text) // "<SomeComp onClick={foo}><OtherComp..... etc

    let component = MAGIC(text)

    ReactDom.render(component, '#someDiv')
}

Due to how my server app is structured, ReactServerDOM und hydration is not an option.

Is there a way to implement this on the client side only?



from Compile a JSX string to a component on the fly

Log into spotify using python

I am trying to log into my spotify account using my username and password using requests and 2captcha. When I run my code, I am returned with b'{"error":"errorInvalidCredentials"}' and am unable to login.

I used my personal login and extract the csrf token from my cookies for the post requests payload.

Wondering if the data in the post request is being passed through correctly.

from twocaptcha import TwoCaptcha
from email import header
import json
import requests
 
s = requests.Session()
 
headers = { 
    'documentLifecycle':'active',
    'frameType':'outermost_frame',
    'initiator':'https://accounts.spotify.com',
    'method':'GET',
    'url':'https://accounts.spotify.com/en/login/?continue=https%3A//www.spotify.com/us/account/overview/&_locale=en-US',
    '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',
    'Accept-Encoding':'gzip, deflate, br',
    'Accept-Language':'en-US,en;q=0.9',
    'sec-ch-ua':'" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"',
    'sec-ch-ua-mobile':'?0',
    'sec-ch-ua-platform':'"Windows"',
    'Sec-Fetch-Dest':'document',
    'Sec-Fetch-Mode':'navigate',
    'Sec-Fetch-Site':'same-origin',
    'Sec-Fetch-User':'?1',
    'Upgrade-Insecure-Requests':'1',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
}
 
r = s.get('https://accounts.spotify.com/en/login/?continue=https%3A//www.spotify.com/us/account/overview/&_locale=en-US', headers=headers, allow_redirects=True)
 
print(r.status_code)
print(r.content)
print(r.history)
 
c = r.cookies
csrf = c.items()[1][1]
 
csrf = str(csrf)
 
print(csrf)
 
headers = {
    'documentLifecycle':'active',
    'frameType':'outermost_frame',
    'initiator':'https://accounts.spotify.com',
    'method':'POST',
    'url':'https://accounts.spotify.com/login/password',
    'Accept':'application/json',
    'Accept-Encoding':'gzip, deflate, br',
    'Accept-Language':'en-US,en;q=0.9',
    'Content-Type':'application/x-www-form-urlencoded',
    'Origin':'https://accounts.spotify.com',
    'Referer':'https://accounts.spotify.com/en/login/?continue=https%3A//www.spotify.com/us/account/overview/&_locale=en-US',
    'sec-ch-ua':'" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"',
    'sec-ch-ua-mobile':'?0',
    'sec-ch-ua-platform':'"Windows"',
    'Sec-Fetch-Dest':'empty',
    'Sec-Fetch-Mode':'cors',
    'Sec-Fetch-Site':'same-origin',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
    'X-CSRF-Token': csrf
}
 
solver = TwoCaptcha('xxxx')
 
try:
    result = solver.recaptcha(
        sitekey="6LfCVLAUAAAAALFwwRnnCJ12DalriUGbj8FW_J39",
        url='https://accounts.spotify.com/',
        version="V3",
        id="100000")
 
except Exception as e:
    print('Error')
 
else:
    print('solved') 
    captcha = result
    print(captcha)
 
print(captcha['code'])
 
username = 'xxxx'
password = 'xxxx'
 
data = {
    'username': username,
    'password': password,
    'remember': 'true',
    'recaptchaToken': captcha['code'],
    'continue': 'https://www.spotify.com/us/account/overview/'
}
 
r = s.post('https://accounts.spotify.com/login/password', json=data, headers=headers, allow_redirects=True)
 
print(r.status_code)
print(r.content)


from Log into spotify using python

limiting data set to be used xlim

I have lots of files that contain x, y, yerr columns. I read them and save and apply a change on the x values, then I would like to set a limit on the x values I will use afterwards which are the newxval:

for key, value in files_data.items():
    
    file_short_name = key
    main = value[1]
    data = pd.DataFrame(value[0])
    
    has_error = data.shape[1] == 3
    if has_error:
        error = data[2]
    xval= data[0]
    yval= data[1]
    
    P = 11293 
    B = xval*(2/(5+D))
    newxval = a*((B/P)

I have an idea for the limit on data (for min and max only) but I am not sure how to apply this on newxval instead of data[0] and I am not sure how to set, say a value like between 5 to 100

    xlim = [data[0].min(), data[0].max()]
    data = data[(data[0] >= xlim[0]) & (data[0] <= xlim[1])] 


from limiting data set to be used xlim

Data entry field displaying entered values

My application has a modal window with filters. I would like to add another kind of filter to it. I just don’t know how to implement it in React (perhaps you can help me with the code, recommend links).

The meaning is as follows: I want the filters to have a line in which the user could write some value on his own, press Enter, see the entered result (it is possible to enter several values ​​by which you can filter).

Perhaps my explanation is chaotic, in addition I will provide a screenshot with the desired result:

enter image description here



from Data entry field displaying entered values

Cursor is not centered in an empty editable anchor with text-align center on firefox

I have some anchor tags as buttons in an application on which contenteditable is set to true and tex-align is set to center

but if an anchor has no text in it the cursor should be centered as the tex-align is set to center and it workes as expected on chrome but on firefox it shows the cursor to extreme left when nothing is typed.

for reference here's the HTML code:

<a class="editable" contenteditable>

</a>

and CSS:

.editable {
  display:block;
  color: red;
  border:1px solid red;
    height: 100px;
  width:100%;
  text-align:center;

}

or try this codepen on chrome and firefox:

https://codepen.io/zeeshanadilbutt/pen/ajLqKM?editors=1100

I know it is a bug with Firefox but is there a way to solve this?



from Cursor is not centered in an empty editable anchor with text-align center on firefox

Sunday 29 May 2022

Vue3 equivalent of vNode.computedInstance

I'm in the process of converting my app from Vue2 to Vue3, but have gotten stalled out on one aspect of my forms.

I'm using SFCs for form element components (FormInput, FormTextArea, FormCheckbox, etc.), and passing them into form container components (FormGroup, FormTab, etc) using slots, like so:

<ssi-form>
  <ssi-form-tabs>
    <ssi-form-tab title="tab1">
      <ssi-form-input title="name" ... />
      <ssi-form-checkbox title="active" ... />
    </ssi-form-tab>
  </ssi-form-tabs>
</ssi-form>

Those parent containers need to view some computed properties of the child form elements to pull error messages to the top.

In Vue2, I used the mounted lifecycle hook (with the options API) to read the slots and access the computed properties, like this:

  mounted: function() {
    const vm = this;

    this.$slots.default.forEach((vNode) => {
      const vueComponent = vNode.componentInstance;
      vueComponent.$on("invalid", vm.onInvalid);

      if (vueComponent.errorCount === undefined) return;
      this.childFormElements.push(vueComponent);
    });
  },

Using this setup, I could grab the errorCount computed property from each child in the slot, so I could aggregate errors going up to the top level of the form.

Now that I'm switching to Vue3, it seems like componentInstance doesn't exist. I tried setting up similar logic using the onMounted directive, but when I access the slot elements, I can't find any way to see their errorCount computed property:

onMounted(() => { 
  slots.default().forEach((vNode) => {
    console.log(vNode);
  });
});

The logged object does not contain the computed property. I thought I found something useful when I read about defineExpose, but even after exposing the errorCount property, nothing comes up.

Here is the <script setup> from the SFC for the text input that I'm trying to work with:

<script setup lang="ts">
import { ref, defineProps, defineEmits, computed } from "vue";

let props = defineProps<{
  label: string, 
  id: string, 
  modelValue: string|number, 
  type?: string, 
  description?: string, 
  min?: string|number, 
  max?: string|number, 
  pattern?: string, 
  message?: string
}>();
let emit = defineEmits(["input", "update:modelValue", "invalid"]);

let state = ref(null);
let error = ref("");

const input = ref(null);

function onInput(event: Event) {
  validate();
  emit('update:modelValue', event.target.value)
}

// methods
function validate() {
  let inputText = input.value;
  if (inputText === null) return;

  inputText.checkValidity();
  state.value = inputText.validity.valid;
  error.value = inputText.validationMessage;
}

const errorCount = computed(() => {
  return state.value === false ? 1 : 0;
});

defineExpose({errorCount})

</script>

So the question is - how can a parent component read the errorCount property from a component placed into a slot?



from Vue3 equivalent of vNode.computedInstance

Keeping the marker size to scale when zooming in on a world map

I am just starting out with Python and probably in a little bit over my head here, but I would like to combine this example, by Zack Fizell, with this solution, by Thomas Kühn.

The data below creates a world map with "fire balls". The issue is that when zooming in, the size of the circles remains the same (in absolute terms) and they become smaller relative to the background. I would like to apply the solution by Thomas Kühn to this example by Zack Fizell (not really for the fireballs, but for my own data using a world map).

The problem is that when fiddling around with the code, I hardly ever get a useful error message. Which makes it hard to figure out where I'm going wrong.

I have included all the code, so that it is still an interesting question when the link dies at some point (I am just not sure what to do with the csv-file needed to run the example).

It became quite a long question but I hope it is at least an interesting one.

Please feel free to give me tips on how to improve this question

The example data is as follows:

# Importing libraries
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd

# Reading cvs file using pandas
df = pd.read_csv('cneos_fireball_data.csv', 
                 usecols=["Peak Brightness Date/Time (UT)", 
                 "Calculated Total Impact Energy (kt)", 
                 "Latitude (deg.)", "Longitude (deg.)"])
df = df.rename(columns={"Peak Brightness Date/Time (UT)": 
                        'Datetime',
                        "Calculated Total Impact Energy (kt)": 
                        'Impact Energy [kt]',
                        "Latitude (deg.)": 'Latitude',
                        "Longitude (deg.)": 'Longitude'})

# Converting to a datetime datatype
df['Datetime'] = pd.to_datetime(df['Datetime'], errors='coerce')

# Applying +/- based on direction and converting to numeric datatype
for x in range(len(df['Longitude'])):
    if str(df.loc[x, 'Longitude'])[-1] == 'E':
        df.loc[x, 'Longitude'] = str(df.loc[x, 'Longitude'])[:-1]
    if str(df.loc[x, 'Longitude'])[-1] == 'W':
        df.loc[x, 'Longitude'] = \
            '-' + str(df.loc[x, 'Longitude'])[:-1]

for x in range(len(df['Latitude'])):
    if str(df.loc[x, 'Latitude'])[-1] == 'N':
        df.loc[x, 'Latitude'] = str(df.loc[x, 'Latitude'])[:-1]
    if str(df.loc[x, 'Latitude'])[-1] == 'S':
        df.loc[x, 'Latitude'] = \
            '-' + str(df.loc[x, 'Latitude'])[:-1]

df['Longitude'] = pd.to_numeric(df['Longitude'], errors='coerce')
df['Latitude'] = pd.to_numeric(df['Latitude'], errors='coerce')

# Converting to numeric datatype
threshold = 20
df = df[df['Impact Energy [kt]'] < threshold]
df['Impact Energy [kt]'] = pd.to_numeric(df['Impact Energy [kt]'], 
                                         errors='coerce')

# Dropping the errors from data conversions and resetting index
df.dropna()
df = df.reset_index(drop=True)

# From GeoPandas, our world map data
worldmap = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

# Creating axes and plotting world map
fig, ax = plt.subplots(figsize=(12, 6))
worldmap.plot(color="lightgrey", ax=ax)

# Plotting our Impact Energy data with a color map
x = df['Longitude']
y = df['Latitude']
z = df['Impact Energy [kt]']
plt.scatter(x, y, s=20*z, c=z, alpha=0.6, vmin=0, vmax=threshold,
            cmap='autumn')
plt.colorbar(label='Impact Energy [kt]')

# Creating axis limits and title
plt.xlim([-180, 180])
plt.ylim([-90, 90])

first_year = df["Datetime"].min().strftime("%Y")
last_year = df["Datetime"].max().strftime("%Y")
plt.title("NASA: Fireballs Reported by Government Sensors\n" +     
          str(first_year) + " - " + str(last_year))
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.show()

Result:

enter image description here

The point is that I am having trouble adapting the solution. Mostly because I do not understand the MarkerUpdater class very well (see below).

Solution by Thomas Kühn

from matplotlib import pyplot as plt
import numpy as np

##plt.switch_backend('TkAgg')
class MarkerUpdater:
    def __init__(self):
        ##for storing information about Figures and Axes
        self.figs = {}

        ##for storing timers
        self.timer_dict = {}

    def add_ax(self, ax, features=[]):
        ax_dict = self.figs.setdefault(ax.figure,dict())
        ax_dict[ax] = {
            'xlim' : ax.get_xlim(),
            'ylim' : ax.get_ylim(),
            'figw' : ax.figure.get_figwidth(),
            'figh' : ax.figure.get_figheight(),
            'scale_s' : 1.0,
            'scale_a' : 1.0,
            'features' : [features] if isinstance(features,str) else features,
        }
        ax.figure.canvas.mpl_connect('draw_event', self.update_axes)

    def update_axes(self, event):

        for fig,axes in self.figs.items():
            if fig is event.canvas.figure:

                for ax, args in axes.items():
                    ##make sure the figure is re-drawn
                    update = True

                    fw = fig.get_figwidth()
                    fh = fig.get_figheight()
                    fac1 = min(fw/args['figw'], fh/args['figh'])


                    xl = ax.get_xlim()
                    yl = ax.get_ylim()
                    fac2 = min(
                        abs(args['xlim'][1]-args['xlim'][0])/abs(xl[1]-xl[0]),
                        abs(args['ylim'][1]-args['ylim'][0])/abs(yl[1]-yl[0])
                    )

                    ##factor for marker size
                    facS = (fac1*fac2)/args['scale_s']

                    ##factor for alpha -- limited to values smaller 1.0
                    facA = min(1.0,fac1*fac2)/args['scale_a']

                    ##updating the artists
                    if facS != 1.0:
                        for line in ax.lines:
                            if 'size' in args['features']:
                                line.set_markersize(line.get_markersize()*facS)

                            if 'alpha' in args['features']:
                                alpha = line.get_alpha()
                                if alpha is not None:
                                    line.set_alpha(alpha*facA)


                        for path in ax.collections:
                            if 'size' in args['features']:
                                path.set_sizes([s*facS**2 for s in path.get_sizes()])

                            if 'alpha' in args['features']:
                                alpha = path.get_alpha()
                                if alpha is not None:
                                    path.set_alpha(alpha*facA)

                        args['scale_s'] *= facS
                        args['scale_a'] *= facA

                self._redraw_later(fig)



    def _redraw_later(self, fig):
        timer = fig.canvas.new_timer(interval=10)
        timer.single_shot = True
        timer.add_callback(lambda : fig.canvas.draw_idle())
        timer.start()

        ##stopping previous timer
        if fig in self.timer_dict:
            self.timer_dict[fig].stop()

        ##storing a reference to prevent garbage collection
        self.timer_dict[fig] = timer

if __name__ == '__main__':
    my_updater = MarkerUpdater()

    ##setting up the figure
    fig, axes = plt.subplots(nrows = 2, ncols =2)#, figsize=(1,1))
    ax1,ax2,ax3,ax4 = axes.flatten()

    ## a line plot
    x1 = np.linspace(0,np.pi,30)
    y1 = np.sin(x1)
    ax1.plot(x1, y1, 'ro', markersize = 10, alpha = 0.8)
    ax3.plot(x1, y1, 'ro', markersize = 10, alpha = 1)

    ## a scatter plot
    x2 = np.random.normal(1,1,30)
    y2 = np.random.normal(1,1,30)
    ax2.scatter(x2,y2, c = 'b', s = 100, alpha = 0.6)

    ## scatter and line plot
    ax4.scatter(x2,y2, c = 'b', s = 100, alpha = 0.6)
    ax4.plot([0,0.5,1],[0,0.5,1],'ro', markersize = 10) ##note: no alpha value!

    ##setting up the updater
    my_updater.add_ax(ax1, ['size'])  ##line plot, only marker size
    my_updater.add_ax(ax2, ['size'])  ##scatter plot, only marker size
    my_updater.add_ax(ax3, ['alpha']) ##line plot, only alpha
    my_updater.add_ax(ax4, ['size', 'alpha']) ##scatter plot, marker size and alpha

    plt.show()

Result:

enter image description here

My attempt (I have not touched the MarketUpdater):

from matplotlib import pyplot as plt
import numpy as np

##plt.switch_backend('TkAgg')
class MarkerUpdater:
    def __init__(self):
        ##for storing information about Figures and Axes
        self.figs = {}

        ##for storing timers
        self.timer_dict = {}

    def add_ax(self, ax, features=[]):
        ax_dict = self.figs.setdefault(ax.figure,dict())
        ax_dict[ax] = {
            'xlim' : ax.get_xlim(),
            'ylim' : ax.get_ylim(),
            'figw' : ax.figure.get_figwidth(),
            'figh' : ax.figure.get_figheight(),
            'scale_s' : 1.0,
            'scale_a' : 1.0,
            'features' : [features] if isinstance(features,str) else features,
        }
        ax.figure.canvas.mpl_connect('draw_event', self.update_axes)

    def update_axes(self, event):

        for fig,axes in self.figs.items():
            if fig is event.canvas.figure:

                for ax, args in axes.items():
                    ##make sure the figure is re-drawn
                    update = True

                    fw = fig.get_figwidth()
                    fh = fig.get_figheight()
                    fac1 = min(fw/args['figw'], fh/args['figh'])


                    xl = ax.get_xlim()
                    yl = ax.get_ylim()
                    fac2 = min(
                        abs(args['xlim'][1]-args['xlim'][0])/abs(xl[1]-xl[0]),
                        abs(args['ylim'][1]-args['ylim'][0])/abs(yl[1]-yl[0])
                    )

                    ##factor for marker size
                    facS = (fac1*fac2)/args['scale_s']

                    ##factor for alpha -- limited to values smaller 1.0
                    facA = min(1.0,fac1*fac2)/args['scale_a']

                    ##updating the artists
                    if facS != 1.0:
                        for line in ax.lines:
                            if 'size' in args['features']:
                                line.set_markersize(line.get_markersize()*facS)

                            if 'alpha' in args['features']:
                                alpha = line.get_alpha()
                                if alpha is not None:
                                    line.set_alpha(alpha*facA)


                        for path in ax.collections:
                            if 'size' in args['features']:
                                path.set_sizes([s*facS**2 for s in path.get_sizes()])

                            if 'alpha' in args['features']:
                                alpha = path.get_alpha()
                                if alpha is not None:
                                    path.set_alpha(alpha*facA)

                        args['scale_s'] *= facS
                        args['scale_a'] *= facA

                self._redraw_later(fig)



    def _redraw_later(self, fig):
        timer = fig.canvas.new_timer(interval=10)
        timer.single_shot = True
        timer.add_callback(lambda : fig.canvas.draw_idle())
        timer.start()

        ##stopping previous timer
        if fig in self.timer_dict:
            self.timer_dict[fig].stop()

        ##storing a reference to prevent garbage collection
        self.timer_dict[fig] = timer

if __name__ == '__main__':
    my_updater = MarkerUpdater()

    ##setting up the figure
    fig, axes = plt.subplots(figsize=(12, 6))
    ax2 = axes.flatten()

    ## a line plot
    # x1 = np.linspace(0,np.pi,30)
    # y1 = np.sin(x1)
    # ax1.plot(x1, y1, 'ro', markersize = 10, alpha = 0.8)
    # ax3.plot(x1, y1, 'ro', markersize = 10, alpha = 1)

    ## a scatter plot
    worldmap.plot(color="lightgrey", ax=ax2)

    # Plotting our Impact Energy data with a color map
    x = df['Longitude']
    y = df['Latitude']
    z = df['Impact Energy [kt]']
    # x = np.random.normal(1,1,30)
    # y = np.random.normal(1,1,30)
    ax2.scatter(x, y, s=20*z, c=z, alpha=0.6, vmin=0, vmax=threshold,
        cmap='autumn')

    ## scatter and line plot
    # ax4.scatter(x2,y2, c = 'b', s = 100, alpha = 0.6)
    # ax4.plot([0,0.5,1],[0,0.5,1],'ro', markersize = 10) ##note: no alpha value!

    ##setting up the updater
    # my_updater.add_ax(ax1, ['size'])  ##line plot, only marker size
    my_updater.add_ax(ax2, ['size'])  ##scatter plot, only marker size
    # my_updater.add_ax(ax3, ['alpha']) ##line plot, only alpha
    # my_updater.add_ax(ax4, ['size', 'alpha']) ##scatter plot, marker size and alpha

    plt.show()

However I just get an error:

AttributeError: 'AxesSubplot' object has no attribute 'flatten'

And nothing else happens.. So it's little bit hard to figure out what is going wrong.

If I remove ax2 = axes.flatten(), I just end up with the first map, nothing more.

Would anyone be interested in helping me to move forward?



from Keeping the marker size to scale when zooming in on a world map

What is the proper way to checkpoint during training when using distributed data parallel (DDP) in PyTorch?

I want (the proper and official - bug free way) to do:

  1. resume from a checkpoint to continue training on multiple gpus
  2. save checkpoint correctly during training with multiple gpus

For that my guess is the following:

  1. to do 1 we have all the processes load the checkpoint from the file, then call DDP(mdl) for each process. I assume the checkpoint saved a ddp_mdl.module.state_dict().
  2. to do 2 simply check who is rank = 0 and have that one do the torch.save({'model': ddp_mdl.module.state_dict()})

Approximate code:

def save_ckpt(rank, ddp_model, path):
    if rank == 0:
        state = {'model': ddp_model.module.state_dict(),
             'optimizer': optimizer.state_dict(),
            }
        torch.save(state, path)

def load_ckpt(path, distributed, map_location=map_location=torch.device('cpu')):
    # loads to
    checkpoint = torch.load(path, map_location=map_location)
    model = Net(...)
    optimizer = ...
    model.load_state_dict(checkpoint['model'])
    optimizer.load_state_dict(checkpoint['optimizer'])
    if distributed:
        model = DDP(model, device_ids=[gpu], find_unused_parameters=True)
    return model

Is this correct?


One of the reasons that I am asking is that distributed code can go subtly wrong. I want to make sure this does not happen to me. Of course I want to avoid deadlocks but that would be obvious if it happens to me (e.g. perhaps it could happen if all the processes somehow tried to open the same ckpt file at the same time. In that case I'd somehow make sure that only one of them loads it one at a time or have rank 0 only load it and then send it to the rest of the processes).

I am also asking because the official docs don't make sense to me. I will paste their code and explanation since links can die sometimes:

Save and Load Checkpoints It’s common to use torch.save and torch.load to checkpoint modules during training and recover from checkpoints. See SAVING AND LOADING MODELS for more details. When using DDP, one optimization is to save the model in only one process and then load it to all processes, reducing write overhead. This is correct because all processes start from the same parameters and gradients are synchronized in backward passes, and hence optimizers should keep setting parameters to the same values. If you use this optimization, make sure all processes do not start loading before the saving is finished. Besides, when loading the module, you need to provide an appropriate map_location argument to prevent a process to step into others’ devices. If map_location is missing, torch.load will first load the module to CPU and then copy each parameter to where it was saved, which would result in all processes on the same machine using the same set of devices. For more advanced failure recovery and elasticity support, please refer to TorchElastic.

def demo_checkpoint(rank, world_size):
    print(f"Running DDP checkpoint example on rank {rank}.")
    setup(rank, world_size)

    model = ToyModel().to(rank)
    ddp_model = DDP(model, device_ids=[rank])

    loss_fn = nn.MSELoss()
    optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)

    CHECKPOINT_PATH = tempfile.gettempdir() + "/model.checkpoint"
    if rank == 0:
        # All processes should see same parameters as they all start from same
        # random parameters and gradients are synchronized in backward passes.
        # Therefore, saving it in one process is sufficient.
        torch.save(ddp_model.state_dict(), CHECKPOINT_PATH)

    # Use a barrier() to make sure that process 1 loads the model after process
    # 0 saves it.
    dist.barrier()
    # configure map_location properly
    map_location = {'cuda:%d' % 0: 'cuda:%d' % rank}
    ddp_model.load_state_dict(
        torch.load(CHECKPOINT_PATH, map_location=map_location))

    optimizer.zero_grad()
    outputs = ddp_model(torch.randn(20, 10))
    labels = torch.randn(20, 5).to(rank)
    loss_fn = nn.MSELoss()
    loss_fn(outputs, labels).backward()
    optimizer.step()

    # Not necessary to use a dist.barrier() to guard the file deletion below
    # as the AllReduce ops in the backward pass of DDP already served as
    # a synchronization.

    if rank == 0:
        os.remove(CHECKPOINT_PATH)

    cleanup()

Related:



from What is the proper way to checkpoint during training when using distributed data parallel (DDP) in PyTorch?

How to generate a random sample of points from a 3-D ellipsoid using Python?

I am trying to sample around 1000 points from a 3-D ellipsoid, uniformly. Is there some way to code it such that we can get points starting from the equation of the ellipsoid?

I want points on the surface of the ellipsoid.



from How to generate a random sample of points from a 3-D ellipsoid using Python?

Contenteditable removes trailing whitespaces on firefox, but not on Chrome

I have simple <p> element as contenteditable with a formatting function, which formats the text on the fly (on input event), and moves the caret at the end of the text (because updating innerHTML on contenteditable moves the caret to the beginning of the text).

So on Chrome everything works fine, the text is formatted as you type, but when using Firefox, trailing whitespaces are removed as you type, so you can't really write two separate words, because each time you press space at the end of the first word, it gets trimmed.

Any ideas why the behaviour is different on Firefox?

Fiddle: https://jsfiddle.net/mt8cp2sd/

const content = document.getElementById('content');
content.innerHTML = 'Type text here';

function formatText(text) {
  return text.replaceAll('#', '<b>#</b>');
}

content.addEventListener('input', () => {
  content.innerHTML = formatText(content.innerText);

  let range = document.createRange();
  range.selectNodeContents(content);
  range.collapse(false);
  let selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
});
#content {
  border: solid 1px #555;
}
<html>

  <body>

    <p id="content" contenteditable>
    </p>

  </body>

</html>


from Contenteditable removes trailing whitespaces on firefox, but not on Chrome

Saturday 28 May 2022

How to handle error messages when validating a form across different FieldLists of FormFields?

I have a form that contains (among other fields) 2 FieldLists. Each FieldList is a list of FormFields. In each FieldList, the forms all represent projects. One fieldlist is for projects having budget taken away, and the other list is for projects that will be the recipients of that budget. This is a dynamic form; there can be an arbitrary number of deallocations or allocations. There will be a lot of validations in the overall form, but a simple case that I cannot get working is making sure no project appears twice in the form (that is to say that across both lists, project IDs must be unique). I can test for this and recognize when this situation occurs, but I am having trouble associating error messages with the offending project IDs.

A simplified version of my form classes is:

class AllocationForm(Form):
    project_id(StringField, label='Project ID')
    ... details about amount being allocated here

class DeallocationForm(Form):
    project_id(StringField, label='Project ID')
    ...details about amount being deallocated here

class RequestForm(FlaskForm):

    def validate(self):

        project_id_seen = {}
        project_list = [a for a in self.allocations] + [d for d in self.deallocations]

        for formfield in project_list:
            if project_id_seen.get(formfield.data.get('project_id')) is None:
                project_id_seen[formfield.data.get('project_id')] = 1
            else:
                # *** Here's where I'm having an issue ***
                somethingsomethingsomething['project_id'] = 'A project ID cannot appear more than once in a request'
                return False

        # other form validations happen here
        if not FlaskForm.validate(self):
            return False

    allocations = FieldList(FormField(AllocationForm))
    deallocations = FieldList(FormField(DeallocationForm))

As you can see, I'm overriding RequestForm's validate method. Where I return False in the else clause, I'd like to associate an error message with the project ID in question so that I can display it when the form is re-rendered, but I'm having difficulty accessing the specific project_id field in the subform. Any ideas?

EDIT: It occurs to me that another approach might be to put validators on the project ID fields in the AllocationForm and DeallocationForm classes instead of RequestForm. Is this a more feasible approach? Associating the error message with the field would be easier, but how would the validator in AllocationForm access the project IDs in DeallocationForm and vice versa?



from How to handle error messages when validating a form across different FieldLists of FormFields?

How to recursively export all from folders in node js project?

In my React JS project I have configured a jsconfig.json such that I can recursively export nested directories and import a specific export from the base directory as follows:

jsconfig.json:

{
  "compilerOptions": {
    "jsx": "react",
    "baseUrl": "src"
  }
}

Project folder structure:

react-app
  src
    common
    index.js
      services
        ServiceA.js
        ServiceB.js
        index.js
      components
        ComponentA.jsx
        index.js
    pages
      pageA
        PageA.jsx
        index.js
    App.jsx
    index.js
    

Now in each index.js I would export all from each file/folder. So for example in common/services/index.js:

export * from 'common/services/ServiceA.js';
export * from 'common/services/ServiceB.js';

And in common/index.js:

export * from 'common/services';
export * from 'common/components';

Now if I require ServiceA exported from ServiceA.js in the PageA.jsx file I could import it as follows:

// PageA.jsx
import {
  ServiceA
} from 'common';
// ServiceA.js
export class ServiceA {
  doStuff () {
    // do stuff
  }
}

How can I setup my NodeJS server project to allow for similar exports and imports?

I'd like to do this for consistency between the FE and BE such that I can easily port over any FE code to my BE project without having to make any significant changes to exports and imports.



from How to recursively export all from folders in node js project?

react-rte giving TypeError: r.getEditorState is not a function in next js

I have a nextjs project and it has a react-rte component the react-rte component is displayed correctly but when I go to some other component and click back in the browsers back button I get the following error:

Unhandled Runtime Error TypeError: r.getEditorState is not a function

When I comment out the react-rte componnet the error no longer occurs

react-rte component

import React, { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import PropTypes from "prop-types";
//import the component
const RichTextEditor = dynamic(() => import("react-rte"), { ssr: false });

const MyStatefulEditor = ({ onChange }) => {
  const [value, setValue] = useState([]);
  console.log(value.toString("html"));

  useEffect(() => {
    const importModule = async () => {
      //import module on the client-side to get `createEmptyValue` instead of a component
      const module = await import("react-rte");
      console.log(module);
      setValue(module.createEmptyValue());
    };
    importModule();
  }, []);

  const handleOnChange = (value) => {
    setValue(value);
    if (onChange) {
      onChange(value.toString("html"));
    }
  };

  return <RichTextEditor value={value} onChange={handleOnChange} />;
};

MyStatefulEditor.propTypes = {
  onChange: PropTypes.func,
};

export default MyStatefulEditor;


from react-rte giving TypeError: r.getEditorState is not a function in next js

Get original implementation during jest mock

I'm trying to temporarily mock node-fetch in an ESM module while still retraining the original implementation so I can access a real endpoint's value. However, this errors with "Must use import to load ES Module." I recognize jest support for ESM is still pending - is there any way to have this behavior in a combination of current Node, ES6, and Jest?

worker.ts (dependency):

export default async () => {
    const response = await fetch("http://example2.org");
    return await response.json()
  }

main.test.ts:

import { jest } from "@jest/globals";


jest.mock("node-fetch", () => {
    return Promise.resolve({
        json: () => Promise.resolve({ myItem: "abc" }),
    })
})

import doWork from './worker.js';
import mockedFetch from 'node-fetch';

const originalFetch = jest.requireActual('node-fetch') as any;

test("Ensure mock", async () => {
    const result = await doWork();
    expect(result.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(1);

    const response = await originalFetch("http://www.example.org");
    expect(response.status).toBe(200);

    const result2 = await doWork();
    expect(result2.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(2);
});


from Get original implementation during jest mock

Toggle icon class across all the rows in the table

In this javascript code below there are two icons. fa-circle-pause and fa-circle-play.

When a user clicks the play icon in any one of the rows in the table, it is updated with the icon fa-circle-pause. I have been able to do that for the single rows.

But I am not able to update the rest of the rows in the table with the icon fa-circle-play.

How can I do that using just the javascript?

const data = [{
  Name: 'Chapter 1',
  TrackId: 1
}, {
  Name: 'Chapter 2',
  TrackId: '2',
}, , {
  Name: 'Chapter 3',
  TrackId: '3',
}, , {
  Name: 'Chapter 4',
  TrackId: '4',
}]; // any json data or array of objects
const tableData = data.map(function(value) {
  return (
    `<tr>
           <th scope="row">
            <span data-track-id='${value.TrackId}' class="play-button btn">
                <i class="fa-solid fa-circle-play"></i>
            </span>
          </th>
          <td>${value.Name}</td>
     </tr>`
  );
}).join('');
const tabelBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;

const pauseIconClassName = 'fa-circle-pause'
const playIconClassName = 'fa-circle-play'

const btns = document.querySelectorAll('.play-button')

function onChange(event) {
  // get the button elememt from the event
  const buttonElement = event.currentTarget.querySelector('i');

  const isPlayButton = buttonElement.classList.contains(playIconClassName)

  if (isPlayButton) {
    buttonElement.classList.remove(playIconClassName)
    buttonElement.classList.add(pauseIconClassName)
  } else {
    buttonElement.classList.remove(pauseIconClassName)
    buttonElement.classList.add(playIconClassName)
  }
}

btns.forEach(btn => {
  btn.addEventListener('click', onChange)
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet" />

<table border="2">
  <thead class="thead-dark">
    <tr>
      <th scope="col">#</th>
      <th scope="col">Track</th>
    </tr>
  </thead>
  <tbody id="tableBody">

  </tbody>
</table>


from Toggle icon class across all the rows in the table

Decrypting Windows EC2 password in Python

I would like to launch a Windows EC2 instance and programmatically get the admin password using Python. I know this can be done using the CLI like this, but I would prefer to decrypt locally to avoid sending my private key over the internet.

aws ec2 get-password-data --instance-id i-0d4d8273cadcae0a0 --priv-launch-key .ssh/elliott2.pem

After reading Cryptodome docs, I tried like this:

import boto3
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

ec2 = boto3.resource('ec2', 'us-west-2')
i = ec2.Instance('i-028dee2acb533fc59')

encrypted_str = i.password_data()['PasswordData']
with open('mykey.pem') as fp:
  key = RSA.importKey(fp.read())

cipher = PKCS1_OAEP.new(key)
print(cipher.decrypt(enc_str))

This fails with error:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    print(cipher.decrypt(encrypted_str))
  File "/Users/elliott/Library/Python/3.8/lib/python/site-packages/Crypto/Cipher/PKCS1_OAEP.py", line 167, in decrypt
    raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.

I think cipherkey must be exactly 256 Bytes. But the password data is longer than this, so I'm not sure what to do.



from Decrypting Windows EC2 password in Python

Non FK models tied together by ID (unmanaged model) - how to filter in Django?

I have two models that are related - but they are not a FK relationship in Django because one is a non-managed model with the data coming from a pre-populated DB table.

class Enrollment(models.Model):
    # This comes from a 'shared app' that is used in other projects 
    id = models.IntegerField(db_column="ID", primary_key=True)
    location_id = models.IntegerField(db_column="locationID")
    grade = models.CharField(db_column="grade", max_length=10)

    class Meta(object):
        managed = False
        db_table = "mytable_Enrollments"

class Location(models.Model):
    # This model exists in an app in the specific project I am working on
    name = models.CharField(max_length=50)
    alternate_name = models.IntegerField()

I'm trying to filter Enrollment models using a list of Location models - but they are not tied together in a FK relationship.

I am trying to get enrollments for a particular location like this:

# This does not work properly because it is returning an empty Queryset when it should have results - but does not hit the db which is what I want
location_ids = Location.objects.filter(id=1).values_list("id", flat=True)
enrollments = Enrollment.objects.filter(location_id__in=location_ids)

The above code returns an empty queryset.

If I cast location_ids to a list (like this: list(location_ids)) and then filter on that, it works.

# This works properly - but hits the db which is NOT what I want
location_ids = Location.objects.filter(id=1).values_list("id", flat=True)
enrollments = Enrollment.objects.filter(location_id__in=list(location_ids))

Is there a way to use the Django ORM to get what I want in this case without causing it to evaluate the queryset?

Additionally, I have tried just returning values instead of values_list but it also returns an empty Queryset when it should not.

# This returns empty queryset
location_ids = Location.objects.filter(id=1).values("id")
enrollments = Enrollment.objects.filter(location_id__in=location_ids)


from Non FK models tied together by ID (unmanaged model) - how to filter in Django?

Friday 27 May 2022

Next.js - TypeError: Cannot read properties of null (reading 'useMemo')

Since refactoring my code to move generic hooks and components to their own git submodules within my project I get TypeError: Cannot read properties of null (reading 'useMemo') whenever I call one of my custom hooks referring to useMemo.

I removed all the logic from a hook to make sure it didn't come from undefined arguments, so now my file looks like:

import { useMemo } from 'react'

export function useMyCustomHook() {
    return useMemo(() => [], []) // Does nothing useful, but fails anyway
}

export function useMyCustomHookWithoutMemo() {
    return [] // Does nothing useful, doesn't fail
}

I'm using next.js at the lastest version and the project structure is like this:

  • components/
    • component.js (this is where I call useMyCustomHook imported from 'generics')
  • hooks/
  • pages/
    • index.js (returns component)
  • generics/
    • index.js (with export * from './hooks/useMyCustomHook')
    • hooks/
      • useMyCustomHook.js

I also have a jsconfig.json file with the following content, so I can write stuff like import Component from 'components/component':

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

Is next.js not compiling code in my generics folder? How can I get useMemo to work with this folder structure?



from Next.js - TypeError: Cannot read properties of null (reading 'useMemo')

Import error Symbol not found: _FSPathMakeRef

Can't import Quartz package. Every time I try it throws an error and the weird thing is the error disappears if I execute the same script with Sudo privileges (sudo python3 script.py). The problem started when I forcefully deleted the site-packages folder tried reinstalling python but didn't help.

Python version - 3.10.4

Mac version - Big Sur 11.6.5

>which python3
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3
>sudo which python3
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3

Output:

Traceback (most recent call last):
  File "/Users/user/unknown/test.py", line 1, in <module>
    import Quartz
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/Quartz/__init__.py", line 6, in <module>
    import AppKit
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/AppKit/__init__.py", line 10, in <module>
    import Foundation
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/Foundation/__init__.py", line 9, in <module>
    import CoreFoundation
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/CoreFoundation/__init__.py", line 9, in <module>
    import objc
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/objc/__init__.py", line 6, in <module>
    from . import _objc
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/objc/_objc.cpython-310-darwin.so, 2): Symbol not found: _FSPathMakeRef
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/objc/_objc.cpython-310-darwin.so
  Expected in: flat namespace
 in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/objc/_objc.cpython-310-darwin.so


from Import error Symbol not found: _FSPathMakeRef

Code duplication in API design for URL route functions vs. real world object methods

I have code duplication in my API design for the object methods vs. the URL routing functions:

# door_model.py

class Door:                               
    def open(self):                       # "Door.open" written once...
       ...
# http_api.py (the HTTP server is separated from the real-world object models)

@app.route('/api/door/open')              # ... written twice
def dooropen():                           # ... written three times
    d.open()                              # ... written four times!

d = Door()

How to avoid this unnecessary duplication of names in a similar API design? (while keeping a separation between real-world object models vs. HTTP server).

Is there a general pattern to avoid unnecessary duplication of names when using an object model (with methods), and URL routes functions? (nearly a Model View Controller pattern)

See also Associate methods of an object to API URL routes with Python Flask.



from Code duplication in API design for URL route functions vs. real world object methods

callback is not a function - castv2

I'm following this http://siglerdev.us/blog/2021/02/26/google-home-message-broadcast-system-node-js/31 which uses this library castv2-client to send messages to my google home. It works. I get the messages no problem, but the code throws

C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\receiver.js:72
    callback(null, response.status.volume);
    ^

TypeError: callback is not a function
    at C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\receiver.js:72:5                                                                  ver.js:72
    at fn.onmessage (C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\request-response.js:27:7)
    at fn.emit (events.js:203:15)
    at Channel.onmessage (C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\controller.js:16:10)                                           s\receiver.js:72:5
    at Channel.emit (events.js:198:13)                                              lib\controllers\request-response.js:27:7)
    at Client.onmessage (C:\Users\Phil\Documents\google home\node_modules\castv2\lib\channel.js:23:10)                                                                  ient\lib\controllers\controller.js:16:10)
    at Client.emit (events.js:203:15)
    at PacketStreamWrapper.onpacket (C:\Users\Phil\Documents\google home\node_module\channel.js:23:10)s\castv2\lib\client.js:81:10)
    at PacketStreamWrapper.emit (events.js:198:13)                                  s\castv2\lib\client.js:81:10)
    at TLSSocket.<anonymous> (C:\Users\Phil\Documents\google home\node_modules\castv2\lib\packet-stream-wrapper.js:28:16)                     

What's wrong with the code that is throwing this AND/OR how can I fix it so it's either more graceful in catching error and doesn't throw since the message still delivers to google home or fix it to not throw this at all? I appreciate any help!

I believe it's here in the castv2-client library that it's referencing, but I haven't been able to make it happy.

ReceiverController.prototype.launch = function(appId, callback) {
  this.request({ type: 'LAUNCH', appId: appId }, function(err, response) {
    if(err) return callback(err);
    if(response.type === 'LAUNCH_ERROR') {
      return callback(new Error('Launch failed. Reason: ' + response.reason));
    }
    callback(null, response.status.applications || []);
  });
};

my code

var Client = require('castv2-client').Client;
var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver;
const googleTTS = require('google-tts-api');

var App = {
  playin: false,
  DeviceIp: "",
  Player: null,
  GoogleHome: function (host, url) {
    var client = new Client();
    client.connect(host, function () {
      client.launch(DefaultMediaReceiver, function (err, player) {
        client.setVolume({ level: 1 });
        var media = {
            contentId: url,
            contentType: 'audio/mp3',
            streamType: 'BUFFERED'
        };
        App.Player = player;
        App.Player.load(media, { autoplay: true }, function (err, status) {
            App.Player.on('status', function (status) {
                if (status.playerState === "IDLE" && App.playin === false) {
                    client.close();
                }
            });
        });
    });
});
client.on('error', function (err) {
  console.log('Error: %s', err.message);
  client.close();
});
},
run: function (ip, text) {
  App.DeviceIp = ip;
  const url = googleTTS.getAudioUrl(text, {
      lang: 'en-US',
      slow: false,
      host: 'https://translate.google.com',
  });
  App.GoogleHome(App.DeviceIp, url, function (res) {
      console.log(res);
  })
},
broadcast: function(text){
  const ips = '192.168.0.15'.split(","); //From config, 192.168.68.105,192.168.68.107,192.168.68.124
  for (var s of ips){
      App.run(s, text);
  }
}
}

App.broadcast("Broadcasted to all of the devices"); //Only works if you did step 4.5


from callback is not a function - castv2

How do I use np.linspace() to change the pixels colors of a patch in an image

I drew a straight line by changing the color of 50 pixels in the image below. The line is the diagonal line shown on the image

enter image description here

Here is how I did it.

zeros = torch.zeros_like(img) #img is b,c,h,w

x1, y1, x2, y2, r, g,  b = 16, 50, 100, 100, 6, 2, 4
rgb = torch.tensor([r, g, b])
cx, cy = x2 - x1, y2 - y1

for t in np.linspace(0, 1, 50):
    px, py = x1 + t * cx, y1 + t * cy
    zeros[0, :, int(py), int(px)] = rgb

mask = (zeros == 0).float()
im = mask * img + (1 - mask) *zeros

It is obvious in np.linspace(0, 1, 50) that I am changing 50 pixels. I want to use the same method to change a specific portion of the image, like a 14 x 14 patch of my image if the image size is 224 x 224 or even more. The range of pixels to cover now will be 196 -> (since there are 196 pixels in a 14 x 14 patch) instead of 50. How do I go about it, please?



from How do I use np.linspace() to change the pixels colors of a patch in an image

Storybook: Render a component by clicking on a link (React)

I've got a component, 'Dialog', that renders a modal dialog box basically, when a user clicks on a link or button to invoke/open the dialog. I'm building a storybook component for the Dialog component, and so I need to be able to have a clickable HTML element (anchor tag or button, preferably anchor tag) and open the Dialog component when that clickable HTML element is clicked. I don't know how to go about this in Storybook.

Here is my storybook element as it exists so far:

const Template: ComponentStory<typeof Dialog> = (args) => <Dialog {...args} />;

export const Regular = Template.bind({});

Regular.args = {
    type:"regular",
    show: false,
    children: "Content of Dialog Box",
    dismissable: true,
    classNames: "",
    maxWidth: "1000px",
    displayBoxShadow: true,
    renderOnLoad: false,
}

An example of an implementation of this component/story would be a Log In button that, when clicked, would render a slide-out dialog with appropriate fields (children). I'm trying to implement the Dialog part of the story, as the Dialog component is invoked when another HTML object on page is clicked/interacted with.



from Storybook: Render a component by clicking on a link (React)