问:
iFrame not detecting touch or scroll on mobile with 3D scene - Threejs - React Three
I have created a iFrame on my 3D website in which renders a path from my portfolio. I have been attempting to scroll or touch (mobile) this iFrame for a while now, the desktop version works fine, you can scroll, access pages, etc although on mobile, the touch event does not seem to happens.

I have searched several posts and fixes, but none of them made the touch event, or touch scroll from this iframe to work.

You can access my website through https://niltonsf.dev and on the top right select viewWebpage to focus on the html screen.

Here is the component in which renders the iframe:

```<code>import { Html } from "@react-three/drei";
import { Dispatch, SetStateAction } from "react";
import { isMobile } from "react-device-detect";
import * as THREE from "three";

interface MonitorProps {
  geometry: THREE.BufferGeometry;
  screen: THREE.Mesh;
  bakedTexture: THREE.Texture;
  setIsPointerOnHtml: Dispatch<SetStateAction<boolean>>;
  isFocusOnHtml: boolean;
}

export default function Monitor({
  geometry,
  screen,
  bakedTexture,
  setIsPointerOnHtml,
  isFocusOnHtml,
}: MonitorProps) {
  return (
    <>
      <primitive object={screen}>
        <group position={[-2.57, 1.8, -0.01]} rotation-y={1.565}>
          <Html
            transform
            prepend
            wrapperClass="htmlScreen"
            scale={0.35}
            distanceFactor={1.17}
            zIndexRange={[0, 0]}
          >
            <div
              onClick={(e) => {
                if (!isFocusOnHtml) e.preventDefault();
              }}
              onPointerEnter={(e) => {
                if (isFocusOnHtml) setIsPointerOnHtml(true);
              }}
              onPointerLeave={(e) => {
                if (isFocusOnHtml) setIsPointerOnHtml(false);
              }}
            >
              <iframe
                id="iframe"
                src="https://niltonsf.dev/static"
                // src="http://192.168.1.13:3000/static"
                title="myStaticWebsite"
                style={{
                  width: isMobile ? 1200 : 1500,
                }}
              />
            </div>
          </Html>

          <mesh>
            <planeGeometry args={[1.535, 0.69]} />
            <meshPhysicalMaterial
              blending={THREE.NoBlending}
              opacity={0}
              color={"black"}
              side={THREE.DoubleSide}
            />
          </mesh>
        </group>
      </primitive>
      <mesh geometry={geometry}>
        <meshBasicMaterial map={bakedTexture} />
      </mesh>
    </>
  );
}

</code>```

This is the main css file:

```<code>#root {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: white;
  -webkit-overflow-scrolling: touch;
}

.htmlScreen iframe {
  height: 700px;
  border: none;
  background: #000;
  overflow-y: scroll;
  touch-action: touch;
}

canvas {
  touch-action: touch;
}

</code>```

EDIT: It seems to be something with iPhones, Android devices work correctly

Body:
I have created a iFrame on my 3D website in which renders a path from my portfolio. I have been attempting to scroll or touch (mobile) this iFrame for a while now, the desktop version works fine, you can scroll, access pages, etc although on mobile, the touch event does not seem to happens.

I have searched several posts and fixes, but none of them made the touch event, or touch scroll from this iframe to work.

You can access my website through https://niltonsf.dev and on the top right select viewWebpage to focus on the html screen.

Here is the component in which renders the iframe:

import { Html } from "@react-three/drei";
import { Dispatch, SetStateAction } from "react";
import { isMobile } from "react-device-detect";
import * as THREE from "three";

interface MonitorProps {
  geometry: THREE.BufferGeometry;
  screen: THREE.Mesh;
  bakedTexture: THREE.Texture;
  setIsPointerOnHtml: Dispatch<SetStateAction<boolean>>;
  isFocusOnHtml: boolean;
}

export default function Monitor({
  geometry,
  screen,
  bakedTexture,
  setIsPointerOnHtml,
  isFocusOnHtml,
}: MonitorProps) {
  return (
    <>
      <primitive object={screen}>
        <group position={[-2.57, 1.8, -0.01]} rotation-y={1.565}>

 {
                if (!isFocusOnHtml) e.preventDefault();
              }}
              onPointerEnter={(e) => {
                if (isFocusOnHtml) setIsPointerOnHtml(true);
              }}
              onPointerLeave={(e) => {
                if (isFocusOnHtml) setIsPointerOnHtml(false);
              }}
            >

          <mesh>
            <planeGeometry args={[1.535, 0.69]} />
            <meshPhysicalMaterial
              blending={THREE.NoBlending}
              opacity={0}
              color={"black"}
              side={THREE.DoubleSide}
            />
          </mesh>
        </group>
      </primitive>
      <mesh geometry={geometry}>
        <meshBasicMaterial map={bakedTexture} />
      </mesh>
    </>
  );
}

This is the main css file:

#root {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: white;
  -webkit-overflow-scrolling: touch;
}

.htmlScreen iframe {
  height: 700px;
  border: none;
  background: #000;
  overflow-y: scroll;
  touch-action: touch;
}

canvas {
  touch-action: touch;
}

EDIT: It seems to be something with iPhones, Android devices work correctly


来源: stackexchange

问:
Cannot invoke rest call from java with SSL TLSv1.2 to get an authentication token
The code below is refactored based on existing code that works fine in the prod environment. I developed the test unit below in order to introduce a few improvements to the rest call from Java, mainly to implement the following:

add scope,

use the authentication header Authorization: Basic <base64 of client-id:client-secret>, and

add the grant_type and scope in the body using the x-www-form-urlencoded format.

The purpose of this rest call is to get the authorization token that will be used to authorize the other needed services (rest calls).

I completed the first round of the change and tried to run the test and it failed.

```<code>import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

public class TestValueNETServices {

    @Test
    public void testGetJWT() throws Exception {
        String endPointURLwithToken = "https://<url-base>/path/to/token/service";
        String contentType = "application/x-www-form-urlencoded";
        String requestMethod = "POST";
        URL url;
        boolean isSslFlag = true;
        HttpsURLConnection httpsURLCon = null;
        String webServiceResponse = null;
        try {
            try {
                url = new URL(endPointURLwithToken);
            } catch (MalformedURLException malUrlEx) {
                System.out.println("Malformed URL: " + malUrlEx.toString());
                malUrlEx.printStackTrace();
                return;
            }
            httpsURLCon = (HttpsURLConnection) url.openConnection();
            if (isSslFlag) {
                String securedProtocol = "TLSv1.2";
                SSLContext sc = SSLContext.getInstance(securedProtocol);
                sc.init(null, null, new java.security.SecureRandom());
                httpsURLCon.setSSLSocketFactory(sc.getSocketFactory());
            }
            httpsURLCon.setDoOutput(true);
            httpsURLCon.setRequestMethod(requestMethod);
            httpsURLCon.setRequestProperty("Content-Type", contentType);
            System.out.println("Request Method: " + requestMethod + " Content Type: " + contentType);
            String client_id = "client-id-value";
            String client_secret = "client-secret-value";
            String grant_type = "client_credentials";
            String scope = "scope-value";

            String urlParameters = "client_id=" + client_id + "&client_secret=" + client_secret + "&grant_type=" + grant_type + "scope=" + scope;
            System.out.println("Parameters to get Token --> client_id: " + client_id + " client_secret: " + client_secret + " grant_type: " + grant_type);
            // Send post request
            DataOutputStream wr = new DataOutputStream(httpsURLCon.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            System.out.println("HTTP Status Get JWT call:" + Integer.toString(httpsURLCon.getResponseCode()));
            System.out.println("HTTP ResponseMessage " + httpsURLCon.getResponseMessage());

            if (httpsURLCon.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                InputStream responseInputStr = httpsURLCon.getInputStream();
                String tokenResponse = null;
                if (responseInputStr != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(responseInputStr));
                    String output;
                    StringBuffer responseStrBuf = new StringBuffer();
                    while ((output = br.readLine()) != null) {
                        // System.out.println(output);
                        responseStrBuf.append(output);
                    }
                    br.close();
                    tokenResponse = responseStrBuf.toString();
                    webServiceResponse = tokenResponse;
                }
                assertTrue(webServiceResponse != null && (!webServiceResponse.isEmpty()));
            } else {
                fail("FAILED - HTTP Error code: " + httpsURLCon.getResponseCode());
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            ex.printStackTrace();
            fail(ex.toString());
        }
    }

}
</code>```

The error displayed on the console is shown below:

```<code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

Also, I configured the rest call using postman and it works fine after I disabled SSL Certificate Verification.

The code above still requires further tweaking and implementing Base64 conversion for this part Authorization: Basic <base64 of client-id:client-secret>, however, it is falling for SSL configuration issues. I am not familiar with this part, and I need help. I think the SSL Certificate is configured properly on the prod runtime environment, and I need to do the same on my local dev environment but not sure how. I am OK with bypassing this part to make it work same as in postman for the sake of testing the approach. I appreciate your help.

ContentLicense: CC BY-SA 4.0

Body:
The code below is refactored based on existing code that works fine in the prod environment. I developed the test unit below in order to introduce a few improvements to the rest call from Java, mainly to implement the following:

add scope,

use the authentication header Authorization: Basic <base64 of client-id:client-secret>, and

add the grant_type and scope in the body using the x-www-form-urlencoded format.

The purpose of this rest call is to get the authorization token that will be used to authorize the other needed services (rest calls).

I completed the first round of the change and tried to run the test and it failed.

import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

public class TestValueNETServices {

    @Test
    public void testGetJWT() throws Exception {
        String endPointURLwithToken = "https://<url-base>/path/to/token/service";
        String contentType = "application/x-www-form-urlencoded";
        String requestMethod = "POST";
        URL url;
        boolean isSslFlag = true;
        HttpsURLConnection httpsURLCon = null;
        String webServiceResponse = null;
        try {
            try {
                url = new URL(endPointURLwithToken);
            } catch (MalformedURLException malUrlEx) {
                System.out.println("Malformed URL: " + malUrlEx.toString());
                malUrlEx.printStackTrace();
                return;
            }
            httpsURLCon = (HttpsURLConnection) url.openConnection();
            if (isSslFlag) {
                String securedProtocol = "TLSv1.2";
                SSLContext sc = SSLContext.getInstance(securedProtocol);
                sc.init(null, null, new java.security.SecureRandom());
                httpsURLCon.setSSLSocketFactory(sc.getSocketFactory());
            }
            httpsURLCon.setDoOutput(true);
            httpsURLCon.setRequestMethod(requestMethod);
            httpsURLCon.setRequestProperty("Content-Type", contentType);
            System.out.println("Request Method: " + requestMethod + " Content Type: " + contentType);
            String client_id = "client-id-value";
            String client_secret = "client-secret-value";
            String grant_type = "client_credentials";
            String scope = "scope-value";

            String urlParameters = "client_id=" + client_id + "&client_secret=" + client_secret + "&grant_type=" + grant_type + "scope=" + scope;
            System.out.println("Parameters to get Token --> client_id: " + client_id + " client_secret: " + client_secret + " grant_type: " + grant_type);
            // Send post request
            DataOutputStream wr = new DataOutputStream(httpsURLCon.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            System.out.println("HTTP Status Get JWT call:" + Integer.toString(httpsURLCon.getResponseCode()));
            System.out.println("HTTP ResponseMessage " + httpsURLCon.getResponseMessage());

            if (httpsURLCon.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                InputStream responseInputStr = httpsURLCon.getInputStream();
                String tokenResponse = null;
                if (responseInputStr != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(responseInputStr));
                    String output;
                    StringBuffer responseStrBuf = new StringBuffer();
                    while ((output = br.readLine()) != null) {
                        // System.out.println(output);
                        responseStrBuf.append(output);
                    }
                    br.close();
                    tokenResponse = responseStrBuf.toString();
                    webServiceResponse = tokenResponse;
                }
                assertTrue(webServiceResponse != null && (!webServiceResponse.isEmpty()));
            } else {
                fail("FAILED - HTTP Error code: " + httpsURLCon.getResponseCode());
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            ex.printStackTrace();
            fail(ex.toString());
        }
    }

}

The error displayed on the console is shown below:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Also, I configured the rest call using postman and it works fine after I disabled SSL Certificate Verification.

The code above still requires further tweaking and implementing Base64 conversion for this part Authorization: Basic <base64 of client-id:client-secret>, however, it is falling for SSL configuration issues. I am not familiar with this part, and I need help. I think the SSL Certificate is configured properly on the prod runtime environment, and I need to do the same on my local dev environment but not sure how. I am OK with bypassing this part to make it work same as in postman for the sake of testing the approach. I appreciate your help.


问:
update Rshiny DT table on the fly or by clicking anywhere on the page
The user must occasionally press Ctrl + Enter to save changes in Shiny DT tables. I have the following table and would like to design it so that users can have the table and initial data frame updated right upon editing the table (in other words, on the fly), or after editing, they can press an update button or click anywhere on the page to have the initial data frame updated.
Here is the code (the table is restricted so that only the third column is editable):

```<code>library(shiny)
library(DT)

ui <- fluidPage(
  DTOutput("mytable"),
)

server <- function(input, output) {

  data <- data.frame(col1 = c("A", "B", "C"),
                     col2 = c("X", "Y", "Z"),
                     col3 = c(1, 2, 3))

  mytable <- DT::renderDT({
    DT::datatable(data,
                  editable = list(target = "column", disable = list(columns = c(1,2))),
                  selection = "none"

    )
  })

  output$mytable <- mytable

  observeEvent(input$mytable_cell_edit, {
    # Update the data variable
    data <- editData(data = data, info = input$mytable_cell_edit)
    #print the updated data
    print(data)
  })
}

shinyApp(ui, server)
</code>```

There is an example HERE which have radio buttons in the Table. I wonder if there any way that instead of radio buttons we will have Numerical Input for that given editable column and data to be updated as user changes the data?
Any other suggestion is also appreciated.

Body:
The user must occasionally press Ctrl + Enter to save changes in Shiny DT tables. I have the following table and would like to design it so that users can have the table and initial data frame updated right upon editing the table (in other words, on the fly), or after editing, they can press an update button or click anywhere on the page to have the initial data frame updated.
Here is the code (the table is restricted so that only the third column is editable):

library(shiny)
library(DT)

ui <- fluidPage(
  DTOutput("mytable"),
)

server <- function(input, output) {

  data <- data.frame(col1 = c("A", "B", "C"),
                     col2 = c("X", "Y", "Z"),
                     col3 = c(1, 2, 3))

  mytable <- DT::renderDT({
    DT::datatable(data,
                  editable = list(target = "column", disable = list(columns = c(1,2))),
                  selection = "none"

    )
  })

  output$mytable <- mytable

  observeEvent(input$mytable_cell_edit, {
    # Update the data variable
    data <- editData(data = data, info = input$mytable_cell_edit)
    #print the updated data
    print(data)
  })
}

shinyApp(ui, server)

There is an example HERE which have radio buttons in the Table. I wonder if there any way that instead of radio buttons we will have Numerical Input for that given editable column and data to be updated as user changes the data?
Any other suggestion is also appreciated.


问:
What fill rule must be applied for Adobe Type 1 fonts and Type1 CFF fonts as used in PDF?
The PDF Standard (PDF 32000-1:2008) specifies two rules for filling closed paths, non-zero winding number rule ("NZW") and even-odd rule ("EO"), see p. 136-137.
Among the fonts that are allowed in PDF, my understanding is that TrueType fonts and OpenType CFF2 fonts use always NZW...

But what about Adobe Type1 fonts and Type1 CFF (compact font format) fonts (as described in section 9.6.2.1 on p. 254)? Do these also use NZW?


问:
Is it possible to change Elasticsearch basic license to OSS
I'd like to change the license but couldn't find the solution.
Is there any way to change Elasticsearch basic license to Elasticsearch OSS?
I know how to move OSS to basic but not reverse?

I haven't tried yet.


问:
Why is ASP.NET Core 5 replacing the URL query string with a random query string after the page prerender?
I am creating an ASP.NET 5 Blazor Server application with MudBlazor.

I have a URL https://localhost:44324/OperationsAll?Proj_ID=23407&Tail_Nr=TG6R&Location=N.
The query string is used to initialize the data on the OperationsAll page.

It works great in the prerender stage of the lifecyle, retrieving the query string and initializing the page with the correct data in the Oninitialized() method.

In the render stage of the lifecycle when Oninitialized() is run again, the query string has changed to 'https://localhost:44324/OperationsAll?id=1234ASSAf31', with the id always being something different. This, of course, then causes the page to not have the required data for the final render of the page.

An interesting bit of information is that the query string is not being replaced in the web browser address bar, that still remains as https://localhost:44324/OperationsAll?Proj_ID=23407&Tail_Nr=TG6R&Location=N. The query string is being replaced with the random ?id=ASDF!1234 within the HttpContext.

Why is the query string being replaced?

How do I keep the query string from changing during the page lifecycle?


问:
TanStack Table (React-Table) | How to convert the column filter state into the format that the backend is excepting?
I'm trying to implement server-side column filtering for a table in my React app, but I'm having trouble converting the "ColumnFiltersState" object that I'm using on the frontend into the format that the backend (which uses the "nestjs-paginate" library) is expecting. The "ColumnFiltersState" object contains a "value" field that can be of type "unknown" and I'm not sure how to handle it. I have a couple of possible solutions in mind:

One solution could be to use the "filterFn" property for each column, and pass in the filter operator that the backend is expecting (e.g. '$eq', '$gt', etc.) along with the value.
Another approach would be to define a separate mapping function that maps the "ColumnFiltersState" object into the format that the backend is expecting, using the appropriate filter operator and value for each column, but then how we would know witch operator to use, maybe add custom meta prop to the coulmnDef.
Can anyone provide some guidance on how to correctly map the column filters for the backend, and which solution would be the best approach? I would really appreciate any feedback or advice on the best approach, and even better if there is an example code to help me understand the solution better.


问:
Local package "invalid" when added with yarn
I am trying to add my modified version of vega as a local package as a dependency via:

```<code>yarn add vega@file:../vega/packages/vega
</code>```

however, when I then do yarn, it tells me my package is invalid:

```<code>invalid: vega@5.22.1 /Users/alex/Documents/Work/Research/vega_profiler/VegaProf.nosync/editor/node_modules/vega
</code>```

I think this is because it tries to match the version with the one in my package.json, which does not contain version information for the local package. However, I don't know how to address this.

Body:
I am trying to add my modified version of vega as a local package as a dependency via:

yarn add vega@file:../vega/packages/vega

however, when I then do yarn, it tells me my package is invalid:

invalid: vega@5.22.1 /Users/alex/Documents/Work/Research/vega_profiler/VegaProf.nosync/editor/node_modules/vega

I think this is because it tries to match the version with the one in my package.json, which does not contain version information for the local package. However, I don't know how to address this.


问:
text editing in Enfold for Wordpress Theme
I have the Enfold theme someone else installed with Wordpress. When I try to edit the txt on a page the visual editor displays by default with blank white. The text editor is displaying html code? How do I change it so that I can edit the text content.

I am not an experienced developer but a private home guy trying to edit his own website. I dont use html but I feel comfortable working around wordpress. Any help appreciated


问:
Android Java: Speech Recognition App crashes whenever there are no results
I am developing an Android app that uses the Google speech recognition api. For some reason, when I start up the app (via USB debugging on my Android phone), starting the listening process works just fine, and the app works smoothly if I do actually say something after clicking the button to make the app start listening for audio. However, if I click the button to start listening, and then I don't say anything, then the app crashes for some reason. In other words, if the speech recognition gets no results, then the app just crashes. Does anyone have any idea as to why?

Below is an excerpt of my code. (Yes, I did account for the permissions. I just didn't include that code in the excerpt below).

I have tried putting try catch blocks in various places to see if I could catch the error that causes the crash, but it has yet to work. Furthermore, while there is an onResults method, there does not seem to be an onNoResults method.

```<code>speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognitionListener = new RecognitionListener() {
    @Override
    public void onReadyForSpeech(Bundle params) {
        // Called when the speech recognition process is ready to begin
    }

    @Override
    public void onBeginningOfSpeech() {
        // Called when the user begins speaking
    }

    @Override
    public void onRmsChanged(float rmsdB) {
        // Called when the volume of the spoken input changes
    }

    @Override
    public void onBufferReceived(byte[] buffer) {
        // Called when the app receives a buffer of audio data

    }

    @Override
    public void onEndOfSpeech() {
       // Called when the user stops speaking

    }

    @Override
    public void onError(int error) {
        // Called when an error occurs during the speech recognition process
        TextView textView = findViewById(R.id.errors);
        textView.setText(error);
    }

    @Override
    public void onResults(Bundle results) {
        // Called when the speech recognition process has completed and the results are available
        List<String> resultList = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

        if (resultList != null && resultList.size() > 0) {
            // Display the first result in the text field
            TextView textView = findViewById(R.id.spokenWords);
            textView.setText(resultList.get(0));
        }
        //speechRecognizer.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
    }

    @Override
    public void onPartialResults(Bundle partialResults) {
       // Called when the app receives partial results of the speech recognition process

    }

    @Override
    public void onEvent(int eventType, Bundle params) {
        // Called when the app receives other events from the speech recognition process

    }

};

speechRecognizer.setRecognitionListener(recognitionListener);
Button startSpeech = findViewById(R.id.startSpeech);
startSpeech.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        TextView textView = findViewById(R.id.spokenWords);
        textView.setText("Listening");
        speechRecognizer.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
    }
});
</code>```

Body:
I am developing an Android app that uses the Google speech recognition api. For some reason, when I start up the app (via USB debugging on my Android phone), starting the listening process works just fine, and the app works smoothly if I do actually say something after clicking the button to make the app start listening for audio. However, if I click the button to start listening, and then I don't say anything, then the app crashes for some reason. In other words, if the speech recognition gets no results, then the app just crashes. Does anyone have any idea as to why?

Below is an excerpt of my code. (Yes, I did account for the permissions. I just didn't include that code in the excerpt below).

I have tried putting try catch blocks in various places to see if I could catch the error that causes the crash, but it has yet to work. Furthermore, while there is an onResults method, there does not seem to be an onNoResults method.

speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognitionListener = new RecognitionListener() {
    @Override
    public void onReadyForSpeech(Bundle params) {
        // Called when the speech recognition process is ready to begin
    }

    @Override
    public void onBeginningOfSpeech() {
        // Called when the user begins speaking
    }

    @Override
    public void onRmsChanged(float rmsdB) {
        // Called when the volume of the spoken input changes
    }

    @Override
    public void onBufferReceived(byte[] buffer) {
        // Called when the app receives a buffer of audio data

    }

    @Override
    public void onEndOfSpeech() {
       // Called when the user stops speaking

    }

    @Override
    public void onError(int error) {
        // Called when an error occurs during the speech recognition process
        TextView textView = findViewById(R.id.errors);
        textView.setText(error);
    }

    @Override
    public void onResults(Bundle results) {
        // Called when the speech recognition process has completed and the results are available
        List<String> resultList = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

        if (resultList != null && resultList.size() > 0) {
            // Display the first result in the text field
            TextView textView = findViewById(R.id.spokenWords);
            textView.setText(resultList.get(0));
        }
        //speechRecognizer.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
    }

    @Override
    public void onPartialResults(Bundle partialResults) {
       // Called when the app receives partial results of the speech recognition process

    }

    @Override
    public void onEvent(int eventType, Bundle params) {
        // Called when the app receives other events from the speech recognition process

    }

};

speechRecognizer.setRecognitionListener(recognitionListener);
Button startSpeech = findViewById(R.id.startSpeech);
startSpeech.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        TextView textView = findViewById(R.id.spokenWords);
        textView.setText("Listening");
        speechRecognizer.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
    }
});


问:
Is there a way to make a powershell job accessable from other powershell windows for the same user?
Say I run a powershell job as a user in one window, and then want to retrieve the results in another powershell window;

Is it possible to make it global somehow, so I can pull it up on another machine?

I imagine the answer I'm going to get is something along the lines of, "why don't you write it to a file instead"?


问:
How model nested activities in an Activity Diagram in Papyrus
I am trying to create nested activity diagrams in Papyrus.

My Problem: I don't know how to create a sub-activity-diagram directly from an action of my main activity-diagram. I want also to transfer ports from the action to the sub-diagram. In cameo it works easily as described in MagicGrid Handbook:

create sub-activity-diagram from an action

sub-activity diagram including ports

In Papyrus I can only create a sub-diagram manually and then create a hyperlink to the main diagram. But ports are not transferred in this case.

Any idea? Thanks and BR, Lennox


问:
message not sent from the app once the app is downloaded from google play store
I am trying to send a message from my android app without calling mailing agents.

I am using smtp  and javamail-android libs.

It works fine when testing the release on my or any other device BEFORE uploading to Google play store.

But once uploaded and updated as a new release version from google play store, it stops working. There is no crash, but the mail is simply not sent/received.

I do have  uses-permission android:name="android.permission.INTERNET"   set in AndroidManifest.
I did place the required lib files from https://code.google.com/archive/p/javamail-android/downloads

And I did set up an App Password in my gmail account settings  to use in the application to send mail from my app to my google account.

Is there some blocking mechanism of google play store? It is the first time I encountered such a problem.

Here is my code:

```<code>    public void clickSendMessage(View view) {
        String email = "help@myexample.com";
        String subject = "title of the message";
        String message = "text of the message ";

        sendMail(email, subject, message);

    }

    private void sendMail(String email, String subject, String messageBody) {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Message createMessage(String email, String subject, String messageBody, Session session)
            throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("xxx@myexample.com", "App User"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        message.setSubject(subject);
        message.setText(messageBody);
        return message;
    }

    private Session createSessionObject() {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

// In my google account settings I set up an APP PASSWORD and 2 step verification
        return Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, appPassword);
            }
        });
    }

    private class SendMailTask extends AsyncTask<Message, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(SubscriptionOptions.this,
                    "Please wait.", "we are sending your message.",
                    true, false);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();

            confirmEvent();

        }

        @Override
        protected Void doInBackground(Message... messages) {
            try {
                Transport.send(messages[0]);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public void confirmEvent() {

        final AlertDialog alertDialog2 = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom)).create();
        alertDialog2.setTitle(getString(R.string.result));
        alertDialog2.setMessage(myResponse);
        alertDialog2.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.alertDiaThanks), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        alertDialog2.show();
        alertDialog2.getWindow().setBackgroundDrawableResource(R.drawable.gback_1);
    }
</code>```

Body:
I am trying to send a message from my android app without calling mailing agents.

I am using smtp  and javamail-android libs.

It works fine when testing the release on my or any other device BEFORE uploading to Google play store.

But once uploaded and updated as a new release version from google play store, it stops working. There is no crash, but the mail is simply not sent/received.

I do have  uses-permission android:name="android.permission.INTERNET"   set in AndroidManifest.
I did place the required lib files from https://code.google.com/archive/p/javamail-android/downloads

And I did set up an App Password in my gmail account settings  to use in the application to send mail from my app to my google account.

Is there some blocking mechanism of google play store? It is the first time I encountered such a problem.

Here is my code:

    public void clickSendMessage(View view) {
        String email = "help@myexample.com";
        String subject = "title of the message";
        String message = "text of the message ";

        sendMail(email, subject, message);

    }

    private void sendMail(String email, String subject, String messageBody) {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Message createMessage(String email, String subject, String messageBody, Session session)
            throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("xxx@myexample.com", "App User"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        message.setSubject(subject);
        message.setText(messageBody);
        return message;
    }

    private Session createSessionObject() {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

// In my google account settings I set up an APP PASSWORD and 2 step verification
        return Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, appPassword);
            }
        });
    }

    private class SendMailTask extends AsyncTask<Message, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(SubscriptionOptions.this,
                    "Please wait.", "we are sending your message.",
                    true, false);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();

            confirmEvent();

        }

        @Override
        protected Void doInBackground(Message... messages) {
            try {
                Transport.send(messages[0]);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public void confirmEvent() {

        final AlertDialog alertDialog2 = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom)).create();
        alertDialog2.setTitle(getString(R.string.result));
        alertDialog2.setMessage(myResponse);
        alertDialog2.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.alertDiaThanks), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        alertDialog2.show();
        alertDialog2.getWindow().setBackgroundDrawableResource(R.drawable.gback_1);
    }


问:
I have a question about using vcpkg, I don't seem to get the nice install for boost as when I use .\bootstrap.bat and b2.exe
I am trying to build something for which I have made some packages with vcpkg.  I now realize that I have two installs of vcpkg and I've run the vcpkg integrate install in both of them and I've tried to add a json line and a CMakeLists.txt line that has the basics like this:

set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake"
CACHE STRING "Vcpkg toolchain file")

I'm trying to get the build CMake check which refreshes the CMakeCache.txt file to find everything such as Minizip, etc..  I just need to better pin down the exact sequences of editing of files and environment variables.  Just curious if a little hint would help.  I am beginning to understand the various steps but I don't like the idea of editing the CMakeCache.txt directly (I can do this in CMake GUI) as I feel that it's better to set a bunch of stuff somewhere else - either in the environment variables or just as CMake variables.  I'm very rusty on doing this stuff - haven't done it in like 7 years.  My compiling has all been smaller projects that were easy to compile and link a couple libraries and execs that's all.  Maybe a flowchart or something would help.  My projecct has a bunch of Find this find that.  For example FindMinizip.cmake but it doesn't find Minizip.  I even give it hints where zlib is.  I set some environment variables.  I strongly suspect that I just don't have a mastery yet of vcpkg.

I tried to build but the CMake stalls early in the process due to not finding stuff and I'm also using the wrong set of boost because I don't have a nice boost directory - vcpkg doesn't install correctly as per just doing boost as an external library as before using vcpkg.

I haven't done much yet to troubleshoot the problem.

I think maybe I should build the whole thing without using vcpkg first, so I can better understand the program - I've been away from it for like 7 years.  I might need some -dev setups in there and once I see what the program needs - particularly those lack of boost headers bother me.  Boost is an easy system to use and it's install works so nicely that I have several boosts on my machine, each installed nicely.

The minizip didn't used to be a problem, it was just needing a zlib directory.  Maybe I should just take a step back first.


问:
How do I cancel a create or edit via a button on the form?
I am writing a prototype in Laravel 9. x that, at least so far, is primarily CRUDs for each of several tables. For each table, I have the standard methods in that table's controller: index, show, create, store, edit, update and destroy. All of those work, but I'd like to add Cancel options to the forms used for creating and editing a row in the table.

I'm struggling with how to make a Cancel option work. I was trying to do it by having the Cancel button in the Create form invoke a new method in Controller called cancelCreate; all it would do was redirect to the index view and create a session message indicating that the create had been canceled. Much to my surprise, I found that even when I pressed the Cancel button, the controller's regular create() method would be executed. The create() method insisted that all validations be successful, stored the new record, reported the successful creation, and then displayed the new record in the index view. This was the exact opposite of what a Cancel button should do.

So how do I write my code so that the Cancel button lets the user exit the Create screen regardless of what he has put in the form (or omitted from the form) and return to the Index view WITHOUT having made any change to the table? The course I took on writing CRUDs didn't include Cancel functionality. I can't find any videos about Laravel discussing Cancel functionality, and a search here at StackOverflow didn't bring up anything relevant.

Here is my Create blade so that you can see what I attempted:

```<code><x-layout>
    <x-card xclass="p-10 max-w-lg mx-auto mt-24">
    <h1 class="text-3xl text-center text-white font-bold bg-indigo-700">Create a New Non-driving Reason</h1>
    <h1 class="pb-5"></h1><!-- spacer beneath title -->

    <form method="POST" action="/nonDrivingReasons/store" enctype="multipart/form-data">
    @csrf
        <div class="mb-6">
            <label for="reason_for_not_driving" class="inline-block text-lg mb-2">Reason for not driving</label>
            <input type="text" class="border border-gray-200 rounded p-2 w-full" name="reason_for_not_driving" value="{{old('reason_for_not_driving')}}"/>
            @error('reason_for_not_driving')
                <p class="text-red-500 text-xs mt-1">{{$message}}</p>
            @enderror
        </div>
        <div class="mb-6">
            {{-- Submit the completed form --}}
            <button class="text-xl text-white bg-green-500 rounded-md py-2 px-4 hover:bg-black">Submit</button>
            {{-- Cancel submission of the form --}}
            <form method="POST" action="/nonDrivingReasons/cancelCreate/">
                <button class="text-xl text-black bg-white rounded-md py-2 px-4 hover:bg-grey-500">Cancel</button>
            </form>
            </button>
        </div>
    </form>
    </x-card>
    </x-layout>
</code>```

And here are the create() and cancelCreate() methods from my Controller:

```<code> //Show create the form
    public function create() {
        return view('nonDrivingReasons.create');
    }

    //Cancel creation of a new non-driving reason
    public function cancelCreate() {
        return redirect('/nonDrivingReasons/index')->with('message', 'Creation of non-driving reason cancelled');
    }
</code>```

The table in question is as simple as it gets with just a single column.

I'd be grateful for guidance on building Cancel functionality into my prototype.

Body:
I am writing a prototype in Laravel 9. x that, at least so far, is primarily CRUDs for each of several tables. For each table, I have the standard methods in that table's controller: index, show, create, store, edit, update and destroy. All of those work, but I'd like to add Cancel options to the forms used for creating and editing a row in the table.

I'm struggling with how to make a Cancel option work. I was trying to do it by having the Cancel button in the Create form invoke a new method in Controller called cancelCreate; all it would do was redirect to the index view and create a session message indicating that the create had been canceled. Much to my surprise, I found that even when I pressed the Cancel button, the controller's regular create() method would be executed. The create() method insisted that all validations be successful, stored the new record, reported the successful creation, and then displayed the new record in the index view. This was the exact opposite of what a Cancel button should do.

So how do I write my code so that the Cancel button lets the user exit the Create screen regardless of what he has put in the form (or omitted from the form) and return to the Index view WITHOUT having made any change to the table? The course I took on writing CRUDs didn't include Cancel functionality. I can't find any videos about Laravel discussing Cancel functionality, and a search here at StackOverflow didn't bring up anything relevant.

Here is my Create blade so that you can see what I attempted:

<x-layout>
    <x-card xclass="p-10 max-w-lg mx-auto mt-24">

Create a New Non-driving Reason

    <form method="POST" action="/nonDrivingReasons/store" enctype="multipart/form-data">
    @csrf

            Reason for not driving
            <input type="text" class="border border-gray-200 rounded p-2 w-full" name="reason_for_not_driving" value="{{old('reason_for_not_driving')}}"/>
            @error('reason_for_not_driving')

{{$message}}

            @enderror

            {{-- Submit the completed form --}}
            <button class="text-xl text-white bg-green-500 rounded-md py-2 px-4 hover:bg-black">Submit</button>
            {{-- Cancel submission of the form --}}
            <form method="POST" action="/nonDrivingReasons/cancelCreate/">
                <button class="text-xl text-black bg-white rounded-md py-2 px-4 hover:bg-grey-500">Cancel</button>
            </form>
            </button>

    </form>
    </x-card>
    </x-layout>

And here are the create() and cancelCreate() methods from my Controller:

 //Show create the form
    public function create() {
        return view('nonDrivingReasons.create');
    }

    //Cancel creation of a new non-driving reason
    public function cancelCreate() {
        return redirect('/nonDrivingReasons/index')->with('message', 'Creation of non-driving reason cancelled');
    }

The table in question is as simple as it gets with just a single column.

I'd be grateful for guidance on building Cancel functionality into my prototype.


问:
How to force value of First & Last Name Fields on Contact Form 7 in Wordpress to be Sentence Case before submitting?
I am trying to find a way to force the capitalization of the First & Last Name fields in my forms when a user submits. I don’t care if the user sees the change or not, I am more interested in the submission that gets processed being changed before the data from the form gets posted. Forcing the input to be Sentence case or validating/changing automatically before submitting would work.

So if:

joHn, jOHN, or john are entered they would all be changed to John (first letter capitalized, others lowercase).

Here are my fields for reference:

```<code><label> First name
    [text* FirstName] </label>
<label> Last name
    [text* LastName] </label>
</code>```

Thanks in advance for any direction.

I've found similar documentation on general fields, and changing the email field content after submitting, but can't seem to find how to change it before submitting so that the data that posts does so using the properly formatted values.

Tried various examples of code snippets to be run, but they only seem to affect the mailer data, not the submitted data.

Body:
I am trying to find a way to force the capitalization of the First & Last Name fields in my forms when a user submits. I don’t care if the user sees the change or not, I am more interested in the submission that gets processed being changed before the data from the form gets posted. Forcing the input to be Sentence case or validating/changing automatically before submitting would work.

So if:

joHn, jOHN, or john are entered they would all be changed to John (first letter capitalized, others lowercase).

Here are my fields for reference:

 First name
    [text* FirstName]
 Last name
    [text* LastName]

Thanks in advance for any direction.

I've found similar documentation on general fields, and changing the email field content after submitting, but can't seem to find how to change it before submitting so that the data that posts does so using the properly formatted values.

Tried various examples of code snippets to be run, but they only seem to affect the mailer data, not the submitted data.


问:
radio button made by handlebars.js when checked by an Eventlistener using javaScript doesn't take effect on the script
i have a plugin installed on my wordpress Called MapSVG, in the plugin it have radio button Filters, i added custom buttons using the builder and i am trying to add an EVENT Listener for each button ID to it's corresponding Radio, the script works fine and when i click on the button it refelects to the coresponding radio, but the problem is the radio in the frontend checked, but doesn't take effect in the plugin, however when i try to check the  radio by myself it takes effect.
Radios with buttons

these radios is written in handlebars.js

```<code><div class="col-sm-9">
            {{#if placeholder}}
                <div class="radio">
                    <input class="form-check-input" type="radio" name="{{parameterNameShort}}" value="" {{#ifeq value ../value}}checked{{/ifeq}} data-parameter-name="{{parameterNameShort}}">
                    <label class="form-check-label">

                        {{placeholder}}
                    </label>
                </div>
            {{/if}}
    {{#each options}}
                <div class="radio">
                    <input class="form-check-input" type="radio" name="{{../parameterNameShort}}" value="{{value}}" {{#ifeq value ../value}}checked{{/ifeq}} data-parameter-name="{{../parameterNameShort}}">

                    <label class="form-check-label">
                         {{label}}
                    </label>
                </div>
</code>```

i tried to add an action in the footer to run a JavaScript function to change the value of the radio button to checked and it works fine but the plugin filter doesn't take effect, i don't know what might be the problem?

here is the function i used

```<code>function radios_to_button(){
    ?>
<script>
    const element = document.getElementById("button-1");
    const radios = document.getElementsByClassName("form-check-input");
    element.addEventListener("click", myFunction);

function myFunction() {

    radios[3].checked = true;

}
    </script>
<?php
}
add_action ('wp_footer', 'radios_to_button');
</code>```

i expected that when the radio checked by the JavaScript Funcion it takes effect on the plugin filters

Body:
i have a plugin installed on my wordpress Called MapSVG, in the plugin it have radio button Filters, i added custom buttons using the builder and i am trying to add an EVENT Listener for each button ID to it's corresponding Radio, the script works fine and when i click on the button it refelects to the coresponding radio, but the problem is the radio in the frontend checked, but doesn't take effect in the plugin, however when i try to check the  radio by myself it takes effect.
Radios with buttons

these radios is written in handlebars.js

            {{#if placeholder}}

                    <input class="form-check-input" type="radio" name="{{parameterNameShort}}" value="" {{#ifeq value ../value}}checked{{/ifeq}} data-parameter-name="{{parameterNameShort}}">

                        {{placeholder}}

            {{/if}}
    {{#each options}}

                    <input class="form-check-input" type="radio" name="{{../parameterNameShort}}" value="{{value}}" {{#ifeq value ../value}}checked{{/ifeq}} data-parameter-name="{{../parameterNameShort}}">

                         {{label}}

i tried to add an action in the footer to run a JavaScript function to change the value of the radio button to checked and it works fine but the plugin filter doesn't take effect, i don't know what might be the problem?

here is the function i used

function radios_to_button(){
    ?>

<?php
}
add_action ('wp_footer', 'radios_to_button');

i expected that when the radio checked by the JavaScript Funcion it takes effect on the plugin filters


问:
Cant get Alpha Vantage to work Python? No module named 'alpha_vantage'
ModuleNotFoundError: No module named 'alpha_vantage'

line 22, in
from alpha_vantage.fundamentaldata import FundamentalData

I have Alpha Vantage installed using pip install alpha-vantage that didnt fix the problem so then I tried pip install alpha_vantage and that didnt fix it either.

I am a python noob, just following a tutorial online for python finance to learn.


问:
How do you get the name of a google account in Python using their email?
In Gmail it allows you to see who you are sending it to because it correlates email address and name. I have been doing research and haven't found any methods of just getting the first and last name of the account as the Gmail client does using the email address. Does anyone know a way? It must work on Python 3.10</p>


问:
arrowChecker slows image loading
I incorporated the arrowChecker script for navigating between a series of webpages. Each page include an image. It works well except that I found that with arrowChecker included, the image loads very much more slowly. Presumably the browser is busy checking for keypresses instead of getting on with loading the image.

Any suggestions?

I was expecting the page to behave much the same with and without arrow checker. It didn't - image loading was much slower.

Title: arrowChecker slows image loading


问:
Global Payments eComm API - Not retrieving ALL TransactionDetail
Someone asked about how to retrieve transaction detail from Global Payments last year and I know how to do this, but when I make the call to retrieve the transaction detail, I'm not getting ALL the details.

I ran into a situation where several customers paid, and my service was inaccessible due to a URL change. Using the ReportingService.TransactionDetail() method seemed the way to go but it only retrieves some of the data. Some critical information is missing from the response:  Amount, TransactionDate, Customer Info...just to name a few.

Why doesn't the ReportingService.TransactionDetail respond with all of the transaction detail?


问:
How to add html tag in template String in React
```<code>    const warning = <strong>t('Warning')</strong>
    const helperMessage = `${warning} ${t(
    'phrases:updating your name can impact your production environment.'
  )}`
</code>```

I want the text Warning as bold and rest of the text as normal.
t() is a function for translation

Body:
    const warning = t('Warning')
    const helperMessage = `${warning} ${t(
    'phrases:updating your name can impact your production environment.'
  )}`

I want the text Warning as bold and rest of the text as normal.
t() is a function for translation


问:
RabbitMQ consumer prefetch ignored
In our application, the consumer prefetch is set to 100000. From Is there any way to set rabbitmq prefetch count to 100000 using spring amqp library? I understand that the value will be set to 34464 due to the int to short conversion. I see this from the rmq web console too.

Now, my application has been going out of memory when the load is high. On examination of the heap dump, I see a massive number (much larger than 34464) of com.rabbitmq.client.QueueingConsumer$Delivery objects held in the bufferQueue (see code snippet).

We are using RabbitMQ server v3.7.8, Erlang v21.1 and RabbitMQ Java Client v4.0.0. There is a plan to upgrade the versions, but not in the next 3-4 months. As a part of the upgrade, we will get rid of QueueingConsumer (deprecated). So, we would like to continue with QueueingConsumer for the time being and still fix this memory issue.

This is the code snippet for declaring the consumer:

```<code>String queueName = "my_queue";
boolean autoAck = false;
String consumerTag = "";
boolean noLocal = true;
boolean exclusiveConsumer = true;
Map<String, Object> arguments = null;

BlockingQueue<Delivery> bufferQueue = new LinkedBlockingQueue<>();
QueueingConsumer consumer = new QueueingConsumer(channel, bufferQueue);
channel.basicQos(100000, false);
channel.basicConsume(queueName, autoAck, consumerTag, noLocal, exclusiveConsumer, arguments, consumer);
</code>```

There is only one consumer.

Now, my question is that why is RabbitMQ not abiding by the 34464 prefetch count that is shown in the web console?

Also, when I look at the AutorecoveringChannel object in the heap dump, the consumer prefetch count shows as 0 irrespective of what the prefetch count is set to be (I tried setting it to something like 1000). Why is this happening?

Title: RabbitMQ consumer prefetch ignored

Body:
In our application, the consumer prefetch is set to 100000. From Is there any way to set rabbitmq prefetch count to 100000 using spring amqp library? I understand that the value will be set to 34464 due to the int to short conversion. I see this from the rmq web console too.

Now, my application has been going out of memory when the load is high. On examination of the heap dump, I see a massive number (much larger than 34464) of com.rabbitmq.client.QueueingConsumer$Delivery objects held in the bufferQueue (see code snippet).

We are using RabbitMQ server v3.7.8, Erlang v21.1 and RabbitMQ Java Client v4.0.0. There is a plan to upgrade the versions, but not in the next 3-4 months. As a part of the upgrade, we will get rid of QueueingConsumer (deprecated). So, we would like to continue with QueueingConsumer for the time being and still fix this memory issue.

This is the code snippet for declaring the consumer:

String queueName = "my_queue";
boolean autoAck = false;
String consumerTag = "";
boolean noLocal = true;
boolean exclusiveConsumer = true;
Map<String, Object> arguments = null;

BlockingQueue<Delivery> bufferQueue = new LinkedBlockingQueue<>();
QueueingConsumer consumer = new QueueingConsumer(channel, bufferQueue);
channel.basicQos(100000, false);
channel.basicConsume(queueName, autoAck, consumerTag, noLocal, exclusiveConsumer, arguments, consumer);

There is only one consumer.

Now, my question is that why is RabbitMQ not abiding by the 34464 prefetch count that is shown in the web console?

Also, when I look at the AutorecoveringChannel object in the heap dump, the consumer prefetch count shows as 0 irrespective of what the prefetch count is set to be (I tried setting it to something like 1000). Why is this happening?


问:
How to increase performance Azure function app http trigger
I'm using @azure/cosmos v3.17.2 for node in an Azure function app to query Cosmos DB (for NoSQL) and return all items in a container. There are only ~200 items in the container currently, but the network tab of developer tools shows that the API call is taking 5.74s to complete, which seems ridiculous. You can see in the following image that 4.95s is waiting for response from server.

Here is my function code to query the database:

```<code>const CosmosClient = require('@azure/cosmos').CosmosClient;
const config = require('../config/config');
const { endpoint, key, databaseId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);

module.exports = async function (context, req) {
    const containerId = req.query.containerId;
    const container = database.container(containerId);

    const querySpec = {
        query: 'SELECT * from c'
    }

    const { resources: items } = await container.items
        .query(querySpec)
        .fetchAll()

    context.res = {
        body: items
    }
}
</code>```

Is there a way to speed this up? The partition key is currently id, would changing this make it faster? Another thought is that the response times could possibly be from cold starts, but how can I prevent that in a function app that's already established? I know that a dedicated app service plan helps minimize cold starts, but it doesn't seem possible to change consumption to dedicated after it's already been created. Also of note, I already have WEBSITE_RUN_FROM_PACKAGE set to 0 in configurations and I have removed all unnecessary npm packages

Any help would be appreciated!

Body:
I'm using @azure/cosmos v3.17.2 for node in an Azure function app to query Cosmos DB (for NoSQL) and return all items in a container. There are only ~200 items in the container currently, but the network tab of developer tools shows that the API call is taking 5.74s to complete, which seems ridiculous. You can see in the following image that 4.95s is waiting for response from server.

Here is my function code to query the database:

const CosmosClient = require('@azure/cosmos').CosmosClient;
const config = require('../config/config');
const { endpoint, key, databaseId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);

module.exports = async function (context, req) {
    const containerId = req.query.containerId;
    const container = database.container(containerId);

    const querySpec = {
        query: 'SELECT * from c'
    }

    const { resources: items } = await container.items
        .query(querySpec)
        .fetchAll()

    context.res = {
        body: items
    }
}

Is there a way to speed this up? The partition key is currently id, would changing this make it faster? Another thought is that the response times could possibly be from cold starts, but how can I prevent that in a function app that's already established? I know that a dedicated app service plan helps minimize cold starts, but it doesn't seem possible to change consumption to dedicated after it's already been created. Also of note, I already have WEBSITE_RUN_FROM_PACKAGE set to 0 in configurations and I have removed all unnecessary npm packages

Any help would be appreciated!


问:
Write a DataFrame to multiple paths
I would like to write a DataFrame to 4 differents paths /A, /B, /C, /D on AWS S3.

def heavy_computation(df1: DataFrame, df2: DataFrame) -> DataFrame:
    ...

res: DataFrame = heavy_computation(df1, df2)

res.write.parquet("s3://bucket/path/to/A")
res.write.parquet("s3://bucket/path/to/B")
res.write.parquet("s3://bucket/path/to/C")
res.write.parquet("s3://bucket/path/to/D")
```
<p>Because in practice, <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code> are unrelated and don't necessarily represent partitions of my data, my snippets runs in about 4 times the duration necessary to write only a single path. To optimize the code, I was thinking of writing only once to <code>/A</code> and then running this Bash Script.</p>
<pre class="lang-bash prettyprint-override"><code>aws s3 sync --recursive s3://bucket/path/to/A s3://bucket/path/to/B
aws s3 sync --recursive s3://bucket/path/to/A s3://bucket/path/to/C
aws s3 sync --recursive s3://bucket/path/to/A s3://bucket/path/to/D
</code>```

Is there a smarter way to do this with only Spark SQL functional API?

Title: Write a DataFrame to multiple paths

Body:
I would like to write a DataFrame to 4 differents paths /A, /B, /C, /D on AWS S3.

def heavy_computation(df1: DataFrame, df2: DataFrame) -> DataFrame:
    ...

res: DataFrame = heavy_computation(df1, df2)

res.write.parquet("s3://bucket/path/to/A")
res.write.parquet("s3://bucket/path/to/B")
res.write.parquet("s3://bucket/path/to/C")
res.write.parquet("s3://bucket/path/to/D")

Because in practice, A, B, C and D are unrelated and don't necessarily represent partitions of my data, my snippets runs in about 4 times the duration necessary to write only a single path. To optimize the code, I was thinking of writing only once to /A and then running this Bash Script.

aws s3 sync --recursive s3://bucket/path/to/A s3://bucket/path/to/B
aws s3 sync --recursive s3://bucket/path/to/A s3://bucket/path/to/C
aws s3 sync --recursive s3://bucket/path/to/A s3://bucket/path/to/D

Is there a smarter way to do this with only Spark SQL functional API?


问:
why dart doesn't execute the code in order?
My Flutter app is executing the code inside the .then() function after everything is finished. I thought that this function was used to wait for the code to be executed. Am I understanding something wrong about dart?

This is my code:

```<code>static Future<List<Quiz>> getUserQuizzes(
      {FirebaseFirestore? firestore}) async {
    if (firestore == null) {
      firestore = FirebaseFirestore.instance;
    }

    List<Quiz> quizzes = [];

    /// Get the the id's of all quizzes whose creatorID is the current user's id
    await firestore
        .collection('quizzes')
        .where('creatorID', isEqualTo: getCurrentUserID())
        .get()
        .then((QuerySnapshot querySnapshot) {
      print('print 1: ${querySnapshot.docs.length}');

      querySnapshot.docs.forEach((doc) async {
        print('print inside forEach');
        Quiz? tempQuiz;

        await Quiz().retrieveQuizFromId(id: doc.id).then((value) {
          tempQuiz = value;
          quizzes.add(tempQuiz!);
          print('print inside then: ${quizzes.length}');
        });
      });
    });

    print('print 2: ${quizzes.length}');
    return quizzes;
  }
}
</code>```

And this is the console output:

```<code>Performing hot reload...
Syncing files to device iPhone 14 Pro Max...
Reloaded 1 of 1330 libraries in 385ms (compile: 61 ms, reload: 147 ms, reassemble: 128 ms).
flutter: print 1: 5
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print 2: 0
flutter: print inside then: 1
flutter: print inside then: 2
flutter: print inside then: 3
flutter: print inside then: 4
flutter: print inside then: 5
</code>```

Body:
My Flutter app is executing the code inside the .then() function after everything is finished. I thought that this function was used to wait for the code to be executed. Am I understanding something wrong about dart?

This is my code:

static Future<List<Quiz>> getUserQuizzes(
      {FirebaseFirestore? firestore}) async {
    if (firestore == null) {
      firestore = FirebaseFirestore.instance;
    }

    List<Quiz> quizzes = [];

    /// Get the the id's of all quizzes whose creatorID is the current user's id
    await firestore
        .collection('quizzes')
        .where('creatorID', isEqualTo: getCurrentUserID())
        .get()
        .then((QuerySnapshot querySnapshot) {
      print('print 1: ${querySnapshot.docs.length}');

      querySnapshot.docs.forEach((doc) async {
        print('print inside forEach');
        Quiz? tempQuiz;

        await Quiz().retrieveQuizFromId(id: doc.id).then((value) {
          tempQuiz = value;
          quizzes.add(tempQuiz!);
          print('print inside then: ${quizzes.length}');
        });
      });
    });

    print('print 2: ${quizzes.length}');
    return quizzes;
  }
}

And this is the console output:

Performing hot reload...
Syncing files to device iPhone 14 Pro Max...
Reloaded 1 of 1330 libraries in 385ms (compile: 61 ms, reload: 147 ms, reassemble: 128 ms).
flutter: print 1: 5
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print 2: 0
flutter: print inside then: 1
flutter: print inside then: 2
flutter: print inside then: 3
flutter: print inside then: 4
flutter: print inside then: 5


问:
Angular ng-zorror examples with conditional and paging queries
Are there Angular ng-zorror examples of conditional and paging queries？Please give me one.Thanks.</p>


问:
How to force hide keyboard without affecting ColorPicker?
I have a SwiftUI view composed of a TextEditor and a ColorPicker. I want the user to be able to tap outside of the TextEditor to close the keyboard.

It makes the most sense to use this onTapGesture modifier, on the background of the main content view that holds the TextEditor and ColorPicker.

```<code>.onTapGesture {
     print("Hiding popups")
     UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
</code>```

While this code performs the intended function of hiding the keyboard when tapping outside of the TextEditor, after the keyboard hides, tapping the ColorPicker to open the default iOS Color Picker view does nothing. The ColorPicker selector view acts like it is disabled and therefore I cannot open it.

Is there a way to force hide the keyboard, without affecting the ColorPicker? I would like an answer in SwiftUI if possible.

Body:
I have a SwiftUI view composed of a TextEditor and a ColorPicker. I want the user to be able to tap outside of the TextEditor to close the keyboard.

It makes the most sense to use this onTapGesture modifier, on the background of the main content view that holds the TextEditor and ColorPicker.

.onTapGesture {
     print("Hiding popups")
     UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}

While this code performs the intended function of hiding the keyboard when tapping outside of the TextEditor, after the keyboard hides, tapping the ColorPicker to open the default iOS Color Picker view does nothing. The ColorPicker selector view acts like it is disabled and therefore I cannot open it.

Is there a way to force hide the keyboard, without affecting the ColorPicker? I would like an answer in SwiftUI if possible.


问:
Reshaping a Pandas Dataframe to set values from rows to columns
My question is about rearranging the df1 dataframe to match df2. I was thinking in filtering by Num followed by pd.concat(). My question is whether there is a more clever way to do it. Thanks in advance!

```<code>df1 = pd.DataFrame({"Month": ["2022-07-01","2022-08-01","2022-09-01","2022-10-01"]*3,
                    "Num": [10,10,10,10,20,20,20,20,30,30,30,30],
                    "MB": range(12)}
                   )
df1["Month"] = pd.to_datetime(df1['Month'])
</code>```

enter image description here

```<code>df2 = pd.DataFrame({"Month": ["2022-06-01"]*3,
                    "Num": [10, 20, 30],
                    "MB1": [0,4,8],
                    "MB2": [1,5,9],
                    "MB3": [2,6,10],
                    "MB4": [3,7,11],
                   }
                  )

df2["Month"] = pd.to_datetime(df2['Month'])
</code>```

enter image description here

Try to filtering by Num and then made a contatenation over all values.

Body:
My question is about rearranging the df1 dataframe to match df2. I was thinking in filtering by Num followed by pd.concat(). My question is whether there is a more clever way to do it. Thanks in advance!

df1 = pd.DataFrame({"Month": ["2022-07-01","2022-08-01","2022-09-01","2022-10-01"]*3,
                    "Num": [10,10,10,10,20,20,20,20,30,30,30,30],
                    "MB": range(12)}
                   )
df1["Month"] = pd.to_datetime(df1['Month'])

enter image description here

df2 = pd.DataFrame({"Month": ["2022-06-01"]*3,
                    "Num": [10, 20, 30],
                    "MB1": [0,4,8],
                    "MB2": [1,5,9],
                    "MB3": [2,6,10],
                    "MB4": [3,7,11],
                   }
                  )

df2["Month"] = pd.to_datetime(df2['Month'])

enter image description here

Try to filtering by Num and then made a contatenation over all values.


问:
VSCode stuck on formatting c++ in remote server
I am trying to use VSCode on a windows machine, and connected to a linux server via ssh. The c++ formatter won't work for the remote no matter what I do. I tried:

Updating VSCode to latest stable version

Uninstalling and reinstalling C++ extension

Deleting the .vscode and .vscode-server folder on server (under my home directory)

But the extension worked when I tried to connect to the server using my MacBook.

In the output panel, there's no options for C++ plugin, and I don't know how to check the output of the formatter.


问:
Python Docx -Extracting Table data from multiple word doc and save the result in a single excel file
I have a 100+ word files that have a table data that I need to extract and save them into a csv/excel as a separate sheet for each word.docx.

Below code works for a single file, but fails when I loop though a folder and also generates multiple files. How can I wrote them into a single file with multiple sheets. Also, df doesn't show me tabular data not sure what's the deal here?

```<code>from docx import Document
import pandas as pd
document = Document('C:/Users/trans/downloads/Example.docx')

tables = []
for table in document.tables:
    df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))
    print(df)
    for nr, i in enumerate(tables):
        i.to_csv('C:/Users/trans/downloads/'"table_" + str(nr) + ".csv")
</code>```

below is failing

```<code>import os
from docx import Document
import pandas as pd
folder = 'C:/Users/trans/downloads/test'
file_names = [f for f in os.listdir(folder) if f.endswith(".docx") ]
file_names = [os.path.join(folder, file) for file in file_names]
print(file_names)
tables = []
for file in file_names:
    document = Document(file)
    for table in document.tables:
     df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
     for i, row in enumerate(table.rows):
         for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))
    print(df)
    for nr, i in enumerate(tables):
        i.to_csv('C:/Users/trans/downloads/test/'"table_" + str(nr) + ".csv")
</code>```

Body:
I have a 100+ word files that have a table data that I need to extract and save them into a csv/excel as a separate sheet for each word.docx.

Below code works for a single file, but fails when I loop though a folder and also generates multiple files. How can I wrote them into a single file with multiple sheets. Also, df doesn't show me tabular data not sure what's the deal here?

from docx import Document
import pandas as pd
document = Document('C:/Users/trans/downloads/Example.docx')

tables = []
for table in document.tables:
    df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))
    print(df)
    for nr, i in enumerate(tables):
        i.to_csv('C:/Users/trans/downloads/'"table_" + str(nr) + ".csv")

below is failing

import os
from docx import Document
import pandas as pd
folder = 'C:/Users/trans/downloads/test'
file_names = [f for f in os.listdir(folder) if f.endswith(".docx") ]
file_names = [os.path.join(folder, file) for file in file_names]
print(file_names)
tables = []
for file in file_names:
    document = Document(file)
    for table in document.tables:
     df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
     for i, row in enumerate(table.rows):
         for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))
    print(df)
    for nr, i in enumerate(tables):
        i.to_csv('C:/Users/trans/downloads/test/'"table_" + str(nr) + ".csv")


问:
Spyder ModuleNotFoundError:
I am trying to run python code that uses modules that does not come with the Spyder installer.  When I follow the instructions here: installing Python packages to use with Spyder

I get the errror "ModuleNotFoundError: sqlalchemy"

I have also tried updating the PYTHON PATH as described here: Spyder Module Trick
I have resarted Spyder as well.

But I am still getting the same error.
Any help would be appreciated. Thanks

Title: Spyder ModuleNotFoundError:


问:
Call my Anki add-on's Python function from JavaScript
How can I let my add-on's JavaScript (loaded in the reviewer's webview) communicate request values from my add-on's Python parts?

pycmd doesn't seem able to do this, because as far as I can see there is no way for the receiving python to return a value to the calling JS:

```<code>name="webview_did_receive_js_message",
args=["handled: tuple[bool, Any]", "message: str", "context: Any"],
return_type="tuple[bool, Any]",
doc="""Used to handle pycmd() messages sent from Javascript.

Message is the string passed to pycmd().
For messages you don't want to handle, return 'handled' unchanged.

If you handle a message and don't want it passed to the original
bridge command handler, return (True, None).

If you want to pass a value to pycmd's result callback, you can
return it with (True, some_value).

Context is the instance that was passed to set_bridge_command().
It can be inspected to check which screen this hook is firing
in, and to get a reference to the screen. For example, if your
code wishes to function only in the review screen, you could do:
    if not isinstance(context, aqt.reviewer.Reviewer):
        # not reviewer, pass on message
        return handled

    if message == "my-mark-action":
        # our message, call onMark() on the reviewer instance
        context.onMark()
        # and don't pass message to other handlers
        return (True, None)
    else:
        # some other command, pass it on
        return handled
""",
</code>```

Anki's gui_hooks

So code like my first idea

from typing import Any

from aqt import gui_hooks

def handle_calls(handled: tuple[bool, Any], message: str, context: Any) -> tuple[bool, Any]:
    if not message.startswith('myaddon:'):
        return handled
    # handle my custom message ...
    return (True, None) # but how to give the JavaScript information??

gui_hooks.webview_did_receive_js_message(handle_calls)

```
<p>seems like a dead-end.</p>
<p>I surprisingly get an error from that code too:</p>
<pre class="lang-none prettyprint-override"><code>    gui_hooks.webview_did_receive_js_message(handle_calls)
TypeError: __call__() missing 2 required positional arguments: 'message' and 'context'
</code>```

Body:
How can I let my add-on's JavaScript (loaded in the reviewer's webview) communicate request values from my add-on's Python parts?

pycmd doesn't seem able to do this, because as far as I can see there is no way for the receiving python to return a value to the calling JS:

name="webview_did_receive_js_message",
args=["handled: tuple[bool, Any]", "message: str", "context: Any"],
return_type="tuple[bool, Any]",
doc="""Used to handle pycmd() messages sent from Javascript.

Message is the string passed to pycmd().
For messages you don't want to handle, return 'handled' unchanged.

If you handle a message and don't want it passed to the original
bridge command handler, return (True, None).

If you want to pass a value to pycmd's result callback, you can
return it with (True, some_value).

Context is the instance that was passed to set_bridge_command().
It can be inspected to check which screen this hook is firing
in, and to get a reference to the screen. For example, if your
code wishes to function only in the review screen, you could do:
    if not isinstance(context, aqt.reviewer.Reviewer):
        # not reviewer, pass on message
        return handled

    if message == "my-mark-action":
        # our message, call onMark() on the reviewer instance
        context.onMark()
        # and don't pass message to other handlers
        return (True, None)
    else:
        # some other command, pass it on
        return handled
""",

Anki's gui_hooks

So code like my first idea

from typing import Any

from aqt import gui_hooks

def handle_calls(handled: tuple[bool, Any], message: str, context: Any) -> tuple[bool, Any]:
    if not message.startswith('myaddon:'):
        return handled
    # handle my custom message ...
    return (True, None) # but how to give the JavaScript information??

gui_hooks.webview_did_receive_js_message(handle_calls)

seems like a dead-end.

I surprisingly get an error from that code too:

    gui_hooks.webview_did_receive_js_message(handle_calls)
TypeError: __call__() missing 2 required positional arguments: 'message' and 'context'


问:
Script optimization : combinations chain set issubset counter
Do you have an idea to optimize my script ?

Python

```<code>from itertools import combinations, chain
from collections import Counter

R1=8
R2=[X for X in range (0, R1)]
P=4
S=5

if R1<=P*S and S<R1:

    Combi3=[X for X in combinations(chain(*(combinations(R2,Y) for Y in range(1,NbPiste+1))),NbSerie) if set(R2).issubset(chain(*X)) and max(Counter(chain(*X)).values())==1]
</code>```

R1, P, S may later be larger values,
so the Combi3 result will take days or weeks to arrive for now.
I was able to use Multiprocessing,
but I would like to improve the speed of this piece of script.
Thank you.

Body:
Do you have an idea to optimize my script ?

Python

from itertools import combinations, chain
from collections import Counter

R1=8
R2=[X for X in range (0, R1)]
P=4
S=5

if R1<=P*S and S<R1:

    Combi3=[X for X in combinations(chain(*(combinations(R2,Y) for Y in range(1,NbPiste+1))),NbSerie) if set(R2).issubset(chain(*X)) and max(Counter(chain(*X)).values())==1]

R1, P, S may later be larger values,
so the Combi3 result will take days or weeks to arrive for now.
I was able to use Multiprocessing,
but I would like to improve the speed of this piece of script.
Thank you.


问:
When attempting to add the .fill(.black) modifier to a Path shape, this error's given "cannot infer contextual base in reference to member 'black'"
```<code>import SwiftUI

Path { path in

}
.fill(.black)
</code>```

I couldn't find the same error online about the .fill() modifier - there are similar errors "cannot infer contextual base..." for other modifiers suggested importing a UIKit which didn't address the error.

Body:
import SwiftUI

Path { path in

}
.fill(.black)

I couldn't find the same error online about the .fill() modifier - there are similar errors "cannot infer contextual base..." for other modifiers suggested importing a UIKit which didn't address the error.


问:
Deploy a React & Node.js project to Railway
I am new to using railway, but I have a MERN full-stack app, and I am migrating it from Heroku to railway. I inserted my environment variables to railway from my .env file (such as my MONGODB_URI, API_KEYs, PORT, exc.)

the current project file structure is as follows:

```<code>client
 |
  -build
node_modules
server
 |
  -server.js
.env
.gitignore
package-lock.json
package.json
Procfile
README.md
</code>```

Here is a screenshot for better illustration:

In my Procfile it has the following script:

web: npm run start

Here is the list of scripts for my package.json (root level):

```<code> "scripts": {
    "start": "node server/server.js",
    "develop": "concurrently \"cd server && npm run watch\" \"cd client && npm start\"",
    "install": "cd server && npm i && cd ../client && npm i ",
    "seed": "cd server && cd config && node seeds.js",
    "build": "cd client && npm install && npm run build"
  }
</code>```

Here is what I tried:

I went to Settings in railway and added a custom build command as the one in my package.json:

I tried deploying without a Procfile as well.

I tried adding a custom script command to railway (the same as the one in my package.json)

I still get a build error showing the following:

```<code>#11 1.731 npm ERR! code EUSAGE

#11 1.735 npm ERR!
#11 1.735 npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
#11 1.735 npm ERR!
#11 1.735 npm ERR! Missing: react@18.2.0 from lock file
#11 1.735 npm ERR! Missing: loose-envify@1.4.0 from lock file
#11 1.735 npm ERR! Missing: js-tokens@4.0.0 from lock file
#11 1.735 npm ERR!
#11 1.735 npm ERR! Clean install a project
#11 1.735 npm ERR!
#11 1.735 npm ERR! Usage:
#11 1.735 npm ERR! npm ci
#11 1.735 npm ERR!
#11 1.735 npm ERR! Options:
#11 1.735 npm ERR! [-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle]
#11 1.735 npm ERR! [-E|--save-exact] [-g|--global] [--global-style] [--legacy-bundling]
#11 1.735 npm ERR! [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
#11 1.735 npm ERR! [--strict-peer-deps] [--no-package-lock] [--foreground-scripts]
#11 1.735 npm ERR! [--ignore-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run]
#11 1.735 npm ERR! [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
#11 1.735 npm ERR! [-ws|--workspaces] [--include-workspace-root] [--install-links]
#11 1.735 npm ERR!
#11 1.736 npm ERR! aliases: clean-install, ic, install-clean, isntall-clean
#11 1.736 npm ERR!
#11 1.736 npm ERR! Run "npm help ci" for more info
#11 1.737
#11 1.737 npm ERR! A complete log of this run can be found in:
#11 1.737 npm ERR!     /root/.npm/_logs/2023-01-12T00_02_06_608Z-debug-0.log

#11 ERROR: executor failed running [/bin/bash -ol pipefail -c npm ci]: exit code: 1
-----
> [stage-0  7/10] RUN --mount=type=cache,id=s/0a73518e-f9d9-405d-83da-4e03db5e343a-/root/npm,target=/root/.npm npm ci:
-----
executor failed running [/bin/bash -ol pipefail -c npm ci]: exit code: 1

Error: Docker build failed
</code>```

Body:
I am new to using railway, but I have a MERN full-stack app, and I am migrating it from Heroku to railway. I inserted my environment variables to railway from my .env file (such as my MONGODB_URI, API_KEYs, PORT, exc.)

the current project file structure is as follows:

client
 |
  -build
node_modules
server
 |
  -server.js
.env
.gitignore
package-lock.json
package.json
Procfile
README.md

Here is a screenshot for better illustration:

In my Procfile it has the following script:

web: npm run start

Here is the list of scripts for my package.json (root level):

 "scripts": {
    "start": "node server/server.js",
    "develop": "concurrently \"cd server && npm run watch\" \"cd client && npm start\"",
    "install": "cd server && npm i && cd ../client && npm i ",
    "seed": "cd server && cd config && node seeds.js",
    "build": "cd client && npm install && npm run build"
  }

Here is what I tried:

I went to Settings in railway and added a custom build command as the one in my package.json:

I tried deploying without a Procfile as well.

I tried adding a custom script command to railway (the same as the one in my package.json)

I still get a build error showing the following:

#11 1.731 npm ERR! code EUSAGE

#11 1.735 npm ERR!
#11 1.735 npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
#11 1.735 npm ERR!
#11 1.735 npm ERR! Missing: react@18.2.0 from lock file
#11 1.735 npm ERR! Missing: loose-envify@1.4.0 from lock file
#11 1.735 npm ERR! Missing: js-tokens@4.0.0 from lock file
#11 1.735 npm ERR!
#11 1.735 npm ERR! Clean install a project
#11 1.735 npm ERR!
#11 1.735 npm ERR! Usage:
#11 1.735 npm ERR! npm ci
#11 1.735 npm ERR!
#11 1.735 npm ERR! Options:
#11 1.735 npm ERR! [-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle]
#11 1.735 npm ERR! [-E|--save-exact] [-g|--global] [--global-style] [--legacy-bundling]
#11 1.735 npm ERR! [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
#11 1.735 npm ERR! [--strict-peer-deps] [--no-package-lock] [--foreground-scripts]
#11 1.735 npm ERR! [--ignore-scripts] [--no-audit] [--no-bin-links] [--no-fund] [--dry-run]
#11 1.735 npm ERR! [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
#11 1.735 npm ERR! [-ws|--workspaces] [--include-workspace-root] [--install-links]
#11 1.735 npm ERR!
#11 1.736 npm ERR! aliases: clean-install, ic, install-clean, isntall-clean
#11 1.736 npm ERR!
#11 1.736 npm ERR! Run "npm help ci" for more info
#11 1.737
#11 1.737 npm ERR! A complete log of this run can be found in:
#11 1.737 npm ERR!     /root/.npm/_logs/2023-01-12T00_02_06_608Z-debug-0.log

#11 ERROR: executor failed running [/bin/bash -ol pipefail -c npm ci]: exit code: 1
-----
> [stage-0  7/10] RUN --mount=type=cache,id=s/0a73518e-f9d9-405d-83da-4e03db5e343a-/root/npm,target=/root/.npm npm ci:
-----
executor failed running [/bin/bash -ol pipefail -c npm ci]: exit code: 1

Error: Docker build failed


问:
Calculating the maximum numbers of people in a room, when given entry and exit times (both object type)
this has proven to be a challenging task for me so would really appreciate any help:

We have two columns in a data frame: start_time, end_time (both object type hh:mm:ss) which I converted into seconds (float64).

An example of our data (out of 20000 rows):

```<code>start_time=["00:01:14", "00:01:15", "00:01:30"]
end_time=["00:01:39", "00:02:25", "00:02:10"]
</code>```

I am running the following code, but I am not convinced it's correct:

```<code>def findMaxPassengers(arrl, exit, n):# define function
    arrl.sort() # Sort arrival and exit arrays
    exit.sort()
    passengers_in = 1
    max_passengers = 1
    time = arrl[0]
    i = 1
    j = 0

    while (i < n and j < n):
        if (arrl[i] <= exit[j]): # if the next event in sorted order is an arrival, then add 1
            passengers_in = passengers_in + 1
            # Update max_passengers if needed
            if(passengers_in > max_passengers):
                max_passengers = passengers_in
                time = arrl[i]
            i = i + 1
        else:
            passengers_in = passengers_in - 1
            j = j + 1
    print("Maximum Number of passengers =", max_passengers, "at time", time)

df = pd.read_excel("Venue_Capacity.xlsx")
arrl = list(df.loc[:,"start_time"]);
exit = list(df.loc[:,"end_time"]);
n = len(arrl);
findMaxPassengers(arrl, exit, n);
</code>```

Is the thinking/code structure behind it correct?

I am not sure if the way the code&time works, if it's adding 1 or subtracting one correctly. The code is running ok and is giving out:

Maximum Number of Passengers = 402 at time 12:12:09
```

but I am unable to check a dataset of 20000+ rows.

Body:
this has proven to be a challenging task for me so would really appreciate any help:

We have two columns in a data frame: start_time, end_time (both object type hh:mm:ss) which I converted into seconds (float64).

An example of our data (out of 20000 rows):

start_time=["00:01:14", "00:01:15", "00:01:30"]
end_time=["00:01:39", "00:02:25", "00:02:10"]

I am running the following code, but I am not convinced it's correct:

def findMaxPassengers(arrl, exit, n):# define function
    arrl.sort() # Sort arrival and exit arrays
    exit.sort()
    passengers_in = 1
    max_passengers = 1
    time = arrl[0]
    i = 1
    j = 0

    while (i < n and j < n):
        if (arrl[i] <= exit[j]): # if the next event in sorted order is an arrival, then add 1
            passengers_in = passengers_in + 1
            # Update max_passengers if needed
            if(passengers_in > max_passengers):
                max_passengers = passengers_in
                time = arrl[i]
            i = i + 1
        else:
            passengers_in = passengers_in - 1
            j = j + 1
    print("Maximum Number of passengers =", max_passengers, "at time", time)

df = pd.read_excel("Venue_Capacity.xlsx")
arrl = list(df.loc[:,"start_time"]);
exit = list(df.loc[:,"end_time"]);
n = len(arrl);
findMaxPassengers(arrl, exit, n);

Is the thinking/code structure behind it correct?

I am not sure if the way the code&time works, if it's adding 1 or subtracting one correctly. The code is running ok and is giving out:

Maximum Number of Passengers = 402 at time 12:12:09

but I am unable to check a dataset of 20000+ rows.


问:
Debugging Django request lifecycle
What's the first function Django executes after receiving a request?
I need to put a breakpoint just at the moment Django receives the request and observe the methods being called next, step by step.
For example, I call

localhost:8000/test

where do I insert the very first breakpoint to see how the middleware processes the request?

Title: Debugging Django request lifecycle


问:
google chart vertical text not showing in JQuery UI Dialog
I am using Google Chart API to display a graph. If I display the graph in a DIV on a page it works fine. However, when I display the exact same graph in a DIV in a Dialog Box created using JQuery UI, the vertical text does not display. Everything else is fine, just the vertical text is missing from the graph in the UI Dialog Box.

I have tried overriding with "vAxis:{textPosition:'out'}" which is the default with no luck.

ContentLicense: CC BY-SA 3.0