问:
Core WCF - Visual Studio for Mac Proxy Settings
Running Visual Studio for Mac 17.4.2 (build 17)

I have a unit test that uses core WCF to call a web service at: https://www.dataaccess.com/webservicesserver/NumberConversion.wso

This works fine when I run the test if I have the ProxyMan app running. However, without ProxyMan I get a timeout after one minute.

In order to generate the wcf proxy class, I ran the following against my unit test project:

```<code>dotnet tool install --global dotnet-svcutil
dotnet-svcutil --roll-forward LatestMajor https://www.dataaccess.com/webservicesserver/NumberConversion.wso?WSDL
</code>```

This generated a large reference.cs file - which I've copied here

My unit test that calls into this can be seen below:

[Fact]
    public async Task CanConvertNumber()
    {
        var client  = new NumberConversionSoapTypeClient(NumberConversionSoapTypeClient.EndpointConfiguration.NumberConversionSoap,
            "https://www.dataaccess.com/webservicesserver/NumberConversion.wso");
        var response = await client.NumberToWordsAsync(46);
        Trace.WriteLine($"The response is: {response.Body.NumberToWordsResult}");
        response.Body.Should().Equals("Forty Six");
    }
```

I have now created a simple console app to reproduce what I have in the unit test. The code for this can be found at: https://github.com/RobBowman/core-wcf-client

Any ideas why it could be dependent on proxyman? It seems as if core wcf code is routing to localhost for some reason.

Thanks,

Rob.

Body:
Running Visual Studio for Mac 17.4.2 (build 17)

I have a unit test that uses core WCF to call a web service at: https://www.dataaccess.com/webservicesserver/NumberConversion.wso

This works fine when I run the test if I have the ProxyMan app running. However, without ProxyMan I get a timeout after one minute.

In order to generate the wcf proxy class, I ran the following against my unit test project:

dotnet tool install --global dotnet-svcutil
dotnet-svcutil --roll-forward LatestMajor https://www.dataaccess.com/webservicesserver/NumberConversion.wso?WSDL

This generated a large reference.cs file - which I've copied here

My unit test that calls into this can be seen below:

[Fact]
    public async Task CanConvertNumber()
    {
        var client  = new NumberConversionSoapTypeClient(NumberConversionSoapTypeClient.EndpointConfiguration.NumberConversionSoap,
            "https://www.dataaccess.com/webservicesserver/NumberConversion.wso");
        var response = await client.NumberToWordsAsync(46);
        Trace.WriteLine($"The response is: {response.Body.NumberToWordsResult}");
        response.Body.Should().Equals("Forty Six");
    }

I have now created a simple console app to reproduce what I have in the unit test. The code for this can be found at: https://github.com/RobBowman/core-wcf-client

Any ideas why it could be dependent on proxyman? It seems as if core wcf code is routing to localhost for some reason.

Thanks,

Rob.


来源: stackexchange

问:
How can I refer to a None/NaT value in a pandas dataframe?
I have a pandas dataframe:

```<code> index    timestamp
  0       06:00:00
  1       07:00:00
  2         NaT
</code>```

I am working in Python and would like to map the NaT value in the dataframe to something else.

How can I reference this NaT? I am NOT allowed to use the index column. I must use the timestamp column and refer to NaT specifically.

I have tried something like:

```<code>market_info_df.loc[market_info_df['timestamp'] == None, 'market_state'] = MARKET_STATES.CLOSED
</code>```

But this does not work. Instead of None I have also tried numpy.NaN doesn't work either!

ContentLicense: CC BY-SA 4.0

Body:
I have a pandas dataframe:

 index    timestamp
  0       06:00:00
  1       07:00:00
  2         NaT

I am working in Python and would like to map the NaT value in the dataframe to something else.

How can I reference this NaT? I am NOT allowed to use the index column. I must use the timestamp column and refer to NaT specifically.

I have tried something like:

market_info_df.loc[market_info_df['timestamp'] == None, 'market_state'] = MARKET_STATES.CLOSED

But this does not work. Instead of None I have also tried numpy.NaN doesn't work either!


问:
Stopping and starting a sessionQueue.async
I've got a AV captureSession which starts like this on app init:

```<code>class FrameExtractor: NSObject {

    private let captureSession = AVCaptureSession()

    deinit {
        captureSession.stopRunning()
    }

    fileprivate override init() {

        super.init()

        sessionQueue.async {
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }

                self.configureSession()
                self.captureSession.startRunning()

                self.listener = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
                    .compactMap { _ in (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.interfaceOrientation ?? .unknown }
                    .assign(to: \.orientation, on: self)
            }
        }
    }
}
</code>```

This works fine. But for some reason the captureSession stops after a certain amount of (completely unrelated) file input/output. Thus I was thinking maybe I should stop (captureSession.stopRunning()) and start the captureSession before all file I/O since this class never gets deinitialised where the stopRunning is located. My question what would be the best practice to stop this session from outside this class without starting additional threats (Queues)?

Body:
I've got a AV captureSession which starts like this on app init:

class FrameExtractor: NSObject {

    private let captureSession = AVCaptureSession()

    deinit {
        captureSession.stopRunning()
    }

    fileprivate override init() {

        super.init()

        sessionQueue.async {
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }

                self.configureSession()
                self.captureSession.startRunning()

                self.listener = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
                    .compactMap { _ in (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.interfaceOrientation ?? .unknown }
                    .assign(to: \.orientation, on: self)
            }
        }
    }
}

This works fine. But for some reason the captureSession stops after a certain amount of (completely unrelated) file input/output. Thus I was thinking maybe I should stop (captureSession.stopRunning()) and start the captureSession before all file I/O since this class never gets deinitialised where the stopRunning is located. My question what would be the best practice to stop this session from outside this class without starting additional threats (Queues)?


问:
For loop over elements in list
This is my list:

```<code>letters = ['A', 'B', 'C']
</code>```

I would like to make a for loop in my dataframe over the elements in my list and then winsorize the rows in my dataframe with the same index, so I tried:

```<code>index_a = df.index.tolist()
index_a = list(OrderedDict.fromkeys(index_a))

for l in letters:
    for j in index_a:
          df[l].loc[j] = winsorize(df[l].loc[j], limits=[0.01, 0.01])
</code>```

But I get the error: 'list' object is not callable

Title: For loop over elements in list

Body:
This is my list:

letters = ['A', 'B', 'C']

I would like to make a for loop in my dataframe over the elements in my list and then winsorize the rows in my dataframe with the same index, so I tried:

index_a = df.index.tolist()
index_a = list(OrderedDict.fromkeys(index_a))

for l in letters:
    for j in index_a:
          df[l].loc[j] = winsorize(df[l].loc[j], limits=[0.01, 0.01])

But I get the error: 'list' object is not callable


问:
how to use static in django project
Is this not the correct way of making use of Django's static directories in code?

The folder is static/assets/css/style.css

settings.py

```<code>    STATIC_URL = 'static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
</code>```

urls.py

```<code>    from django.conf.urls.static import static
    from django.conf import settings

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

base.html

```<code>    {% load static %}

    <!DOCTYPE html>
    <head>
        <link rel="stylesheet" href="{% static 'assets/css/style.css' %}">
    </head>

    <body>
        <a href="">Go somewhere</a>
    </body>
    </html>
</code>```

style.css

```<code>    a{
        text-decoration: none;
    }
</code>```

Title: how to use static in django project

Body:
Is this not the correct way of making use of Django's static directories in code?

The folder is static/assets/css/style.css

settings.py

    STATIC_URL = 'static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

urls.py

    from django.conf.urls.static import static
    from django.conf import settings

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

base.html

    {% load static %}

    <!DOCTYPE html>

        <link rel="stylesheet" href="{% static 'assets/css/style.css' %}">

        Go somewhere

style.css

    a{
        text-decoration: none;
    }


问:
Can't connect to external API using Laravel Sail
The project was working fine, suddenly I couldn't connection to Stripe nor Mailtrap APIs.

Stripe error

Could not connect to Stripe (https://api.stripe.com/v1/setup_intents). Please check your internet connection and try again. If this problem persists, you should check Stripe's service status at https://twitter.com/stripestatus, or let us know at support@stripe.com. (Network error [errno 6]: Could not resolve host: api.stripe.com)
```
<p>Mailtrap error</p>
<pre class="lang-html prettyprint-override"><code>Connection could not be established with host "smtp.mailtrap.io:587": stream_socket_client(): php_network_getaddresses: getaddrinfo for smtp.mailtrap.io failed: Temporary failure in name resolution
</code>```

I tried to delete the containers and build them again with --no-cache

```<code>sail down -v
sail build --no-cache
</code>```

But I got an error running apt-get commands because it can't reach to the endpoint.

Body:
The project was working fine, suddenly I couldn't connection to Stripe nor Mailtrap APIs.

Stripe error

Could not connect to Stripe (https://api.stripe.com/v1/setup_intents). Please check your internet connection and try again. If this problem persists, you should check Stripe's service status at https://twitter.com/stripestatus, or let us know at support@stripe.com. (Network error [errno 6]: Could not resolve host: api.stripe.com)

Mailtrap error

Connection could not be established with host "smtp.mailtrap.io:587": stream_socket_client(): php_network_getaddresses: getaddrinfo for smtp.mailtrap.io failed: Temporary failure in name resolution

I tried to delete the containers and build them again with --no-cache

sail down -v
sail build --no-cache

But I got an error running apt-get commands because it can't reach to the endpoint.


问:
API/Library for accessing pre-defined TypeScript globals
I'm looking to access an officially-sourced listing of the pre-defined globals or global constructs of TypeScript, ranging from Uint32ArrayConstructor to Pick, etc.

A simple search of the repo didn't turn up instances of Uint32ArrayConstructor, but I see in the typescript release package that there are declaration files including ones which include this interface.

I was wondering, however, if there is some TypeScript API or third-party library which allows easy introspection on these types from JavaScript (rather than having to parse the files individually). I just need a listing of the available globals as strings.

I'm guessing for what I guess would be more syntactical vocabulary like Pick or T, these might not have a central listing, but these would be nice to have as well.

This is intended for the sake of ensuring eslint-plugin-jsdoc's no-undefined-types rule doesn't treat TypeScript's constructs as undefined types.


问:
Salesforce assigning Service Territories to Assets based on coordinates
I want to assign service territories to Assets, based on a Geolocation field whihc containts two coordinates.

With my below attempt I keep getting the error: Error: Compile Error: Unexpected token ','. at line 14 column 163
I can't seem to find the actual error in my code.

My first thought that I did not have a Relationship between the Asset and the Map Polygon object, but there is a lookup relationship between them.

```<code>    trigger AssetTerritoryAssignment on Asset (before insert, before update) {
// Create a list to store the Ids of the Assets that need to be updated
List<Id> assetIds = new List<Id>();
// Loop through the trigger records to collect the Ids of the Assets that need to be updated
for (Asset asset : Trigger.new) {
    if (asset.gps_fix__c != null && asset.Polygon_Relationship__c != null) {
        assetIds.add(asset.Id);
    }
}
// Use a map to store the Ids of the territories that contain the Assets
Map<Id, Id> territoryIdMap = new Map<Id, Id>();
//Use a query to find the territories that contain the Assets
for(Asset a: [SELECT Id, gps_fix__c, Service_Territory__c, Polygon_Relationship__c FROM Asset WHERE Id IN :assetIds]) {
    FSL__Polygon__c polygon = [SELECT Id FROM FSL__Polygon__c WHERE Id =: a.Polygon_Relationship__c                                 AND ST_WITHIN(a.gps_fix__c, FSL__KML__c) = true limit 1];
    if(polygon != null) {
        territoryIdMap.put(a.Id, polygon.Id);
    }
}
// Create a list of Assets to update
List<Asset> assetsToUpdate = new List<Asset>();
// loop through the assets and update their territory
for (Asset asset : [SELECT Id, Territory__c FROM Asset WHERE Id IN :assetIds]) {
    if (territoryIdMap.containsKey(asset.Id)) {
        asset.Territory__c = territoryIdMap.get(asset.Id);
        assetsToUpdate.add(asset);
    }
}
update assetsToUpdate;
}
</code>```

Body:
I want to assign service territories to Assets, based on a Geolocation field whihc containts two coordinates.

With my below attempt I keep getting the error: Error: Compile Error: Unexpected token ','. at line 14 column 163
I can't seem to find the actual error in my code.

My first thought that I did not have a Relationship between the Asset and the Map Polygon object, but there is a lookup relationship between them.

    trigger AssetTerritoryAssignment on Asset (before insert, before update) {
// Create a list to store the Ids of the Assets that need to be updated
List<Id> assetIds = new List<Id>();
// Loop through the trigger records to collect the Ids of the Assets that need to be updated
for (Asset asset : Trigger.new) {
    if (asset.gps_fix__c != null && asset.Polygon_Relationship__c != null) {
        assetIds.add(asset.Id);
    }
}
// Use a map to store the Ids of the territories that contain the Assets
Map<Id, Id> territoryIdMap = new Map<Id, Id>();
//Use a query to find the territories that contain the Assets
for(Asset a: [SELECT Id, gps_fix__c, Service_Territory__c, Polygon_Relationship__c FROM Asset WHERE Id IN :assetIds]) {
    FSL__Polygon__c polygon = [SELECT Id FROM FSL__Polygon__c WHERE Id =: a.Polygon_Relationship__c                                 AND ST_WITHIN(a.gps_fix__c, FSL__KML__c) = true limit 1];
    if(polygon != null) {
        territoryIdMap.put(a.Id, polygon.Id);
    }
}
// Create a list of Assets to update
List<Asset> assetsToUpdate = new List<Asset>();
// loop through the assets and update their territory
for (Asset asset : [SELECT Id, Territory__c FROM Asset WHERE Id IN :assetIds]) {
    if (territoryIdMap.containsKey(asset.Id)) {
        asset.Territory__c = territoryIdMap.get(asset.Id);
        assetsToUpdate.add(asset);
    }
}
update assetsToUpdate;
}


问:
Dynamic sitemap times out sometimes (next-sitemap)
I implemented a dynamic server side sitemap using next-sitemap package.
And it works smoothly on my local, but when i visit the production sitemap url (https://www.my-url.com/sitemap-dynamic.xml ) it takes too long to load sometimes.

The issue is that the proxy cuts of the request with a 499 response or even 500, after its timeout (30/60 seconds+), resulting in search engines not being able to read the sitemap.

FYI what I did is the same as it's explained in the demo with my customization :

```<code>// pages/server-sitemap-index.xml/index.tsx
import { getServerSideSitemapIndex } from 'next-sitemap'
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  // Method to source urls from cms
  // const urls = await fetch('https//example.com/api')

  return getServerSideSitemapIndex(ctx, [
    'https://example.com/path-1.xml',
    'https://example.com/path-2.xml',
  ])
}

// Default export to prevent next.js errors
export default function SitemapIndex() {}
</code>```

For instance check if we can prewarm the sitemap and refresh it at interval x (hourly/daily ?)
Did someone face or hear about this problem before ? please a hint , and thanks in advance

Body:
I implemented a dynamic server side sitemap using next-sitemap package.
And it works smoothly on my local, but when i visit the production sitemap url (https://www.my-url.com/sitemap-dynamic.xml ) it takes too long to load sometimes.

The issue is that the proxy cuts of the request with a 499 response or even 500, after its timeout (30/60 seconds+), resulting in search engines not being able to read the sitemap.

FYI what I did is the same as it's explained in the demo with my customization :

// pages/server-sitemap-index.xml/index.tsx
import { getServerSideSitemapIndex } from 'next-sitemap'
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  // Method to source urls from cms
  // const urls = await fetch('https//example.com/api')

  return getServerSideSitemapIndex(ctx, [
    'https://example.com/path-1.xml',
    'https://example.com/path-2.xml',
  ])
}

// Default export to prevent next.js errors
export default function SitemapIndex() {}

For instance check if we can prewarm the sitemap and refresh it at interval x (hourly/daily ?)
Did someone face or hear about this problem before ? please a hint , and thanks in advance


问:
Meteor Tool 1.4.4.1 stuck on extracting or downloading. Deploying app on AWS EC2 Linux
Ive scoured to web with no avail..
noob here as well... sorry im still learning

App Dependencies are all out of date... I honestly dont know how to go about updating them yet
System Meteor version is 2.9.1
App Meteor version is 1.4.4.1

when I run Yarn Start, Meteor Tools starts download and extracting. well, it never finishes extracting, even if i leave it for hours.

Works locally no problems but when running on the AWS server or Digital Ocean droplets, both get stuck on Meteor Tools Extracting

I attempted to remove meteor and reinstall meteor globally. Didn't touch anything inside the app as i dont want to break the app. Tried running

```<code>meteor update
</code>```

only for it to freeze on meteor tools extracting. Also tried

```<code>meteor update --patch
</code>```

only to have it freeze as well.

Body:
Ive scoured to web with no avail..
noob here as well... sorry im still learning

App Dependencies are all out of date... I honestly dont know how to go about updating them yet
System Meteor version is 2.9.1
App Meteor version is 1.4.4.1

when I run Yarn Start, Meteor Tools starts download and extracting. well, it never finishes extracting, even if i leave it for hours.

Works locally no problems but when running on the AWS server or Digital Ocean droplets, both get stuck on Meteor Tools Extracting

I attempted to remove meteor and reinstall meteor globally. Didn't touch anything inside the app as i dont want to break the app. Tried running

meteor update

only for it to freeze on meteor tools extracting. Also tried

meteor update --patch

only to have it freeze as well.


问:
Too slow loading of jsp fragment
devs. Here I have a problem with the speed of jsp footer loading

I have my jsp page, where I include header.jsp, footer.jsp and navigation bar. header and navbar loads in a wink, but content of footer loads too slow (about 10-15 sec). But when I place

```<code><jsp:include page="/WEB-INF/fragments/footer.jsp"/>
</code>```

in the the top of jsp page, it works normally. What is the reason of it?

```<code><%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<c:set var="language"
       value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}"
       scope="session"/>
<fmt:setLocale value="${language}"/>
<fmt:setBundle basename="resources"/>

<!DOCTYPE html>
<html lang="${language}">
<head>
    <title>Conferences World</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        <%@ include file="../../css/w3style.css" %>
        body, h1, h2, h3, h4, h5, h6 {
            font-family: "Raleway", sans-serif
        }

        body, html {
            height: 100%;
            line-height: 1.8;
        }

        .w3-bar .w3-button {
            padding: 16px;
        }
    </style>
</head>
<body>
<jsp:include page="/WEB-INF/fragments/header.jsp"/>
<br><br>
<jsp:include page="/WEB-INF/fragments/role_bar.jsp"/>

<!-- Overlay effect when opening sidebar on small screens -->

<!-- Main content: shift it to the right by 250 pixels when the sidebar is visible -->
<div class="w3-main" style="margin-left:250px">
    <div class="w3-row w3-padding-64">
        <div class="w3-twothird w3-container">
            <h1 class="w3-text-teal">WELCOME, ${user.email}, ${user.role} </h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
                dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
                ex ea commodo consequat. Lorem ipsum
                dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
                aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat.</p>
        </div>
        <div class="w3-third w3-container">
            <p class="w3-border w3-padding-large w3-padding-32 w3-center">AD</p>
            <p class="w3-border w3-padding-large w3-padding-64 w3-center">AD</p>
        </div>
    </div>
    <div class="w3-row">
        <div class="w3-twothird w3-container">
            <h1 class="w3-text-teal">We miss you, ${user.email} </h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum
                dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
        </div>
        <div class="w3-third w3-container">
            <p class="w3-border w3-padding-large w3-padding-32 w3-center">AD</p>
            <p class="w3-border w3-padding-large w3-padding-64 w3-center">AD</p>
        </div>
    </div>

</div>

<%--<%@ include file="/WEB-INF/fragments/footer.jsp" %>--%>
<jsp:include page="/WEB-INF/fragments/footer.jsp"/>

</body>
</html>
</code>```

I've already tried to change <jsp:include to <%@ include file as my footer have no dynamic content, it doesn't work. The interesting moment is that, when I place my footer in the top, it loads instantly

Title: Too slow loading of jsp fragment

Body:
devs. Here I have a problem with the speed of jsp footer loading

I have my jsp page, where I include header.jsp, footer.jsp and navigation bar. header and navbar loads in a wink, but content of footer loads too slow (about 10-15 sec). But when I place

<jsp:include page="/WEB-INF/fragments/footer.jsp"/>

in the the top of jsp page, it works normally. What is the reason of it?

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<c:set var="language"
       value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}"
       scope="session"/>
<fmt:setLocale value="${language}"/>
<fmt:setBundle basename="resources"/>

<!DOCTYPE html>

    <title>Conferences World</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<jsp:include page="/WEB-INF/fragments/header.jsp"/>

<jsp:include page="/WEB-INF/fragments/role_bar.jsp"/>

WELCOME, ${user.email}, ${user.role}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
                dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
                ex ea commodo consequat. Lorem ipsum
                dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
                aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat.

AD

AD

We miss you, ${user.email}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum
                dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

AD

AD

<%--<%@ include file="/WEB-INF/fragments/footer.jsp" %>--%>
<jsp:include page="/WEB-INF/fragments/footer.jsp"/>

I've already tried to change <jsp:include to <%@ include file as my footer have no dynamic content, it doesn't work. The interesting moment is that, when I place my footer in the top, it loads instantly


问:
Spring Boot JAR deployment
I have a Spring Boot Java application with property yaml files located under resources folder.
I packaged it in maven using jar format. But the issue is whenever there's a change required in the yaml file I will have to redeploy the jar file.

Is there any way to build the jar file with the reference to yaml files remain outside of the jar?

Title: Spring Boot JAR deployment


问:
How to play PCM data in AVPlayer?
I am trying to play raw linear PCM in swift iOS received from socketio. I can convert the "NSData" to AVAudioPCMBuffer. How can I play it in AVPlayer?

I tried using MobileVlcKit but it doesn't accept live stream data.

Title: How to play PCM data in AVPlayer?


问:
Gradle build failing to parse and build while running the app
I was just launching my app on an avd and this weird "Failed to parse" error is occurring again and again. This is what is popping up:
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.res.ParseLibraryResourcesTask$ParseResourcesRunnable

I tried to build the entire project again, but it gives the same output again and again. Can somebody help? Cheers :)


问:
Permission issue with Android 13 / SDK 33 accessing gallery?
I am trying to access the device photo gallery, I can successfully access the camera and take a photo, however the access to gallery appears to be denied, even though Camera, Photos And Videos permission have been granted.

Here is the method used for the click on accessing gallery;

I am testing using Android 13 device (Oppo X3)

Targeting SDK 32 = Works fine

Targeting SDK 33 = Error

```<code>case R.id.relativeLayoutEditor:
  String[] arrPermissionsEdit = {
    "android.permission.READ_EXTERNAL_STORAGE",
    "android.permission.WRITE_EXTERNAL_STORAGE",
    "android.permission.CAMERA",
    "android.permission.READ_MEDIA_IMAGES"
  };
if (Build.VERSION.SDK_INT >= 29) arrPermissionsEdit = new String[] {
  "android.permission.READ_EXTERNAL_STORAGE",
  "android.permission.READ_MEDIA_IMAGES"
};
Dexter.withContext(HomeActivity.this).withPermissions(arrPermissionsEdit).withListener(new MultiplePermissionsListener() {
  public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
    if (multiplePermissionsReport.areAllPermissionsGranted()) {
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_PICK);
      intent.setType("image/*");
      String[] mimetypes = {
        "image/*"
      };
      intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
      startActivityForResult(intent, IMAGE_GALLERY_REQUEST);
    }

    if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied()) {
      DetailsDialog.showDetailsDialog(HomeActivity.this);
    }
  }

  public void onPermissionRationaleShouldBeShown(List < PermissionRequest > list, PermissionToken permissionToken) {
    permissionToken.continuePermissionRequest();
  }

}).withErrorListener(dexterError -> Toast.makeText(HomeActivity.this, "Error occurred! ", Toast.LENGTH_SHORT).show()).onSameThread().check();

return;
</code>```

Body:
I am trying to access the device photo gallery, I can successfully access the camera and take a photo, however the access to gallery appears to be denied, even though Camera, Photos And Videos permission have been granted.

Here is the method used for the click on accessing gallery;

I am testing using Android 13 device (Oppo X3)

Targeting SDK 32 = Works fine

Targeting SDK 33 = Error

case R.id.relativeLayoutEditor:
  String[] arrPermissionsEdit = {
    "android.permission.READ_EXTERNAL_STORAGE",
    "android.permission.WRITE_EXTERNAL_STORAGE",
    "android.permission.CAMERA",
    "android.permission.READ_MEDIA_IMAGES"
  };
if (Build.VERSION.SDK_INT >= 29) arrPermissionsEdit = new String[] {
  "android.permission.READ_EXTERNAL_STORAGE",
  "android.permission.READ_MEDIA_IMAGES"
};
Dexter.withContext(HomeActivity.this).withPermissions(arrPermissionsEdit).withListener(new MultiplePermissionsListener() {
  public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
    if (multiplePermissionsReport.areAllPermissionsGranted()) {
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_PICK);
      intent.setType("image/*");
      String[] mimetypes = {
        "image/*"
      };
      intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
      startActivityForResult(intent, IMAGE_GALLERY_REQUEST);
    }

    if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied()) {
      DetailsDialog.showDetailsDialog(HomeActivity.this);
    }
  }

  public void onPermissionRationaleShouldBeShown(List < PermissionRequest > list, PermissionToken permissionToken) {
    permissionToken.continuePermissionRequest();
  }

}).withErrorListener(dexterError -> Toast.makeText(HomeActivity.this, "Error occurred! ", Toast.LENGTH_SHORT).show()).onSameThread().check();

return;


问:
angular-archwizard doesn't render next step programatically
I'm using angular-archwizard andI want to validate a field with a request before go to the next step.
The function is performed but doesn't render the change until I manipulate the form again.

in controller:

```<code>@ViewChild('wizardform') wizard: WizardComponent;

checkCompanyName() {
    this._CompaniesService.checkCompanyName(this.company.name).subscribe( (data: any) => {
      this.wizard.goToNextStep();
      this.ref.detectChanges();
    }, err => {...});}
</code>```

I expected the form render to the next step.

Body:
I'm using angular-archwizard andI want to validate a field with a request before go to the next step.
The function is performed but doesn't render the change until I manipulate the form again.

in controller:

@ViewChild('wizardform') wizard: WizardComponent;

checkCompanyName() {
    this._CompaniesService.checkCompanyName(this.company.name).subscribe( (data: any) => {
      this.wizard.goToNextStep();
      this.ref.detectChanges();
    }, err => {...});}

I expected the form render to the next step.


问:
RTK Query createSelector that uses query cache
I'm trying to selected some data that is deeply nested within the result of the RTK Query api cache.

The issue I'm having is that I'm unsure how to define and use the custom createSelector properly so I can pass in the multiple parameters needed to get the data.  I seem to run into the same error of expected 2 arguments but got 3.

From what I understand from the docs, and YouTube/articles, is that you pass in each param which will correspond with an input parameter in the selector.  The final thing in the selector is the output where you grab the final data you want.

So I need to pass in 2 params.  First one for the query cache signature so I can get the initial data.  The second param is to filter the data in the output selector.

slice.ts

export const selectOnboardingCategoryFormInfoResult = (state: RootState, { category_id, project_id }: { category_id: number; project_id?: number }) => (!!project_id ? wordprestoApi.endpoints.getOnboardingFormInfo.select({ category_id, project_id })(state).data : undefined);
export const selectAnswer = (answer: OnboardingAnswersResponse) => answer;
export const selectApprovalByAnswer = createSelector([selectOnboardingCategoryFormInfoResult, (cats, answer: OnboardingAnswersResponse) => selectAnswer(answer)], (queryCategories, answer) => {
    if (!queryCategories) return [];

    let foundApproval: OnboardingApproval | undefined = undefined;
    if (!queryCategories) return foundApproval;

    for (const category of queryCategories) {
        const questionResult = category.OnboardingQuestions.find(question => question.OnboardingAnswers.length > 0 && question.OnboardingAnswers[0].id === answer?.id);

        if (questionResult) {
            foundApproval = questionResult.OnboardingAnswers[0].OnboardingAnswerApprovals[0];
            break;
        }
    }

    return foundApproval;
});
```
<p><strong>usage</strong></p>
<pre class="lang-js prettyprint-override"><code>const storedApproval = useSelector(state => selectApprovalByAnswer(state, { project_id: answer?.project_id, category_id }, answer));
</code>```

I'm sure I'm missing a key piece of understanding here.  Any help would be fantastic :)

Body:
I'm trying to selected some data that is deeply nested within the result of the RTK Query api cache.

The issue I'm having is that I'm unsure how to define and use the custom createSelector properly so I can pass in the multiple parameters needed to get the data.  I seem to run into the same error of expected 2 arguments but got 3.

From what I understand from the docs, and YouTube/articles, is that you pass in each param which will correspond with an input parameter in the selector.  The final thing in the selector is the output where you grab the final data you want.

So I need to pass in 2 params.  First one for the query cache signature so I can get the initial data.  The second param is to filter the data in the output selector.

slice.ts

export const selectOnboardingCategoryFormInfoResult = (state: RootState, { category_id, project_id }: { category_id: number; project_id?: number }) => (!!project_id ? wordprestoApi.endpoints.getOnboardingFormInfo.select({ category_id, project_id })(state).data : undefined);
export const selectAnswer = (answer: OnboardingAnswersResponse) => answer;
export const selectApprovalByAnswer = createSelector([selectOnboardingCategoryFormInfoResult, (cats, answer: OnboardingAnswersResponse) => selectAnswer(answer)], (queryCategories, answer) => {
    if (!queryCategories) return [];

    let foundApproval: OnboardingApproval | undefined = undefined;
    if (!queryCategories) return foundApproval;

    for (const category of queryCategories) {
        const questionResult = category.OnboardingQuestions.find(question => question.OnboardingAnswers.length > 0 && question.OnboardingAnswers[0].id === answer?.id);

        if (questionResult) {
            foundApproval = questionResult.OnboardingAnswers[0].OnboardingAnswerApprovals[0];
            break;
        }
    }

    return foundApproval;
});

usage

const storedApproval = useSelector(state => selectApprovalByAnswer(state, { project_id: answer?.project_id, category_id }, answer));

I'm sure I'm missing a key piece of understanding here.  Any help would be fantastic :)


问:
PDFPageCountError: Unable to get page count
I am trying to use pdf2image, but I am getting this error:

PDFPageCountError: Unable to get page count.
I/O Error: Couldn't open file 'C:\Users\user_name\Desktop\folder_name\folder2_name\folder3_name\007-084841-1 to 31 Dec'22': No error.
```
<p>It is confusing as it doesn't give any error, it just says <code>'No error'</code></p>
<p>My code is:</p>
```doc = convert_from_path("C:\\Users\\user_name\\Desktop\\folder_name\\folder2_name\\folder3_name\\007-084841-1 to 31 Dec'22")
path, fileName = os.path.split("C:\\Users\\user_name\\Desktop\\folder_name\\folder2_name\\folder3_name\\007-084841-1 to 31 Dec'22")
fileBaseName, fileExtension = os.path.splitext(fileName)

for page_number, page_data in enumerate(doc):
    txt = pytesseract.image_to_string(Image.fromarray(page_data)).encode("utf-8")
    print("Page # {} - {}".format(str(page_number),txt))
```

Can anyone help me please?

I don't know what to try as the error message just says Unable to open...: No error

Body:
I am trying to use pdf2image, but I am getting this error:

PDFPageCountError: Unable to get page count.
I/O Error: Couldn't open file 'C:\Users\user_name\Desktop\folder_name\folder2_name\folder3_name\007-084841-1 to 31 Dec'22': No error.

It is confusing as it doesn't give any error, it just says 'No error'

My code is:

doc = convert_from_path("C:\\Users\\user_name\\Desktop\\folder_name\\folder2_name\\folder3_name\\007-084841-1 to 31 Dec'22")
path, fileName = os.path.split("C:\\Users\\user_name\\Desktop\\folder_name\\folder2_name\\folder3_name\\007-084841-1 to 31 Dec'22")
fileBaseName, fileExtension = os.path.splitext(fileName)

for page_number, page_data in enumerate(doc):
    txt = pytesseract.image_to_string(Image.fromarray(page_data)).encode("utf-8")
    print("Page # {} - {}".format(str(page_number),txt))

Can anyone help me please?

I don't know what to try as the error message just says Unable to open...: No error


问:
Playwright (angular) expect fails with empty array when it's not empty
I have an Assert checking the array of a dropdown list vs a hard coded Array.  When I set the array to the dropdown allInnerText(), the variable shows a length of 1, and the expected array.  When checking in the expect, it's coming back with an actual of Array[] (empty).  I have a feeling I'm missing something small, but am stuck as to why it's failing.

```<code>const ddlList = await getDropdownListOptions();  // ddlList = ['Item 1\nItem 2\nItem 3\nItem 4']; when debugging
const expectedList: string[] = ['Item 1\nItem 2\nItem 3\nItem 4'];
console.log(ddlList);
console.log(expectedList);
expect(ddlList).toEqual(expectedList);

async getDropdownListOptions() : Promise<string[]> {
    return await this.page.locator('my locator query here').allInnerTexts();
}
</code>```

When debugging, both ddlList and expectedList appear to be the same.  proto = Array(0), length = 1 and the values match.

When the expect statement executes, it fails it gives the following error (Note: it's the same error whether using expect(ddlList).toBe(expectedList) or expect(ddlList).toEqual(expectedList):

After adding console.log(ddlList) and console.log(expectedList), it further shows they should be equal and pass the expect(ddlList).toEqual(expectedList).  See screenshot below:

Any help would be greatly appreciated

Body:
I have an Assert checking the array of a dropdown list vs a hard coded Array.  When I set the array to the dropdown allInnerText(), the variable shows a length of 1, and the expected array.  When checking in the expect, it's coming back with an actual of Array[] (empty).  I have a feeling I'm missing something small, but am stuck as to why it's failing.

const ddlList = await getDropdownListOptions();  // ddlList = ['Item 1\nItem 2\nItem 3\nItem 4']; when debugging
const expectedList: string[] = ['Item 1\nItem 2\nItem 3\nItem 4'];
console.log(ddlList);
console.log(expectedList);
expect(ddlList).toEqual(expectedList);

async getDropdownListOptions() : Promise<string[]> {
    return await this.page.locator('my locator query here').allInnerTexts();
}

When debugging, both ddlList and expectedList appear to be the same.  proto = Array(0), length = 1 and the values match.

When the expect statement executes, it fails it gives the following error (Note: it's the same error whether using expect(ddlList).toBe(expectedList) or expect(ddlList).toEqual(expectedList):

After adding console.log(ddlList) and console.log(expectedList), it further shows they should be equal and pass the expect(ddlList).toEqual(expectedList).  See screenshot below:

Any help would be greatly appreciated


问:
Adding globally defined objects for Intellisense and linting to Monaco Editor in javascript/typescript
I have a working Monaco editor in a React app that correctly underlines out javascript errors.

I am trying to register an object called data that I have defined as a JSON schema, so that:

Typing the letter 'd' in the code editor would prompt intellisense to suggest data

Intellisense would correctly suggest all the properties of the data object, and the properties of all of its child properties according to the JSON schema

The editor does not show an undefined variable error when data is used.

I have tried to use monarch to register data as a keyword but am only managing to handle the coloring and error handling, not the properties suggestion.

I also looked at registerDocumentSymbolProvider. registerCompletionItemProvider and registerDeclarationProvider (I think the last one will help with intellisense but not with getting rid of the undefined error) but I don't understand what the purpose of each are and the documentation only defines their usage with sentences like "registers a document symbol provider" which I haven't so far found very helpful.

Would appreciate any help with this. I am excited to use the more advanced features of this great tool but the steep learning curve and my inability to find information has left me pretty disheartened so far!


问:
Configure multiple base url's in Karate
I have run a test case against multiple servers, ie Dev, QA, and STAGING. How can I configure all the URLs in the Karate configuration?

These server names are passed to Karate from the command line, using -D option

Title: Configure multiple base url's in Karate


问:
reset the neural network model after each iteration of a for loop in Tensorflow
I am calculating the power consumption of several neural networks in a for loop, hence in order to get the accurate power consumption I need to reset the model after each iteration of the loop. could you please let me know whether there is a solution in Python or Tensorflow to start the training process over again somehow the model will be reloaded like the first iteration of the for-loop.</p>


问:
An Unintentionally Recursive Sub
One of my Subs repeats numerous times and I don't know how to handle it.

On my MainWindow I have a status bar that contains several Labels that should show the local time in countries around the world.  Here is the computation for one of the labels:

```<code>Private Sub PopulateStatusBar()
Dim UTCTime As Date = Date.UtcNow

Dim timezone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time")
Dim localtime As Date = TimeZoneInfo.ConvertTimeFromUtc(UTCTime, timezone)
AtlanticLabel = " Atlantic" & localtime.ToString("ddd HH:mm") & " "
....
End Sub
</code>```

This routine calls itself until it serendiptiously calculates the samve value for UTCTime two times in a row.  To investigate this problrm, I put Debug.WriteLine(UTCTime) in line XXX and it repeated itself 77 times before ending.  The problem is that it keeps recalculating UTCTime every time it needs that value.

Here are the steps I have talken to resolve the issue.

STEP 1:
I removed UTCTime entirely and simply put the it's calculation into the formulas where it is used.  This did not solve the problem.

STEP 2:
I removed all three local variables (UTCTime, timezone and localtime) and dropped the calculations directly into the AtlanticLabel line making one very long, ugly piece of code.  This did not solve the problem.

STEP 3:
I did even more drasticc surgery to end up with this:

```<code>Private UTCTime As Date
Private timezone As TimeZoneInfo
Private localtime As Date

Private Sub PopulateStatusBar()
    UTCTime = Date.UtcNow
    timezone = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time")
    localtime = TimeZoneInfo.ConvertTimeFromUtc(UTCTime, timezone)
    Go()
End Sub

Private Sub Go()
    AtlanticLabel = " Atlantic" & localtime.ToString("ddd HH:mm") & " "
....
End Sub
</code>```

This did not solve the problem.

Apparently, whenever UTCTime is used, it goes back to the source code (UTCTime = Date.UtcNow) whereever it might be by calling the Sub that contains it.  Essentially PopulateStatusBar is recursive under the hood.

I have no idea how to fix this.

Added In response to Dr.Null

Here is how PopulateStatusBar gets called.

In my Application Class

```<code>  Private Sub Main(sender As Object, e As StartupEventArgs) Handles Me.Startup
     ....
     Dim win As New MainWindow
     win.Show()
 End Sub
</code>```

In MainWindow

```<code> <Window
     x:Class="MainWindow"
     ....
     <i:Interaction.Triggers>
         <i:EventTrigger EventName="Loaded">
             <i:InvokeCommandAction Command="{Binding LoadMe}" />
         </i:EventTrigger>
     </i:Interaction.Triggers>
     ....
 </Window>
</code>```

In the MainWindow View Model

```<code> Public Class MainWindowVM
         ....
         Private ReadOnly Property _LoadMe As New RelayCommand(AddressOf PerformLoadMe)
         Public ReadOnly Property LoadMe As RelayCommand
             Get
                 Return _LoadMe
             End Get
         End Property
         Private Sub PerformLoadMe()
             Dim tmr As New System.Timers.Timer With {.AutoReset = True, .Enabled = True}
             AddHandler tmr.Elapsed, AddressOf PopulateStatusBar
             PopulateStatusBar()   <----Called Here
         End Sub
</code>```

Title: An Unintentionally Recursive Sub

Body:
One of my Subs repeats numerous times and I don't know how to handle it.

On my MainWindow I have a status bar that contains several Labels that should show the local time in countries around the world.  Here is the computation for one of the labels:

Private Sub PopulateStatusBar()
Dim UTCTime As Date = Date.UtcNow

Dim timezone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time")
Dim localtime As Date = TimeZoneInfo.ConvertTimeFromUtc(UTCTime, timezone)
AtlanticLabel = " Atlantic" & localtime.ToString("ddd HH:mm") & " "
....
End Sub

This routine calls itself until it serendiptiously calculates the samve value for UTCTime two times in a row.  To investigate this problrm, I put Debug.WriteLine(UTCTime) in line XXX and it repeated itself 77 times before ending.  The problem is that it keeps recalculating UTCTime every time it needs that value.

Here are the steps I have talken to resolve the issue.

STEP 1:
I removed UTCTime entirely and simply put the it's calculation into the formulas where it is used.  This did not solve the problem.

STEP 2:
I removed all three local variables (UTCTime, timezone and localtime) and dropped the calculations directly into the AtlanticLabel line making one very long, ugly piece of code.  This did not solve the problem.

STEP 3:
I did even more drasticc surgery to end up with this:

Private UTCTime As Date
Private timezone As TimeZoneInfo
Private localtime As Date

Private Sub PopulateStatusBar()
    UTCTime = Date.UtcNow
    timezone = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time")
    localtime = TimeZoneInfo.ConvertTimeFromUtc(UTCTime, timezone)
    Go()
End Sub

Private Sub Go()
    AtlanticLabel = " Atlantic" & localtime.ToString("ddd HH:mm") & " "
....
End Sub

This did not solve the problem.

Apparently, whenever UTCTime is used, it goes back to the source code (UTCTime = Date.UtcNow) whereever it might be by calling the Sub that contains it.  Essentially PopulateStatusBar is recursive under the hood.

I have no idea how to fix this.

Added In response to Dr.Null

Here is how PopulateStatusBar gets called.

In my Application Class

  Private Sub Main(sender As Object, e As StartupEventArgs) Handles Me.Startup
     ....
     Dim win As New MainWindow
     win.Show()
 End Sub

In MainWindow

 <Window
     x:Class="MainWindow"
     ....

     ....
 </Window>

In the MainWindow View Model

 Public Class MainWindowVM
         ....
         Private ReadOnly Property _LoadMe As New RelayCommand(AddressOf PerformLoadMe)
         Public ReadOnly Property LoadMe As RelayCommand
             Get
                 Return _LoadMe
             End Get
         End Property
         Private Sub PerformLoadMe()
             Dim tmr As New System.Timers.Timer With {.AutoReset = True, .Enabled = True}
             AddHandler tmr.Elapsed, AddressOf PopulateStatusBar
             PopulateStatusBar()   <----Called Here
         End Sub


问:
Process cannot access the file because it is being used by another Python process: when trying to move file
Every month I have a bunch of messy Excel files which I need to sort and clean before saving them in a different location.

I've got the cleaning of the Excel files figured out, but when I try to move them once data is cleaned I get:

```<code>---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
File c:\Users\chachu\AppData\Local\Programs\Python\Python310\lib\shutil.py:815, in move(src, dst, copy_function)
    814 try:
--> 815     os.rename(src, real_dst)
    816 except OSError:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\chachu\PSI2\\01.April\\05.04.2022_Final.xlsx' -> 'c:\\Users\\chachu\\processed\\05.04.2022_Final.xlsx'

During handling of the above exception, another exception occurred:

PermissionError                           Traceback (most recent call last)
Cell In [17], line 18
     16     for sheet in sheets:
     17         result = clean_data(sheets)
---> 18 shutil.move(file, dest)

File c:\Users\chachu\AppData\Local\Programs\Python\Python310\lib\shutil.py:836, in move(src, dst, copy_function)
    834     else:
    835         copy_function(src, real_dst)
--> 836         os.unlink(src)
    837 return real_dst

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\chachu\\PSI2\\01.April\\05.04.2022_Final.xlsx'
</code>```

Below is my code:

```<code>path = r'C:\Users\chachu\PSI2\**\*.xlsx'

file_dict = get_file_dict(path) #Fucntion which returns dictionary of excel files as key and sheet name as value

file_dict = get_file_dict(path)
dest = os.getcwd()
for file, sheet in file_dict.items():
    df = pd.read_excel(file, sheet_name=sheet)
    df = clean_data(df) #clean_data function does all the transformations to the excel file to clean it
    df.to_csv(f'{file}-{sheet}.csv', index=False)
    shutil.move(file, dest)
</code>```

I cannot understand why i get permission error, once the cleaning of the data is done by pandas its supposed to move the source file to the processed location.

Body:
Every month I have a bunch of messy Excel files which I need to sort and clean before saving them in a different location.

I've got the cleaning of the Excel files figured out, but when I try to move them once data is cleaned I get:

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
File c:\Users\chachu\AppData\Local\Programs\Python\Python310\lib\shutil.py:815, in move(src, dst, copy_function)
    814 try:
--> 815     os.rename(src, real_dst)
    816 except OSError:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\chachu\PSI2\\01.April\\05.04.2022_Final.xlsx' -> 'c:\\Users\\chachu\\processed\\05.04.2022_Final.xlsx'

During handling of the above exception, another exception occurred:

PermissionError                           Traceback (most recent call last)
Cell In [17], line 18
     16     for sheet in sheets:
     17         result = clean_data(sheets)
---> 18 shutil.move(file, dest)

File c:\Users\chachu\AppData\Local\Programs\Python\Python310\lib\shutil.py:836, in move(src, dst, copy_function)
    834     else:
    835         copy_function(src, real_dst)
--> 836         os.unlink(src)
    837 return real_dst

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\chachu\\PSI2\\01.April\\05.04.2022_Final.xlsx'

Below is my code:

path = r'C:\Users\chachu\PSI2\**\*.xlsx'

file_dict = get_file_dict(path) #Fucntion which returns dictionary of excel files as key and sheet name as value

file_dict = get_file_dict(path)
dest = os.getcwd()
for file, sheet in file_dict.items():
    df = pd.read_excel(file, sheet_name=sheet)
    df = clean_data(df) #clean_data function does all the transformations to the excel file to clean it
    df.to_csv(f'{file}-{sheet}.csv', index=False)
    shutil.move(file, dest)

I cannot understand why i get permission error, once the cleaning of the data is done by pandas its supposed to move the source file to the processed location.


问:
Trying to install Haskell: C Compiler not working
On my MacOS 11.6.2 (Big Sur), I am trying to install Haskell, but my C compiler is not working. I've reinstalled XCode already as some other posts mention, and I ran a test on a simple C program using: gcc -o main main.c and got this error:

"ld: unsupported tapi file type '!tapi-tbd' in YAML file '/Library/Developer/CommandLineTools/SDKs/MacOSX11.sdk/usr/lib/libSystem.tbd' for architecture x86_64
collect2: error: ld returned 1 exit status"

$ which gcc: /usr/local/bin/gcc

$ gcc --version: gcc (Homebrew GCC 12.2.0) 12.2.0

Associated installation error:

```<code>[ Info  ] Installing GHC (this may take a while)
[ ghc-configure ] configure: Xcode version component 2: 2
[ ghc-configure ] checking for gcc... gcc
[ ghc-configure ] checking whether the C compiler works... no
[ ghc-configure ] configure: error: in `/Users/chandyego84/.ghcup/tmp...
[ ghc-configure ] configure: error: C compiler cannot create executab...
[ ghc-configure ] See `config.log' for more details
[ Error ] Process "sh" with arguments ["./configure",
[ ...   ]                              "--prefix=/Users/chandyego84/.ghcup/ghc/9.2.5",
[ ...   ]                              "--disable-ld-override"] failed with exit code 77.
</code>```

ghc-configure.log:

```<code>checking host system type... x86_64-apple-darwin20.6.0
checking target system type... x86_64-apple-darwin20.6.0
Build platform inferred as: x86_64-apple-darwin
Host platform inferred as: x86_64-apple-darwin
Target platform inferred as: x86_64-apple-darwin
GHC build  : x86_64-apple-darwin
GHC host   : x86_64-apple-darwin
GHC target : x86_64-apple-darwin
LLVM target: x86_64-apple-darwin
checking for path to top of build tree... /Users/chandyego84/.ghcup/tmp/ghcup-78f66d443cb0bfcc/ghc-9.2.5-x86_64-apple-darwin
checking for a BSD-compatible install... /usr/bin/install -c
checking whether ln -s works... yes
checking for gsed... sed
checking for python3... /Users/chandyego84/anaconda3/bin/python3
checking Xcode version... 13.2.1
configure: Xcode version component 1: 13
configure: Xcode version component 2: 2
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: in `/Users/chandyego84/.ghcup/tmp/ghcup-78f66d443cb0bfcc/ghc-9.2.5-x86_64-apple-darwin':
configure: error: C compiler cannot create executables
</code>```

Body:
On my MacOS 11.6.2 (Big Sur), I am trying to install Haskell, but my C compiler is not working. I've reinstalled XCode already as some other posts mention, and I ran a test on a simple C program using: gcc -o main main.c and got this error:

"ld: unsupported tapi file type '!tapi-tbd' in YAML file '/Library/Developer/CommandLineTools/SDKs/MacOSX11.sdk/usr/lib/libSystem.tbd' for architecture x86_64
collect2: error: ld returned 1 exit status"

$ which gcc: /usr/local/bin/gcc

$ gcc --version: gcc (Homebrew GCC 12.2.0) 12.2.0

Associated installation error:

[ Info  ] Installing GHC (this may take a while)
[ ghc-configure ] configure: Xcode version component 2: 2
[ ghc-configure ] checking for gcc... gcc
[ ghc-configure ] checking whether the C compiler works... no
[ ghc-configure ] configure: error: in `/Users/chandyego84/.ghcup/tmp...
[ ghc-configure ] configure: error: C compiler cannot create executab...
[ ghc-configure ] See `config.log' for more details
[ Error ] Process "sh" with arguments ["./configure",
[ ...   ]                              "--prefix=/Users/chandyego84/.ghcup/ghc/9.2.5",
[ ...   ]                              "--disable-ld-override"] failed with exit code 77.

ghc-configure.log:

checking host system type... x86_64-apple-darwin20.6.0
checking target system type... x86_64-apple-darwin20.6.0
Build platform inferred as: x86_64-apple-darwin
Host platform inferred as: x86_64-apple-darwin
Target platform inferred as: x86_64-apple-darwin
GHC build  : x86_64-apple-darwin
GHC host   : x86_64-apple-darwin
GHC target : x86_64-apple-darwin
LLVM target: x86_64-apple-darwin
checking for path to top of build tree... /Users/chandyego84/.ghcup/tmp/ghcup-78f66d443cb0bfcc/ghc-9.2.5-x86_64-apple-darwin
checking for a BSD-compatible install... /usr/bin/install -c
checking whether ln -s works... yes
checking for gsed... sed
checking for python3... /Users/chandyego84/anaconda3/bin/python3
checking Xcode version... 13.2.1
configure: Xcode version component 1: 13
configure: Xcode version component 2: 2
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: in `/Users/chandyego84/.ghcup/tmp/ghcup-78f66d443cb0bfcc/ghc-9.2.5-x86_64-apple-darwin':
configure: error: C compiler cannot create executables


问:
Google Cloud OAuth 2.0 Application Verification Language
I'm planning to publish an application using the Google OAuth 2.0 consent screen with sensitive scopes.

In the FAQ under Preparing for verification by creating a video it states

show the OAuth grant process that users will experience, in English

The application is only in German and intended for use in German speaking regions (for now), therefore everything in the application is in German.

My question is, do I have to translate my whole application to English, or is it enough to simply switch the language in the OAuth popup to English?

Also, how would this effect the links to the privacy policy, homepage and such. Would they also need to be translate from German into English?

I tried to find more on that topic on the official FAQ page, through a Google search and here on SO. Sadly to no avail.


问:
Detect if browser is buffering audio stream from mixcloud
My app embeds mixcloud's player widget. It's an embedded swf.

```<code><object>
<embed src="http://www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed=x">
</embed>
</object>
</code>```

If audio is presently streaming, then I want to alert any user who might click on one of my site's internal navigation links that the buffer will be lost if they continue.

Is there a way to detect whether or not the browser is buffering (or has finished buffering) a particular stream?

I think I need to distinguish between the objects that initialize the player (on page load), and the actual audio itself so that this alert only appears if the user has something playing or buffering.

Is there a js library that can help me here?

ContentLicense: CC BY-SA 3.0

Body:
My app embeds mixcloud's player widget. It's an embedded swf.

<object>
<embed src="http://www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed=x">
</embed>
</object>

If audio is presently streaming, then I want to alert any user who might click on one of my site's internal navigation links that the buffer will be lost if they continue.

Is there a way to detect whether or not the browser is buffering (or has finished buffering) a particular stream?

I think I need to distinguish between the objects that initialize the player (on page load), and the actual audio itself so that this alert only appears if the user has something playing or buffering.

Is there a js library that can help me here?


问:
Allow matplotlib figure interaction until button is pressed
I'm making some additions to a plugin for QGIS, which has me creating a figure in a bunch of nested functions. I want the user to be able to interact with the figure using matplotlib radio and checkbuttons, but since these are created inside the inner function, the figure is of course frozen when the script is run. Here's a simplified version of the code:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RadioButtons, CheckButtons

class Vulta:
    """class description"""
    def __init__(self, x_min_val, y_min_val, x_max_val, y_max_val, data_type_val):
        self.x_min = x_min_val
        self.y_min = y_min_val
        self.x_max = x_max_val
        self.y_max = y_max_val
        self.data_type = data_type_val

    def fetch_vulta(self):

        #database access here, returns dataframe df_vs
        d = {'ksb':[1,2,3], 'ksf':[2,3,4], 'ftm':[3,4,5], 'tykf':[4,5,6], 'tykb':[5,6,7] } #example dataframe
        df_vs = pd.DataFrame(d)

        return df_vs

    def plot_vulta(self):
        """

        :return:
        """
        df_vs = self.fetch_vulta()

        plt.ion()
        fig, ax = plt.subplots()
        colors = np.where(df_vs["ksf"]==True, 'g', 'r')
        colors2 = np.where((df_vs["ksb"]!=df_vs["ksf"]), 'k', '#FF000000')
        diff=ax.scatter(df_vs.tykf, df_vs.ftm, s=50, edgecolors=colors2, facecolors='none')
        f=ax.scatter(df_vs.tykf, df_vs.ftm, c=colors, s=20)
        diff.set_visible(False)

        fig.subplots_adjust(left=0.3)

        rax = fig.add_axes([0.05, 0.7, 0.15, 0.15])
        radio = RadioButtons(rax, ('F', 'J'))
        rax2 = fig.add_axes([0.05, 0.6, 0.15, 0.10])
        check = CheckButtons(rax2, ['Diff'])
        plt.show()

        return fig,df_vs,f,radio,check,diff

    def tykfunc(label,f,diff,df_vs):
        def clicked(label):
            tykdict = {'F': [df_vs.tykf, df_vs.ksf], 'J': [df_vs.tykb, df_vs.ksb]}
            [xdata, cdata] = tykdict[label]
            colors3 = np.where(cdata==True,'g','r')
            f.set_offsets(np.c_[xdata.loc[:],df_vs.ftm.loc[:]])
            f.set_color(colors3)
            diff.set_offsets(np.c_[xdata.loc[:],df_vs.ftm.loc[:]])
            plt.draw()
        return clicked

    def func(event,diff):
        def clicked(event):
            diff.set_visible(not diff.get_visible())
            plt.draw()
        return clicked

    def press(event):
        print('press', event.key)
        if event.key == "escape":
            plt.close()

def plot_data(data_type, x_min, y_min, x_max, y_max):
    mk = Vulta(x_min, y_min, x_max, y_max, data_type)
    fig,df_vs,f,radio,check,diff=mk.plot_vulta()
    check.on_clicked(mk.func(diff))
    radio.on_clicked(mk.tykfunc(f,diff,df_vs))
    #fig.canvas.mpl_connect('key_press_event', mk.press()) #this was my initial idea but it doesn't work

xy = [491346.3, 6092271.9, 495478.0, 6112381.9, 'Vultatype']    #doesn't matter here since I cleaned out the code
plot_data(xy[4], xy[0], xy[1], xy[2], xy[3])
</code>```

I thought I'd be able to work around it by implementing a "wait for user input" thing, but so far I can't make anything work.
I'll be happy with any solution that either lets the user interact with the figure after the entire code has run, or pauses the code until the user is done interacting. However, I would prefer to keep it simple (and avoid using Qwidgets for the radio buttons). This is only a snippet of a much larger code that I didn't write myself.

Body:
I'm making some additions to a plugin for QGIS, which has me creating a figure in a bunch of nested functions. I want the user to be able to interact with the figure using matplotlib radio and checkbuttons, but since these are created inside the inner function, the figure is of course frozen when the script is run. Here's a simplified version of the code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RadioButtons, CheckButtons

class Vulta:
    """class description"""
    def __init__(self, x_min_val, y_min_val, x_max_val, y_max_val, data_type_val):
        self.x_min = x_min_val
        self.y_min = y_min_val
        self.x_max = x_max_val
        self.y_max = y_max_val
        self.data_type = data_type_val

    def fetch_vulta(self):

        #database access here, returns dataframe df_vs
        d = {'ksb':[1,2,3], 'ksf':[2,3,4], 'ftm':[3,4,5], 'tykf':[4,5,6], 'tykb':[5,6,7] } #example dataframe
        df_vs = pd.DataFrame(d)

        return df_vs

    def plot_vulta(self):
        """

        :return:
        """
        df_vs = self.fetch_vulta()

        plt.ion()
        fig, ax = plt.subplots()
        colors = np.where(df_vs["ksf"]==True, 'g', 'r')
        colors2 = np.where((df_vs["ksb"]!=df_vs["ksf"]), 'k', '#FF000000')
        diff=ax.scatter(df_vs.tykf, df_vs.ftm, s=50, edgecolors=colors2, facecolors='none')
        f=ax.scatter(df_vs.tykf, df_vs.ftm, c=colors, s=20)
        diff.set_visible(False)

        fig.subplots_adjust(left=0.3)

        rax = fig.add_axes([0.05, 0.7, 0.15, 0.15])
        radio = RadioButtons(rax, ('F', 'J'))
        rax2 = fig.add_axes([0.05, 0.6, 0.15, 0.10])
        check = CheckButtons(rax2, ['Diff'])
        plt.show()

        return fig,df_vs,f,radio,check,diff

    def tykfunc(label,f,diff,df_vs):
        def clicked(label):
            tykdict = {'F': [df_vs.tykf, df_vs.ksf], 'J': [df_vs.tykb, df_vs.ksb]}
            [xdata, cdata] = tykdict[label]
            colors3 = np.where(cdata==True,'g','r')
            f.set_offsets(np.c_[xdata.loc[:],df_vs.ftm.loc[:]])
            f.set_color(colors3)
            diff.set_offsets(np.c_[xdata.loc[:],df_vs.ftm.loc[:]])
            plt.draw()
        return clicked

    def func(event,diff):
        def clicked(event):
            diff.set_visible(not diff.get_visible())
            plt.draw()
        return clicked

    def press(event):
        print('press', event.key)
        if event.key == "escape":
            plt.close()

def plot_data(data_type, x_min, y_min, x_max, y_max):
    mk = Vulta(x_min, y_min, x_max, y_max, data_type)
    fig,df_vs,f,radio,check,diff=mk.plot_vulta()
    check.on_clicked(mk.func(diff))
    radio.on_clicked(mk.tykfunc(f,diff,df_vs))
    #fig.canvas.mpl_connect('key_press_event', mk.press()) #this was my initial idea but it doesn't work

xy = [491346.3, 6092271.9, 495478.0, 6112381.9, 'Vultatype']    #doesn't matter here since I cleaned out the code
plot_data(xy[4], xy[0], xy[1], xy[2], xy[3])

I thought I'd be able to work around it by implementing a "wait for user input" thing, but so far I can't make anything work.
I'll be happy with any solution that either lets the user interact with the figure after the entire code has run, or pauses the code until the user is done interacting. However, I would prefer to keep it simple (and avoid using Qwidgets for the radio buttons). This is only a snippet of a much larger code that I didn't write myself.


问:
Google Search Console says "Page isn't usable on Mobile" but screenshot rendered by Googlebot smartphone is inaccurate
Our website got a "Page isn't usable on mobile" error on Google Search Console but the screenshot rendered by Googlebot smartphone is totally inaccurate from the actual mobile view. It said "Clickable elements too close together," and "Content wider than screen"

This is taken by Googlebot: https://prnt.sc/8hrffemsqqaW
But these are the actual mobile views: https://prnt.sc/-lnaoWh34FQZ, https://prnt.sc/tkOBAEKuoVlj

How can we possibly take some actions if what Google is seeing is inaccurate?


问:
How to detect when ctrl+s is triggered in a visual studio code file in typescript
Im building an extension for VS Code in Typescript. I want to upload a Excel file everytime that the user saves a document. How can i detect the ctrl+s action so i can use the code to update the excel file?

I tried to declare a event but it doesnt seem to work


问:
Module parse failed: Unexpected token error with @prismicio/react?
I have a react app created with CRA using prismic.io. It used to work but now I keep getting module not found error which I keep fixing by running npm install @prismicio/react @prismicio/client @prismicio/helpers after which I get the following error:

./node_modules/@prismicio/react/dist/PrismicRichText.js 115:23
Module parse failed: Unexpected token (115:23)
You may need an appropriate loader to handle this file type.
|       var img = /* @__PURE__ */jsx("img", {
|         src: node.url,
>         alt: node.alt ?? void 0,
|         "data-copyright": node.copyright ? node.copyright : void 0
|       });
```

Anyone have any idea what to do?

I have tried rm node modules and package-lock and reinstalling everything multiple times with no success.

Body:
I have a react app created with CRA using prismic.io. It used to work but now I keep getting module not found error which I keep fixing by running npm install @prismicio/react @prismicio/client @prismicio/helpers after which I get the following error:

./node_modules/@prismicio/react/dist/PrismicRichText.js 115:23
Module parse failed: Unexpected token (115:23)
You may need an appropriate loader to handle this file type.
|       var img = /* @__PURE__ */jsx("img", {
|         src: node.url,
>         alt: node.alt ?? void 0,
|         "data-copyright": node.copyright ? node.copyright : void 0
|       });

Anyone have any idea what to do?

I have tried rm node modules and package-lock and reinstalling everything multiple times with no success.


问:
Design Automation Inventor shut down error
I have a working plugin width Autodesk Design Automation API for 2 years and suddenly stop working and throw next error of time out server.

```<code>[01/11/2023 14:55:28] display name input.iam
[01/11/2023 14:55:28] doc type kAssemblyDocumentObject
[01/11/2023 14:55:28] docdir C:\Users\acesworker\Documents\Inventor Server x64 SDK
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Generate drawing document
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Create a new drawing document
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Get or create a new drawing sheet
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Create a base view
[01/11/2023 14:55:33]     InventorCoreConsole.exe Information: 0 : Change scale of base drawing view
[01/11/2023 14:55:33]     InventorCoreConsole.exe Information: 0 : Create projected view
[01/11/2023 14:55:33]     InventorCoreConsole.exe Information: 0 : Create part list
[01/11/2023 14:55:35]     InventorCoreConsole.exe Information: 0 : Create Revision table
[01/11/2023 14:55:35]     InventorCoreConsole.exe Information: 0 : Done:Create Revision table
[01/11/2023 14:55:35]     InventorCoreConsole.exe Information: 0 : Saving IDW C:\Users\acesworker\Documents\Inventor Server x64 SDK\input.idw
[01/11/2023 14:56:36] Error: Inventor Core Engine Core Console is shut down due to timeout.
[01/11/2023 14:56:36] End script phase.
[01/11/2023 14:56:36] Error: An unexpected error happened during phase CoreEngineExecution of job.
[01/11/2023 14:56:36] Job finished with result FailedExecution
[01/11/2023 14:56:36] Job Status:
</code>```

It's happened when at the last step saving the output file, proved with small files (500Kb) and no intensive process (only open file and save it, no processes needed inside de bundle and the HeartBeat function). It's been working properly a few weeks ago and now throw this error.

Any ideas? Thanks for advance!

Updates 2023-03-22:
Finally, I have made it work. I cleaned ActivityIds, AppIds, etc. It seems works but sometimes it resolves with success response and other times it needs 3 o more tries to resolve (even somtimes DA don't achieve give a success result). Here some logs of the results:

```<code>Create workitem
21/03/2023 12:54:19 : Workitem id: 11d07facf3ed4cff926a7c70425cc6aa
21/03/2023 12:54:21 : Work item status : inprogress
...
21/03/2023 12:55:42 : Work item status : inprogress
21/03/2023 12:55:44 : Work item status : failedInstructions
21/03/2023 12:55:52 : Create workitem
21/03/2023 12:55:53 : Workitem id: 210e2c7b8f2f4922be9a7e33cb29e947
21/03/2023 12:55:55 : Work item status : inprogress
21/03/2023 12:55:57 : Work item status : inprogress
...
21/03/2023 12:57:32 : Work item status : inprogress
21/03/2023 12:57:34 : Work item status : success
</code>```

Any new ideas? Thanks at advance

Body:
I have a working plugin width Autodesk Design Automation API for 2 years and suddenly stop working and throw next error of time out server.

[01/11/2023 14:55:28] display name input.iam
[01/11/2023 14:55:28] doc type kAssemblyDocumentObject
[01/11/2023 14:55:28] docdir C:\Users\acesworker\Documents\Inventor Server x64 SDK
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Generate drawing document
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Create a new drawing document
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Get or create a new drawing sheet
[01/11/2023 14:55:28]     InventorCoreConsole.exe Information: 0 : Create a base view
[01/11/2023 14:55:33]     InventorCoreConsole.exe Information: 0 : Change scale of base drawing view
[01/11/2023 14:55:33]     InventorCoreConsole.exe Information: 0 : Create projected view
[01/11/2023 14:55:33]     InventorCoreConsole.exe Information: 0 : Create part list
[01/11/2023 14:55:35]     InventorCoreConsole.exe Information: 0 : Create Revision table
[01/11/2023 14:55:35]     InventorCoreConsole.exe Information: 0 : Done:Create Revision table
[01/11/2023 14:55:35]     InventorCoreConsole.exe Information: 0 : Saving IDW C:\Users\acesworker\Documents\Inventor Server x64 SDK\input.idw
[01/11/2023 14:56:36] Error: Inventor Core Engine Core Console is shut down due to timeout.
[01/11/2023 14:56:36] End script phase.
[01/11/2023 14:56:36] Error: An unexpected error happened during phase CoreEngineExecution of job.
[01/11/2023 14:56:36] Job finished with result FailedExecution
[01/11/2023 14:56:36] Job Status:

It's happened when at the last step saving the output file, proved with small files (500Kb) and no intensive process (only open file and save it, no processes needed inside de bundle and the HeartBeat function). It's been working properly a few weeks ago and now throw this error.

Any ideas? Thanks for advance!

Updates 2023-03-22:
Finally, I have made it work. I cleaned ActivityIds, AppIds, etc. It seems works but sometimes it resolves with success response and other times it needs 3 o more tries to resolve (even somtimes DA don't achieve give a success result). Here some logs of the results:

Create workitem
21/03/2023 12:54:19 : Workitem id: 11d07facf3ed4cff926a7c70425cc6aa
21/03/2023 12:54:21 : Work item status : inprogress
...
21/03/2023 12:55:42 : Work item status : inprogress
21/03/2023 12:55:44 : Work item status : failedInstructions
21/03/2023 12:55:52 : Create workitem
21/03/2023 12:55:53 : Workitem id: 210e2c7b8f2f4922be9a7e33cb29e947
21/03/2023 12:55:55 : Work item status : inprogress
21/03/2023 12:55:57 : Work item status : inprogress
...
21/03/2023 12:57:32 : Work item status : inprogress
21/03/2023 12:57:34 : Work item status : success

Any new ideas? Thanks at advance


问:
Why is pyspark not recognising existing columns in the dataframe?
I have a dummy data frame:

```<code>import pandas as pd
df = spark.createDataFrame(pd.DataFrame({'a':[1,1,1,2,2,3],'b':[1,1,2,2,2,4]}))
</code>```

and I want the most frequent value from column a.
I tried to solve it using the following code:

```<code>from pyspark.sql import functions as F
df_agged = df.groupby(F.col('a')).agg(F.count('a'))
df_agged.columns
#['a', 'count(a)']
df_agged.where(F.col('count(a)')==F.max(F.col('count(a)')))
</code>```

I get the error:

```<code> Resolved attribute(s) count(a)#472L missing from a#465L,b#466L in operator !Aggregate [a#465L], [a#465L, count(a#465L) AS count(a)#472L, max(count(a)#472L) AS max(count(a)#472L)#477L].;
</code>```

But as I can see that the column exists as I have in the output of df_agged.columns above

I think the where clause is getting pushed before the window function and hence the column is not computed. But, in that case, what is the way to achieve what I want to achieve?

Body:
I have a dummy data frame:

import pandas as pd
df = spark.createDataFrame(pd.DataFrame({'a':[1,1,1,2,2,3],'b':[1,1,2,2,2,4]}))

and I want the most frequent value from column a.
I tried to solve it using the following code:

from pyspark.sql import functions as F
df_agged = df.groupby(F.col('a')).agg(F.count('a'))
df_agged.columns
#['a', 'count(a)']
df_agged.where(F.col('count(a)')==F.max(F.col('count(a)')))

I get the error:

 Resolved attribute(s) count(a)#472L missing from a#465L,b#466L in operator !Aggregate [a#465L], [a#465L, count(a#465L) AS count(a)#472L, max(count(a)#472L) AS max(count(a)#472L)#477L].;

But as I can see that the column exists as I have in the output of df_agged.columns above

I think the where clause is getting pushed before the window function and hence the column is not computed. But, in that case, what is the way to achieve what I want to achieve?


问:
How to manage triggers in a synapse workspace for each environment
I'm working on importing a repository from Git repository and creating its own branch per environment (DEV,Test,PreProd,Production) when I import the repository I import triggers too, but, looks like they only run off of the live mode but not against a branch. If I were to overwrite live mode I run into errors with the below error message which is a bit misleading as I don't have these named objects in my repository.

Error:

```<code>The document creation or update failed because of invalid reference. Please ensure exists in data factory mode and recreate it in Git mode if already present.
</code>```

What would be a good practice to manage triggers in all these different environments.

Body:
I'm working on importing a repository from Git repository and creating its own branch per environment (DEV,Test,PreProd,Production) when I import the repository I import triggers too, but, looks like they only run off of the live mode but not against a branch. If I were to overwrite live mode I run into errors with the below error message which is a bit misleading as I don't have these named objects in my repository.

Error:

The document creation or update failed because of invalid reference. Please ensure exists in data factory mode and recreate it in Git mode if already present.

What would be a good practice to manage triggers in all these different environments.


问:
Angular 14 : I have service in a module and I want to use it in other module but VS code says that could not find it
Cannot find module '../../myservice;' or its corresponding type declarations.

By having the service as Injectable with providedIn root , this should be available throughout the project right?

@Injectable({
providedIn: 'root',
})

I have them in both services. Has anyone faced similar issues ?

I have tried importing myservice from the other service but it says the service that I am looking for is not found

unable to import actually


问:
handling the non availability in filter feature AngularJS
I implemented the filter feature using angularJS

```<code><input type="text" ng-model="vm.searchedItem" />

‹div ng-if = "vm.searchedItem" class="absolute border scroll-y bg-color-white"
style="max-height: 300px;width: 355px;top : 35px;-index: 99;"
>
<span class="wid-100 fl p5"
ng-repeat="v in vm.cityList | filter: vm.searchedItem"
ng-bind ="v.cityName">
</span>
</div>
</code>```

vm.cityList = [{cityName: "London"}, {cityName: "NewYork"}, {cityName:"Delhi"}, {cityName: "Tokyo"}];

I need to handle the case if after filter,
no relevant data is found.
I like to handle the case if, I type NewYork123 in the input,
the ng-bind should show "No data found", as there is none.

Body:
I implemented the filter feature using angularJS

<input type="text" ng-model="vm.searchedItem" />

‹div ng-if = "vm.searchedItem" class="absolute border scroll-y bg-color-white"
style="max-height: 300px;width: 355px;top : 35px;-index: 99;"
>

vm.cityList = [{cityName: "London"}, {cityName: "NewYork"}, {cityName:"Delhi"}, {cityName: "Tokyo"}];

I need to handle the case if after filter,
no relevant data is found.
I like to handle the case if, I type NewYork123 in the input,
the ng-bind should show "No data found", as there is none.


问:
SSIS C# WebRequest from non SQL Server
I have an issue I am trying to solve but I am not sure if this is possible. I have a SQL Server with SSIS Components installed but the SQL Server is completely locked down without any Internet Access

I have an SSIS Package that uses C# to authenticate with a RestAPI URL and then Parse JSON from two other URLs using the authentication. Currently I am manually executing the SSIS package through an app server that can access the SQL Server as well as internet. But now I need to figure out how to get this package to run on its own.

If I deploy to the SQL Server it obviously wont connect because it cannot access the RestAPI URLs. Are there any options to either get the SSIS Package to run on the App server on its own or be able to have the C# reach out to the app server for internet access first while deployed to the SQL Server.

Any thoughts on how to achieve this? Thanks!

Manually running package on App server runs fine.
Deploying SSIS package to SQL Server without internet returns a unable to connect to remote host

Title: SSIS C# WebRequest from non SQL Server


问:
how can I send files and json together without having to convert json to objects in express/node
so I have a simple express/node with a vanillah js front-end.
Here is what my post request looks like:

```<code>const postContent = document.querySelector('#post-content');
const postButton = document.querySelector('#post-button');
const img = document.querySelector('#img');
const formData = new FormData();

postButton.addEventListener("click", function(e) {
    e.preventDefault();
    let data = {
        body: postContent.value,
        comments: [],
        reactionEmoji: [{
            "type": "",
            "count": 0
          },
          {
            "type": "",
            "count": 0
          },
          {
            "type": "",
            "count": 0
          }]
    }

    let imgData = img.files[0]
    console.log(imgData)
    formData.append("photo", imgData);
    formData.append("data", JSON.stringify(data));
    console.log(formData.get("photo"))
    sendPost(formData)
  });

  const sendPost = (input) => {

    //console.log(input.get("photo"))
    let url = `http://localhost:3000/posts`
    let obj = {
        method: 'POST',
        headers: {
        'Accept': 'application/json',
        },
        body: input
        }

    return new Promise(async (res, rej) => {

        try {
            const response = await fetch(url, obj);
            const data = await response.json();
            res(data)
        } catch (err) {
            console.log(err)
            rej(`${err}`)
        }
    })
}
</code>```

Now because i am sending a multipart/form-data, i have to json parse the req.body.data
which looks like this on the server-side

```<code>console.log('req.file')
    console.log(req.file)

    let postToAdd = JSON.parse(req.body.data);
    postToAdd = req.body.data
</code>```

If I were to send just json with content type of application/json, express was parsing for me with express.json but now I have to JSON.parse.

Is this the right way to do it?

Body:
so I have a simple express/node with a vanillah js front-end.
Here is what my post request looks like:

const postContent = document.querySelector('#post-content');
const postButton = document.querySelector('#post-button');
const img = document.querySelector('#img');
const formData = new FormData();

postButton.addEventListener("click", function(e) {
    e.preventDefault();
    let data = {
        body: postContent.value,
        comments: [],
        reactionEmoji: [{
            "type": "",
            "count": 0
          },
          {
            "type": "",
            "count": 0
          },
          {
            "type": "",
            "count": 0
          }]
    }

    let imgData = img.files[0]
    console.log(imgData)
    formData.append("photo", imgData);
    formData.append("data", JSON.stringify(data));
    console.log(formData.get("photo"))
    sendPost(formData)
  });

  const sendPost = (input) => {

    //console.log(input.get("photo"))
    let url = `http://localhost:3000/posts`
    let obj = {
        method: 'POST',
        headers: {
        'Accept': 'application/json',
        },
        body: input
        }

    return new Promise(async (res, rej) => {

        try {
            const response = await fetch(url, obj);
            const data = await response.json();
            res(data)
        } catch (err) {
            console.log(err)
            rej(`${err}`)
        }
    })
}

Now because i am sending a multipart/form-data, i have to json parse the req.body.data
which looks like this on the server-side

console.log('req.file')
    console.log(req.file)

    let postToAdd = JSON.parse(req.body.data);
    postToAdd = req.body.data

If I were to send just json with content type of application/json, express was parsing for me with express.json but now I have to JSON.parse.

Is this the right way to do it?


问:
How to configure vscode to shaw values of stdlib objects in a human readable format
I am trying to debug a C++ via remote debugging with VSCODE running on my Windows, whereas the remote is Ubuntu server.
When I try to watch values of smart-pointers or of other stdlib containers (strings, vectors) instead of getting human-readable contents, I get pile of methods fields, parent classes with their fields an so on. For instance, an std::string value is represented as:

```<code>variable
|--------npos
|--------_M_dataplus
|         |----------std::allocator<char> (base): ... (even more unreadable hierarchy)
|         |----------_M_p ... (even more unreadable hierarchy)
|         |----------_M_string_length
|
|---------<anonymous union> ... (even more unreadable hierarchy)

</code>```

What I would like to get here was a string value "--name".

I tried to find any direction on VSCODE official site (e.g. how to configure debugger). Tried looking for a dedicated VSCODE extension, which perhaps does the parsing. Tried to search for an existing post that asks this - found a few similar questions with no answer (mostly old posts).

Body:
I am trying to debug a C++ via remote debugging with VSCODE running on my Windows, whereas the remote is Ubuntu server.
When I try to watch values of smart-pointers or of other stdlib containers (strings, vectors) instead of getting human-readable contents, I get pile of methods fields, parent classes with their fields an so on. For instance, an std::string value is represented as:

variable
|--------npos
|--------_M_dataplus
|         |----------std::allocator<char> (base): ... (even more unreadable hierarchy)
|         |----------_M_p ... (even more unreadable hierarchy)
|         |----------_M_string_length
|
|---------<anonymous union> ... (even more unreadable hierarchy)

What I would like to get here was a string value "--name".

I tried to find any direction on VSCODE official site (e.g. how to configure debugger). Tried looking for a dedicated VSCODE extension, which perhaps does the parsing. Tried to search for an existing post that asks this - found a few similar questions with no answer (mostly old posts).


问:
Hashing passwords to protect against brute force attacks
I am trying to add a small proof of work function to protect a password from brute force attacks. The solution I have so far is based on the security iPhones have on their lock screen passcodes. I'm repeatedly hashing the password to achieve this.

```<code>import CryptoJS from 'crypto-js';

function sha256_digest(content) {
    return CryptoJS.SHA256(content).toString(CryptoJS.enc.Hex);
}

function hash_n_times(content,n) {
    let hash = content;
    for (let _ = 0; _ < n; _++) { hash = sha256_digest(content); }
    return hash;
}

let password = hash_n_times('Password12345',100000);
</code>```

However, for iPhones, as I understand it, the way the password is stored is device specific and hardware dependent. So they only need to ensure that their work function would take time (like 80ms I heard) to compute on that particular hardware. On the other hand, my application is going to be used on the web so, I have no way to tie this to hardware, so I would like my work function to hold up (at least to some degree) to attacks from other hardware.

The issue is there seems to be a huge discrepancy between the hashing power of a mobile phone or PC compared to crypto mining hardware on the market. With my Mac on Chrome, I can get like 350K hashes in a second. Meanwhile the latest Antminers are doing over 100TH/s...

Assuming a password input that's 8 characters, case sensitive, and alphanumeric, to brute force every permutation it would take 62^8 attempts. Let's say I use 100K hashes so slow mobiles don't freeze up, a single Antminers could brute force it in 62^8 * 10^5 / 10^13 seconds or approx 25 days.

Users are pretty bad an generating random passwords, so that's really worst case, probably most passwords would get broken much faster. So I need a solution that is ideally a few orders of magnitude stronger.

Unfortunately due to hardware limitations, I can't really hash that much more on mobiles. Maybe there's a better operation than hashing or something to be done in addition to hashing? I can't really make users use longer and safer passwords because in practice they will forget them, and making a friendly password recovery system will reduce the effective security as a whole to that of the recovery system.

I also have a salt (and even pepper), but I'm not really sure it helps in this case against brute force on the password itself since the salt is usually stored in the database anyways, so if the attacker has the password hash, he also has the salt. For pepper, I'm looking at worst case where everything is compromised, so while I implement these, I would like to have a more robust foundation for my work function to be harder to intrinsically break.

How do I do this more effectively?

Body:
I am trying to add a small proof of work function to protect a password from brute force attacks. The solution I have so far is based on the security iPhones have on their lock screen passcodes. I'm repeatedly hashing the password to achieve this.

import CryptoJS from 'crypto-js';

function sha256_digest(content) {
    return CryptoJS.SHA256(content).toString(CryptoJS.enc.Hex);
}

function hash_n_times(content,n) {
    let hash = content;
    for (let _ = 0; _ < n; _++) { hash = sha256_digest(content); }
    return hash;
}

let password = hash_n_times('Password12345',100000);

However, for iPhones, as I understand it, the way the password is stored is device specific and hardware dependent. So they only need to ensure that their work function would take time (like 80ms I heard) to compute on that particular hardware. On the other hand, my application is going to be used on the web so, I have no way to tie this to hardware, so I would like my work function to hold up (at least to some degree) to attacks from other hardware.

The issue is there seems to be a huge discrepancy between the hashing power of a mobile phone or PC compared to crypto mining hardware on the market. With my Mac on Chrome, I can get like 350K hashes in a second. Meanwhile the latest Antminers are doing over 100TH/s...

Assuming a password input that's 8 characters, case sensitive, and alphanumeric, to brute force every permutation it would take 62^8 attempts. Let's say I use 100K hashes so slow mobiles don't freeze up, a single Antminers could brute force it in 62^8 * 10^5 / 10^13 seconds or approx 25 days.

Users are pretty bad an generating random passwords, so that's really worst case, probably most passwords would get broken much faster. So I need a solution that is ideally a few orders of magnitude stronger.

Unfortunately due to hardware limitations, I can't really hash that much more on mobiles. Maybe there's a better operation than hashing or something to be done in addition to hashing? I can't really make users use longer and safer passwords because in practice they will forget them, and making a friendly password recovery system will reduce the effective security as a whole to that of the recovery system.

I also have a salt (and even pepper), but I'm not really sure it helps in this case against brute force on the password itself since the salt is usually stored in the database anyways, so if the attacker has the password hash, he also has the salt. For pepper, I'm looking at worst case where everything is compromised, so while I implement these, I would like to have a more robust foundation for my work function to be harder to intrinsically break.

How do I do this more effectively?


问:
FetchRequest results doesn't want to convert to an Array
I simply have an extension:

```<code>extension NSManagedObject {
    class func all(sortedBy: String?, ascending: Bool, predicate: NSPredicate?, context: NSManagedObjectContext) -> [NSManagedObject] {
        let request = fetchRequest()
        if let predicate = predicate {
            request.predicate = predicate
        }
        if let sortedBy = sortedBy {
            request.sortDescriptors = [NSSortDescriptor(key: sortedBy, ascending: ascending)]
        }
            do {
                return try context.fetch(request) //Cannot convert return expression of type '[any NSFetchRequestResult]' to return type '[NSManagedObject]'
            } catch let error as NSError {
                print("❌ Core Data Fetch All Error \(error), \(error.userInfo)")
                return []
            }
    }
}
</code>```

I want to use it like this for example:

```<code>Person.all(sortedBy: nil, ascending: true, predicate: nil, context: context)
Home.all(sortedBy: "streer", ascending: true, predicate: nil, context: context)
</code>```

Implementation of Fetchable protocol:

```<code>protocol Fetchable {
    associatedtype FetchableType: NSManagedObject = Self
    func delete()
}

extension Fetchable where Self: NSManagedObject, FetchableType == Self {

    func delete() {}
}
</code>```

Body:
I simply have an extension:

extension NSManagedObject {
    class func all(sortedBy: String?, ascending: Bool, predicate: NSPredicate?, context: NSManagedObjectContext) -> [NSManagedObject] {
        let request = fetchRequest()
        if let predicate = predicate {
            request.predicate = predicate
        }
        if let sortedBy = sortedBy {
            request.sortDescriptors = [NSSortDescriptor(key: sortedBy, ascending: ascending)]
        }
            do {
                return try context.fetch(request) //Cannot convert return expression of type '[any NSFetchRequestResult]' to return type '[NSManagedObject]'
            } catch let error as NSError {
                print("❌ Core Data Fetch All Error \(error), \(error.userInfo)")
                return []
            }
    }
}

I want to use it like this for example:

Person.all(sortedBy: nil, ascending: true, predicate: nil, context: context)
Home.all(sortedBy: "streer", ascending: true, predicate: nil, context: context)

Implementation of Fetchable protocol:

protocol Fetchable {
    associatedtype FetchableType: NSManagedObject = Self
    func delete()
}

extension Fetchable where Self: NSManagedObject, FetchableType == Self {

    func delete() {}
}


问:
How to authenticate friends by phone number in Android (Kotlin)?
I want make app to have friends concept between certain users.

For example, person A and person B are friends offline.

Person A is registered in App, and if he submit person B's phone number and sends link of this app to person B, person B can register this app with certain authentication number.

So when person B is registered, with this authentication number, app can save data in DB as person A and person B are friends.

This process needs way to send link to user having authentication.

Is there way to implement this in Android (especially Kotlin)?

Or other ways are also fine if it can also authenticate they are frieds.

Please help me.