Thursday, 31 March 2022

DOMDocument removes HTML tags in JavaScript string

I'm developing PHP applications for quite a while now. But this one realy gets me struggled. I’m loading complete HTML pages using the DomDocument. These pages are external and may contain JavaScript. This is beyond my control.

On some pages things were not rendered the way it supposed to when it came down to basic HTML formatting in JavaScript strings. I've wrote down an example which explains it all.

<?php
$html = new DOMDocument();

libxml_use_internal_errors(true);

$strPage = '<html>
<head>
<title>Demo</title>
<script type="text/javascript">
var strJS = "<b>This is bold.</b><br /><br />This should not be bold. Where did my closing tag go to?";
</script>
</head>
<body>
<script type="text/javascript">
document.write(strJS);
</script>
</body>
</html>';

$html->loadHTML($strPage);
echo $html->saveHTML();
exit;
?>

Am I missing something?

Edit: I've changed the demo. Changing the LoadHTML to LoadXML doesn't work anymore now and the output of the demo will pass w3c validation. Also adding the CDATA block to the JavaScript doesn't seem to have any effect.



from DOMDocument removes HTML tags in JavaScript string

How to insert n random NaN consecutive and no consecutive data by month?

I have this df:

       CODE      DATE     PP
0      000130 1991-01-01  0.0
1      000130 1991-01-02  1.0
2      000130 1991-01-03  2.0
3      000130 1991-01-04  2.0
4      000130 1991-01-05  1.1
      ...        ...  ...
10861  000142 2020-12-27  2.1
10862  000142 2020-12-28  2.2
10863  000142 2020-12-29  2.1
10864  000142 2020-12-30  0.4
10865  000142 2020-12-31  1.1

I want to have at least 3 consecutive nans and 5 non consecutive nans in df['PP'] by each df['CODE'] with their corresponding df['DATE'].dt.year and df['DATE'].dt.month so i must convert random values of df['PP'] to NaN to reach that 3 consecutive and 5 non consecutive NaNs. Expected result:

       CODE      DATE     PP
0      000130 1991-01-01  0.0
1      000130 1991-01-02  NaN
2      000130 1991-01-03  NaN
3      000130 1991-01-04  NaN
4      000130 1991-01-05  1.1
5      000130 1991-01-06  2.1
6      000130 1991-01-07  NaN
7      000130 1991-01-08  2.1
8      000130 1991-01-09  0.4
9      000130 1991-01-10  NaN
...    ...    ...         ...

Important: consecutive nans + alternate nans = 5. So i can have 3 consecutive nans per month inside the 5 nans. And if i already have n nans in a month, i should only add the difference to reach 5 nans. For example if i already have 2 nans in a month i should only add 3 consecutive nans. If i already have 5 nans in the month the code should do nothing with that month.

I tried this:

df['PPNEW']=df['PP'].groupby([df['CODE'],df['DATE'].dt.month]).sample(frac=0.984)

But i can't get the exact quantity of NaNs (only in percentage and months sometimes have 30-31 days) and i can't get consecutive NaNs.

Would you mind to help me?

Thanks in advance.



from How to insert n random NaN consecutive and no consecutive data by month?

BadWindow crash in tkinter after calling glfw.init()

I have the following code, which works on Windows, but crashes on Linux with X11:

#! /usr/bin/env python3
"""Tkinter crashes on X11 when popup windows
are closed after calling glfw.init()
"""

from sys import exit

from tkinter import Tk
from tkinter.messagebox import showinfo

from glfw import init


class MainWindow(Tk):
    """Main window."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if not init():
            exit(2)

        showinfo('Close me', 'I dare you')


def main():
    """Run the script."""

    MainWindow().mainloop()


if __name__ == '__main__':
    main()

After clicking OK in the message box on Linux/X11, the program crashes with:

X Error of failed request:  BadWindow (invalid Window parameter)
  Major opcode of failed request:  15 (X_QueryTree)
  Resource id in failed request:  0x4c0000a
  Serial number of failed request:  778
  Current serial number in output stream:  778

The addresses vary after each run, but the overall error stays the same.
I was able to reduce the problem to the call of glfw.init() which results in subsequent closing of tkinter Windows to crash the program. However, this does not happen on Windows systems.

Some system info:

$ uname -r
5.16.16-arch1-1
$ pacman -Q xorg-server
xorg-server 21.1.3-6
$ echo $XDG_SESSION_TYPE
x11
$ pacman -Q glfw python-glfw
glfw-x11 3.3.6-1
python-glfw 2.1.0-2

Why is this program crashing on my system?
What can I do to make it run just like on windows?



from BadWindow crash in tkinter after calling glfw.init()

python telegram bot ignoring messages

From time to time my telegram bot seems to ignore messages. Unfortunately it never happens to me but to other users and only when they are asked to upload a photo or pdf. Sometimes the corresponding handler is not called. The problem persists even when the MessageHandler has no filters at all. I am using python-telegram-bot v13.7.

Please find below a minimal sample. It should print "receiving something" whenever the handler is called but sometimes it doesn't.

Is there anything I can do?

EDIT: modified the sample to be a MWE (you have to provide a valid telegram bot ID). Most of the time it works just fine but sometimes it will fail and not print "receiving something" although the user uploaded some document (mostly images).

from telegram import Update
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    Filters,
    ConversationHandler,
    CallbackContext,
)

UPLOAD = 0

def welcome(update: Update, context: CallbackContext) -> int:
    update.message.reply_text('Available commands: /upload')
    return ConversationHandler.END

def upload(update: Update, context: CallbackContext) -> int:
    update.message.reply_text('Please upload document.')
    return UPLOAD

def receive(update: Update, context: CallbackContext) -> int:
    print('receiving something...')
    update.message.reply_text('Thank you.')
    return ConversationHandler.END

def cancel(*args) -> int:
    print('cancelled')
    return welcome(*args)

def handle(*args, **options):
    updater = Updater(" ...... ")
    dispatcher = updater.dispatcher

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('upload', upload),
                      MessageHandler(Filters.text, welcome)
                      ],
        states={
            # UPLOAD: [CommandHandler('cancel', cancel), MessageHandler(Filters.photo | Filters.document.pdf, receive)],
            UPLOAD: [CommandHandler('cancel', cancel), MessageHandler(Filters.all, receive)],
        },
        fallbacks=[CommandHandler('cancel', cancel)],
        conversation_timeout=60
    )

    dispatcher.add_handler(conv_handler)
    updater.start_polling()
    updater.idle()

handle()


from python telegram bot ignoring messages

Supabase-Py: TypeError: __init__() got an unexpected keyword argument 'headers' when making client

I have been using supabase in python without problem but today I got an error when I went to create my client. Code is below, all help would be great. Code

from supabase import create_client, Client
supabaseUrl = 'REDACTED'
supabaseKey = 'REDACTED'
supabase = create_client(supabaseUrl, supabaseKey)
path_data = supabase.table('otto').select('*').execute()
print(path_data)

My Error:

Traceback (most recent call last):
  File "andrew_main.py", line 7, in <module>
    supabase: Client = create_client(supabase_url=supabaseUrl, supabase_key=supabaseKey)
  File "/home/garb/.local/lib/python3.8/site-packages/supabase/client.py", line 226, in create_client
    return Client(supabase_url=supabase_url, supabase_key=supabase_key, **options)
  File "/home/garb/.local/lib/python3.8/site-packages/supabase/client.py", line 70, in __init__
    self.postgrest: PostgrestClient = self._init_postgrest_client(
  File "/home/garb/.local/lib/python3.8/site-packages/supabase/client.py", line 185, in _init_postgrest_client
    client = PostgrestClient(rest_url, headers=headers)
TypeError: __init__() got an unexpected keyword argument 'headers'



from Supabase-Py: TypeError: __init__() got an unexpected keyword argument 'headers' when making client

Scroll Snap only when scrolling down

I am struggling with scroll-snap in CSS.

Is there a way to use scroll-snap only in one vertical direction?

I want to make it snap on every section when scrolling down, but not to snap when scrolling back up again. Is it possible inside CSS or do I need some JavaScript?

html {
    scroll-snap-type: y mandatory;
}

body {
    margin: 0;
    scroll-snap-type: y mandatory;
  }
  
  section {
    font-family: sans-serif;
    font-size: 12ch;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    scroll-snap-align: start; 
  }
 
  <head>

    <!-- MAIN STYLE -->
    <link rel="stylesheet" href="style.css">
    

  </head>

    <main>
     <section>
        <h1>Hello!</h1>
     </section>

     <section>
        <h1>Toodles~</h1>
     </section>

     <section>
        <h1>Boodles~</h1>
     </section>
            
    </main>

</html> 


from Scroll Snap only when scrolling down

maxLength causes a crash while a longer text is pasted in

I have declared in my fragment a textInputLayout which contains an edit text with parameters

     android:inputType="textCapCharacters"
     android:maxLength="3"
     android:maxLines="1"

and it works correctly on most devices, it "survives" while user is trying to input more than 3 characters, but IF user tries to paste a string, which contains more than 3 characters it ends up crashing.

"java.lang.IndexOutOfBoundsException: setSpan (0 ... 10) ends beyond length 3" enter image description here

and just to be clear, the app doesn't crash after pasting longer strings on most of the devices but on some it does, and thus is why I'm here, is there any way I could prevent that?



from maxLength causes a crash while a longer text is pasted in

Unity how can i swerve box with use joint?

:Joint

I want to get an image like in the picture with code. I stacked boxes because i must add joint with code. I want to make the boxes look like this as the character slides left and right smoothly. And how can i smooth swerving control in unity for touch or mouse button?



from Unity how can i swerve box with use joint?

Wednesday, 30 March 2022

How can I select text between anchors and highlight them as such?

I have some HTML that looks roughly like this:

<div>
    <p>Herp derpsum sherper herpy derpus jerpy berps cerp terpus.
        Derpy merpus <a name="a1start" type="start"></a>pee derpler berps! Perp
        sherper herp terp herpy derpler.</p>

        <p>Sherper merp herpler herp pee. Derpler terpus, mer re berp
            der perp se?<a name="a2start" type="start"></a> Ze ter derps tee! Herpsum derp
            sherper ler merp derperker <a name="a3start" type="start"></a>jerpy derpler
            herderder zerpus.</p>
</div>
<div>
    <p>Derp sherper perper tee. Derperker
        zerpus ner cerp terpus herpy sherpus sherp. Perp derp pee serp herp
        zerpus herpem herderder derpler berp! Merpus derpy <a name="a1end" type="end"></a>
        herpler sherp derps perper derperker derp dee der. Merpus der
        derps, <a name="a2end" type="end"></a>derpus herpderpsmer! Derp merp er sherpus dee perp herpy derpsum
        perper pee. Herpler derpsum me sherlamer ler derpler derpy. Cerp de
        perper derpy. Le herderder herpler re ter. Serp ze derperker re. Terp
        berps terpus ter, er perp derpsum. </p>
<a name="a3end" type="end"></a>
</div>

In other words, anchors used to mark starts and ends of highlighted areas. They are irrespective of their locations in <div> or other containers. The highlights are overlapping, thus a1start corresponds to a1end.

I'm trying to figure out a way to highlight them, going from start anchors to end anchors, and ignoring all the HTML in between. So, one highlight from a1start to a1end. Another, overlapping highlight from a2start to a2end, and so on.

Note again that these are overlapping, so I can't just use spans, because then how would a given </span> know that it's the end of, e.g., a2 rather than a closer one at a1?

In other words, think of this structure:

<highlightA>
Here is something highlighted in A.
<hightlightB>
Here is something highlighted in A and B. 
</hightlightA>
Here is something only highlighted in B. 
</hightlightB> 
Here is something not highlighted.

I would usually just transform these <a> tags to <span> and </span>, and then highlight them with CSS: span { background-color: yellow }. But that would produce overlapping tag sets, no? Which is illegal in the HTML/XML world?

So I need to use JavaScript to identify these markers, figure out which ones match, and highlight those spans of text, without trying to edit the HTML. In other words, I need to overlay some highlighting on top of the page, without messing with this markup.

I'm a JavaScript beginner, so go easy on me, please.

Edit: Here's a Codepen I put together which illustrates this problm a little better, and tries to implement the (non-working) solution below. It uses different highlight colors to show how the overlapping highlights aren't working.



from How can I select text between anchors and highlight them as such?

When Intent is received in Xamarin, ensure that only one instance is running at any given time

The Xamarin App sends and receives requests to the "central microservice" every 5 seconds using a timer. We can do an "action" in two ways: using intent from another app or scanning a QR code from a web app. Our app sends a request to the "central microservice" when scanning a QR Code or receiving an Intent, and receives a request from the "central microservice" after "5" seconds.

When scanning a QR code, the "central microservice" sends a single request per call. However, while using Intent from another app, you may receive an additional request. Apps are executing in two instances on Intent.

In the AndroidManifest.xml file, I tried adding android:launchMode="singleInstance" and android:launchMode="singleTask".

In MainActivity.cs, I inserted LaunchMode = LaunchMode.SingleTask and LaunchMode = LaunchMode.SingleInstance.

In Another App (the Intent comes from), I inserted intent.addFlags(Intent.FLAG ACTIVITY REORDER TO FRONT).

Both Apps are still active (can be seen by minimizing the app). How can I ensure that only one instance of the app is running at any given time when the Intent is being received?



from When Intent is received in Xamarin, ensure that only one instance is running at any given time

Issue with query params getting undefined in Vuejs?

HelloWorld.vue

import axios from "axios";
export const deploymentattribute = (Ser, id) =>
    axios.get(
        `http://api call here......
    );
<template>
  <div>
    <div v-for="(attribute, index) in attributes" :key="index">
      
    </div>
  </div>
</template> 

<script>
import { deploymentattribute } from "../../assets/deploymentattribute";
export default {
  name: "DeploymentAttributeView",
  data() {
    return {
      attributes: [],
    };
  },
  mounted() {
    this.loadData();
  },
  computed: {
    deploymentattribute() {
      return this.$route.query.Ser, this.$route.query.id;
    },
  },
  methods: {
    loadData() {
      if (!this.deploymentattribute) return; // no ID, leave early
      deploymentattribute(
        this.$route.params.Ser,
        this.$route.params.id
      ).then((attribute) => {
        this.attributes = attribute.data;
      });
    },
  },
 </script>

While calling the api, i am getting ser as undefined. Not sure why.

Attaching the image below.

Where if u see above image, for id, i am getting dynamic one, and for ser. it is always showing as undefined

Is there any way to solve that issue.

Or did i choose the ser correctly like passing query params correctly?

I am thinking that, issue is with the computed property where, i am returning multiple conditions with , i think i schould right the condition there?



from Issue with query params getting undefined in Vuejs?

How to filter common array field from different arrays in Vuejs?

HelloWorld.vue

<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.did">
      <b>.</b>
      <router-link :to="{ name: 'UserWithID', params: { id: item.did } }">
        
      </router-link>
    </div>
    <br /><br /><br />
    <User />
  </div>
</template>

<script>
import User from "./User.vue";
import { datalist } from "./datalist";
export default {
  name: "HelloWorld",
  components: {
    User,
  },
  data() {
    return {
      items: [],
    };
  },
  mounted() {
    datalist().then((r) => {
      this.items = r.data;
    });
  },
  computed: {
    id() {
      return this.$route.params.id;
    },
  },
};
</script>

User.vue

<template>
  <div>
    <div v-for="(idbyval, key) in idbyvals" :key="key">
      
    </div>
  </div>
</template>

<script>
import { datalisttwo } from "./datalisttwo";
export default {
  name: "User",
  data() {
    return {
      lists: [],
    };
  },
  mounted() {
    if (this.$route.params.id)
      datalisttwo(this.$route.params.id).then((r) => {
        let obj = r.data;
        this.lists = [{ ...obj }];
      });
  },
  computed: {
    idbyvals: function () {
      return this.lists.filter((idbyval) => {
        return idbyval.did === this.$route.params.id;
      });
    },
  },
};
</script>

(having errors)Codesandbox for complete code- https://codesandbox.io/s/route-by-id-e365ss?file=/src/components/User.vue

Errors:-

[Vue warn]: Error in mounted hook: "TypeError: (0 , _datalist.datalist) is not a function" TypeError: (0 , _datalist.datalist) is not a function

Expected output:-

I have two arrays called datalist, datalisttwo array. Where in both i have common field called did so based on did i want to filter the array and want to display the data accordingly by id.

During this process, i am unable to display the data, from the array and getting errors as stated above.



from How to filter common array field from different arrays in Vuejs?

Get python3 package metadata given source directory without installing

I am trying to get some package metadata (name, version) given a path to the source directory without installing said package.

These work, using setup.py if you're sitting in the root directory:

> python3 setup.py --name
my_package_name

> python3 setup.py --version
0.1.0

However, I have been cautioned away from using python3 setup.py commands -- and indeed see a warning:

.../lib/python3.7/site-packages/setuptools/installer.py:30: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
  SetuptoolsDeprecationWarning,

I know pip show my_package_name will print various metadata about a package (including name/version), however it requires that the package is installed into the environment. It also doesn't take a source directory and thus requires I already know the name of the package I want the info on.

> pip show .
WARNING: Package(s) not found: .

> pip show my_package_name
WARNING: Package(s) not found: my_package_name

> pip install .
...

> pip show my_package_name
Name: my_package_name
Version: 0.1.0
...
...

Is there any equivalent pip command (or other tool) that will show me the version of a package given the source directory without actually installing the package?

Thanks in advance!



from Get python3 package metadata given source directory without installing

norm of differences of variables in cvxpy

How can I take the following norm in cvxpy

enter image description here

sum(norm(x[i] - x[j], p=2), i=1, j>i, i, j = n)

where x is (n, 2) variable matrix defined by x = cp.Variable((n, 2)). For the problem, I am taking n=16. The following is the code I am trying to completely

import numpy as np
import cvxpy as cp


def solver(pts, var, lmb):
    objective = cp.Minimize(cp.norm(pts - var, 2) + cp.norm(var, 2))
    prob = cp.Problem(objective)
    prob.solve()
    print(prob.value)
    return np.round(var.value, 2)

pts = np.array([(-2, 3), (-3, 5), (-1, 4), (-3, 7) , (0, 3), 
                (-2, -2), (-3, 8), (3, 1), (1, -2), (2, 6), 
                (-2, 6), (-2, 5), (-4, 3), (-4, 6), (-3, 10), 
                (2, -3)])

n = pts.shape[0]
var = cp.Variable((n, 2))

solver(pts, var, 1)


from norm of differences of variables in cvxpy

Tuesday, 29 March 2022

How to set Kotlin version

Hello I'm facing the following error when building the android portion of https://github.com/jitsi/jitsi-meet

'let((T) -> R): R' is only available since Kotlin 1.3.50 and cannot be used in Kotlin 1.3

on line https://github.com/software-mansion/react-native-screens/blob/6c87d7749ec62fbb51fb4ec50af1fa8733ebae86/android/src/main/java/com/swmansion/rnscreens/Screen.kt#L156

In Android Studio settings shows using Kotlin 1.6 in the compiler settings and when I set a project variable kotlinVersion in build.gradle to 1.6.10 I still get the same error.



from How to set Kotlin version

How do cookie consent banners work on the background? Can a website that sets 3rd party cookies on another website ask to allow its cookies?

I'm working on a hobby project. The project is basically an integrable live support service. To describe my questions easily, I will call my service service.com and call the website that uses my service website.com. I'm thinking on implementing session management to restore disconnected visitors chat. To do that I'm planning to use cookie based session management. If owner of the website.com wants to use my service I will provide them a JavaScript file which will inject some HTML on the body, style tags on head and implement interaction. All the website.com's have to do will be importing that JS file and calling a function defined by that JS file. To set 3rd party cookies on that website.com from my service.com I will use this request/response. When website.com requests my JS file from service.com, my service will respond the request with the JS file along with a cookie to manage visitor's sessions. This way service.com will set 3rd party on website.com's visitors.

1st Question: Could this stage of setting cookie on website.com's visitor done on the front-end with that requested JS file or locally (from the website.com's web server) requested JS file? Would that still be a 3rd party cookie since it would be set on the front-end of the website.com?

2nd Questios: My other question is about cookie consents. Can a website that sets 3rd party cookies (e.g service.com) on some other website (e.g website.com) ask to allow their cookies on that website.com? In other words, can I ask website.com's visitors to allow only 3rd party cookies that are set by service.com with the JS file I serve/give to website.com? Would that be legal?

3rd Question: How do cookie consent banners work behind the scenes? What happens when you accept/deny all of the 3rd party cookies used on a website? Or what happens when you filter and accepy only a few of them? How does the process of allowing/disallowing work? Is there some kind of JavaScript that is triggered when you click that "Accept" button or "Decline" button? You can provide me any resources on this topic.

Thanks!



from How do cookie consent banners work on the background? Can a website that sets 3rd party cookies on another website ask to allow its cookies?

Access a .pem public key from .env file

I am storing a public key in a env variable as a string. This public key is from a .pem file. When I try to use it in my code, I get the following error

error:0909006C:PEM routines:get_name:no start line

I have tried what other users have suggested, by converting it to base64 and then using the key, but I still get the same error.

env variable for the public key

PUB_KEY='-----BEGIN PUBLIC KEY-----randomgibberish-----END PUBLIC KEY-----'

Code for converting it to base64

const pubKey = process.env.PUB_KEY
const buff = Buffer.from(pubKey).toString('base64');
console.log(buff)

Using it in the createPublicKey method here

crypto.createPublicKey({
                key: buff,
                format: 'pem',
            });

Any idea what could be going wrong? TIA



from Access a .pem public key from .env file

Monday, 28 March 2022

I am trying to display video stream from opencv to pyqt5 interface but my code is not working

I am trying to display video stream from opencv to pyqt5 interface. I adapted the code from the answer to one question - https://stackoverflow.com/questions/44404349/pyqt-showing-video-stream-from-opencv#:~:text=The%20problem%20is,label.%20For%20example %3A. But when I run my code in pycharm, I get this error:

Process finished with exit code -1073740791 (0xC0000409)

Here is my code:

class Gests_Recognition(QtCore.QObject):

    def __init__(self):
        super(Gests_Recognition, self).__init__()
        self.running = True

    change_pixmap = pyqtSignal(QImage)

    gest_map = {
        0: "up",
        1: "down",
        2: "right",
        3: "left",
        4: "forward",
        5: "back"
    }

    columns = ['x11', 'x21', 'x12', 'x22', 'x13', 'x23', 'x14', 'x24', 'x15', 'x25',
               'x16', 'x26', 'x17', 'x27', 'x18', 'x28', 'x19', 'x29', 'x110', 'x210', 'x111',
               'x211', 'x112', 'x212', 'x113', 'x213', '114', '214', '115', 'x215', 'x116',
               'x216', 'x117', 'x217', 'x118', 'x218', 'x119', 'x219', 'x120', 'x220', 'x121',
               'x221']

    def mapper(self, val):
        return Gests_Recognition.gest_map[val]

    def run(self):
        model = load_model("gestures_model.h5", compile=False)
        drawingModule = mediapipe.solutions.drawing_utils
        handsModule = mediapipe.solutions.hands

        capture = cv2.VideoCapture(0)

        with handsModule.Hands(static_image_mode=False, min_detection_confidence=0.7, min_tracking_confidence=0.7,
                               max_num_hands=1) as hands:
            while self.running:
                # frame == 480 640
                ret, frame = capture.read()
                if ret:
                    processed_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    height_frame, width_frame, channels_frame = frame.shape
                    bytes_line = channels_frame * width_frame
                    qt_frame = QImage(processed_frame.data, width_frame, height_frame, bytes_line, QImage.Format_RGB888)
                    qt_frame = qt_frame.scaled(640, 480, QtCore.Qt.KeepAspectRatio)

                    self.change_pixmap.emit(qt_frame)

                    results = hands.process(processed_frame)

                    cv2.imshow('Hands recognizer', frame)
                    k = cv2.waitKey(1)

                    # do something else.

            cv2.destroyAllWindows()
            capture.release()

class Ui_MainWindow(object):

    @pyqtSlot(QImage)
    def set_image(self, image):
        self.label.setPixmap(QPixmap.fromImage(image))

    def setupUi(self, MainWindow):
        self.cam_btn = QtWidgets.QPushButton(self.centralwidget)
        self.cam_btn.setGeometry(QtCore.QRect(280, 60, 160, 150))
        self.cam_btn.setObjectName("cam_btn")
        self.cam_btn.setCheckable(True)
        self.cam_btn.clicked.connect(self.gest_recognition)
        self.cam_btn.setStyleSheet("QPushButton{background-color: #aae053;\n"
                                        "border-radius: 60%;\nbackground-image: url('images/hand.png');\n"
                                        "background-repeat: no-repeat;\nbackground-position: center;}\n"
                                        "QPushButton:hover{background-color: #81eb3b;}")

        self.label = QLabel(self.centralwidget)
        self.label.move(40, 240)
        self.label.resize(640, 480)
        self.label.setStyleSheet("border: 5px solid black;")

    def gest_recognition(self):
        if self.cam_btn.isChecked():
            self.cam_btn.setStyleSheet("QPushButton{background-color: red;\n"
                                       "border-radius: 60%;\nbackground-image: url('images/pause.png');\n"
                                       "background-repeat: no-repeat;\nbackground-position: center;}\n")
            self.thread_gests = QtCore.QThread()
            self.g_recog = Gests_Recognition()

            self.g_recog.moveToThread(self.thread_gests)
            self.g_recog.change_pixmap.connect(self.set_image)
            self.thread_gests.start()
        else:
            self.cam_btn.setStyleSheet("QPushButton{background-color: #aae053;\n"
                                       "border-radius: 60%;\nbackground-image: url('images/hand.png');\n"
                                       "background-repeat: no-repeat;\nbackground-position: center;}\n"
                                       "QPushButton:hover{background-color: #81eb3b;}")
            self.g_recog.running = False
            self.thread_gests.terminate()


from I am trying to display video stream from opencv to pyqt5 interface but my code is not working

Annotate a function argument as being a specific module

I have a pytest fixture that imports a specific module. This is needed as importing the module is very expensive, so we don't want to do it on import-time (i.e. during pytest test collection). This results in code like this:

@pytest.fixture
def my_module_fix():
    import my_module
    yield my_module

def test_something(my_module_fix):
    assert my_module_fix.my_func() = 5

I am using PyCharm and would like to have type-checking and autocompletion in my tests. To achieve that, I would somehow have to annotate the my_module_fix parameter as having the type of the my_module module.

I have no idea how to achieve that. All I found is that I can annotate my_module_fix as being of type types.ModuleType, but that is not enough: It is not any module, it is always my_module.



from Annotate a function argument as being a specific module

Why do I get UNKNOWN/CUSTOM URL SCHEME error in React Native Expo Google/Facebook login?

I have a react native expo managed workflow project with Firebase backend set up. On android emulator facebook and google login WORKS with firebase, however when I release the apk (expo build:android) I get the following error during redirect: "UNKNOWN/CUSTOM URL SCHEME"

I use the following packeges: Google with expo-auth-session Facebook with expo-facebook

enter image description here

Since it works in emulator, I am pretty sure my Secrets, ID's and redirect URL's are okay, it redirects me without any problem. Also firebase created the google cloud profile for me, I just added the valid Oauth redirect URI's to my WEB ID settings. Same for facebook, added the firebase redirect URL, as well as the expo one.

I tried to add "scheme":"myapp" to app.json, but no luck. Not sure what to do...

import {GoogleAuthProvider, FacebookAuthProvider, signInWithCredential} from 'firebase/auth';
import * as Facebook from 'expo-facebook';
import * as Google from 'expo-auth-session/providers/google';
import * as WebBrowser from 'expo-web-browser';

WebBrowser.maybeCompleteAuthSession();

//Google
const [request, response, promptAsync] = Google.useIdTokenAuthRequest(
    {
      clientId: 'xxxxxxxxxxxxxxxxxxxx24u2l7k576m03n.apps.googleusercontent.com',
      redirectUriOptions: {
        // scheme: 'com.graphite.ekisallatkonyv',
        useProxy: true,
      },
      },
  );
  React.useEffect(() => {
    if (response?.type === 'success') {
        const { id_token } = response.params;
  
        const credential = GoogleAuthProvider.credential(id_token);
        signInWithCredential(auth, credential)
        .then((result) => {
            addDefaultData(result.user.uid)
        });
    }
  }, [response]);


const google_login_ButtonClick = async() => {
    promptAsync({useProxy: true,showInRecents: true})
}


const facebook_login = async() => {
    try {
        await Facebook.initializeAsync({
          appId: FBAPPID,
        });
        const { type, token } =
          await Facebook.logInWithReadPermissionsAsync({
            permissions: ['public_profile', 'email'],
          });
        if (type === 'success') {
          const credential = FacebookAuthProvider.credential(token)
          signInWithCredential(auth, credential)
          .then((result) => {
            addDefaultData(result.user.uid)
          })
        } else {
          // type === 'cancel'
        }
      } catch ({ message }) {
        Alert.alert(`ERROR: ${message}`);
      }
}


from Why do I get UNKNOWN/CUSTOM URL SCHEME error in React Native Expo Google/Facebook login?

Is there anyway we can run dart code while in terminated or background state?

I'm currently working on an App which have video calling integrated in it. I'm using Flutter language to build my app but I want my app to be Like WhatsApp. I want to have the same functionality for example when someone calls you the calling UI appears. I used CallKeep and WorkManager packages but those did not helped at all. If anyone have a solution for that please let me know! Thank you!



from Is there anyway we can run dart code while in terminated or background state?

How to download magnet or torrent file in react native

Is there a way for downloading and saving torrent files in react native? I tried using react-native-torrent-streamer but it doesn't work anymore with the latest version of react native. So is there another way to do it?



from How to download magnet or torrent file in react native

replace with the id if it match with id of other using node js / javascript

const data = [
    {
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        content: { type: { name: "Author" } },
      },
      DataDetails: {
        shortSlugOption: { "en-us": "some value", "za-op": "random value" },
        mediaFileAssetLink: { "en-us": "some file", "za-op": "file Linl" },
        mediaFileAssetGalary: { hi: "file link 2" },
        singleMediaImage: { hi: "file link single", "en-us": "english link" },
        gallery: {
          "za-op": [
            {
              conf: {
                type: "media",
                id: "01",
              },
            },
            {
              conf: {
                type: "media",
                id: "10",
              },
            },
          ],
        },
        mediaAccess: {
          hi: {
            conf: {
              type: "media",
              id: "01",
            },
          }, 
          en: {
            conf: {
              type: "media",
              id: "1000",
            },
          },
        },
      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        content: { type: { name: "Author" } },
      },
      DataDetails: {
        short: { "en-us": ["shorts", "values"], "za-op": "short details" },
        shortSlugOption: { "hi-In": "options" },
        booleanField: { "hi-In": "true" },
        entryDetails: {
          "hi-In": [
            {
              conf: {
                type: "entry",
                id: "100",
              },
            },
            {
              conf: {
                type: "entry",
                id: "34",
              },
            },
          ],
        },
        singleEntry: {
          "en-us": {
            conf: {
              type: "entry",
              id: "34",
            },
          },
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        content: { type: { name: "testing" } },
      },
      DataDetails: { testingNewValue: { "en-us": "details value" } },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        content: { type: { name: "new" } },
      },
      DataDetails: {
        oneReference: { hi: "values 1" },
        multiReference: { "hi-In": "values 2" },
        media: {
          hi: {
            conf: {
              type: "media",
              id: "01",
            },
          },
        },
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        content: { type: { name: "new" } },
      },
      DataDetails: { testingNewValue: { "hi-IN": "jksdsdo" } },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        content: { type: { name: "testing" } },
      },
      DataDetails: { testingNewValue: { "en-us": "kknksdo" } },
    },
    {
      system: {
        id: "2OspeCtNK0sh2cPiuU9jIz",
        type: "Entry",
        content: { type: { name: "dummy" } },
      },
      DataDetails: {
        short: { "za-op": "dfvndkssa" },
        shortSlugOption: { hi: "sdocjosmdc" },
        mediaFileAssetLink: { "en-us": "jdsojocis" },
        booleanField: { "hi-In": "true" },
      },
    },
    {
      system: {
        id: "2eAmIIuG4xkLvatkU3RUSy",
        type: "Entry",
        content: { type: { name: "dummy" } },
      },
      DataDetails: {
        dummy: { "en-us": "dshcifdvk" },
        india: { "za-op": "sdci", hi: "hewd" },
      },
    },
    {
      system: {
        id: "7hbdS3MgfZ73TOtlu1WfXw",
        type: "Entry",
        content: { type: { name: "dummy" } },
      },
      DataDetails: {
        testingNewValue: { "en-us": "sdcoklsdc" },
        locationField: { hi: "sdcndkdc" },
      },
    },
  ],
  result = data.reduce(
    (
      r,
      {
        system: {
          id,
          content: {
            type: { name },
          },
        },
        DataDetails,
      }
    ) => {
      r[name] ??= {};
      Object.entries(DataDetails).forEach(([key, object]) => {
        Object.entries(object).forEach(([loc, value]) => {
          r[name][loc] ??= {};
          r[name][loc][id] ??= {};
          if (typeof value !== "object") {
            r[name][loc][id][key] = value;
          } else {
            console.log(value);
          }
        });
      });
      return r;
    },
    {}
  );

console.log(result)

In the above output I am trying to replace the media with the below object as the below code is for the media I want to match the id which is present inside the data output and replace the object with the mediaObj matching id

let mediaObj = {
  "01": {
    status: true,
    tag: [],
    filename: "exute-image.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "02": {
    status: true,
    tag: [],
    filename: "wallpapers-6.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "10": {
    status: true,
    tag: [],
    filename: "in-space-rk.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "25": {
    status: true,
    tag: [],
    filename: "justice-league.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "67": {
    status: true,
    tag: [],
    filename: "batman.jpg",
    is_dir: false,
    parent_uid: null,
  },
};

so my expected output is like this when I run my program

Expected Value

{
  "Author": {
    "en-us": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "shortSlugOption": "some value",
        "mediaFileAssetLink": "some file",
        "singleMediaImage": "english link"
      },
      "1aBOO8tu3lUsjtICuIbUM5": {}
    },
    "za-op": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "shortSlugOption": "random value",
        "mediaFileAssetLink": "file Linl"
      },
      "1aBOO8tu3lUsjtICuIbUM5": {
        "short": "short details",
        "gallery": [
          {
            "status": true,
            "tag": [],
            "filename": "exute-image.jpg",
            "is_dir": false,
            "parent_uid": null
          },
          {
            "status": true,
            "tag": [],
            "filename": "in-space-rk.jpg",
            "is_dir": false,
            "parent_uid": null
          }
        ]
      }
    },
    "hi": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "mediaFileAssetGalary": "file link 2",
        "singleMediaImage": "file link single",
        "mediaAccess": [
          {
            "status": true,
            "tag": [],
            "filename": "exute-image.jpg",
            "is_dir": false,
            "parent_uid": null
          }
        ]
      }
    },
    "hi-In": {
      "1aBOO8tu3lUsjtICuIbUM5": {
        "shortSlugOption": "options",
        "booleanField": "true"
      }
    }
  }
}

as the id get changed and I want to match every-time with the mediaObj object and replace the value if there is multiple or single media file exits but if the media id does not match with mediaObj then it should delete the that object as you can see in mediaAccess id 1000 does not match with the mediaObj so it should delete it

as the same applies with the entries if I get the media replace code then I can try with the entry code too



from replace with the id if it match with id of other using node js / javascript

Sunday, 27 March 2022

Extended Logout in MVC 5

Extending logged in time as per user's choice.

Scenario: The ASP.NET MVC 5 web application is hosted in Azure WebApp WebConfig is set to timeout in 60 minutes of no requests made to the server as shown below

WebConfig:

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="60" slidingExpiration="true" name="MYAUTHDV" cookieSameSite="None" requireSSL="true" />
</authentication>

In the login screen, we would like to provide a CHECKBOX and if user ticks it and login, the webapp should not log them out for next 12 hours even if there is no activity.

enter image description here

So far, I have tried a javascript timer running on the _layoutpage.chtml and a local storage time value registered at loggged in time at the client side. The javascript timer will ping to the server every 20 minutes to keep the login alive. This is not always working for multiple reasons like browser, machine sleep mode, hard disk turnoff internet interruptions and other unknown reasons as well etc. There is also an issue we have to overcome regarding sliding expiration vs javascript pinging .https://ift.tt/1xWMQDA I am also open to solutions involving server handling as well. Hoping a client side solution will incur less modification in our existing app.



from Extended Logout in MVC 5

Python Eclipse Paho Client - TLS Connection to MQTT Broker Exception: No ciphers available

I am trying to create a connection to a TLS (TLSv1) secured MQTT Broker(Rabbitmq with MQTT Plugin enabled) with the python implementation of the eclipse paho client. The same works fine with the MQTTFX application which is based on the java implementation of paho. For this i am using self signed certificates.

    Java version uses: 
    CA-File: ca_certificate.crt 
    Client Certificate client_cert.crt  
    Client Key File: client_key.key 
    Python Version should use:  
    CA-File: ca_certificate.pem 
    Client Certificate: client_cert.pem  
    Client key file: client_key.key

I tried to establish a connection like this:

    import ssl
    
    import paho.mqtt.client as paho
    
    # Locations of CA Authority, client certificate and client key file
    ca_cert = "ca_certificate.pem"
    client_cert = "client_certificate.pem"
    client_key = "client_key.pem"
    
    # Create ssl context with TLSv1
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    context.load_verify_locations(ca_cert)
    context.load_cert_chain(client_cert, client_key)
    
    # Alternative to using ssl context but throws the exact same error
    # client.tls_set(ca_certs=ca_cert, certfile=client_cert, keyfile=client_key, tls_version=ssl.PROTOCOL_TLSv1)
    
    client = paho.Client()
    client.username_pw_set(username="USER", password="PASSWORD")
    client.tls_set_context(context)
    client.tls_insecure_set(False)
    client.connect_async(host="HOSTNAME", port="PORT")
    client.loop_forever()

Which results in the following error:

    ssl.SSLError: [SSL: NO_CIPHERS_AVAILABLE] no ciphers available (_ssl.c:997)

Could it be that I need to explicitly pass a cipher that the broker supports or could it be due of an older openssl version? I am a little bit lost right now, maybe someone has a clue on how to solve this.

Edit: I got it to work by myself but still not sure why exactly it works now.

  1. Changed context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    to context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  2. Changed client.tls_insecure_set(False)
    to client.tls_insecure_set(True)


from Python Eclipse Paho Client - TLS Connection to MQTT Broker Exception: No ciphers available

How do I send SMS using the adb shell command on all versions from Android 6 to Android 12?

I'm trying to send messages using adb shell commands. I sent on Android 10 but not on Android 11. I tried everything but without success. I found source code of isms service for android 11 here. I have 2 more Android 11 phones and when I test them the result is the same. To test that my shell commands are working on the device, I tried the input command and it does. I read this and still it didn't help.

The command I use:

adb shell service call isms 7 i32 0 s16 "com.android.mms.service" s16 "%number%" s16 "null" s16 "%message%" s16 "null" s16 "null"

Output of this command:

Result: Parcel(00000000 '....')

Can someone help, how do I send messages with adb shell commands on Android 11?

(I tried on Android 12 and result is same)



from How do I send SMS using the adb shell command on all versions from Android 6 to Android 12?

How to call array values dynamically and pass it as query params in Vuejs?

HelloWorld.vue

export const datalist = [
  { id: 1, val: "11", kk: "potter" },
  { id: 2, val: "22", kk: "james" },
  { id: 3, val: "55", kk: "limda" },
  { id: 4, val: "77", kk: "stepen" }
];
 
<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <b>.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        
      </router-link>
    </div>
    <br /><br /><br />
    <User />
  </div>
</template>

<script>
import User from "./User.vue";
import { datalist } from "./datalist";
export default { 
  name: "HelloWorld",
  components: {
    User,
  },
  data() {
    return {
      items: datalist,
    };
  },
};
</script>

User.vue

import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
import book from "./components/book.vue";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    { path: "/", name: "User", component: HelloWorld },
    { path: "/", name: "BookWithID", component: book },
    { path: "/:id", name: "UserWithID", component: HelloWorld }
  ]
});

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#app");
export const datalisttwo = [
  { id: 1, book: "steel", pen: "p1", gap: "1" },
  { id: 2, book: "iron", pen: "jp2", gap: "5" },
  { id: 3, book: "platinium", pen: "p3", gap: "2" },
  { id: 4, book: "gold", pen: "p4", gap: "9" }
];
<template>
  <div>
    <router-link :to="{ name: 'BookWithID' }">
      
    </router-link>
  </div>
</template>

<script>
import { datalisttwo } from "./datalisttwo";
export default {
  name: "User",
  components: {},
  data() {
    return {
      lists: datalisttwo,
    };
  },
  computed: {
    user: function () {
      return this.lists.find((item) => item.id === this.$route.params.id);
    },
  },
};
</script>

As per the below code, in the datalisttwo.js I have array values like steel and pen Where i want to call both of them together like steel/pen as an api call in the mounted() .

When i click on the router-link, from User.vue component.

Ex:- I want to pass the pen/gap array values as query parameters. when clicked on from user.vue componet. Please go through codesandbox once, I tried adding computed property for pen and gap. But pen/gap --- but not calling dynamically

Here is my code:- https://codesandbox.io/s/new-hill-6yum4o?file=/src/components/User.vue



from How to call array values dynamically and pass it as query params in Vuejs?

ipdb stops showing prompt text after carriage return

Recently when setting up a breakpoint using ipdb.set_trace(context=20) I can see the command I'm inputing the first time, after hitting return, next time I write an instruction or command in my ipdb prompt is not showing. When I hit enter it executes it and shows it in the previous lines.

This wasn't happening until very recently. I'm using mac, with iterm, latest ipdb and pytest.



from ipdb stops showing prompt text after carriage return

Saturday, 26 March 2022

Typescript Generics for nested array of objects

Hello i am trying to add correct type to object with nested values.

Here is code in sandbox: https://codesandbox.io/s/0tftsf

interface Product {
  name: string,
  id: number
  productList?:ProductItem[]
}

interface ProductItem { 
  color: string, 
  size: number 
 }


type IValidation<T> = {
  field: keyof T
  nestedValidations?: IValidation<
    Pick<
      T,
      {
        [K in keyof T]-?: T[K] extends object ? K : never
      }[keyof T]
      >
    >[] // THIS IS IMPORTANT FOR QUESTION!
  validators?: (any | any | any)[]
}

export async function validateIt<T>(payload: T, validations: IValidation<T>[]): Promise<
  Partial<{
    [key in keyof T]: string[]
  }>
  > { 
    return Promise.resolve(payload);
  }

const product: Product = {
  id: 1,
  name: 'playstation',
  productList: [{
    color: 'red',
    size: 32
    }
  ]
}

const test = validateIt<Product>(product, [
  {
    field: "productList",
    validators: [],
    nestedValidations: [
      {
        field: 'color',
        validators: []
      }
    ]
  }
])

So getting type error and overall i am trying to find correct type for nestedValidations property, which should match interface Product

ERROR



from Typescript Generics for nested array of objects

Android databinding generated files disappears when coding

I am facing a strange problem when Fragment*Binding files are deleted while I am writing code (all references become unresolved, generated files absent in files system) that can be fixed by clean project-> make the project but it is time-consuming.
Such behavior occurs 3-4 times per hour. Originally I thought I might be deleted by antivirus software, but I checked that all paths related to development are in Av exceptions. Android studio bumblebee latest updates (happened few updates before too)



from Android databinding generated files disappears when coding

How to Create a Tamil Phonetic keyboard inputs in python?

My target: create a Phonetic Keyboard in the Tamil language, using dictionary key mapping. My struggle: How to replace my keys with values and set that value to my textbox. For Example: If I press "K" in textbox1, then my textbox1.text will change into the Tamil letter "க்", if I press "Ku" then textbox1.text will be replaced by the Tamil letter "கு",, if I press "kuu" then textbox1.text will be replaced by the Tamil letter "கூ" And then If I press "m" then the Tamil letter "à®®்" will be added to the previous letter "கூ" and now textbox1.text becomes "கூà®®்"

import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

tamil_dict = {"a":{'a':'அ','aa':'ஆ'},
              "k":{'k':'க்','ka':'க','kaa':'கா','ki':'கி','kii':'கீ','ku':'கு','kuu':'கூ'},
              "m":{'m':'à®®்','ma':'à®®','maa':'à®®ா','mi':'à®®ி','mii':'à®®ீ','mu':'à®®ு','muu':'à®®ூ'},
              "i":{"i":"இ"},
              "e":"ஈ "}


class Keyboard_Dict(QWidget):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Tamil InPut ")

        self.tbox1 = QLineEdit()
        self.tbox1.setFont(QFont('Arial Unicode MS', 10, QFont.Bold))
        self.tbox1.textChanged.connect(self.func_textbox_textchanged)

        self.tbox2 = QLineEdit()
        self.tbox2.setFont(QFont('Arial Unicode MS', 10, QFont.Bold))

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.tbox1)
        self.vbox.addWidget(self.tbox2)
        self.setLayout(self.vbox)

        self.process_txt_temp_letter = ""
        self.process_txt_temp_position = 0
        self.process_letter_found = False
        self.process_letter_temp = False
        self.processed_text =""
    def func_textbox_textchanged(self,txt):
        self.txt_len = len(self.tbox1.text())
        if self.txt_len >= 1:
            self.process_txt_position = self.txt_len-1
            self.process_text_letter = (txt[self.process_txt_position])


            if self.process_letter_found == False:
                if (txt[self.txt_len-1]) in tamil_dict:
                    self.process_letter_found = True
                    self.process_txt_temp_position = (self.txt_len-1)
                    self.process_txt_temp_letter = (txt[self.txt_len-1])
                    self.process_letter_temp = True

            if self.process_letter_temp == True :
                if (txt[self.process_txt_temp_position:]) in tamil_dict[self.process_txt_temp_letter]:
                    self.processed_text =  tamil_dict[self.process_txt_temp_letter][txt[self.process_txt_temp_position:]]
                    print(self.processed_text)
                    # print("jjjjjjjjj",tamil_dict[self.process_txt_temp_letter][txt[self.process_txt_temp_position:]])

                elif (txt[self.process_txt_temp_position:]) not in tamil_dict[self.process_txt_temp_letter]:
                    self.process_txt_temp_position = self.txt_len - 1
                    self.process_txt_temp_letter = (txt[self.process_txt_temp_position])

                    if self.process_txt_temp_letter not in tamil_dict:
                        self.process_letter_temp = False
                        self.process_letter_found = False
                    else:
                        self.processed_text = tamil_dict[self.process_txt_temp_letter][txt[self.process_txt_temp_position:]]
                        print(self.processed_text)
                        # print("ffffff", tamil_dict[self.process_txt_temp_letter][txt[self.process_txt_temp_position:]])
        self.tbox2.setText(self.processed_text)





def main():
    app = QApplication(sys.argv)

    mainscreen = Keyboard_Dict()
    app.setStyle("Fusion")
    mainscreen.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

update : 1 I Have a keys Maps as follows :

      *Main character/processed first character : "k"* 
        k     : "Apple"
        ka    : "Bannana"
        kaa   : "Citrus:
        ki    : "Orange"
        kii   : "Pine" 
        *Main character/processed first character : "M"* 
         m     : "is" 
         ma    : "more"
         maa   : "taste"
 *Main character/processed first character : "i"* 
         i     : "world"
         ii    : "earth"

tamil_dict ={"k":{"k":"apple","ka":"bannana","kaa":"citrus","ki":"orange","kii":"pine"},
             "m":{"m":"is","ma":"more","maa":"taste"},
             "i":{"i":"world","ii":"earth"}
            }


     

In my textbox.text, my first character is "A", not found in dictionary, so need not process that character and display as it is.

In my textbox.text, my second input word is "k", which is found in my dictionery and also "k" is the main Word. Now My processed word is "A"+"k", my textbox is replaced as follows, "A" + "Apple" = AApple.

In my textbox.text, my third charcter is "a", Now my processed word is "ka", its found in dict . so replaced with that equivalent value "Banana". Now My processed word is "A"+"ka", and now my textbox.text as follows : "A"+"banana" = Abanana.

In my textbox.text, my fourth charcter is "a", my processed word becomes "Kaa" its equvilient value is "citrus", now my processed word is "A"+"kaa" , its equvlient value is "A"+"citrus" = "Acitrus"

In my textbox.text my fifth input character is "m", now my processed word is "kaam",not found in dictionery. Now we split character "m" and check it in dict, whether its found or not, if Found, then we replace its equvilent value. Now My processed word is "A"+'kaa'+"m" and its vaule is "A"+"citurs"+"is", my textbox.text as follows "Acitrusis"

sixth input word is "a", now my processed character is "A"+"kaa"+"ma" equvilaent value is "A"+"citrus"+"more". Textbox.text become "Acitrusmore"

Now, if I press charcter "i" not found in "m" set. so we split "i" sepreately and check it in dict, if found, replace that value or leave as it is.

If 7th input character is " space bar" then process will end.

if my 8th input charcter is some english alphabet, once agin start process and replace equvilaent value and so on

update : 2 For more cleareance : enter image description here



from How to Create a Tamil Phonetic keyboard inputs in python?

How to pass focus from an iframe to next focusable element in host page?

Background

I have an iframe widget which will be embedded in other pages - I have no prior knowledge of the host page's structure and code, and the iframe will be cross-domain and likely sandboxed.

My goal is to give the iframe widget a single tab stop - after focusing on it there's a dedicated key combination to "enter" the widget, but normal tabbing should skip forward to the next focusable element in the host page.

Question: After the iframe receives focus and a new tab keypress is detected, how can I pass the focus to the host page's next focusable element?

Simple example:

<!-- host page -->
<button> first button </button>
<iframe src="myIframeWidget.com"/>
<button> second button </button>

In the above, if the first button is focused, then the expected behavior is that on first tab the iframe will receive focus, and on the next tab the second button will receive focus (skipping all focusable elements inside the iframe).

Once the iframe is focused and tab is pressed, I need to pass the focus from my iframe to the second button.

Notes

  1. Since my iframe DOM is rather large, I don't want to set tabindex=-1 to all internal focusable elements.
  2. At the time of writing, aria-hidden="true" does not remove an element or its descendants from the focus sequence. I'm not aware of any other aria attribute which removes an entire subtree from the focus sequence.
  3. A pure JS solution is preferred to one relaying on external packages.
  4. I'll also need to handle reverse-tabbing, but I assume that the same approach for forward-tabbing will apply - if there are any crucial differences, please mention them in your answer if possible.
  5. There's an edge case where there isn't anything focusable after the widget - typically in those cases the browser will focus on the address bar buttons - if there's a way to handle that it'll be great to know, but this probably should be handled in a separate question.

Thanks!



from How to pass focus from an iframe to next focusable element in host page?

update pug variable with client side javascript onchange event

I have server side code which serves up a pug file, the pug file has variables parsed to it when rendered by my server side code.

I would like to be able to update that variable in pug when a check box is checked / unchecked.

my server side code:

// load the express module
const express = require('express');

const simpleVarDisplaySite = 'simpleVarDisplay.pug';

const app = express();
app.use(express.urlencoded({extended: false}))
app.use(express.static(__dirname+'/static'));

// simpleVarDisplaySite page
app.get('/', function (req, res) {
    console.log(req.url);
    let myHeading = 'Simple Pug Page';
    let simpleObject = {
        'date': {
            'day': 'time'
        }
    }
    
    res.render(simpleVarDisplaySite, { 
        heading: myHeading,
        pugObject: simpleObject,
    });
})

app.listen(8082)

my pug file:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Simple Pug</title>
    <link rel="stylesheet" href="/styles/MainStyling.css">
    <script src="/scripts/pugVarUpdater.js"></script>
</head>

<body>    
    <form method="POST">
        <div>
            <header>
                <h1 class="HeaderEl" id="heading">#{ heading }</h1>
            </header>
            <div>
                <input type="checkbox" id="simpleCheckBox" onchange="JavaScript:updatePugVarFunc()">
            </div>
            <br>

            each valueDict, date in pugObject
                <div>
                    <div>
                        <span>#{date}</span>
                    </div>
                    <br>
                    each time, day in valueDict
                        <div>
                            <span>#{day}</span>
                        </div>
                        <div>
                            <span>#{time}</span>
                        </div>
                </div>
        </div>
    </form>
</body>

</html>

my client-side js when checkbox is checked / unchecked:

function updatePugVarFunc() {

    const simpleVarDisplaySite = 'simpleVarDisplay.pug';

    let newSimpleObject = {
        'new_date': {
            'new_day': 'new_time'
        }
    }
    alert(newSimpleObject)

    let myNewHeading = 'My New Simple Heading'
    alert(myNewHeading)

    document.body.innerHTML = simpleVarDisplaySite({
        heading: myNewHeading,
        pugObject: newSimpleObject,
    });
}

I would like to have pug variable: pugObject updated when the checkbox is checked / unchecked onChange event, and see the updates in my browser, which I have tried with:

document.body.innerHTML = simpleVarDisplaySite({
  heading: myNewHeading,
  pugObject: newSimpleObject,
});

But that does not work.

I know that client-side is handled rather differently from server-side, but I am soo hoping that there is a solution to my specific problem.

Please note that I am a nood with javascript and pug, and I am very open to any and all suggestions to better achieve my goal.

My File structure:

server.js
views
  simpleVarDisplay.pug
static
  scripts
    pugVarUpdater.js

PS: I have had a look at: use client-side js variable in pug And that did not help me.

Your assistance and guidance is much appreciated.



from update pug variable with client side javascript onchange event

Is there a way to subscribe to Course Changes (Archive/Deletion) in Google Classroom PubSub Registrations?

I have a working Google Classroom Pub Sub Registration Service.

There is a sequential registration process for each course in the organization, however this only emits when there are course work changes.

Is there a way to tap into courses being Archived or Deleted? I would like to run a background function to update our system by removing courses that are either archived or deleted by any teacher or admin.



from Is there a way to subscribe to Course Changes (Archive/Deletion) in Google Classroom PubSub Registrations?

Friday, 25 March 2022

Passing a promise in a Custom Event detail

I'm trying to pass a promise object via a Custom Event's detail property.

scriptA.js

async function myFunc() {...}

document.addEventListener('eventA', function (event) {
    const outputEvent = new CustomEvent('eventB', { detail: { promise: myFunc() } });
    document.dispatchEvent(outputEvent);
});

scriptB.js

document.addEventListener('eventB', async function (event) {
    const { promise } = event.detail;
    const result = await promise;
    console.log('result', result);
});

Then I try to call this (either from scriptB or from a 3rd unrelated script, after both scriptA and scriptB were loaded):

document.dispatchEvent(new CustomEvent('eventA'));

When I print the detail object in scriptA before dispatching the event, it shows the promise object correctly, but it doesn't arrive to to scriptB at all - the detail property arrives as null.

Am I missing something here?


When I create a sandbox to replicate it, it works fine.

However, in my actual code, it doesn't. here are screenshots from Chrome debugger:

In the dispatch part: enter image description here enter image description here

In the listener part: enter image description here

If I don't include the response (which is a Promise object) in the dispatched detail, everything arrives correctly.



from Passing a promise in a Custom Event detail

Multi-tenant authentication flow

How do companies handle authentication in their multi-tenant web apps?

Essentially I have a single PostgreSQL database instance with many tables. Each table has a workspace_id column which I will use to use to grant/deny access. You can think of a workspace as a client and a single user can be associated with multiple workspaces.

My initial thought was to:

  1. Use the frontend app and let the user send the email and password to the backend.
  2. Backend validates details and returns all the workspaces the user belongs to.
  3. The frontend app displays the workspaces.
  4. User selects the workspace they want to login into. The id of the workspace and the user details that were passed in step 1 is again to the backend.
  5. The backend validates again all the details and issues a jwt token containing the user details and the workspace id.
  6. Later when the user tries to access any resource I will extract the workspace id from the token to check if the user has access to a resource or not.

I am halfway through implementing what I've described above but I am not sure if that's the best approach. What do you think?



from Multi-tenant authentication flow

Record Video and Screen together and overlay with Javascript

I want to record a user's screen alongside their webcam and display the result as an overlay, like this:

Screen and webcam overlay

I assume that while recording I can display the multiple streams in two separate video elements and overlay them with CSS.

However, how do I save the result as an overlay of the two videos?



from Record Video and Screen together and overlay with Javascript

Efficiently count all the combinations of numbers having a sum close to 0

I have following pandas dataframe df

column1 column2 list_numbers          sublist_column
x        y      [10,-6,1,-4]             
a        b      [1,3,7,-2]               
p        q      [6,2,-3,-3.2]             

the sublist_column will contain the numbers from the column "list_numbers" that adds up to 0 (0.5 is a tolerance) I have written following code.

def return_list(original_lst,target_sum,tolerance):
    memo=dict()
    sublist=[]
    for i, x in enumerate(original_lst):
    
        if memo_func(original_lst, i + 1, target_sum - x, memo,tolerance) > 0:
            sublist.append(x)
            target_sum -= x          
    return sublist  

def memo_func(original_lst, i, target_sum, memo,tolerance):
    
    if i >= len(original_lst):
        if target_sum <=tolerance and target_sum>=-tolerance:
            return 1
        else:
            return 0
    if (i, target_sum) not in memo:  
        c = memo_func(original_lst, i + 1, target_sum, memo,tolerance)
        c += memo_func(original_lst, i + 1, target_sum - original_lst[i], memo,tolerance)
        memo[(i, target_sum)] = c  
    return memo[(i, target_sum)]    
    

Then I am using the "return_list" function on the "sublist_column" to populate the result.

target_sum = 0
tolerance=0.5

df['sublist_column']=df['list_numbers'].apply(lambda x: return_list(x,0,tolerance))

the following will be the resultant dataframe

column1 column2 list_numbers          sublist_column
x        y      [10,-6,1,-4]             [10,-6,-4]
a        b      [1,3,7,-2]               []
p        q      [6,2,-3,-3.2]            [6,-3,-3.2]  #sum is -0.2(within the tolerance)

This is giving me correct result but it's very slow(takes 2 hrs to run if i use spyder IDE), as my dataframe size has roughly 50,000 rows, and the length of some of the lists in the "list_numbers" column is more than 15. The running time is particularly getting affected when the number of elements in the lists in the "list_numbers" column is greater than 15. e.g following list is taking almost 15 minutes to process

[-1572.35,-76.16,-261.1,-7732.0,-1634.0,-52082.42,-3974.15,
-801.65,-30192.79,-671.98,-73.06,-47.72,57.96,-511.18,-391.87,-4145.0,-1008.61,
-17.53,-17.53,-1471.08,-119.26,-2269.7,-2709,-182939.59,-19.48,-516,-6875.75,-138770.16,-71.11,-295.84,-348.09,-3460.71,-704.01,-678,-632.15,-21478.76]

How can i significantly improve my running time?



from Efficiently count all the combinations of numbers having a sum close to 0

how to send audio stream between child processes in nodejs

How do i properly send stream to a child process. I am trying to stream audio from client to server using this method

I am getting the audio stream from client


const ss = require('socket.io-stream');
const socketIo = require('socket.io');

server = http.createServer(app);
io = socketIo(server);

const child_process = childProcess.fork('./child_process.js');


io.on('connect', (client) => {


    // when the client sends 'stream-transcribe' events
    // when using audio streaming
    ss(client).on('stream-transcribe', function(stream, data) {
     
    var combine_data = {
            "data": data,
            "stream": stream,
            "event":"new_stream"
          }
    
     child_process.send(combine_data)


  }


}
 

this call

     child_process.send(combine_data)

throws the error

node:internal/child_process/serialization:127 const string = JSONStringify(message) + '\n'; ^

TypeError: Converting circular structure to JSON --> starting at object with constructor 'Namespace' | property 'server' -> object with constructor 'Server' | property 'nsps' -> object with constructor 'Object' --- property '/' closes the circle at stringify () at writeChannelMessage (node:internal/child_process/serialization:127:20) at ChildProcess.target._send (node:internal/child_process:837:17) at ChildProcess.target.send (node:internal/child_process:737:19) at Socket. (/Volumes/GoogleDrive/My Drive/app/server.js:236:40) at Socket.onstream (/Volumes/GoogleDrive/My Drive/app/node_modules/socket.io-stream/lib/socket.js:184:14) at Socket.emit (node:events:526:28) at Socket. (/Volumes/GoogleDrive/My Drive/app/node_modules/component-bind/index.js:21:15) at Socket.emit (node:events:526:28) at /Volumes/GoogleDrive/My Drive/app/node_modules/socket.io/lib/socket.js:528:12

Node.js v17.5.0

what is causing the error and how can I send the stream to child_process ?



from how to send audio stream between child processes in nodejs

Applying LiveServer Logic for Tkinter File

The people who are familiar with the Live Server of VS Code, would have easily understood what is the main motive of this question.

But for others, here's the explanation:

  • Main motive of Live Server is to Automatically Reload Your Site on Save in web development! (Which get changed for python tkinter).
  • When ever I change something in my python file which contains tkinter code, the change should be reflected in the main window (the main window should not re-open to reflect the changes).

I have tried to search on web as well as on stack over flow, but all the results are for updating value in entry, label, buttons etc. But what I want is, the whole window should be updated when ever I change something in my main file, and the main window should not be reopened to do so. So in short, updating whole window without closing it, on every changes in the main file or automatically reload your program on save without reopening!

What have I tried?:

  • I tried to detect change in file using os.getsize which satisfied the first part of my question, but however I am not able to solve the second part i.e window should not be closed.
import os
main__tkinter_filename="myfile.py"
initial_filesize=os.path.getsize(main_tkinter_filename) # Getting size of the file for
                                                        # comparison.
while 1:
    final_filesize=os.path.getsize(main_tkinter_filename)
    if final_filsize<intial_filesize or final_filesize>initial_filesize:
        webbrowser.open(main_tkinter_filename)


from Applying LiveServer Logic for Tkinter File

Api ebaysdk trading error 2191930 while uploading an item

I've been having trouble with eBay's API for days when it comes to trading. I would like to upload a sample item (extracted from the timotheus trading module) to the Sandbox but my little program reports the following error:

ebaysdk.exception.ConnectionError: 'AddItem: Class: RequestError, Severity: Error, Code: 21919303, The item specific Book Title\xa0is missing. The item specific Book Title\xa0is missing.\xa0Add Book Title to this listing, enter a valid value, and then try again., Class: RequestError, Severity: Error, Code: 21919303, The item specific Author\xa0is missing. The item specific Author\xa0is missing.\xa0Add Author to this listing, enter a valid value, and then try again., Class: RequestError, Severity: Error, Code: 21919303, The item specific Language\xa0is missing. The item specific Language\xa0is missing.\xa0Add Language to this listing, enter a valid value, and then try again.'

The code executed is the following:

from ebaysdk.trading import Connection

if __name__ == '__main__':
    api = Connection(config_file="ebay.yaml", domain="api.sandbox.ebay.com", debug=True)
    request = {
        "Item": {
            "Title": "Harry Potter and the Philosopher's Stone",
            "Description": "This is the first book in the Harry Potter series. In excellent condition!",
            "PrimaryCategory": {"CategoryID": "377"},
            "StartPrice": "10.0",
            "BuyItNowPrice": "15.0",
            "CategoryMappingAllowed": "true",
            "Country": "US",
            "ConditionID": "3000",
            "Currency": "USD",
            "DispatchTimeMax": "3",
            "ListingDuration": "Days_7",
            "ListingType": "Chinese",
            "PaymentMethods": "PayPal",
            "PayPalEmailAddress": "tkeefdddder@gmail.com",
            "PictureDetails": {"PictureURL": "http://i1.sandbox.ebayimg.com/03/i/00/30/07/20_1.JPG?set_id=8800005007"},
            "PostalCode": "95125",
            "Quantity": "1",
            "ReturnPolicy": {
                "ReturnsAcceptedOption": "ReturnsAccepted",
                "RefundOption": "MoneyBack",
                "ReturnsWithinOption": "Days_30",
                "Description": "If you are not satisfied, return the book for refund.",
                "ShippingCostPaidByOption": "Buyer"
            },
            "SellerProfiles": {
                "SellerPaymentProfile": {
                    "PaymentProfileName": "PayPal:Immediate pay",
                },
                "SellerReturnProfile": {
                    "ReturnProfileName": "30 Day Return Policy",
                },
                "SellerShippingProfile": {
                    "ShippingProfileName": "USPS First Class, Priority, Priority Express Flat Rate Envelope",
                }
            },
            "ShippingDetails": {
                "ShippingType": "Calculated",
                "ShippingServiceOptions": {
                    "ShippingServicePriority": "1",
                    "ShippingService": "USPSMedia"
                },
                "CalculatedShippingRate": {
                    "OriginatingPostalCode": "95125",
                    "PackagingHandlingCosts": "0.0",
                    "ShippingPackage": "PackageThickEnvelope",
                    "WeightMajor": "1",
                    "WeightMinor": "0"
                }
            },
            "Site": "US"
        }
    }

    api.execute("AddItem", request)

I tried to heuristically add the features reported by the error but with little success.

My goal is to create in the future an application that allows the automatic loading of items on eBay, since I have many second-hand items to sell with almost identical characteristics. I hope to succeed despite the bad/poor eBay api python sdk documentation.

Thanks in advance.



from Api ebaysdk trading error 2191930 while uploading an item

Thursday, 24 March 2022

How do I show a custom Android notification using Flutter widgets?

I want to show custom notifications on Android using Flutter widgets? I'll like to know if that is possible.

What I've done:

I tried using showing a Flutter widget in an Android Fragment and display that Fragment using RemoteViews for custom Android notifications.

A notification shows but it does not include the Flutter widget. See screenshot below:

Screenshot showing a notification without any content

Code:

 var newFlutterFragment: FlutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
     .shouldAttachEngineToActivity(false)
     .build()
 if (fragmentManager != null) {
     fragmentManager
         .beginTransaction()
         .add(
             R.id.fragment_container,
             newFlutterFragment,
             TAG_FLUTTER_FRAGMENT
         )
         .commit()
 }



 val notificationLayout = RemoteViews(packageName, R.layout.activity_layout)
 val notificationLayoutExpanded = RemoteViews(packageName, R.layout.activity_layout)


 var builder = NotificationCompat.Builder(this, CHANNEL_ID)
     .setSmallIcon(R.drawable.ic_bg_service_small)
     .setCustomContentView(notificationLayout)
     .setCustomBigContentView(notificationLayoutExpanded)
     .setPriority(NotificationCompat.PRIORITY_DEFAULT)

 var notificationId = 1;

 with(NotificationManagerCompat.from(this)) {
     // notificationId is a unique int for each notification that you must define
     notify(notificationId, builder.build())
 }


from How do I show a custom Android notification using Flutter widgets?

App Icon Launcher not showing in Android 7.1.1

We are implementing a round icon (with a foreground and a background) and icon.

<application
    android:allowBackup="false"
    tools:replace="android:allowBackup"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:icon="@mipmap/logo" //normal logo
    android:roundIcon="@mipmap/logo_o" //Our logo with foreground and background
    android:name=".MyApplication"/>

Works for every version but not for API 25

enter image description here

Our code for Foreground with Background is the next one

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@mipmap/logo_background"/>
    <foreground android:drawable="@mipmap/logo_foreground"/>
</adaptive-icon>


from App Icon Launcher not showing in Android 7.1.1

How can i improve the performance of my python task?

I have a problem. So I have a task that runs every time when a user writes a chat message on my discord server - it's called on_message. So my bot has many things to do in this event, and I often get this kind of error:

Task was destroyed but it is pending!
task: <Task pending name='pycord: on_message' coro=<Client._run_event() done, defined at /Bots/gift-bot/discord/client.py:374> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f68a7bdfc10>()]>>

So I think if I want to fix this, I need to speedup my code. But sadly, I don't have any clue how i can do it to fix this error.

Edit: I integrated timings and this is what I get printed:

after cooldown: 7.677078247070312e-05
after mysql: 0.07229304313659668
after cooldown: 7.557868957519531e-05
after mysql: 0.05353689193725586


  @commands.Cog.listener("on_message")
  async def on_message(self, message):
    start = time.time()


    if message.author.bot:
        return

    if message.type != discord.MessageType.default:
        return

    if isinstance(message.channel, discord.channel.DMChannel):
        return


    # Cooldown


    self.member_cooldown_list = [i for i in self.member_cooldown_list if i[1] + self.cooldown_val > int(time.time())]
    member_index = next((i for i, v in enumerate(self.member_cooldown_list) if v[0] == message.author.id), None)
    if member_index is not None:
        if self.member_cooldown_list[member_index][1] + self.cooldown_val > int(time.time()):
            return

    self.member_cooldown_list.append((message.author.id, int(time.time())))

    print(f"after cooldown: {time.time() - start}")
    start2 = time.time()


    # Role-Check (Bonus/Ignore)


    count = 1
    mydb = await getConnection()
    mycursor = await mydb.cursor()
    await mycursor.execute("SELECT ignore_role_id, bonus_role_id FROM guild_role_settings WHERE guild_id = %s", (message.author.guild.id,))
    in_database = await mycursor.fetchone()
    if in_database:
        if in_database[0] is not None:
            role_list = in_database[0].split(" ")
            for roleid in role_list:
                try:
                    int(roleid)
                except ValueError:
                    continue

                role = message.author.guild.get_role(int(roleid))
                if role is None:
                    continue

                if role in message.author.roles:
                    await mycursor.close()
                    mydb.close()
                    return

        if in_database[1] is not None:
            role_list = in_database[1].split(" ")
            for roleid in role_list:
                try:
                    int(roleid)
                except ValueError:
                    continue

                role = message.author.guild.get_role(int(roleid))
                if role is None:
                    continue

                if role in message.author.roles:
                    count += 1


    # Channel-Check (Bonus/Ignore)


    await mycursor.execute("SELECT ignore_channel_id FROM guild_channel_settings WHERE guild_id = %s", (message.author.guild.id,))
    in_database1 = await mycursor.fetchone()
    if in_database1:
        if in_database1[0] is not None:
            channel_list = in_database1[0].split(" ")
            for channelid in channel_list:

                try:
                    int(channelid)
                except ValueError:
                    continue

                if int(message.channel.id) == int(channelid):
                    await mycursor.close()
                    mydb.close()
                    return


    # write to database


    await mycursor.execute("SELECT * FROM guild_message_count WHERE guild_id = %s AND user_id = %s", (message.author.guild.id, message.author.id))
    in_database2 = await mycursor.fetchone()
    if in_database2:
        await mycursor.execute("INSERT INTO guild_message_count (user_id, message_count, guild_id) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE message_count = message_count + 1", (message.author.id, count, message.author.guild.id))

    await mydb.commit()
    await mycursor.close()
    mydb.close()

    print(f"after mysql: {time.time() - start2}")


from How can i improve the performance of my python task?

How to get more details on a requests.exceptions.SSLError?

When I request a URL with an expired HTTPS certificate I do not get a meaningful error from requests. Instead it gives me a cascade of "ssl.SSLError: A failure in the SSL library occurred".

See this example with https://expired.badssl.com/ :

>python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.get("https://expired.badssl.com/")
Traceback (most recent call last):
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 978, in _validate_conn
    conn.connect()
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connection.py", line 362, in connect
    self.sock = ssl_wrap_socket(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\util\ssl_.py", line 386, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Users\me\apps\Python39\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\me\apps\Python39\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\me\apps\Python39\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: A failure in the SSL library occurred (_ssl.c:1129)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 726, in urlopen
    retries = retries.increment(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\util\retry.py", line 446, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='expired.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, 'A failure in the SSL library occurred (_ssl.c:1129)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='expired.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, 'A failure in the SSL library occurred (_ssl.c:1129)')))
>>>

requests is 2.24.0 and ssl.OPENSSL_VERSION says "OpenSSL 1.1.1h 22 Sep 2020". I can not update the packages.

How can I get a meaningful error or error message that tells me that the certificate is expired?



from How to get more details on a requests.exceptions.SSLError?