问:
Is there any specific way to implement Damerau-Levenshtein distances so they perform better on integer pairs?
Say I have a list of numbers composed of a sequential ID followed by two mod11 check digits, for example:

ls = [191, 272, 353, 434, 515, 604, 787, 868, 949, 1082, 1163, 1244, 1325, 1406,
      1597, 1678, 1759, 1830, 1910, 2054, 2135, 2216, 2305, 2488, 2569, 2640, 2720,
      2801, 2992, 3026, 3107, 3298, 3379, 3450, 3530, 3611, 3700, 3883, 3964, 4006,
      4189, 4260, 4340, 4421, 4502, 4693, 4774, 4855, 4936, ...]
```
<p>And I want to understand, for each of my keys, the smallest Damerau-Levenshtein distance achievable to another key with the same magnitude in the list. <code>len(ls) == 10**9</code>, so doing it in the most optimal manner is going to be crucial.</p>
<p>My current approach is the following:</p>
<pre class="lang-py prettyprint-override"><code>from tqdm.notebook import trange, tqdm
from fastDamerauLevenshtein import damerauLevenshtein

###################################
# Insert code to generate ls here #
###################################
def calculate_dual_mod11(n):
    m11 = ((n//10**8) + (n%10**8//10**7)*2 + (n%10**7//10**6)*3 + (n%10**6//10**5)*4 + (n%10**5//10**4)*5 + \
         (n%10**4//10**3)*6 + (n%10**3//10**2)*7 + (n%10**2//10)*8 + (n%10)*9)%11%10
    n_backup = n*10 + m11
    n = n_backup%10**9

    m11 = ((n//10**8) + (n%10**8//10**7)*2 + (n%10**7//10**6)*3 + (n%10**6//10**5)*4 + (n%10**5//10**4)*5 + \
         (n%10**4//10**3)*6 + (n%10**3//10**2)*7 + (n%10**2//10)*8 + (n%10)*9)%11%10
    return (n*10 + m11)%100

ls = [i*100+calculate_dual_mod11(i) for i in range(10**9)]

# Instantiate a list of Nones to prevent those pesky O(n) inserts
# when CPython needs to move data. This way, we only have one O(n)
# operation and a bunch of O(1)s later down the road.
damerau_ls = [None]*len(ls)

for i in trange(len(ls)):
    first_str = str(ls[i])

    # Except for the edge cases beginning in a sequence of 9s
    # where the next key is a character longer, the upper bound
    # of the minimum Damerau-Levenshtein distance is equal to the first string's size
    # I'm willing to compromise on those edge cases.
    damerau_ls[i] = len(first_str)

    for j in range(i+1,len(ls)):
        other_str = str(ls[j])
        # Once we get to a string longer than the main, break the inner loop.
        if len(other_str) > len(first_str):
            break
        damerau_ls[i] = min(damerau_ls[i], damerauLevenshtein(first_str, other_str, similarity=False))
        # Damerau-Levenshtein distance between two distinct strings will never be less than 1.
        if damerau_ls[i] == 1:
            break
</code>```

Is there any faster way to achieve this, especially given the constraint that I'm working with integers and that they have the same order of magnitude? This code runs pretty quickly for the first 1000 iterations, then it evidently starts getting considerably slower as we progress through the longer strings.

The specific Damerau-Levenshtein implementation I'm using is fastDamerauLevenshtein.

Body:
Say I have a list of numbers composed of a sequential ID followed by two mod11 check digits, for example:

ls = [191, 272, 353, 434, 515, 604, 787, 868, 949, 1082, 1163, 1244, 1325, 1406,
      1597, 1678, 1759, 1830, 1910, 2054, 2135, 2216, 2305, 2488, 2569, 2640, 2720,
      2801, 2992, 3026, 3107, 3298, 3379, 3450, 3530, 3611, 3700, 3883, 3964, 4006,
      4189, 4260, 4340, 4421, 4502, 4693, 4774, 4855, 4936, ...]

And I want to understand, for each of my keys, the smallest Damerau-Levenshtein distance achievable to another key with the same magnitude in the list. len(ls) == 10**9, so doing it in the most optimal manner is going to be crucial.

My current approach is the following:

from tqdm.notebook import trange, tqdm
from fastDamerauLevenshtein import damerauLevenshtein

###################################
# Insert code to generate ls here #
###################################
def calculate_dual_mod11(n):
    m11 = ((n//10**8) + (n%10**8//10**7)*2 + (n%10**7//10**6)*3 + (n%10**6//10**5)*4 + (n%10**5//10**4)*5 + \
         (n%10**4//10**3)*6 + (n%10**3//10**2)*7 + (n%10**2//10)*8 + (n%10)*9)%11%10
    n_backup = n*10 + m11
    n = n_backup%10**9

    m11 = ((n//10**8) + (n%10**8//10**7)*2 + (n%10**7//10**6)*3 + (n%10**6//10**5)*4 + (n%10**5//10**4)*5 + \
         (n%10**4//10**3)*6 + (n%10**3//10**2)*7 + (n%10**2//10)*8 + (n%10)*9)%11%10
    return (n*10 + m11)%100

ls = [i*100+calculate_dual_mod11(i) for i in range(10**9)]

# Instantiate a list of Nones to prevent those pesky O(n) inserts
# when CPython needs to move data. This way, we only have one O(n)
# operation and a bunch of O(1)s later down the road.
damerau_ls = [None]*len(ls)

for i in trange(len(ls)):
    first_str = str(ls[i])

    # Except for the edge cases beginning in a sequence of 9s
    # where the next key is a character longer, the upper bound
    # of the minimum Damerau-Levenshtein distance is equal to the first string's size
    # I'm willing to compromise on those edge cases.
    damerau_ls[i] = len(first_str)

    for j in range(i+1,len(ls)):
        other_str = str(ls[j])
        # Once we get to a string longer than the main, break the inner loop.
        if len(other_str) > len(first_str):
            break
        damerau_ls[i] = min(damerau_ls[i], damerauLevenshtein(first_str, other_str, similarity=False))
        # Damerau-Levenshtein distance between two distinct strings will never be less than 1.
        if damerau_ls[i] == 1:
            break

Is there any faster way to achieve this, especially given the constraint that I'm working with integers and that they have the same order of magnitude? This code runs pretty quickly for the first 1000 iterations, then it evidently starts getting considerably slower as we progress through the longer strings.

The specific Damerau-Levenshtein implementation I'm using is fastDamerauLevenshtein.


来源: stackexchange

问:
How to communicate simultaneously with an exe using Java process object?
Here I am trying to communicate with a chess engine, but every time when I write commands to it with an OutputStream object, it never gives any output. Only if I close the output stream it gives an output. However, then the engine stops. How can I resolve this issue please guide me the mistake that I did.

Here is the code:

URL resource = new Object().getClass().getResource("/engine/stockfish.exe");
String path = resource.getPath();
ProcessBuilder pb = new ProcessBuilder(path);
try {
    Process engine = pb.start();
    InputStream inputStream = engine.getInputStream();
    OutputStream outputStream = engine.getOutputStream();
    Thread T = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (engine.isAlive()) {
                    String s = "";
                    while (inputStream.available() > 0) {
                        s = s + (char) inputStream.read();
                    }
                    if (!"".equals(s)) {
                        System.out.println(s);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });
    T.start();
    outputStream.write("isready".getBytes());
    outputStream.flush();
//    outputStream.close();
} catch (Exception ex) {
    ex.printStackTrace();
}
```

What I want the program to do is once the engine starts java program needs to write commands to it and read the output while keeping the engine running. In other words, I need to write multiple commands to it.

ContentLicense: CC BY-SA 4.0

Body:
Here I am trying to communicate with a chess engine, but every time when I write commands to it with an OutputStream object, it never gives any output. Only if I close the output stream it gives an output. However, then the engine stops. How can I resolve this issue please guide me the mistake that I did.

Here is the code:

URL resource = new Object().getClass().getResource("/engine/stockfish.exe");
String path = resource.getPath();
ProcessBuilder pb = new ProcessBuilder(path);
try {
    Process engine = pb.start();
    InputStream inputStream = engine.getInputStream();
    OutputStream outputStream = engine.getOutputStream();
    Thread T = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (engine.isAlive()) {
                    String s = "";
                    while (inputStream.available() > 0) {
                        s = s + (char) inputStream.read();
                    }
                    if (!"".equals(s)) {
                        System.out.println(s);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });
    T.start();
    outputStream.write("isready".getBytes());
    outputStream.flush();
//    outputStream.close();
} catch (Exception ex) {
    ex.printStackTrace();
}

What I want the program to do is once the engine starts java program needs to write commands to it and read the output while keeping the engine running. In other words, I need to write multiple commands to it.


问:
How to add comas between numbers Excel, Csv
I have this data of numbers in csv file, pretty lot of them.

I want to give 1 comas in the first 3 nominals and comas in the first 1 nominals

Example : 10686200000000000 to 106,86200000000000
and this too -6286540000000000 to -6,286540000000000

I get this data from excel and save them into csv, because when save as cannot contain comas in csv I I use number without comas.

How to make it fast so I don't need to add it one by one?


问:
Network Graph is displayed without colored nodes
I am trying to run the DSATUR algorithm on a graph but the problem is that the result is displayed with the default color.
Dsatur is an algorithm that colors the vertices that have the highest degree of saturation, that is to say that it is the vertex that has the maximum number of colored neighbors.

The algorithm I use comes from the NetworkX documentation, i tried another algorithm like the 'strategy_largest_first' which returns the list of nodes in decreasing order by degree and it works like so many other algorithms dealing with graph problems.
So I think the problem might comes from how I display my graph, i.e. nx.draw(G, with_labels=True).

```<code>import matplotlib.pyplot as plt
import networkx as nx
import tkinter
from tkinter import *

node_colors = {
    0: (255, 0, 0),
    1: (0, 255, 0),
    2: (200, 20, 128),
    3: (127, 127, 127),
    4: (152, 53, 91),
    5: (44, 200, 100),
    6: (100, 44, 200),
    'null': (0, 0, 0),  # Default Color
    'OOB': (180, 200, 10),  # Color to denote that the node is "Out of bounds" or cannot be colored.
}
Gr = nx.Graph()
Gr.add_node("A")
Gr.add_node("B")
Gr.add_node("F")
Gr.add_node("P")
Gr.add_node("U")

Gr.add_edge("A", "B")
Gr.add_edge("Z", "B")
Gr.add_edge("A", "P")
Gr.add_edge("U", "B")
Gr.add_edge("Z", "F")

def strategy_saturation_largest_first(G, colors):
    """Iterates over all the nodes of ``G`` in "saturation order" (also
    known as "DSATUR").

    ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
    ``G`` to colors, for those nodes that have already been colored.

    """
    distinct_colors = {v: set() for v in G}
    for i in range(len(G)):
        # On the first time through, simply choose the node of highest degree.
        if i == 0:
            node = max(G, key=G.degree)
            yield node
            # Add the color 0 to the distinct colors set for each
            # neighbors of that node.
            for v in G[node]:
                distinct_colors[v].add(0)
        else:
            # Compute the maximum saturation and the set of nodes that
            # achieve that saturation.
            saturation = {
                v: len(c) for v, c in distinct_colors.items() if v not in colors
            }
            # Yield the node with the highest saturation, and break ties by
            # degree.
            node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
            yield node
            # Update the distinct color sets for the neighbors.
            color = colors[node]
            for v in G[node]:
                distinct_colors[v].add(color)

strategy_saturation_largest_first(Gr, node_colors)

nx.draw(Gr, with_labels=True)
plt.margins(0.1)
plt.show()
</code>```

Body:
I am trying to run the DSATUR algorithm on a graph but the problem is that the result is displayed with the default color.
Dsatur is an algorithm that colors the vertices that have the highest degree of saturation, that is to say that it is the vertex that has the maximum number of colored neighbors.

The algorithm I use comes from the NetworkX documentation, i tried another algorithm like the 'strategy_largest_first' which returns the list of nodes in decreasing order by degree and it works like so many other algorithms dealing with graph problems.
So I think the problem might comes from how I display my graph, i.e. nx.draw(G, with_labels=True).

import matplotlib.pyplot as plt
import networkx as nx
import tkinter
from tkinter import *

node_colors = {
    0: (255, 0, 0),
    1: (0, 255, 0),
    2: (200, 20, 128),
    3: (127, 127, 127),
    4: (152, 53, 91),
    5: (44, 200, 100),
    6: (100, 44, 200),
    'null': (0, 0, 0),  # Default Color
    'OOB': (180, 200, 10),  # Color to denote that the node is "Out of bounds" or cannot be colored.
}
Gr = nx.Graph()
Gr.add_node("A")
Gr.add_node("B")
Gr.add_node("F")
Gr.add_node("P")
Gr.add_node("U")

Gr.add_edge("A", "B")
Gr.add_edge("Z", "B")
Gr.add_edge("A", "P")
Gr.add_edge("U", "B")
Gr.add_edge("Z", "F")

def strategy_saturation_largest_first(G, colors):
    """Iterates over all the nodes of ``G`` in "saturation order" (also
    known as "DSATUR").

    ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
    ``G`` to colors, for those nodes that have already been colored.

    """
    distinct_colors = {v: set() for v in G}
    for i in range(len(G)):
        # On the first time through, simply choose the node of highest degree.
        if i == 0:
            node = max(G, key=G.degree)
            yield node
            # Add the color 0 to the distinct colors set for each
            # neighbors of that node.
            for v in G[node]:
                distinct_colors[v].add(0)
        else:
            # Compute the maximum saturation and the set of nodes that
            # achieve that saturation.
            saturation = {
                v: len(c) for v, c in distinct_colors.items() if v not in colors
            }
            # Yield the node with the highest saturation, and break ties by
            # degree.
            node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
            yield node
            # Update the distinct color sets for the neighbors.
            color = colors[node]
            for v in G[node]:
                distinct_colors[v].add(color)

strategy_saturation_largest_first(Gr, node_colors)

nx.draw(Gr, with_labels=True)
plt.margins(0.1)
plt.show()


问:
How do I plot Horizontal ray from custom date day High-Low to till the present date in Pine Script
In simple words ,
I need to plot Horizontal ray that needs to be extended to right Forever,
from custom date that (I must select date in the settings), from that day to the present day , straight horizontal ray lines need to be plotted & that horizontal lines must be everyday high and low
So Everyday has 2 Horizontal ray ( Extended to right forever )line One Red line is Every day high , & Green line is Every day low,

This all code must be in pine script

I tried to plot horizontal line but it was breaking at the day end , and new high line is forming on next day high or low,

But in simple to say the previous day high-low line must be extended right forever without breaking and also it should form new present day high-low line must be formed at the present day also.


问:
No Module found on PyPrind
I installed using pip install PyPrind as follows;
C:\Users\peter>pip install PyPrind Requirement already satisfied: PyPrind in c:\users\peter\appdata\local\programs\python\python38-32\lib\site-packages (2.11.3)

But still I have an error message as follows

```<code>ModuleNotFoundError: No module named 'pyprind'
</code>```

I installed using pip install PyPrind as follows;
C:\Users\peter>pip install PyPrind Requirement already satisfied: PyPrind in c:\users\peter\appdata\local\programs\python\python38-32\lib\site-packages (2.11.3)

Title: No Module found on PyPrind

Body:
I installed using pip install PyPrind as follows;
C:\Users\peter>pip install PyPrind Requirement already satisfied: PyPrind in c:\users\peter\appdata\local\programs\python\python38-32\lib\site-packages (2.11.3)

But still I have an error message as follows

ModuleNotFoundError: No module named 'pyprind'

I installed using pip install PyPrind as follows;
C:\Users\peter>pip install PyPrind Requirement already satisfied: PyPrind in c:\users\peter\appdata\local\programs\python\python38-32\lib\site-packages (2.11.3)


问:
Why image inside CSS doesn't load after changing the document root for serving static files?
I have a packaged static file of Vue that directory structure like this:

```<code>public
   assets
      css
      js
      fonts
      img
   favicon.ico
   index.html
</code>```

And then I config this works well.

```<code>location / {
    root /opt/homebrew/var/www/public;
}
</code>```

Now, I want to add /min to the url path, so the config changed to this:

```<code>location /min {
   alias /opt/homebrew/var/www/public/;
}

location ~ ^/assets/(.*)$ {
   alias /opt/homebrew/var/www/public/assets/$1;
}
</code>```

but it looks like doesn't load images when I access http://localhost:8080/min, I check it in the network panel, and there is no image request. But I've tested accessing any image directory by: http://localhost:8080/assets/img/xxx.ff022fbb.png  or http://localhost:8080/min/assets/img/xxx.ff022fbb.png. They are both ok.

These unloaded images are referenced with relative path in the CSS source file:

```<code>.img {
            width: 120px;
            height: 120px;
            background-image: url(../assets/img/home/xxx.ff022fbb.png);
            background-repeat: no-repeat;
            background-size: 100% auto;
            background-position: center;
            display: inline-block;
            text-align: center;
            margin-top: 40px;
        }
</code>```

After packaged look like this:

```<code>background-image:url(../../assets/img/xxx.ff022fbb.png);
</code>```

Why is this? I have no idea. Anyone can explain it to me? Thanks

Body:
I have a packaged static file of Vue that directory structure like this:

public
   assets
      css
      js
      fonts
      img
   favicon.ico
   index.html

And then I config this works well.

location / {
    root /opt/homebrew/var/www/public;
}

Now, I want to add /min to the url path, so the config changed to this:

location /min {
   alias /opt/homebrew/var/www/public/;
}

location ~ ^/assets/(.*)$ {
   alias /opt/homebrew/var/www/public/assets/$1;
}

but it looks like doesn't load images when I access http://localhost:8080/min, I check it in the network panel, and there is no image request. But I've tested accessing any image directory by: http://localhost:8080/assets/img/xxx.ff022fbb.png  or http://localhost:8080/min/assets/img/xxx.ff022fbb.png. They are both ok.

These unloaded images are referenced with relative path in the CSS source file:

.img {
            width: 120px;
            height: 120px;
            background-image: url(../assets/img/home/xxx.ff022fbb.png);
            background-repeat: no-repeat;
            background-size: 100% auto;
            background-position: center;
            display: inline-block;
            text-align: center;
            margin-top: 40px;
        }

After packaged look like this:

background-image:url(../../assets/img/xxx.ff022fbb.png);

Why is this? I have no idea. Anyone can explain it to me? Thanks


问:
How to write UnitTest with Coroutines in Repository Android Kotlin
In my repository there is a function set to suspend function, but I really don't know how to write UnitTest for this repo.

```<code>class MovieRepositoryImpl(val movieDao: MovieDao) : MovieRepository {

    override suspend fun insertMovieToDB(movie: Movie) {
        movieDao.insert(movie)
    }
}
</code>```

can anyone suggest me how to write UnitTest for it.
I am using MockK library

Body:
In my repository there is a function set to suspend function, but I really don't know how to write UnitTest for this repo.

class MovieRepositoryImpl(val movieDao: MovieDao) : MovieRepository {

    override suspend fun insertMovieToDB(movie: Movie) {
        movieDao.insert(movie)
    }
}

can anyone suggest me how to write UnitTest for it.
I am using MockK library


问:
Displaying appbar above alert dialog in flutter
I am building a flutter web app. For my login page, i have a dialog that can not be dismissed until the user is logged in successfully. On my app bar, i have general information that could be valuable to the anonymous user. The problem is, the dialog overlays the entire page. Is there a way i can set my app bar above the alert dialog?</p>


问:
Npm run build or ng build --prod in spurtcommerce community edition giving below error in admin part
npm run build or ng build --prod in spurtcommerce community edition are giving the following error in admin:

```<code>ERROR in node_modules/ng2-ckeditor/ckbutton.directive.d.ts(1,23): error TS2688: Cannot find type definition file for 'ckeditor'.
node_modules/ng2-ckeditor/ckbutton.directive.d.ts(15,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckbutton.directive.d.ts(23,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckbutton.directive.d.ts(24,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵDirectiveDeclaration'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(1,23): error TS2688: Cannot find type definition file for 'ckeditor'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(13,13): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(16,26): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(17,32): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(18,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(19,24): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(20,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(21,30): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(22,37): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(23,38): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(24,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(25,24): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(30,15): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(37,9): error TS1086: An accessor cannot be declared in an ambient context.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(38,9): error TS1086: An accessor cannot be declared in an ambient context.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(59,26): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(69,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(70,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵComponentDeclaration'.
node_modules/ng2-ckeditor/ckeditor.module.d.ts(10,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckeditor.module.d.ts(11,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵNgModuleDeclaration'.
node_modules/ng2-ckeditor/ckeditor.module.d.ts(12,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵInjectorDeclaration'.
node_modules/ng2-ckeditor/ckgroup.directive.d.ts(22,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckgroup.directive.d.ts(23,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵDirectiveDeclaration'.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! spurtcommerce@3.0.2 build: ng build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the spurtcommerce@3.0.2 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/ubuntu/.npm/_logs/2022-05-13T12_42_11_549Z-debug.log
</code>```

Body:
npm run build or ng build --prod in spurtcommerce community edition are giving the following error in admin:

ERROR in node_modules/ng2-ckeditor/ckbutton.directive.d.ts(1,23): error TS2688: Cannot find type definition file for 'ckeditor'.
node_modules/ng2-ckeditor/ckbutton.directive.d.ts(15,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckbutton.directive.d.ts(23,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckbutton.directive.d.ts(24,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵDirectiveDeclaration'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(1,23): error TS2688: Cannot find type definition file for 'ckeditor'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(13,13): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(16,26): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(17,32): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(18,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(19,24): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(20,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(21,30): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(22,37): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(23,38): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(24,25): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(25,24): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(30,15): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(37,9): error TS1086: An accessor cannot be declared in an ambient context.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(38,9): error TS1086: An accessor cannot be declared in an ambient context.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(59,26): error TS2503: Cannot find namespace 'CKEDITOR'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(69,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckeditor.component.d.ts(70,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵComponentDeclaration'.
node_modules/ng2-ckeditor/ckeditor.module.d.ts(10,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckeditor.module.d.ts(11,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵNgModuleDeclaration'.
node_modules/ng2-ckeditor/ckeditor.module.d.ts(12,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵInjectorDeclaration'.
node_modules/ng2-ckeditor/ckgroup.directive.d.ts(22,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.
node_modules/ng2-ckeditor/ckgroup.directive.d.ts(23,21): error TS2694: Namespace '"/home/ubuntu/admin/node_modules/@angular/core/core"' has no exported member 'ɵɵDirectiveDeclaration'.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! spurtcommerce@3.0.2 build: ng build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the spurtcommerce@3.0.2 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/ubuntu/.npm/_logs/2022-05-13T12_42_11_549Z-debug.log


问:
Docker is unable to reach service inside WSL2
I have Caddy running inside docker from WSL2 with a simple docker-compose.yml. Caddy is configured to reverse proxy to a service running inside Ubuntu. Caddy was unable to reach this service.

version: '3.1'

services:
  caddy:
    image: caddy:2.6-alpine
    volumes:
      - ./CaddyFile:/etc/caddy/Caddyfile
    ports:
      - 80:80
      - 443:443
```
<p>Caddyfile</p>
```localhost {
    reverse_proxy 172.21.153.84:8000
}
```
<p>IP addresses:</p>
<ul>
<li>Ubuntu under WSL2 (from <code>inet</code> under <code>ifconfig</code>): <code>172.21.153.84</code></li>
<li>Windows host (from <code>nameserver</code> under <code>cat /etc/resolv.conf</code>): <code>172.21.144.1</code></li>
</ul>
<p>From the docker shell, I am not able to ping Ubuntu or Windows.</p>
<pre class="lang-bash prettyprint-override"><code>docker compose run exec -it caddy bin/sh

/srv # ping 172.21.153.84
PING 172.21.153.84 (172.21.153.84): 56 data bytes
^C
--- 172.21.153.84 ping statistics ---
10 packets transmitted, 0 packets received, 100% packet loss

/srv # ping 172.21.144.1
PING 172.21.144.1 (172.21.144.1): 56 data bytes
^C
--- 172.21.144.1 ping statistics ---
8 packets transmitted, 0 packets received, 100% packet loss
</code>```

How can I reach services running inside WSL2 from within docker?

Body:
I have Caddy running inside docker from WSL2 with a simple docker-compose.yml. Caddy is configured to reverse proxy to a service running inside Ubuntu. Caddy was unable to reach this service.

version: '3.1'

services:
  caddy:
    image: caddy:2.6-alpine
    volumes:
      - ./CaddyFile:/etc/caddy/Caddyfile
    ports:
      - 80:80
      - 443:443

Caddyfile

localhost {
    reverse_proxy 172.21.153.84:8000
}

IP addresses:

Ubuntu under WSL2 (from inet under ifconfig): 172.21.153.84

Windows host (from nameserver under cat /etc/resolv.conf): 172.21.144.1

From the docker shell, I am not able to ping Ubuntu or Windows.

docker compose run exec -it caddy bin/sh

/srv # ping 172.21.153.84
PING 172.21.153.84 (172.21.153.84): 56 data bytes
^C
--- 172.21.153.84 ping statistics ---
10 packets transmitted, 0 packets received, 100% packet loss

/srv # ping 172.21.144.1
PING 172.21.144.1 (172.21.144.1): 56 data bytes
^C
--- 172.21.144.1 ping statistics ---
8 packets transmitted, 0 packets received, 100% packet loss

How can I reach services running inside WSL2 from within docker?


问:
Python - xml.etree.ElementTree - How to get root attributes name
I'm trying to get root attributes but I get empy dict.
My file, an xbrl Italian balance sheet file, has these first lines:

```<code><?xml version="1.0" encoding="UTF-8"?>

<**xbrl** **xmlns**="http://www.xbrl.org/2003/instance" **xmlns:itcc-ci-ese**="http://www.infocamere.it/itnn/fr/itcc/ci/ese/2018-11-04" **xmlns:link**="http://www.xbrl.org/2003/linkbase" **xmlns:itcc-ci**="http://www.infocamere.it/itnn/fr/itcc/ci/2018-11-04" **xmlns:iso4217**="http://www.xbrl.org/2003/iso4217" **xmlns:xlink**="http://www.w3.org/1999/xlink" **xmlns:xbrli**="http://www.xbrl.org/2003/instance">
... ... .... ....
<**/xbrl**>
</code>```

My code is:

```<code>import xml.etree.ElementTree as ET
tree = ET.parse('...\\000001108.XBRL')
root = tree.getroot()
print(root.attrib)
</code>```

Output:

```<code>{}
</code>```

I was expecting:

```<code>{xmlns: .., xmlns:itcc-ci-ese .., xmlns:link: .., xmlns:itcc-ci: ..., xmlns:iso4217: ..., xmlns:xlink: ..., xmlns:xbrli: ...}
</code>```

Body:
I'm trying to get root attributes but I get empy dict.
My file, an xbrl Italian balance sheet file, has these first lines:

<?xml version="1.0" encoding="UTF-8"?>

<**xbrl** **xmlns**="http://www.xbrl.org/2003/instance" **xmlns:itcc-ci-ese**="http://www.infocamere.it/itnn/fr/itcc/ci/ese/2018-11-04" **xmlns:link**="http://www.xbrl.org/2003/linkbase" **xmlns:itcc-ci**="http://www.infocamere.it/itnn/fr/itcc/ci/2018-11-04" **xmlns:iso4217**="http://www.xbrl.org/2003/iso4217" **xmlns:xlink**="http://www.w3.org/1999/xlink" **xmlns:xbrli**="http://www.xbrl.org/2003/instance">
... ... .... ....
<**/xbrl**>

My code is:

import xml.etree.ElementTree as ET
tree = ET.parse('...\\000001108.XBRL')
root = tree.getroot()
print(root.attrib)

Output:

{}

I was expecting:

{xmlns: .., xmlns:itcc-ci-ese .., xmlns:link: .., xmlns:itcc-ci: ..., xmlns:iso4217: ..., xmlns:xlink: ..., xmlns:xbrli: ...}


问:
Data extraction from website with non-tabular data in python
I'm trying to extract data from this site: https://act.ucsd.edu/webreg2/main?p1=WI23&p2=UN#tabs-0T

I'm trying to extract the value of each class and I want to convert it into a dataframe. If this was a website which had a table, that would have been easy, but since I have to navigate and interact with the website, this has become a little hard. Does anyone have suggestions on how I can extract data from this site and what libraries could be helpful in python?

I've tried navigation and extraction using requests and beautiful soup, but beautiful soup can only get requests and not send them, so I have been stuck.


问:
filter data in tfrecord with spark/scala without aggregate steps?
I have a very large tfrecord directory, and need to filter it with some column to generate new tfrecord files.

Code likes that

```<code>val df = spark.read.format("tfrecords").option("recordType", "Example").load(input_path).filter(udf_filter(col("label")))
df.write.format("tfrecords").option("recordType", "Example").mode(SaveMode.Overwrite).save(output_path)
</code>```

When I run it in spark cluster, I find it will run with two steps(aggregate + write)

I check the code in https://github.com/tensorflow/ecosystem/blob/master/spark/spark-tensorflow-connector/src/main/scala/org/tensorflow/spark/datasources/tfrecords/TensorFlowInferSchema.scala#L39, it have the aggregate steps !

Can I avoid it?

The issue in github is here https://github.com/tensorflow/ecosystem/issues/201

Body:
I have a very large tfrecord directory, and need to filter it with some column to generate new tfrecord files.

Code likes that

val df = spark.read.format("tfrecords").option("recordType", "Example").load(input_path).filter(udf_filter(col("label")))
df.write.format("tfrecords").option("recordType", "Example").mode(SaveMode.Overwrite).save(output_path)

When I run it in spark cluster, I find it will run with two steps(aggregate + write)

I check the code in https://github.com/tensorflow/ecosystem/blob/master/spark/spark-tensorflow-connector/src/main/scala/org/tensorflow/spark/datasources/tfrecords/TensorFlowInferSchema.scala#L39, it have the aggregate steps !

Can I avoid it?

The issue in github is here https://github.com/tensorflow/ecosystem/issues/201


问:
While Converting V2 pine script to V5 Facing error
```<code>//@version=2
study(title="EMA & MA Crossover", shorttitle="EMA & MA Crossover", overlay = true)

LengthMA = input(50, minval=1)
LengthEMA = input(200,minval=1)

xMA = ema(close, LengthMA)
xEMA = ema(close, LengthEMA)
pos = iff(xEMA < xMA , 1, iff(xEMA > xMA, -1, nz(pos[1], 0)))
barcolor(pos == -1 ? red: pos == 1 ? green : blue)

plot(xMA, color=red, title="MA")
plot(xEMA, color=blue, title="EMA")
</code>```

Conversion failed, reason: Source pine is incorrect. line 10: Undeclared identifier pos;
line 11: Undeclared identifier pos

Please help me

I Hade tried too many time but not succeeded please help me

Body:
//@version=2
study(title="EMA & MA Crossover", shorttitle="EMA & MA Crossover", overlay = true)

LengthMA = input(50, minval=1)
LengthEMA = input(200,minval=1)

xMA = ema(close, LengthMA)
xEMA = ema(close, LengthEMA)
pos = iff(xEMA < xMA , 1, iff(xEMA > xMA, -1, nz(pos[1], 0)))
barcolor(pos == -1 ? red: pos == 1 ? green : blue)

plot(xMA, color=red, title="MA")
plot(xEMA, color=blue, title="EMA")

Conversion failed, reason: Source pine is incorrect. line 10: Undeclared identifier pos;
line 11: Undeclared identifier pos

Please help me

I Hade tried too many time but not succeeded please help me


问:
I am getting value error Py Object is null
I am new to python getting error in my code. Im trying to

```<code>
    def __getitem__(self,k):
        if not 0<=abs(k)<self.n:
            return IndexError('k is out of bound')
        elif  0<=k<self.n:
            return self.A[k]
        else:
            return self.A[len(self.A)+k]
</code>```

when I ma passing negative value in argument it gives error
ValueError: PyObject is NULL

I tried using absolute value of K and changed the + and - signs before but its not  working

Body:
I am new to python getting error in my code. Im trying to

    def __getitem__(self,k):
        if not 0<=abs(k)<self.n:
            return IndexError('k is out of bound')
        elif  0<=k<self.n:
            return self.A[k]
        else:
            return self.A[len(self.A)+k]

when I ma passing negative value in argument it gives error
ValueError: PyObject is NULL

I tried using absolute value of K and changed the + and - signs before but its not  working


问:
setState is assigning the function not the value
I'm trying to setState by accessing prev value. But setState makes data a function not the returned value. I do not want to pass data to openElements function or access it by any different way which causes a re-render in my component any time data change.

Here is current code:

```<code>const openElements = ({ childsIds, i, setData, isItemChildClick }: OpenElementsFunc) => {
  setData((prev: Items) => {
    const tempData = [...prev];
    tempData[i] = { ...tempData[i], isOpen: isItemChildClick ? tempData[i].isOpen : true };
    childsIds.map((el) => {
      const i = prev.findIndex((elm) => elm.id === el);
      if (i !== -1) tempData[i] = { ...tempData[i], isShown: true };
    });
    return tempData;
  });
};
</code>```

When I console.log the data it gives me this:

```<code>prev => {
    const tempData = [...prev];
    tempData[i] = {
      ...tempData[i],
      isOpen: isItemChildClick ? tempData[i].isOpen : true
    };
    childsIds.map(el => {
      const i = prev.fi…
</code>```

Body:
I'm trying to setState by accessing prev value. But setState makes data a function not the returned value. I do not want to pass data to openElements function or access it by any different way which causes a re-render in my component any time data change.

Here is current code:

const openElements = ({ childsIds, i, setData, isItemChildClick }: OpenElementsFunc) => {
  setData((prev: Items) => {
    const tempData = [...prev];
    tempData[i] = { ...tempData[i], isOpen: isItemChildClick ? tempData[i].isOpen : true };
    childsIds.map((el) => {
      const i = prev.findIndex((elm) => elm.id === el);
      if (i !== -1) tempData[i] = { ...tempData[i], isShown: true };
    });
    return tempData;
  });
};

When I console.log the data it gives me this:

prev => {
    const tempData = [...prev];
    tempData[i] = {
      ...tempData[i],
      isOpen: isItemChildClick ? tempData[i].isOpen : true
    };
    childsIds.map(el => {
      const i = prev.fi…


问:
Metadata using python - How to get the other @ type value for person like-headline, image for the following in python
`

```<code>def get_dictionary_by_key_value(dictionary, target_key, target_value):

    for key in dictionary:
        if len(dictionary[key]) > 0:
            for item in dictionary[key]:
                if item[target_key] == target_value:
                    return item

</code>```

The output for the above code is

```<code>{'@type': 'SocialMediaPosting',
 'author': {'@type': 'Person',
  'name': 'valli',
  'url': 'https://...'},
 'headline': '',
 'articleBody': 'Oct 10, 2016 - ',
 'image': 'https://.jpg',
 'datePublished': '',
 'sharedContent': {'@type': 'WebPage',
  'headline': '',
  'url': 'https://'},
 '@context': 'http://schema.org/',
 'mainEntityOfPage': {'@type': 'WebPage',
  '@id': 'https://'}}
</code>```

I want the data present in the @type for person and in particular, the headline, image, URL
I am running the function like this

Organization = get_dictionary_by_key_value(metadata_box, '@type','SocialMediaPosting')

kindly guide

I want the data present in the @type for person and in particular, the headline, image, URL
I am running the function like this

Organization = get_dictionary_by_key_value(metadata_box, '@type','SocialMediaPosting')

kindly guide

Body:
`

def get_dictionary_by_key_value(dictionary, target_key, target_value):

    for key in dictionary:
        if len(dictionary[key]) > 0:
            for item in dictionary[key]:
                if item[target_key] == target_value:
                    return item

The output for the above code is

{'@type': 'SocialMediaPosting',
 'author': {'@type': 'Person',
  'name': 'valli',
  'url': 'https://...'},
 'headline': '',
 'articleBody': 'Oct 10, 2016 - ',
 'image': 'https://.jpg',
 'datePublished': '',
 'sharedContent': {'@type': 'WebPage',
  'headline': '',
  'url': 'https://'},
 '@context': 'http://schema.org/',
 'mainEntityOfPage': {'@type': 'WebPage',
  '@id': 'https://'}}

I want the data present in the @type for person and in particular, the headline, image, URL
I am running the function like this

Organization = get_dictionary_by_key_value(metadata_box, '@type','SocialMediaPosting')

kindly guide

I want the data present in the @type for person and in particular, the headline, image, URL
I am running the function like this

Organization = get_dictionary_by_key_value(metadata_box, '@type','SocialMediaPosting')

kindly guide


问:
Saving additional data to a custom react-flow node
I want to save additional data for the custom node, I used this article for creating a custom node using additional data.

Custom node:

```<code>import { useState } from 'react';
import { Handle, Position } from 'react-flow-renderer';
import { Modal } from "react-bootstrap";
import {  Form } from 'react-bootstrap';
import { triggerLimitationType } from "../../../enums/triggerLimitationType";
import _ from 'lodash';
import i18next from "../../../i18n";

function CustomNode({ data }) {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const defaultValues = { type: 0 };
const [formData, setFormData] = useState(defaultValues);
const handleChange = event => {
    const name = event.target.name;
    const value = event.target.value;
    setFormData(values => ({ ...values, [name]: value }))
    data.attribute = formData;
}

return (
    <row>
        <div onDoubleClick={handleShow}>
            <Handle type="target" position={Position.Top} />
            <div className="node-icon" >
                <i className="feather icon-skip-back"></i>
            </div>
            <Handle type="source" position={Position.Bottom} id="b" />
        </div>

        {show && (
            <Modal show={show} onHide={handleClose} className="right fade">
                <Modal.Header closeButton>
                    <Modal.Title>{i18next.t("Trigger")} : {i18next.t("VisitorReturn")}      </Modal.Title>
                </Modal.Header>

                <Modal.Body>
                    <Form.Group >
                        <Form.Label>Type</Form.Label>
                        <Form.Control required as="select" placeholder="Enter Name" value={formData.type} name="type" onChange={handleChange} >
                            {_.map(triggerLimitationType, (value, key) => (
                                <option value={value} key={value}>{key}</option>
                            ))}
                        </Form.Control>
                        <Form.Control.Feedback type="invalid">Please choose a type.</Form.Control.Feedback>
                    </Form.Group>
                </Modal.Body>
            </Modal>
        )}
    </row>
  );
 }

export default CustomNode;
</code>```

Created node:

```<code> const onDrop = (event) => {
    event.preventDefault();

    const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
    const type = event.dataTransfer.getData("type");

    const position = reactFlowInstance.project({
        x: event.clientX - reactFlowBounds.left,
        y: event.clientY - reactFlowBounds.top
    });
    console.log("event", event.dataTransfer);
    const newNode = {
        id: getId(),
        position,
        type: type,
        data: {
            label: `${type} node`, attribute: {
                type: 0
            } }
    };
    // setElements((es) => es.concat(newNode));
    setElements([...elements, newNode]);
    // onSave();
    dispatch(updateElements(newNode));
    console.log("ONDROP", elements);
};
</code>```

But when I set the value for an attribute, I get the error: "attribute" is read-only.

Body:
I want to save additional data for the custom node, I used this article for creating a custom node using additional data.

Custom node:

import { useState } from 'react';
import { Handle, Position } from 'react-flow-renderer';
import { Modal } from "react-bootstrap";
import {  Form } from 'react-bootstrap';
import { triggerLimitationType } from "../../../enums/triggerLimitationType";
import _ from 'lodash';
import i18next from "../../../i18n";

function CustomNode({ data }) {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const defaultValues = { type: 0 };
const [formData, setFormData] = useState(defaultValues);
const handleChange = event => {
    const name = event.target.name;
    const value = event.target.value;
    setFormData(values => ({ ...values, [name]: value }))
    data.attribute = formData;
}

return (
    <row>

            <Handle type="target" position={Position.Top} />

            <Handle type="source" position={Position.Bottom} id="b" />

        {show && (
            <Modal show={show} onHide={handleClose} className="right fade">
                <Modal.Header closeButton>
                    <Modal.Title>{i18next.t("Trigger")} : {i18next.t("VisitorReturn")}      </Modal.Title>
                </Modal.Header>

                <Modal.Body>
                    <Form.Group >
                        <Form.Label>Type</Form.Label>
                        <Form.Control required as="select" placeholder="Enter Name" value={formData.type} name="type" onChange={handleChange} >
                            {_.map(triggerLimitationType, (value, key) => (
                                <option value={value} key={value}>{key}</option>
                            ))}
                        </Form.Control>
                        <Form.Control.Feedback type="invalid">Please choose a type.</Form.Control.Feedback>
                    </Form.Group>
                </Modal.Body>
            </Modal>
        )}
    </row>
  );
 }

export default CustomNode;

Created node:

 const onDrop = (event) => {
    event.preventDefault();

    const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
    const type = event.dataTransfer.getData("type");

    const position = reactFlowInstance.project({
        x: event.clientX - reactFlowBounds.left,
        y: event.clientY - reactFlowBounds.top
    });
    console.log("event", event.dataTransfer);
    const newNode = {
        id: getId(),
        position,
        type: type,
        data: {
            label: `${type} node`, attribute: {
                type: 0
            } }
    };
    // setElements((es) => es.concat(newNode));
    setElements([...elements, newNode]);
    // onSave();
    dispatch(updateElements(newNode));
    console.log("ONDROP", elements);
};

But when I set the value for an attribute, I get the error: "attribute" is read-only.


问:
Python selenium no schema supplied while downloading images
The script should download images from IG and it seems to fail locate the url src of the image. Even with defining the class name. This code used to work last year and all I did is changed the class name and updated driver.find_elements() since it was changed in selenium. I am getting an error:

```<code>requests.exceptions.MissingSchema: Invalid URL 'None': No scheme supplied. Perhaps you meant http://None?
</code>```

If I add print(img.get_attribute("src")) I get None.
Full code:

```<code>import requests
import selenium.webdriver as webdriver
import time
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()

url = ('https://www.instagram.com/cats')
driver.get(url)

scroll_delay = 3
last_height = driver.execute_script("return document.body.scrollHeight")
counter = 0

print('[+] Downloading:\n')

def screens(get_name):
    with open("img_{}.jpg".format(get_name), 'wb') as f:
        r = requests.get(img_url)
        f.write(r.content)

old_imgs = set()

while True:
    imgs = driver.find_elements(By.CLASS_NAME, "_aagv")

    imgs_dedupe = set(imgs) - set(old_imgs)

    for img in imgs_dedupe:
        img_url = img.get_attribute("src")
        print(img.get_attribute("src"))
        print('=> [+] img_{}'.format(counter))
        screens(counter)
        counter = counter + 1

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(scroll_delay)
    new_height = driver.execute_script("return document.body.scrollHeight")

    old_imgs = imgs

    if new_height == last_height:
        break
    last_height = new_height

driver.quit()
</code>```

Any ideas why this would behave like that?

Body:
The script should download images from IG and it seems to fail locate the url src of the image. Even with defining the class name. This code used to work last year and all I did is changed the class name and updated driver.find_elements() since it was changed in selenium. I am getting an error:

requests.exceptions.MissingSchema: Invalid URL 'None': No scheme supplied. Perhaps you meant http://None?

If I add print(img.get_attribute("src")) I get None.
Full code:

import requests
import selenium.webdriver as webdriver
import time
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()

url = ('https://www.instagram.com/cats')
driver.get(url)

scroll_delay = 3
last_height = driver.execute_script("return document.body.scrollHeight")
counter = 0

print('[+] Downloading:\n')

def screens(get_name):
    with open("img_{}.jpg".format(get_name), 'wb') as f:
        r = requests.get(img_url)
        f.write(r.content)

old_imgs = set()

while True:
    imgs = driver.find_elements(By.CLASS_NAME, "_aagv")

    imgs_dedupe = set(imgs) - set(old_imgs)

    for img in imgs_dedupe:
        img_url = img.get_attribute("src")
        print(img.get_attribute("src"))
        print('=> [+] img_{}'.format(counter))
        screens(counter)
        counter = counter + 1

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(scroll_delay)
    new_height = driver.execute_script("return document.body.scrollHeight")

    old_imgs = imgs

    if new_height == last_height:
        break
    last_height = new_height

driver.quit()

Any ideas why this would behave like that?


问:
Prevent Safari from closing in Mac using Selenium Python?
```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

safari_option = Options()
safari_option.add_experimental_option("detach", True)
# Prevent closing browser after done execution

driver = webdriver.Safari(options=safari_option)
driver.get("https://www.google.com/?client=safari")
elem = driver.find_element(By.NAME, "q")
elem.clear()
elem.send_keys("test")
</code>```

I want to prevent safari from closing after the webdriver has finished so that I can see the process of automating another website clearly one by one.

I tried using the safari_option.add_experimental_option("detach", True)
as has been done here

Python selenium keep browser open

for chrome. But I'm not quite sure why it did not work for Safari instead.Seems like a simple problem but couldn't find an answer for it on google or maybe Im blind. Im pretty new to Selenium btw.

Thanks

Body:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

safari_option = Options()
safari_option.add_experimental_option("detach", True)
# Prevent closing browser after done execution

driver = webdriver.Safari(options=safari_option)
driver.get("https://www.google.com/?client=safari")
elem = driver.find_element(By.NAME, "q")
elem.clear()
elem.send_keys("test")

I want to prevent safari from closing after the webdriver has finished so that I can see the process of automating another website clearly one by one.

I tried using the safari_option.add_experimental_option("detach", True)
as has been done here

Python selenium keep browser open

for chrome. But I'm not quite sure why it did not work for Safari instead.Seems like a simple problem but couldn't find an answer for it on google or maybe Im blind. Im pretty new to Selenium btw.

Thanks


问:
how does this python function continue even after return is called?
```<code># Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from queue import Queue
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        ret = []
        q = Queue()
        q.put(root)
        q.put('levelEnd')
        a = []

        while(not q.empty()):
            e = q.get()
            print("-e-",q.empty(), e)
            if (q.empty()) :
                print("return is called") #------------------------------------
                return(ret)
            if e == 'levelEnd':
               ret.append(a)
               a = []
               if (not q.empty()) : q.put('levelEnd')
            else:
                a.append(e.val) #------------------------------------Line 27
                if (e.left != None) : q.put(e.left)
                if (e.right != None) : q.put(e.right)

</code>```

this is the code i wrote on leetcode for problem "102. Binary Tree Level Order Traversal " and the input is [3,9,20,null,null,15]

and the output i get is :

-e- False TreeNode{val: 3, left: TreeNode{val: 9, left: None, right: None}, right: TreeNode{val: 20, left: TreeNode{val: 15, left: None, right: None}, right: None}}
-e- False levelEnd
-e- False TreeNode{val: 9, left: None, right: None}
-e- False TreeNode{val: 20, left: TreeNode{val: 15, left: None, right: None}, right: None}
-e- False levelEnd
-e- False TreeNode{val: 15, left: None, right: None}
-e- True levelEnd
return is called
-e- False TreeNode{val: 1, left: None, right: None}
-e- True levelEnd
return is called
-e- False None

```<code>AttributeError: 'NoneType' object has no attribute 'val'
    a.append(e.val)
Line 27 in levelOrder (Solution.py)
    ret = Solution().levelOrder(param_1)
Line 52 in _driver (Solution.py)
    _driver()
Line 63 in <module> (Solution.py)
</code>```

How does this python function continue even after return is called?

this function should stop after return is called

Body:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from queue import Queue
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        ret = []
        q = Queue()
        q.put(root)
        q.put('levelEnd')
        a = []

        while(not q.empty()):
            e = q.get()
            print("-e-",q.empty(), e)
            if (q.empty()) :
                print("return is called") #------------------------------------
                return(ret)
            if e == 'levelEnd':
               ret.append(a)
               a = []
               if (not q.empty()) : q.put('levelEnd')
            else:
                a.append(e.val) #------------------------------------Line 27
                if (e.left != None) : q.put(e.left)
                if (e.right != None) : q.put(e.right)

this is the code i wrote on leetcode for problem "102. Binary Tree Level Order Traversal " and the input is [3,9,20,null,null,15]

and the output i get is :

-e- False TreeNode{val: 3, left: TreeNode{val: 9, left: None, right: None}, right: TreeNode{val: 20, left: TreeNode{val: 15, left: None, right: None}, right: None}}
-e- False levelEnd
-e- False TreeNode{val: 9, left: None, right: None}
-e- False TreeNode{val: 20, left: TreeNode{val: 15, left: None, right: None}, right: None}
-e- False levelEnd
-e- False TreeNode{val: 15, left: None, right: None}
-e- True levelEnd
return is called
-e- False TreeNode{val: 1, left: None, right: None}
-e- True levelEnd
return is called
-e- False None

AttributeError: 'NoneType' object has no attribute 'val'
    a.append(e.val)
Line 27 in levelOrder (Solution.py)
    ret = Solution().levelOrder(param_1)
Line 52 in _driver (Solution.py)
    _driver()
Line 63 in <module> (Solution.py)

How does this python function continue even after return is called?

this function should stop after return is called


问:
To find position of index
Consider there are C containers in a refinery. The container is designed with a capacity of holding B number of blocks. The blocks are arranged in slots B1, B2 up to Bn. The blocks are arranged as B1 in block 1, B2 in block 2 and Bn in block n. The block size when reached should continue in the next container having the same specifications. The arrangement of blocks can be continued in reverse order in the consecutive container and vice versa in the sequential containers. The problem is to find the position of index in the container where the kth block has been placed as well as the container index.

1.Pattern of Input
• The input should be displayed in a single line requesting number of blocks to be placed and the size of the container as integers.

2.Pattern of Output
• The first line mentions the position of block • The second line mentions the container index • The values should be printed for each of the cases.

3.Restraint
• The block size is less than container count and test cases are atleast 3.

Title: To find position of index


问:
Matplotlib shows blank window
The code runs fine on Linux but when I try it on MacOS Ventura the popup Python window shows blank figure. It is a matplotlib plot, but pretty heavy. Do you have any ideas on resolving it for MacOS?</p>

Title: Matplotlib shows blank window


问:
How to change Discord application name using Python
I want to change a Discord's application name (NOT username) dynamically through code.

Is there any way to do it? I have scrapped through Documentation and not yet found any.

```<code>headers = {"Authorization": "MTA1MTM5OTgyMzk3NjMxNjk1OA.GQ3Imi.ga8ZG0r96u1V8peV9hW2ImZQLE2zrOgDj_xQnQ"}
    data2 = {"name": "BabyDoll"}

    response2 = requests.patch("https://discord.com/api/v6/oauth2/applications/1051399823976316958", headers=headers, json=data2
</code>```

It gave Error 401: Unauthorized

Have given ALL permissions, turned on Message Intent etc

Body:
I want to change a Discord's application name (NOT username) dynamically through code.

Is there any way to do it? I have scrapped through Documentation and not yet found any.

headers = {"Authorization": "MTA1MTM5OTgyMzk3NjMxNjk1OA.GQ3Imi.ga8ZG0r96u1V8peV9hW2ImZQLE2zrOgDj_xQnQ"}
    data2 = {"name": "BabyDoll"}

    response2 = requests.patch("https://discord.com/api/v6/oauth2/applications/1051399823976316958", headers=headers, json=data2

It gave Error 401: Unauthorized

Have given ALL permissions, turned on Message Intent etc


问:
Using linearHypothesis to obtain a p-value for the null hypothesis that the intercept = 0.5
I'm doing question C5.1 in Wooldridge's econometrics textbook. The question asks you to test the hypothesis H0:intercept equals.5 against H1: intercept does not equal .5. Wooldridge instructs you to do so by running a regression of the dependent variable on a constant, which I've done. I'm then trying to use linearHypothesis to test the H0 that the intercept is equal to .5, but something seems to not be working.

I input the following code

```<code>install.packages('wooldridge')
library('wooldridge')
data(pntsprd)
reg<-lm(sprdcvr~1,data=data)
H0<-("Intercept"=0.5)
linearHypothesis(reg,H0)
</code>```

and get this output:

```<code>Linear hypothesis test

Hypothesis:
0.5 ((Intercept) = 0

Model 1: restricted model
Model 2: sprdcvr ~ 1

  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1    553 285.00
2    552 138.12  1    146.88 587.01 < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
</code>```

What am I doing wrong?

Body:
I'm doing question C5.1 in Wooldridge's econometrics textbook. The question asks you to test the hypothesis H0:intercept equals.5 against H1: intercept does not equal .5. Wooldridge instructs you to do so by running a regression of the dependent variable on a constant, which I've done. I'm then trying to use linearHypothesis to test the H0 that the intercept is equal to .5, but something seems to not be working.

I input the following code

install.packages('wooldridge')
library('wooldridge')
data(pntsprd)
reg<-lm(sprdcvr~1,data=data)
H0<-("Intercept"=0.5)
linearHypothesis(reg,H0)

and get this output:

Linear hypothesis test

Hypothesis:
0.5 ((Intercept) = 0

Model 1: restricted model
Model 2: sprdcvr ~ 1

  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1    553 285.00
2    552 138.12  1    146.88 587.01 < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

What am I doing wrong?


问:
Client socket doesn't connect with server socket
I have a problem with setting up socket.io server everything works fine except the client can't connect to the server.

server.js:

```<code>const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('index');
});

io.on('connection', (socket) => {
    console.log("new connection on: " + socket.id);
});

server.listen(3000, () => {
    console.log('listening on port 3000');
});
</code>```

index.ejs:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>socket Response</h1>
</body>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
<script>
    const URL = "http://localhost:3000/";
    const socket = io(URL, { autoConnect: false, transports : ['websocket', 'polling', 'flashsocket'] });
    //console.log(socket.id);
</script>
</html>
</code>```

package.json:

```<code>{
  "name": "socket.io-server",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Lotar122",
  "license": "",
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "socket.io": "^4.5.4",
    "socket.io-client": "^4.5.4"
  }
}
</code>```

I get no errors i just can't get any communication between client and server.

Body:
I have a problem with setting up socket.io server everything works fine except the client can't connect to the server.

server.js:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('index');
});

io.on('connection', (socket) => {
    console.log("new connection on: " + socket.id);
});

server.listen(3000, () => {
    console.log('listening on port 3000');
});

index.ejs:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

socket Response

package.json:

{
  "name": "socket.io-server",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Lotar122",
  "license": "",
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "socket.io": "^4.5.4",
    "socket.io-client": "^4.5.4"
  }
}

I get no errors i just can't get any communication between client and server.


问:
Issue using custom sign in with Apple | SwiftUI
Essentially the goal is to create a custom sign in with apple button. The following is what I have so far, the code compiles fine and the prompt to login shows up as expected but after logging in appleIDCredential does not return any values, name, email, etc. all nil. What am I doing wrong here?</p>
```<code>import SwiftUI
import AuthenticationServices

class AppleSignInHandler: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
         // Return the first window in the current window scene as the presentation anchor for the ASAuthorizationController
         return UIApplication.shared.connectedScenes
             .first { $0.activationState == .foregroundActive }
             .map { $0 as? UIWindowScene }
             .flatMap { $0?.windows.first } ?? UIApplication.shared.windows.first!
     }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            // Apple Sign In was successful.
            // You can now use the `appleIDCredential` to authenticate the user in your app.
            let userFullName = appleIDCredential
            print("Apple Sign In was successful. User's full name is: \(userFullName)")
        }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Apple Sign In failed.
        // You can handle the error here.
        print("Apple Sign In failed with error: \(error.localizedDescription)")
    }
}

struct CustomAppleSignInButton: View {
    let appleSignInHandler = AppleSignInHandler()
    var body: some View {
        Button(action: {
            // Perform the Apple Sign In process here
            let appleIDProvider = ASAuthorizationAppleIDProvider()
            let request = appleIDProvider.createRequest()
            request.requestedScopes = [.fullName, .email]

            let authorizationController = ASAuthorizationController(authorizationRequests: [request])
            authorizationController.delegate = appleSignInHandler
            authorizationController.presentationContextProvider = appleSignInHandler
            authorizationController.performRequests()
        }) {
            HStack {
                Image(systemName: "apple.logo")
                    .resizable()
                    .frame(width: 26, height: 32)
                    .foregroundColor(Color("black"))
                Text("Continue With Apple")
                    .foregroundColor(Color("black"))
            }
            .padding()
            .frame(width: 340, height: 55)
            .background(Color(.label))
            .cornerRadius(28)
        }
    }
}

struct TestView: View {
    var body: some View {
        CustomAppleSignInButton()
    }
}
</code>```

Body:
Essentially the goal is to create a custom sign in with apple button. The following is what I have so far, the code compiles fine and the prompt to login shows up as expected but after logging in appleIDCredential does not return any values, name, email, etc. all nil. What am I doing wrong here?

import SwiftUI
import AuthenticationServices

class AppleSignInHandler: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
         // Return the first window in the current window scene as the presentation anchor for the ASAuthorizationController
         return UIApplication.shared.connectedScenes
             .first { $0.activationState == .foregroundActive }
             .map { $0 as? UIWindowScene }
             .flatMap { $0?.windows.first } ?? UIApplication.shared.windows.first!
     }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            // Apple Sign In was successful.
            // You can now use the `appleIDCredential` to authenticate the user in your app.
            let userFullName = appleIDCredential
            print("Apple Sign In was successful. User's full name is: \(userFullName)")
        }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Apple Sign In failed.
        // You can handle the error here.
        print("Apple Sign In failed with error: \(error.localizedDescription)")
    }
}

struct CustomAppleSignInButton: View {
    let appleSignInHandler = AppleSignInHandler()
    var body: some View {
        Button(action: {
            // Perform the Apple Sign In process here
            let appleIDProvider = ASAuthorizationAppleIDProvider()
            let request = appleIDProvider.createRequest()
            request.requestedScopes = [.fullName, .email]

            let authorizationController = ASAuthorizationController(authorizationRequests: [request])
            authorizationController.delegate = appleSignInHandler
            authorizationController.presentationContextProvider = appleSignInHandler
            authorizationController.performRequests()
        }) {
            HStack {
                Image(systemName: "apple.logo")
                    .resizable()
                    .frame(width: 26, height: 32)
                    .foregroundColor(Color("black"))
                Text("Continue With Apple")
                    .foregroundColor(Color("black"))
            }
            .padding()
            .frame(width: 340, height: 55)
            .background(Color(.label))
            .cornerRadius(28)
        }
    }
}

struct TestView: View {
    var body: some View {
        CustomAppleSignInButton()
    }
}


问:
Adobe Photoshop ComObject throws error while dispatching
I want to automate some tasks in Photoshop using python win32com. But I'm getting error while dispatching the Photoshop Application, error along with code show below.
I have tried solutions available on stackoverflow like deleting genpy folder, reinstall packages, reinstall photoshop but none of them works. Similar discussion links Link1 Link2

import win32com.client as win32
app = win32.gencache.EnsureDispatch("Photoshop.Application")
```
```com_error                                 Traceback (most recent call last)
File ~\miniconda3\lib\site-packages\win32com\client\gencache.py:621, in EnsureDispatch(prog_id, bForDemand)
    620 try:
--> 621     ti = disp._oleobj_.GetTypeInfo()
    622     disp_clsid = ti.GetTypeAttr()[0]

com_error: (-2147312566, 'Error loading type library/DLL.', None, None)

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 app = win32.gencache.EnsureDispatch("Photoshop.Application.130")
      2 app

File ~\miniconda3\lib\site-packages\win32com\client\gencache.py:633, in EnsureDispatch(prog_id, bForDemand)
    631         disp = disp_class(disp._oleobj_)
    632     except pythoncom.com_error:
--> 633         raise TypeError(
    634             "This COM object can not automate the makepy process - please run makepy manually for this object"
    635         )
    636 return disp

TypeError: This COM object can not automate the makepy process - please run makepy manually for this object
```

If I use win32.Disptach instead of win32.gencache.EnsureDispatch, then I'm not getting error but results has no use as not able to execute any command.

I tried loading in with PowerShell "New-Object -ComObject" command. But it also doesn't give desired results. Below screenshot shows outcome is not proper. Also, it throws error if i try any com method.

For reference below are powershell results of another machine where it runs without any issue on PowerShell as well as on python.

Body:
I want to automate some tasks in Photoshop using python win32com. But I'm getting error while dispatching the Photoshop Application, error along with code show below.
I have tried solutions available on stackoverflow like deleting genpy folder, reinstall packages, reinstall photoshop but none of them works. Similar discussion links Link1 Link2

import win32com.client as win32
app = win32.gencache.EnsureDispatch("Photoshop.Application")

com_error                                 Traceback (most recent call last)
File ~\miniconda3\lib\site-packages\win32com\client\gencache.py:621, in EnsureDispatch(prog_id, bForDemand)
    620 try:
--> 621     ti = disp._oleobj_.GetTypeInfo()
    622     disp_clsid = ti.GetTypeAttr()[0]

com_error: (-2147312566, 'Error loading type library/DLL.', None, None)

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 app = win32.gencache.EnsureDispatch("Photoshop.Application.130")
      2 app

File ~\miniconda3\lib\site-packages\win32com\client\gencache.py:633, in EnsureDispatch(prog_id, bForDemand)
    631         disp = disp_class(disp._oleobj_)
    632     except pythoncom.com_error:
--> 633         raise TypeError(
    634             "This COM object can not automate the makepy process - please run makepy manually for this object"
    635         )
    636 return disp

TypeError: This COM object can not automate the makepy process - please run makepy manually for this object

If I use win32.Disptach instead of win32.gencache.EnsureDispatch, then I'm not getting error but results has no use as not able to execute any command.

I tried loading in with PowerShell "New-Object -ComObject" command. But it also doesn't give desired results. Below screenshot shows outcome is not proper. Also, it throws error if i try any com method.

For reference below are powershell results of another machine where it runs without any issue on PowerShell as well as on python.


问:
How to customize Pipeline Steps in Jenkins?
I am new to Jenkins. I am working on a project where I need to frequently check if there are any steps failed in the Jenkins pipeline steps area (attached to the image).

I am not able to find anything appropriate on google. Any suggestions or links to the documentation will help me to work on this. Here in the attached I want to apply a filter of the status column where I can apply a filter for error/success steps.


问:
'notice' ? new NoticeMessage(length, messageValue) : new DatabaseError(messageValue, length, name)
i am getting an error like this

```<code>C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:369
      name === 'notice' ? new NoticeMessage(length, messageValue) : new DatabaseError(messageValue, length, name)
                                                                    ^
error: client selected an invalid SASL authentication mechanism
    at Parser.parseErrorMessage (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:369:69)
    at Parser.handlePacket (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:188:21)
    at Parser.parse (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:103:30)
    at Socket.<anonymous> (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\index.ts:7:48)
    at Socket.emit (node:events:527:28)
    at Socket.emit (node:domain:475:12)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

the file giving the error

```<code> let fieldType = this.reader.string(1)
    while (fieldType !== '\0') {
      fields[fieldType] = this.reader.cstring()
      fieldType = this.reader.string(1)
    }

    const messageValue = fields.M

    const message =
      name === 'notice' ? new NoticeMessage(length, messageValue) : new DatabaseError(messageValue, length, name)

    message.severity = fields.S
    message.code = fields.C
    message.detail = fields.D
    message.hint = fields.H
    message.position = fields.P
    message.internalPosition = fields.p
    message.internalQuery = fields.q
    message.where = fields.W
</code>```

I will be glad if you can solve this.

I couldn't do anything because I didn't know anything about it. I pressed ctrl + c, then I entered the npm install command and when I wrote the npm run dev code, it gave this error.

Body:
i am getting an error like this

C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:369
      name === 'notice' ? new NoticeMessage(length, messageValue) : new DatabaseError(messageValue, length, name)
                                                                    ^
error: client selected an invalid SASL authentication mechanism
    at Parser.parseErrorMessage (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:369:69)
    at Parser.handlePacket (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:188:21)
    at Parser.parse (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\parser.ts:103:30)
    at Socket.<anonymous> (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg-protocol\src\index.ts:7:48)
    at Socket.emit (node:events:527:28)
    at Socket.emit (node:domain:475:12)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
[nodemon] app crashed - waiting for file changes before starting...

the file giving the error

 let fieldType = this.reader.string(1)
    while (fieldType !== '\0') {
      fields[fieldType] = this.reader.cstring()
      fieldType = this.reader.string(1)
    }

    const messageValue = fields.M

    const message =
      name === 'notice' ? new NoticeMessage(length, messageValue) : new DatabaseError(messageValue, length, name)

    message.severity = fields.S
    message.code = fields.C
    message.detail = fields.D
    message.hint = fields.H
    message.position = fields.P
    message.internalPosition = fields.p
    message.internalQuery = fields.q
    message.where = fields.W

I will be glad if you can solve this.

I couldn't do anything because I didn't know anything about it. I pressed ctrl + c, then I entered the npm install command and when I wrote the npm run dev code, it gave this error.


问:
Is it possible to know whether the user who cloned the repository has write access or not?
I'm using GitHub. Let's say John has read access to git@github.com:Org/Repo and Jack has read and write access.

I want to create a small tool to facilitate some git operations.

I want to know whether the user who has cloned the repo has write access or not.

Is it possible? How can I do that?

I searched but I could not find anything.


问:
TypeError: Cannot convert undefined or null to object, javascript
Exception from Finished function when I run it: TypeError: Undefined or null cannot be converted to object,
It gives this error, I couldn't find why it was caused or on which line, thanks for your help

Exception from Finished function when I run it: TypeError: Undefined or null cannot be converted to object,
It gives this error, I couldn't find why it was caused or on which line, thanks for your help

```<code> try {
   fetch("https://www.tcmb.gov.tr/kurlar/today.xml")
  .then((response) => response.text())
  .then((data) => {
   const parser = new DOMParser();
   const xml = parser.parseFromString(data, "text/xml");
   const jsonData = xmlToJson(xml);
   const currencyData = jsonData.Tarih_Date.Currency;
   currencyData.forEach(async (doviz) => {
       await db.collection("currencies").add({
         name: doviz.CurrencyName,
       });
   });
 })

 } catch (error) {
     console.error(error);
 }
</code>```

My method to convert xml to json

```<code>function xmlToJson(xml) {
 var obj = {};

if (xml.nodeType == 1) {

  if (xml.attributes.length > 0) {
    obj["@attributes"] = {};
    for (var j = 0; j < xml.attributes.length; j++) {
      var attribute = xml.attributes.item(j);
      obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
    }
  }
 } else if (xml.nodeType == 3) {
   obj = xml.nodeValue;
}

var textNodes = [].slice.call(xml.childNodes).filter(function(node) {
  return node.nodeType === 3;
 });
 if (xml.hasChildNodes() && xml.childNodes.length === textNodes.length) {
   obj = [].slice.call(xml.childNodes).reduce(function(text, node) {
    return text + node.nodeValue;
  }, "");
 } else if (xml.hasChildNodes()) {
 for (var i = 0; i < xml.childNodes.length; i++) {
   var item = xml.childNodes.item(i);
   var nodeName = item.nodeName;
   if (typeof obj[nodeName] == "undefined") {
     obj[nodeName] = xmlToJson(item);
   } else {
     if (typeof obj[nodeName].push == "undefined") {
       var old = obj[nodeName];
       obj[nodeName] = [];
       obj[nodeName].push(old);
     }
     obj[nodeName].push(xmlToJson(item));
   }
 }
}
return obj;
}
</code>```

Body:
Exception from Finished function when I run it: TypeError: Undefined or null cannot be converted to object,
It gives this error, I couldn't find why it was caused or on which line, thanks for your help

Exception from Finished function when I run it: TypeError: Undefined or null cannot be converted to object,
It gives this error, I couldn't find why it was caused or on which line, thanks for your help

 try {
   fetch("https://www.tcmb.gov.tr/kurlar/today.xml")
  .then((response) => response.text())
  .then((data) => {
   const parser = new DOMParser();
   const xml = parser.parseFromString(data, "text/xml");
   const jsonData = xmlToJson(xml);
   const currencyData = jsonData.Tarih_Date.Currency;
   currencyData.forEach(async (doviz) => {
       await db.collection("currencies").add({
         name: doviz.CurrencyName,
       });
   });
 })

 } catch (error) {
     console.error(error);
 }

My method to convert xml to json

function xmlToJson(xml) {
 var obj = {};

if (xml.nodeType == 1) {

  if (xml.attributes.length > 0) {
    obj["@attributes"] = {};
    for (var j = 0; j < xml.attributes.length; j++) {
      var attribute = xml.attributes.item(j);
      obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
    }
  }
 } else if (xml.nodeType == 3) {
   obj = xml.nodeValue;
}

var textNodes = [].slice.call(xml.childNodes).filter(function(node) {
  return node.nodeType === 3;
 });
 if (xml.hasChildNodes() && xml.childNodes.length === textNodes.length) {
   obj = [].slice.call(xml.childNodes).reduce(function(text, node) {
    return text + node.nodeValue;
  }, "");
 } else if (xml.hasChildNodes()) {
 for (var i = 0; i < xml.childNodes.length; i++) {
   var item = xml.childNodes.item(i);
   var nodeName = item.nodeName;
   if (typeof obj[nodeName] == "undefined") {
     obj[nodeName] = xmlToJson(item);
   } else {
     if (typeof obj[nodeName].push == "undefined") {
       var old = obj[nodeName];
       obj[nodeName] = [];
       obj[nodeName].push(old);
     }
     obj[nodeName].push(xmlToJson(item));
   }
 }
}
return obj;
}


问:
Flutter Error (while build apk) : FAILURE: Build failed with an exception. > Could not resolve all files for configuration ':classpath'
I wanted to test my flutter app in phone. I tried to build an apk by Android Studio. But i toke error.

I said, I click Build > Flutter > Build APK

Results:

```<code>C:\SRC\flutter\bin\flutter.bat --no-color build apk

 Building with sound null safety

Running Gradle task 'assembleRelease'...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find com.android.tools.build:gradle:7.6.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.6/gradle-7.6.pom
       - https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.6/gradle-7.6.pom
     Required by:
         project :

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 11s
Running Gradle task 'assembleRelease'...                           12,6s
Gradle task assembleRelease failed with exit code 1
Process finished with exit code 1
</code>```

My build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

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

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My gradle.properties:

```<code>org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
</code>```

My gradle-wrapper.properties:

```<code>#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-7.6-all.zip
</code>```

I have 7.6 gradle files.

gradle files

I have Java 19 and 17

java files

That is solved my error:
Could not find com.android.tools.build:gradle:7.3.3. error found in build.gradle file

Body:
I wanted to test my flutter app in phone. I tried to build an apk by Android Studio. But i toke error.

I said, I click Build > Flutter > Build APK

Results:

C:\SRC\flutter\bin\flutter.bat --no-color build apk

 Building with sound null safety

Running Gradle task 'assembleRelease'...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find com.android.tools.build:gradle:7.6.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.6/gradle-7.6.pom
       - https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.6/gradle-7.6.pom
     Required by:
         project :

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 11s
Running Gradle task 'assembleRelease'...                           12,6s
Gradle task assembleRelease failed with exit code 1
Process finished with exit code 1

My build.gradle:

buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

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

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My gradle.properties:

org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true

My gradle-wrapper.properties:

#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-7.6-all.zip

I have 7.6 gradle files.

gradle files

I have Java 19 and 17

java files

That is solved my error:
Could not find com.android.tools.build:gradle:7.3.3. error found in build.gradle file


问:
Rest Api call throwing connection error while connected to vpn
I'm trying to make a call to the xmatter api to pull information using http basicauth
its working fine with my vpn turned off, but when I'm connected to the company vpn, I'm getting the below error:

ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

I've also tried running in a loop and running after sometime, but no luck

```<code>import requests
from requests.auth import HTTPBasicAuth
import json

base_URL = "https://acmeco.xmatters.com/api/xm/1"

groupId = "954ada78-7b89-4356-b02c-df85ff30dfd2"

limit = "2"

membersPerShift = "5"

endpoint_URL = (
    "/on-call?groups="
    + groupId
    + "&offset=0&limit="
    + limit
    + "&membersPerShift="
    + membersPerShift
    + "&embed=shift,members.owner"
)

url = base_URL + endpoint_URL

print("Sending request to url: " + url)
auth = HTTPBasicAuth("username", "password")

response = requests.get(url, auth=auth)
responseCode = response.status_code
if responseCode == 200:
    rjson = response.json()
    for d in rjson.get("data"):
        print(
            "Found shift with name: "
            + d["shift"]["name"]
            + " and id: "
            + d["shift"]["id"]
        )
        for md in d["members"]["data"]:
            print(
                "\tFound member with targetName: "
                + md["member"]["targetName"]
                + ", id: "
                + md["member"]["id"]
                + ", and recipientType: "
                + md["member"]["recipientType"]
            )

else:
    rjson = response.json()
    print(
        "The request did not succeed.  Response code is: "
        + str(responseCode)
        + "\n"
        + json.dumps(rjson, indent=4, sort_keys=False)
    )

</code>```

Body:
I'm trying to make a call to the xmatter api to pull information using http basicauth
its working fine with my vpn turned off, but when I'm connected to the company vpn, I'm getting the below error:

ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

I've also tried running in a loop and running after sometime, but no luck

import requests
from requests.auth import HTTPBasicAuth
import json

base_URL = "https://acmeco.xmatters.com/api/xm/1"

groupId = "954ada78-7b89-4356-b02c-df85ff30dfd2"

limit = "2"

membersPerShift = "5"

endpoint_URL = (
    "/on-call?groups="
    + groupId
    + "&offset=0&limit="
    + limit
    + "&membersPerShift="
    + membersPerShift
    + "&embed=shift,members.owner"
)

url = base_URL + endpoint_URL

print("Sending request to url: " + url)
auth = HTTPBasicAuth("username", "password")

response = requests.get(url, auth=auth)
responseCode = response.status_code
if responseCode == 200:
    rjson = response.json()
    for d in rjson.get("data"):
        print(
            "Found shift with name: "
            + d["shift"]["name"]
            + " and id: "
            + d["shift"]["id"]
        )
        for md in d["members"]["data"]:
            print(
                "\tFound member with targetName: "
                + md["member"]["targetName"]
                + ", id: "
                + md["member"]["id"]
                + ", and recipientType: "
                + md["member"]["recipientType"]
            )

else:
    rjson = response.json()
    print(
        "The request did not succeed.  Response code is: "
        + str(responseCode)
        + "\n"
        + json.dumps(rjson, indent=4, sort_keys=False)
    )