问:
Accept Dynamic value in request Body using spring boot

I want  my request body accept dynamic value not accept hard coded
value, I have two token field brandwiseBearerToken and thirdpartyPaymentToken if
my token comes from brandwiseBearerToken it show the result with header other
wise header will not be shown.
I tried below way but my code not working
for reference I post my code.

```<code>private JsonObject gateWayToken(String url  ) throws IOException, AuthenticationException{
            String brandwiseBearerToken = "";
            String token=;
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");

                String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(token);
                RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );

                Request request = null;
                if (request.equals(thirdPartyPaymentGatewayTokenJson)) {
                    new Request.Builder().url(url).post(body)
                    .addHeader("Content-Type", "application/json").addHeader("Bearer", brandwiseBearerToken)
                    .build();
                } else {
                    new Request.Builder().url(url).post(body)
                    .addHeader("Content-Type", "application/json").build();
                }
                Response response = client.newCall(request).execute();
                ResponseBody responseBody = response.body();
                return new Gson().fromJson(responseBody.string(), JsonObject.class);
        }
</code>```

I want to pass Dynamically brandwiseBearerToken and
thirdpartyPaymentGatewayToken inside my request body, How can I do it.
I want to make dynamic exact below point

```<code>String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(token);

RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
</code>```

Body:
I want  my request body accept dynamic value not accept hard coded
value, I have two token field brandwiseBearerToken and thirdpartyPaymentToken if
my token comes from brandwiseBearerToken it show the result with header other
wise header will not be shown.
I tried below way but my code not working
for reference I post my code.

private JsonObject gateWayToken(String url  ) throws IOException, AuthenticationException{
            String brandwiseBearerToken = "";
            String token=;
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");

                String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(token);
                RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );

                Request request = null;
                if (request.equals(thirdPartyPaymentGatewayTokenJson)) {
                    new Request.Builder().url(url).post(body)
                    .addHeader("Content-Type", "application/json").addHeader("Bearer", brandwiseBearerToken)
                    .build();
                } else {
                    new Request.Builder().url(url).post(body)
                    .addHeader("Content-Type", "application/json").build();
                }
                Response response = client.newCall(request).execute();
                ResponseBody responseBody = response.body();
                return new Gson().fromJson(responseBody.string(), JsonObject.class);
        }

I want to pass Dynamically brandwiseBearerToken and
thirdpartyPaymentGatewayToken inside my request body, How can I do it.
I want to make dynamic exact below point

String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(token);

RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );


来源: stackexchange

问:
How do I find out which AWS S3 object caused a spike in Data Transfer Out
My monthly bill from AWS went from a few dollars to over $120 last month. When I view the Cost Explorer I can tell that the spike occurred in S3 and the N. American region, but I can't get down to the bucket, let alone the specific object. Is there a way I can find this information?</p>

ContentLicense: CC BY-SA 4.0


问:
vfs_mount suddenly not working in sqlite for esp8266
I am trying to use Sqlite3 for ESP8266 lib, and it says that I should start with vfs_mount("/SD0", D8);, which i was doing until suddenly I couldn't open the DB anymore. I tried to figure out why, then realized that this function was returning NULL, meaning that the vfs wasn't being created.

I don't know why this happened, I haven't changed any of my code, but here is setup just in case:

void setup(void) {
  Serial.begin(115200);
  Wire.begin();
  RTC.begin();
  SPI.begin();
  nfc.begin();

  if (vfs_mount("/SD0", SS) == NULL)
    Serial.println("Unable to set vfs");

  if (RTC.lostPower())
    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));

  sqlite3_initialize();

  Serial.println("System initialized");
}
```

What is weird is that regular SD communication with SD.h works, so it is definitely not the wiring, but again, just in case, I am wiring:

D5 → SCK

D6 → MISO

D7 → MOSI

D8 → CS

I have also tried reinstalling the library and its dependency, Sqlite3 for ESP8266 and SdFat.

I really appreciate any help you can provide!

Please tell me if you need to see any more of my code.

Body:
I am trying to use Sqlite3 for ESP8266 lib, and it says that I should start with vfs_mount("/SD0", D8);, which i was doing until suddenly I couldn't open the DB anymore. I tried to figure out why, then realized that this function was returning NULL, meaning that the vfs wasn't being created.

I don't know why this happened, I haven't changed any of my code, but here is setup just in case:

void setup(void) {
  Serial.begin(115200);
  Wire.begin();
  RTC.begin();
  SPI.begin();
  nfc.begin();

  if (vfs_mount("/SD0", SS) == NULL)
    Serial.println("Unable to set vfs");

  if (RTC.lostPower())
    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));

  sqlite3_initialize();

  Serial.println("System initialized");
}

What is weird is that regular SD communication with SD.h works, so it is definitely not the wiring, but again, just in case, I am wiring:

D5 → SCK

D6 → MISO

D7 → MOSI

D8 → CS

I have also tried reinstalling the library and its dependency, Sqlite3 for ESP8266 and SdFat.

I really appreciate any help you can provide!

Please tell me if you need to see any more of my code.


问:
How can I derive an expression in Matlab?
I have an integral expression to solve. And I need to get the final expression in the image using Matlab.

clc;close all;clear all;

syms s phis r phir

A=1;m=1;n=1;L=100;alpha=1;

k=(2*pi)/(550*10^-9);

us=A*((-1j*sqrt(2*k*alpha)*s*exp(-1j*phis))^m)*exp(-k*alpha*s*s)*laguerreL(n,m,2*k*alpha*s*s);

C=((-1j*k*exp(1j*k*L))/(2*pi*L))*exp((1j*k*r*r)/(2*L));

f = @(s,phis,r,phir) C*s*us*exp(((1j*k)/(2*L))*(-2*r*s*cos(phir-phis)+(s^2)));

g1 = @(s,phis,r,phir) int(@(phis) f(s,phis,r,phir),0,2*pi)

g2 = @(s,phis,r,phir) int(@(s) g1(s,r,phir),0,Inf)
```


问:
Insert Stream to Google BigQuery get Error "The service is currently unavailable"
I'm using Google BigQuery integrated with Flink (Java) to stream the data. (region : Jakarta)

I've found intermitten issue during insert the data : The service is currently unavailable.

I assume Google should have uptime 99.9%, but I got this error every few days.

How to solve this? Is it becuase of the Google service in my region is not stable?

This is my sample code :

```<code>private Boolean insert(String tableName, JsonArray values) {
    TableId tableId = TableId.of(projectId, datasetId, tableName);
    Builder insertBuilder = InsertAllRequest.newBuilder(tableId);
    for (JsonElement value : values) {
        insertBuilder.addRow(new Gson().fromJson(value.getAsJsonObject(), HashMap.class));
    }
    InsertAllRequest request = insertBuilder.build();
    InsertAllResponse response = bigQuery.insertAll(request);

    return true;
}
</code>```

Thanks in advance

Body:
I'm using Google BigQuery integrated with Flink (Java) to stream the data. (region : Jakarta)

I've found intermitten issue during insert the data : The service is currently unavailable.

I assume Google should have uptime 99.9%, but I got this error every few days.

How to solve this? Is it becuase of the Google service in my region is not stable?

This is my sample code :

private Boolean insert(String tableName, JsonArray values) {
    TableId tableId = TableId.of(projectId, datasetId, tableName);
    Builder insertBuilder = InsertAllRequest.newBuilder(tableId);
    for (JsonElement value : values) {
        insertBuilder.addRow(new Gson().fromJson(value.getAsJsonObject(), HashMap.class));
    }
    InsertAllRequest request = insertBuilder.build();
    InsertAllResponse response = bigQuery.insertAll(request);

    return true;
}

Thanks in advance


问:
Html Modal opens fine in chrome but not in firefox
My html code works fine in chrome but not in firefox. Issue happens when you click "see more" [modal] to see the description. I narrowed down to modal css property being the issue. When i change the position from fixed to relative, firefox it works but it messes with other style components. Can you please help here.

https://testhtmlcode.w3spaces.com/saved-from-Tryit-2023-01-02.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Popoup in javascript</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />

PR1

                PR1 is a health related tracker..
                See more

MEGA DISCOUNT
expand_more

                    Lorem ipsum dolor sit amet. Qui repudiandae omnis eos illo numquam sit doloremque officiis ut sint modi sit nulla praesentium? Ut sunt natus non galisum dolor est omnis quae qui voluptatem atque? Ex excepturi natus aut tempore ipsum ea quia rerum non
                    dolores nihil sed exercitationem autem! Est voluptas sint vel enim dolores ea voluptatem suscipit est dolorem ipsum sed recusandae corrupti. Cum perspiciatis nihil aut velit dignissimos aut temporibus itaque est molestias voluptatum
                    qui sint voluptatem. Aut deleniti galisum ut quia quia quo voluptatem soluta et fugit dolores hic consectetur beatae. Ut cupiditate ipsum et doloribus optio et nisi omnis!

                    Lorem ipsum dolor sit amet. Qui repudiandae omnis eos illo numquam sit doloremque officiis ut sint modi sit nulla praesentium? Ut sunt natus non galisum dolor est omnis quae qui voluptatem atque? Ex excepturi natus aut tempore ipsum ea quia rerum non
                    dolores nihil sed exercitationem autem! Est voluptas sint vel enim dolores ea voluptatem suscipit est dolorem ipsum sed recusandae corrupti. Cum perspiciatis nihil aut velit dignissimos aut temporibus itaque est molestias voluptatum
                    qui sint voluptatem. Aut deleniti galisum ut quia quia quo voluptatem soluta et fugit dolores hic consectetur beatae. Ut cupiditate ipsum et doloribus optio et nisi omnis!

PR1

                PR1 is a health related tracker..
                See more

DISCOUNT 50%
expand_more

                  Lorem ipsum dolor sit amet. Qui repudiandae omnis eos illo numquam sit doloremque officiis ut sint modi sit nulla praesentium? Ut sunt natus non galisum dolor est omnis quae qui voluptatem atque? Ex excepturi natus aut tempore ipsum ea quia rerum non
                  dolores nihil sed exercitationem autem! Est voluptas sint vel enim dolores ea voluptatem suscipit est dolorem ipsum sed recusandae corrupti. Cum perspiciatis nihil aut velit dignissimos aut temporibus itaque est molestias voluptatum
                  qui sint voluptatem. Aut deleniti galisum ut quia quia quo voluptatem soluta et fugit dolores hic consectetur beatae. Ut cupiditate ipsum et doloribus optio et nisi omnis!

                  Lorem ipsum dolor sit amet. Qui repudiandae omnis eos illo numquam sit doloremque officiis ut sint modi sit nulla praesentium? Ut sunt natus non galisum dolor est omnis quae qui voluptatem atque? Ex excepturi natus aut tempore ipsum ea quia rerum non
                  dolores nihil sed exercitationem autem! Est voluptas sint vel enim dolores ea voluptatem suscipit est dolorem ipsum sed recusandae corrupti. Cum perspiciatis nihil aut velit dignissimos aut temporibus itaque est molestias voluptatum
                  qui sint voluptatem. Aut deleniti galisum ut quia quia quo voluptatem soluta et fugit dolores hic consectetur beatae. Ut cupiditate ipsum et doloribus optio et nisi omnis!

```


问:
Jupyter Notebook doesn't print until execution is done
I am using jupyter notebook to download data and write to a zip in chunks as below:

```<code>def _download(url, dest_path):
    req = requests.get(url, stream=True)
    req.raise_for_status()

    completed = 0
    size = len(req.content)
    for chunk in req.iter_content(chunk_size=2 ** 20):
      fd.write(chunk)
      completed += 2 ** 20
      print(f"Downloading: {round(completed/size*100, 1)}%")
      sys.stdout.flush()

def get_data():

    ratings_url = ("http://www2.informatik.uni-freiburg.de/" "~cziegler/BX/BX-CSV-Dump.zip")

    if not os.path.exists("data"):
        os.makedirs("data")

        _download(ratings_url, "data/data.zip")
</code>```

The issue is when I try to print the progress. It will not print anything until the execution is done. I have tried flushing to no avail.

I have also tried a simple for loop with time.sleep and it prints i every 2 seconds as expected.

```<code>import time
for i in range(5):
    print(i)
    time.sleep(2)
</code>```

Everything is printed out at once when execution terminates:

Body:
I am using jupyter notebook to download data and write to a zip in chunks as below:

def _download(url, dest_path):
    req = requests.get(url, stream=True)
    req.raise_for_status()

    completed = 0
    size = len(req.content)
    for chunk in req.iter_content(chunk_size=2 ** 20):
      fd.write(chunk)
      completed += 2 ** 20
      print(f"Downloading: {round(completed/size*100, 1)}%")
      sys.stdout.flush()

def get_data():

    ratings_url = ("http://www2.informatik.uni-freiburg.de/" "~cziegler/BX/BX-CSV-Dump.zip")

    if not os.path.exists("data"):
        os.makedirs("data")

        _download(ratings_url, "data/data.zip")

The issue is when I try to print the progress. It will not print anything until the execution is done. I have tried flushing to no avail.

I have also tried a simple for loop with time.sleep and it prints i every 2 seconds as expected.

import time
for i in range(5):
    print(i)
    time.sleep(2)

Everything is printed out at once when execution terminates:


问:
Python Selenium - StaleElementReferenceException - WebDriverWait doesn't work
I'm trying to web scrape some information from a website. The loop works the first time but the 2nd time the error occurs. I've tried several approaches to solve it with implicit wait or WebDriverUntil but the exception continues to appear. Would you give me a hand?

Here is the code:

```<code>website = 'https://www.elempleo.com/co/ofertas-empleo/55-6-millones?'
driver = webdriver.Chrome(path)
driver.get(website)

empleos = driver.find_elements_by_tag_name('div.result-list.js-result-list.js-results-container')

data = []
i = 0

data = empleos[0].text.splitlines()

while i < 4:
    data.append(empleos[0].text.splitlines())
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    siguiente = driver.find_elements_by_tag_name('a.js-btn-next')
    siguiente[0].click()
    i += 1

</code>```

I tried using:

siguiente = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.TAG_NAME, "a.js-btn-next")))

and

driver.implicitly_wait(10) with different times but it didn't work

Body:
I'm trying to web scrape some information from a website. The loop works the first time but the 2nd time the error occurs. I've tried several approaches to solve it with implicit wait or WebDriverUntil but the exception continues to appear. Would you give me a hand?

Here is the code:

website = 'https://www.elempleo.com/co/ofertas-empleo/55-6-millones?'
driver = webdriver.Chrome(path)
driver.get(website)

empleos = driver.find_elements_by_tag_name('div.result-list.js-result-list.js-results-container')

data = []
i = 0

data = empleos[0].text.splitlines()

while i < 4:
    data.append(empleos[0].text.splitlines())
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    siguiente = driver.find_elements_by_tag_name('a.js-btn-next')
    siguiente[0].click()
    i += 1

I tried using:

siguiente = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.TAG_NAME, "a.js-btn-next")))

and

driver.implicitly_wait(10) with different times but it didn't work


问:
GLSL Plane Transparency (Remove Plane Background)
I followed a tutorial online that basically draws a shape on a plane. I want to make only the shape visible, while the background of the plane invisible, so that I can put it onto another plane instead.

I'm extremely new to ThreeJS and GLSL Shaders so I'm completely lost on this, any help is welcome, thank you.

My Fragment Shader:

```<code>uniform float time;
uniform float progress;
uniform vec2 mouse;
uniform sampler2D matcap;
uniform vec4 resolution;
varying vec2 vUv;
varying vec3 vPosition;
float PI = 3.141592653589793238;

mat4 rotationMatrix(vec3 axis, float angle) {
    axis = normalize(axis);
    float s = sin(angle);
    float c = cos(angle);
    float oc = 1.0 - c;

    return mat4(oc * axis.x * axis.x + c,           oc * axis.x * axis.y - axis.z * s,  oc * axis.z * axis.x + axis.y * s,  0.0,
                oc * axis.x * axis.y + axis.z * s,  oc * axis.y * axis.y + c,           oc * axis.y * axis.z - axis.x * s,  0.0,
                oc * axis.z * axis.x - axis.y * s,  oc * axis.y * axis.z + axis.x * s,  oc * axis.z * axis.z + c,           0.0,
                0.0,                                0.0,                                0.0,                                1.0);
}

vec2 getmatcap(vec3 eye, vec3 normal) {
  vec3 reflected = reflect(eye, normal);
  float m = 2.8284271247461903 * sqrt( reflected.z+1.0 );
  return reflected.xy / m + 0.5;
}

vec3 rotate(vec3 v, vec3 axis, float angle) {
    mat4 m = rotationMatrix(axis, angle);
    return (m * vec4(v, 1.0)).xyz;
}

float smin( float a, float b, float k )
{
    float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
    return mix( b, a, h ) - k*h*(1.0-h);
}

float sdSphere( vec3 p, float r ){
    return length(p)-r;
}

float sdBox( vec3 p, vec3 b ){
    vec3 q = abs(p) - b;
    return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.);
}

float rand(vec2 co){
    return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);
}

float sdf(vec3 p){
    vec3 p1 = rotate(p,vec3(1.),time/5.);

    float box = smin(sdBox(p1,vec3(0.2)),sdSphere(p,0.2), 0.3);

    float realsphere = sdSphere(p1, 0.1);
    float final = mix(box,realsphere,progress);

    for(float i = 0.; i < 10.; i++) {
        float randOffset = rand(vec2(i,0.));
        float progr = 1. - fract(time/3. + randOffset*3.);
        vec3 pos = vec3(sin(randOffset*2.*PI),cos(randOffset*2.*PI),0.);
        float gotoCenter = sdSphere(p-pos*progr, 0.1);

        final = smin(final,gotoCenter,0.1);
    }

    float mouseSphere = sdSphere(p - vec3(mouse*2.,0.),0.1);
    return smin(final, mouseSphere, 0.1);
}

vec3 calcNormal( in vec3 p )
{
    const float eps = 0.0001;
    const vec2 h = vec2(eps,0);
    return normalize( vec3(sdf(p+h.xyy) - sdf(p-h.xyy),
                           sdf(p+h.yxy) - sdf(p-h.yxy),
                           sdf(p+h.yyx) - sdf(p-h.yyx) ) );
}
void main() {
    float dist = length(vUv - vec2(0.5));
    vec3 bg = mix(vec3(0.3),vec3(0.0), dist);
    vec3 camPos = vec3(0.,0.,2.);
    vec3 ray = normalize(vec3(vUv - vec2(0.5),-1));

    vec3 rayPos = camPos;
    float t = 0.;
    float tMax = 5.;
    for(int i = 0; i < 256; i++) {
        vec3 pos = camPos + t*ray;
        float h = sdf(pos);
        if(h<0.0001 || t>tMax) break;
        t+=h;
    }

    vec3 color = bg;

    if(t<tMax){
        vec3 pos = camPos + t*ray;
        color = vec3(1.);
        vec3 normal = calcNormal(pos);
        color = normal;
        float diff = dot(vec3(1.),normal);
        vec2 matcapUV = getmatcap(ray,normal);
        color = vec3(diff);
        color = texture2D(matcap,matcapUV).rgb;

        float fresnel = pow(1. + dot(ray,normal),3.);

        color = mix(color,bg,fresnel);
    }

    gl_FragColor = vec4(color,1.);
}
</code>```

Body:
I followed a tutorial online that basically draws a shape on a plane. I want to make only the shape visible, while the background of the plane invisible, so that I can put it onto another plane instead.

I'm extremely new to ThreeJS and GLSL Shaders so I'm completely lost on this, any help is welcome, thank you.

My Fragment Shader:

uniform float time;
uniform float progress;
uniform vec2 mouse;
uniform sampler2D matcap;
uniform vec4 resolution;
varying vec2 vUv;
varying vec3 vPosition;
float PI = 3.141592653589793238;

mat4 rotationMatrix(vec3 axis, float angle) {
    axis = normalize(axis);
    float s = sin(angle);
    float c = cos(angle);
    float oc = 1.0 - c;

    return mat4(oc * axis.x * axis.x + c,           oc * axis.x * axis.y - axis.z * s,  oc * axis.z * axis.x + axis.y * s,  0.0,
                oc * axis.x * axis.y + axis.z * s,  oc * axis.y * axis.y + c,           oc * axis.y * axis.z - axis.x * s,  0.0,
                oc * axis.z * axis.x - axis.y * s,  oc * axis.y * axis.z + axis.x * s,  oc * axis.z * axis.z + c,           0.0,
                0.0,                                0.0,                                0.0,                                1.0);
}

vec2 getmatcap(vec3 eye, vec3 normal) {
  vec3 reflected = reflect(eye, normal);
  float m = 2.8284271247461903 * sqrt( reflected.z+1.0 );
  return reflected.xy / m + 0.5;
}

vec3 rotate(vec3 v, vec3 axis, float angle) {
    mat4 m = rotationMatrix(axis, angle);
    return (m * vec4(v, 1.0)).xyz;
}

float smin( float a, float b, float k )
{
    float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
    return mix( b, a, h ) - k*h*(1.0-h);
}

float sdSphere( vec3 p, float r ){
    return length(p)-r;
}

float sdBox( vec3 p, vec3 b ){
    vec3 q = abs(p) - b;
    return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.);
}

float rand(vec2 co){
    return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);
}

float sdf(vec3 p){
    vec3 p1 = rotate(p,vec3(1.),time/5.);

    float box = smin(sdBox(p1,vec3(0.2)),sdSphere(p,0.2), 0.3);

    float realsphere = sdSphere(p1, 0.1);
    float final = mix(box,realsphere,progress);

    for(float i = 0.; i < 10.; i++) {
        float randOffset = rand(vec2(i,0.));
        float progr = 1. - fract(time/3. + randOffset*3.);
        vec3 pos = vec3(sin(randOffset*2.*PI),cos(randOffset*2.*PI),0.);
        float gotoCenter = sdSphere(p-pos*progr, 0.1);

        final = smin(final,gotoCenter,0.1);
    }

    float mouseSphere = sdSphere(p - vec3(mouse*2.,0.),0.1);
    return smin(final, mouseSphere, 0.1);
}

vec3 calcNormal( in vec3 p )
{
    const float eps = 0.0001;
    const vec2 h = vec2(eps,0);
    return normalize( vec3(sdf(p+h.xyy) - sdf(p-h.xyy),
                           sdf(p+h.yxy) - sdf(p-h.yxy),
                           sdf(p+h.yyx) - sdf(p-h.yyx) ) );
}
void main() {
    float dist = length(vUv - vec2(0.5));
    vec3 bg = mix(vec3(0.3),vec3(0.0), dist);
    vec3 camPos = vec3(0.,0.,2.);
    vec3 ray = normalize(vec3(vUv - vec2(0.5),-1));

    vec3 rayPos = camPos;
    float t = 0.;
    float tMax = 5.;
    for(int i = 0; i < 256; i++) {
        vec3 pos = camPos + t*ray;
        float h = sdf(pos);
        if(h<0.0001 || t>tMax) break;
        t+=h;
    }

    vec3 color = bg;

    if(t<tMax){
        vec3 pos = camPos + t*ray;
        color = vec3(1.);
        vec3 normal = calcNormal(pos);
        color = normal;
        float diff = dot(vec3(1.),normal);
        vec2 matcapUV = getmatcap(ray,normal);
        color = vec3(diff);
        color = texture2D(matcap,matcapUV).rgb;

        float fresnel = pow(1. + dot(ray,normal),3.);

        color = mix(color,bg,fresnel);
    }

    gl_FragColor = vec4(color,1.);
}


问:
Flutter, how to display data from a BIG5 json?
I would like to display some BIG5 characters from a jSON (which is created from Capesoft NetTalk service with SoftVelocity Clarion web server), but how do I display the characters properly?</p>
```<code>List<dataRecord> parseJson(String responseBody) {
    final parsed =
        convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
  }

  Future<List<dataRecord>> fetchData(http.Client client) async {
    isLoading = true;
    print(widget.clientID.toString());
    final response = await client.get(
      Uri.parse('some_api'),
      headers: {
        "Content-type": "application/json",
        "Accept": "application/json",
        "Connection": "Keep-Alive",
      },
    );
    return parseJson(response.body);
  }
</code>```

Body:
I would like to display some BIG5 characters from a jSON (which is created from Capesoft NetTalk service with SoftVelocity Clarion web server), but how do I display the characters properly?

List<dataRecord> parseJson(String responseBody) {
    final parsed =
        convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
  }

  Future<List<dataRecord>> fetchData(http.Client client) async {
    isLoading = true;
    print(widget.clientID.toString());
    final response = await client.get(
      Uri.parse('some_api'),
      headers: {
        "Content-type": "application/json",
        "Accept": "application/json",
        "Connection": "Keep-Alive",
      },
    );
    return parseJson(response.body);
  }


问:
Create Master Excel File with different worksheets from two different excel containing images using python
I have two Excel files (Name : A.xlsx, B.xlsx). Each excel files contains some images. I have to create one master excel file which contains two worksheets(Master.xlsx, sheet A, Sheet B) with all the images using python code(openpyxl or xlsxwriter library).


问:
plt.savefig() overwrite the previous image
I am working on a image unfolding assignment, in my program, I using glob to read multiple images from my pc, and after that after the program unfolded my image, I want to save it in another directory at once, but when I run the program, every new save image will overwrite or replace the previous image, I had try different way to solve it, but all of them failed. Please help me to solve, I will be very thankful for any assistance.

Here is my code:

```<code>import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.ndimage
from PIL import Image
#import cv2
import matplotlib
import glob

images = glob.glob(r'D:\Master of FOE\pythonProject\Program\Dataset\For New Training\NORMAL IMAGE\GOOD\*.png')
thumb_width = 200
Unfolded_image=[]

def main():
    for im in images:
        im = Image.open(im)
        im = im.convert('RGB')
        data = np.array(im)
        print('Data',data.shape,im.size)
        ch0=np.array(im.getchannel(0))
        ch0 = np.where(ch0 > 0, 1, 0)
        ch1=np.array(im.getchannel(1))
        ch1 = np.where(ch1 > 0, 1, 0)
        ch2=np.array(im.getchannel(2))
        ch2 = np.where(ch2 > 0, 1, 0)
        dt0 = np.where(((ch2+ch1+ch0) > 0), 1, 0).T
        print('DTTT',dt0.shape)
        tx=0
        ty=0
        for xx in range(im.width):
            for yy in range(im.height):
                tx+=xx*dt0[xx][yy]
                ty+=yy*dt0[xx][yy]
        ts = np.sum(dt0)
        txc=tx/ts
        tyc=ty/ts
        rr=max(im.width,im.height)
        for xx in range(im.width):
            for yy in range(im.height):
                if dt0[xx][yy]==0:
                    r=np.sqrt((xx -txc)** 2 + (yy-tyc) ** 2)
                    if r<rr:
                        rr=r
        print('RSRS',rr)
        rm=rr
        print('RRR',rm)
        print('Center',txc,tyc)
        print('DT0',dt0)
        print(11, data[0])
        image = plot_polar_image(data, rm, origin=(txc, tyc))
        Unfolded_image.append(image)
        for i in enumerate(Unfolded_image):
            plt.axis('off')
            plt.savefig(r'D:\Master of FOE\pythonProject\Program\Dataset\For New Training\UNFOLLDED IMAGE\UNFOLDED_GOOD\UG{0}.png'.format(i), bbox_inches='tight', transparent=True, pad_inches=0)

def plot_polar_image(data, rm,origin=None):
    polar_grid, r, theta = reproject_image_into_polar(data,rm, origin)
    plt.imshow(polar_grid, extent=(theta.min(), theta.max(), r.max(), r.min()))
    plt.axis('auto')

def index_coords(data, origin=None):
    ny, nx = data.shape[:2]
    if origin is None:
        origin_x, origin_y = nx // 2, ny // 2
    else:
        origin_x, origin_y = origin
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
    x=x.astype('float64')
    y=y.astype('float64')
    x -= origin_x
    y -= origin_y
    print(999,x,y)
    return x, y

def cart2polar(x, y):
    r = np.sqrt(x**2 + y**2)
    print('RR',r)
    theta = np.arctan2(y, x)
    print(33,r,theta)
    return r, theta

def polar2cart(r, theta):
    x = r * np.cos(theta)
    y = r * np.sin(theta)
    return x, y

def bin_by(x, y, nbins=30):
    bins = np.linspace(y.min(), y.max(), nbins+1)
    bins[-1] += 1
    indicies = np.digitize(y, bins)
    output = []
    for i in range(1, len(bins)):
        output.append(x[indicies==i])
    bins = bins[:-1]
    return output, bins

def reproject_image_into_polar(data,rm, origin=None):
    print(22,data.shape)
    nn=data.shape[:2]
    ny=nx=min(nn)
    if origin is None:
        origin = (nx//2, ny//2)
    rmin=min(nx-origin[0],origin[0],nx//2,ny-origin[1],origin[1],ny//2)
    x, y = index_coords(data, origin=origin)
    r, theta = cart2polar(x, y)
    print(111,r.min(),r.max())
    r_i = np.linspace(min(0,r.min(),rm), min(r.max(),rmin), nx)
    print(222,theta.min(), theta.max())
    theta_i = np.linspace(-np.pi,np.pi, ny)
    theta_grid, r_grid = np.meshgrid(theta_i, r_i)
    print(66,theta_grid,r_grid)
    xi, yi = polar2cart(r_grid, theta_grid)
    xi += origin[0]
    yi += origin[1]
    xi, yi = xi.flatten(), yi.flatten()
    print(99,xi,yi)
    coords = np.vstack((xi, yi))
    print(55,coords)
    bands = []
    print(88,data.shape)
    print(77,data.T.shape)
    for band in data.T:
        print(44,band)
        zi = sp.ndimage.map_coordinates(band, coords, order=1)
        bands.append(zi.reshape((nx, ny)))
    output = np.dstack(bands)
    return output, r_i, theta_i

if __name__ == '__main__':
    main()
</code>```

I am expecting a program that can successfully read, process and save my images, please fo me a favor, it will be very meaningful for me!

Body:
I am working on a image unfolding assignment, in my program, I using glob to read multiple images from my pc, and after that after the program unfolded my image, I want to save it in another directory at once, but when I run the program, every new save image will overwrite or replace the previous image, I had try different way to solve it, but all of them failed. Please help me to solve, I will be very thankful for any assistance.

Here is my code:

import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.ndimage
from PIL import Image
#import cv2
import matplotlib
import glob

images = glob.glob(r'D:\Master of FOE\pythonProject\Program\Dataset\For New Training\NORMAL IMAGE\GOOD\*.png')
thumb_width = 200
Unfolded_image=[]

def main():
    for im in images:
        im = Image.open(im)
        im = im.convert('RGB')
        data = np.array(im)
        print('Data',data.shape,im.size)
        ch0=np.array(im.getchannel(0))
        ch0 = np.where(ch0 > 0, 1, 0)
        ch1=np.array(im.getchannel(1))
        ch1 = np.where(ch1 > 0, 1, 0)
        ch2=np.array(im.getchannel(2))
        ch2 = np.where(ch2 > 0, 1, 0)
        dt0 = np.where(((ch2+ch1+ch0) > 0), 1, 0).T
        print('DTTT',dt0.shape)
        tx=0
        ty=0
        for xx in range(im.width):
            for yy in range(im.height):
                tx+=xx*dt0[xx][yy]
                ty+=yy*dt0[xx][yy]
        ts = np.sum(dt0)
        txc=tx/ts
        tyc=ty/ts
        rr=max(im.width,im.height)
        for xx in range(im.width):
            for yy in range(im.height):
                if dt0[xx][yy]==0:
                    r=np.sqrt((xx -txc)** 2 + (yy-tyc) ** 2)
                    if r<rr:
                        rr=r
        print('RSRS',rr)
        rm=rr
        print('RRR',rm)
        print('Center',txc,tyc)
        print('DT0',dt0)
        print(11, data[0])
        image = plot_polar_image(data, rm, origin=(txc, tyc))
        Unfolded_image.append(image)
        for i in enumerate(Unfolded_image):
            plt.axis('off')
            plt.savefig(r'D:\Master of FOE\pythonProject\Program\Dataset\For New Training\UNFOLLDED IMAGE\UNFOLDED_GOOD\UG{0}.png'.format(i), bbox_inches='tight', transparent=True, pad_inches=0)

def plot_polar_image(data, rm,origin=None):
    polar_grid, r, theta = reproject_image_into_polar(data,rm, origin)
    plt.imshow(polar_grid, extent=(theta.min(), theta.max(), r.max(), r.min()))
    plt.axis('auto')

def index_coords(data, origin=None):
    ny, nx = data.shape[:2]
    if origin is None:
        origin_x, origin_y = nx // 2, ny // 2
    else:
        origin_x, origin_y = origin
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
    x=x.astype('float64')
    y=y.astype('float64')
    x -= origin_x
    y -= origin_y
    print(999,x,y)
    return x, y

def cart2polar(x, y):
    r = np.sqrt(x**2 + y**2)
    print('RR',r)
    theta = np.arctan2(y, x)
    print(33,r,theta)
    return r, theta

def polar2cart(r, theta):
    x = r * np.cos(theta)
    y = r * np.sin(theta)
    return x, y

def bin_by(x, y, nbins=30):
    bins = np.linspace(y.min(), y.max(), nbins+1)
    bins[-1] += 1
    indicies = np.digitize(y, bins)
    output = []
    for i in range(1, len(bins)):
        output.append(x[indicies==i])
    bins = bins[:-1]
    return output, bins

def reproject_image_into_polar(data,rm, origin=None):
    print(22,data.shape)
    nn=data.shape[:2]
    ny=nx=min(nn)
    if origin is None:
        origin = (nx//2, ny//2)
    rmin=min(nx-origin[0],origin[0],nx//2,ny-origin[1],origin[1],ny//2)
    x, y = index_coords(data, origin=origin)
    r, theta = cart2polar(x, y)
    print(111,r.min(),r.max())
    r_i = np.linspace(min(0,r.min(),rm), min(r.max(),rmin), nx)
    print(222,theta.min(), theta.max())
    theta_i = np.linspace(-np.pi,np.pi, ny)
    theta_grid, r_grid = np.meshgrid(theta_i, r_i)
    print(66,theta_grid,r_grid)
    xi, yi = polar2cart(r_grid, theta_grid)
    xi += origin[0]
    yi += origin[1]
    xi, yi = xi.flatten(), yi.flatten()
    print(99,xi,yi)
    coords = np.vstack((xi, yi))
    print(55,coords)
    bands = []
    print(88,data.shape)
    print(77,data.T.shape)
    for band in data.T:
        print(44,band)
        zi = sp.ndimage.map_coordinates(band, coords, order=1)
        bands.append(zi.reshape((nx, ny)))
    output = np.dstack(bands)
    return output, r_i, theta_i

if __name__ == '__main__':
    main()

I am expecting a program that can successfully read, process and save my images, please fo me a favor, it will be very meaningful for me!


问:
Plesk SQL Server ODBC Unable to Connect to Server
I am trying to use Plesk’s ODBC function to connect to my personal database and am unable to do so. I keep getting the error that the server cannot be found. I have allowed access to remote connections, created login credentials, and updated the firewall to allow connections through port 1433. I also tired using port forwarding through Cox Wi-Fi.

I can connect to my personal database from my own, separate server using both the name of my computer or the private IP address. However, when trying to connect from Plesk, I am unable to connect when trying the computer name, private IP, private IP with specifying the port, public IP, and public IP when specifying the port. Nothing seems to work.

Any help is greatly appreciated.


问:
Have a summation of some filtered rows
I have a dataframe and i want some specific info out of it. I want to filter some rows and have another column but not sure how to implement the code
This is the dataframe that I have

df
my data are like above and it continues up to 2022. What I want is a code for having a summation of stdedc +aglivc for those time which have .33 at the end. Would you please help me to find it out?

Title: Have a summation of some filtered rows


问:
Prevent data loss in batch logging
We have a service that logs every request with everything required to debug it in case of a failure. The way this is done is that on each request an async functions logs the required data to our database. But as you can already see this is not using our resources in an optimal way because we log requests one by one. Because of that I wanted to do batch logging. Imagine to actually connect to our database to perform the logging we set the threshold to 50 logs in que. If there were 49 logs in que and a power outage occurs(or anything that makes us lose this object), then we just lose all of our logs! If we have 10 servers with the same situation then we lose 49*10 logs. What is the most optimal recommended way to prevent such situation. If there are foolproof libraries for .net, I would love hear about them as well! Thanks for your time.

After having a conversation in the comments, I noticed I might have made the question to compilacted and that's my fault sorry. The core question is 'how to make a batch logging proccess that is not affected from data loss (on power outage, db fault, connection error and so on) or im simpler terms A RELIABLE BATCH LOGGIN SCENARIO.

Title: Prevent data loss in batch logging


问:
training root cause analysis AI: question about dataset, state of the art
There are some companies like Zebrium around saying that they get an AI to do root cause analysis of logs. I think root cause analysis is essentially a multi-class classification problem. So I check for research on classifying logs but data sets and works I manager to find are all binary classifications (normal vs abnormal).

Program: https://github.com/wuyifan18/DeepLog
Dataset: https://github.com/logpai/loghub

Can anyone enlighten me by providing resources on multi-class (root cause analysis) rather than binary class (anomaly detection)? Many thanks.


问:
Why is this RegEx not working on Jenkins?
I am trying to setup a Generic Trigger on a certain repo branch for Jenkins.  I come across this article and this article.  The regex in the first article is .+?(?=myrepository/commits/mybranch).  I try it, and it doesn't work.  The regex ^mybranch$ from the second article works.  Why does the first one not work?


问:
Move first and last element of the RecyclerView to the center of the widget
How move the first and the last element of RecyclerView to the center of the widget?

Example

I found next example: RecyclerView allow first/last items to be scrolled to the centre

But i can't describe this solution for my case. There is my code:

```<code>class CustomLinearLayoutManager(context: Context): LinearLayoutManager(context , LinearLayoutManager.HORIZONTAL, false) {
    override fun getPaddingStart(): Int {
        return width / 2
    }

    override fun getPaddingEnd(): Int {
        return paddingStart
    }
}
</code>```

I feel that I have implemented incorrectly this solution

Please let me know how correctly to realize move outermost items to the center in horizontal RecyclerView widget.

Body:
How move the first and the last element of RecyclerView to the center of the widget?

Example

I found next example: RecyclerView allow first/last items to be scrolled to the centre

But i can't describe this solution for my case. There is my code:

class CustomLinearLayoutManager(context: Context): LinearLayoutManager(context , LinearLayoutManager.HORIZONTAL, false) {
    override fun getPaddingStart(): Int {
        return width / 2
    }

    override fun getPaddingEnd(): Int {
        return paddingStart
    }
}

I feel that I have implemented incorrectly this solution

Please let me know how correctly to realize move outermost items to the center in horizontal RecyclerView widget.


问:
Difficulty typing an async function for a createContext props placeholder react + typescript
I am trying to correctly type one of my functions (without using any) in createContext and keep getting errors in my IDE. I couldn't find anything on google/SE that was quite able to help me out.

This is where I am getting the error (I edited out the other irrelevant functions and attached a screenshot of the error message):

```<code>const MarketplaceContext = createContext<MarketplaceContextProps>({
    ...
    getContract: () => {return Promise.resolve(ethers.Contract)},
    ...
});
</code>```

This is the MarketplaceContextProps interface (edited out irrelevant functions):

```<code>export interface MarketplaceContextProps {
    ...
    getContract: () => Promise<ethers.Contract>,
    ...
}
</code>```

Here is the function:

```<code>async function getContract(): Promise<ethers.Contract>{
const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)
const signer = provider.getSigner()
const contract = new ethers.Contract(contractAddress, contractABI, signer)
return contract;
}
</code>```

I console.logged contract to see what type it is and it returned a large object that I don't think I can make an interface for. Picture of the log if helpful. I tried a generic typing but got a similar error to the first screenshot but with the generic type instead.

Body:
I am trying to correctly type one of my functions (without using any) in createContext and keep getting errors in my IDE. I couldn't find anything on google/SE that was quite able to help me out.

This is where I am getting the error (I edited out the other irrelevant functions and attached a screenshot of the error message):

const MarketplaceContext = createContext<MarketplaceContextProps>({
    ...
    getContract: () => {return Promise.resolve(ethers.Contract)},
    ...
});

This is the MarketplaceContextProps interface (edited out irrelevant functions):

export interface MarketplaceContextProps {
    ...
    getContract: () => Promise<ethers.Contract>,
    ...
}

Here is the function:

async function getContract(): Promise<ethers.Contract>{
const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)
const signer = provider.getSigner()
const contract = new ethers.Contract(contractAddress, contractABI, signer)
return contract;
}

I console.logged contract to see what type it is and it returned a large object that I don't think I can make an interface for. Picture of the log if helpful. I tried a generic typing but got a similar error to the first screenshot but with the generic type instead.


问:
How to connect this speaker and use it?
I have this speakers at home
Very small and simple, i can't figure out how to use them
Where to connect them mobile or pc
What wires to use
If anyone knows, help me[speaker front imagespeaker back image](https://i.stack.imgur.com/lFkXo.jpg)

I'm Posting a picture of the speaker,
I expect to know how it will be used

Title: How to connect this speaker and use it?


问:
How to combine aggregations in new calculated field?
I have a list of customer IDs and calculated an amount owing based on 2 columns (accounts receivable customer). As a customer might appear multiple times in the table, I calculate:

sumOver
(
max
(
{unlock_price} - {total_paid}),
[{unit_number}]
)

Based on how long a customer is owing the amount they are assigned to a class (PAR class).

ifelse ( {days_to_cutoff}<=6, "PAR 0-6", {days_to_cutoff}<=14, "PAR 7-14", {days_to_cutoff}<=30, "PAR 15-30", {days_to_cutoff}<=60, "PAR 30-60", {days_to_cutoff}>60, "PAR>60", "Current")

Now, I can visualise class and individual accounts receivable, see screenshot. What I actually want to get to is a total (SUM) of accounts receivable per class in a new calculated field or, ideally, combining all steps in one.
enter image description here

Whatever I tried results in QS complaining that I am trying to nest aggregations and cant do that.

sumOver ( sum ( {accounts_receivable_customer}), [{unit_number}], [{PAR_class}] )


问:
can I use chrome://inspect to inspect android studio emulator
I have a mobile app apk file and want to run it through the android studio emulator and inspect network requests with chrome//inspect. To debug webview in the app.

But when I go to chrome//inspect. I can see the emulator but not inspect link.

I am not sure why the inspect link doesn't appear and whether I could inspect the emulator in the first place.
Suggesting me alternative ways to debug webview on Macbook will also be appreciated.

PC: Macbook 16 pro / MacOS Ventura 13.0.1

I don't have the source code of the app, Only apk file.

Thank you for your help!


问:
WhisperAI Transcription returns repeating words in the end of transcript. Does anyone know why?
I am running whisper transcription ("base.en") model on an audio file

"https://test-trimpixel.s3.ap-south-1.amazonaws.com/meetingbot//tmp/1672172602702-gzn-rcck-som.ogg", keeping temperature=0 as parameter. But it is returning repeating words in the end of transcript.

In this case it is returning:

Okay. Okay. Okay. Go back. Just go to form. I hope. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Go back. Okay. Okay. Okay. Okay. Go back. Okay. Go back. There was one of those meetings where, you know, we did not get any recordings. So we need to go through those. Can you start from the 1245? Is the meeting at 1245 AM? 1245. 1245 AM. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. So 52 has not even said video. And 53, you know, 53. What is there to get 53 53. It's not just look at the test. Already the bodies are more. You can play the video. Okay. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes.

Does anyone know why this is happening? Here is code for the reference:

```<code>model = whisper.load_model("base.en")
outFile = fileName.split('.ogg')[0] + '.wav'
result = model.transcribe(outFile,  temperature=0)
print(result['text'])
</code>```

Body:
I am running whisper transcription ("base.en") model on an audio file

"https://test-trimpixel.s3.ap-south-1.amazonaws.com/meetingbot//tmp/1672172602702-gzn-rcck-som.ogg", keeping temperature=0 as parameter. But it is returning repeating words in the end of transcript.

In this case it is returning:

Okay. Okay. Okay. Go back. Just go to form. I hope. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Go back. Okay. Okay. Okay. Okay. Go back. Okay. Go back. There was one of those meetings where, you know, we did not get any recordings. So we need to go through those. Can you start from the 1245? Is the meeting at 1245 AM? 1245. 1245 AM. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. Okay. So 52 has not even said video. And 53, you know, 53. What is there to get 53 53. It's not just look at the test. Already the bodies are more. You can play the video. Okay. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes. Yes.

Does anyone know why this is happening? Here is code for the reference:

model = whisper.load_model("base.en")
outFile = fileName.split('.ogg')[0] + '.wav'
result = model.transcribe(outFile,  temperature=0)
print(result['text'])


问:
How to Create a react apex chart to display data of past 12 months?
I have a application submitting portal, I which user his/her request. the issue I am facing is to separate data on base created at field which separates data from current month to past 12 months.
The Data format is like this.

```<code>[
  {
    "_id": "63b3fca07d1f15f5d33e12e0",
    "first_name": "ZANAEN",
    "last_name": "Ullah",
    "date_of_birth": "03/12/2002",
    "cnic_number": "55555-5555555-5",
    "expiry_date": "10/01/2027",
    "current_address": "Qqqq",
    "current_city": "Bhawalpur",
    "permanent_address": "1111",
    "permanent_city": "Bhawalpur",
    "mobile_number": "0000-0000000",
    "loan_ammount": "5000",
    "purpose_of_loan": "Micro-Enterprices",
    "current_occupation": "Job",
    "nature_of_business": "Existing",
    "duration_of_business": "5 years",
    "business_address": "11111",
    "business_city": "Bhawalpur",
    "createdAt": "2022-01-03T10:00:00.562Z",
    "updatedAt": "2022-01-03T10:00:00.562Z",
    "applicationId": 22121022,
    "__v": 0
  },
]
</code>```

and the function is like

```<code>getChartLast1Year(objects) {
    const monthCounts = [];
    const currentMonth = moment().month();
    const currentYear = moment().year();

    for (let i = 0; i < 12; i++) {
      const month = (currentMonth + i) % 12;
      const year = month < currentMonth ? currentYear - 1 : currentYear;
      const monthData = objects.filter((application) => {
        const createdAt = moment(application.createdAt);
        return createdAt.month() === month && createdAt.year() === year;
      });
      monthCounts.push({
        month: moment().month(month).format("MMM"),
        year: moment().year(year).format("YYYY"),
        count: monthData.length,
      });
    }

    console.log("monthCounts", monthCounts);

    return monthCounts;
  },
</code>```

If anyone can help I would be so thankful

Body:
I have a application submitting portal, I which user his/her request. the issue I am facing is to separate data on base created at field which separates data from current month to past 12 months.
The Data format is like this.

[
  {
    "_id": "63b3fca07d1f15f5d33e12e0",
    "first_name": "ZANAEN",
    "last_name": "Ullah",
    "date_of_birth": "03/12/2002",
    "cnic_number": "55555-5555555-5",
    "expiry_date": "10/01/2027",
    "current_address": "Qqqq",
    "current_city": "Bhawalpur",
    "permanent_address": "1111",
    "permanent_city": "Bhawalpur",
    "mobile_number": "0000-0000000",
    "loan_ammount": "5000",
    "purpose_of_loan": "Micro-Enterprices",
    "current_occupation": "Job",
    "nature_of_business": "Existing",
    "duration_of_business": "5 years",
    "business_address": "11111",
    "business_city": "Bhawalpur",
    "createdAt": "2022-01-03T10:00:00.562Z",
    "updatedAt": "2022-01-03T10:00:00.562Z",
    "applicationId": 22121022,
    "__v": 0
  },
]

and the function is like

getChartLast1Year(objects) {
    const monthCounts = [];
    const currentMonth = moment().month();
    const currentYear = moment().year();

    for (let i = 0; i < 12; i++) {
      const month = (currentMonth + i) % 12;
      const year = month < currentMonth ? currentYear - 1 : currentYear;
      const monthData = objects.filter((application) => {
        const createdAt = moment(application.createdAt);
        return createdAt.month() === month && createdAt.year() === year;
      });
      monthCounts.push({
        month: moment().month(month).format("MMM"),
        year: moment().year(year).format("YYYY"),
        count: monthData.length,
      });
    }

    console.log("monthCounts", monthCounts);

    return monthCounts;
  },

If anyone can help I would be so thankful


问:
At a radio ip address (interface login) , I want the browser to auto fill the user and password and login, repeat until login is sucessful
I have hundreds of radio equipment and cameras to log into to change settings , firmware , etc.
I repetitively retype the same 6 or 8 different usernames and passwords until I find the correct ones that work with that device, sometimes I type 60 - 100 times a day!

What I would like:
When I type the devices ip address into a browser, some program (insert mystery code here) goes to a user/password txt file grabs first username and password, fills in fields and enter. If login fails, it goes to the next set, etc. It only stops when login is successful.

I need some ideas or advice on what directions to head to create this.

Thanks

I tried using password savers but there are a lot of common ip addresses on the hundreds of lans with different passwords. do I need to build something? is there something at already exists?

thanks
max


问:
Problem setting a cookie in a react app in production
I'm having issues setting a cookie in a react app, In development, it works but when I switch to production the cookie is not received by the browser. I'm using a node.js/express server.
The backend and frontend are both hosted on vercel.

This is the list of things I've tried:

I've set the domain name to be the domain of the frontend(i.e ".vercel.app"),

In the request to the backend using axios, "withCredentials" is set to true

Secure is set to true

cors is enabled

Here's the code for clarification:

The code sending the cookie:

```<code>function sendCookie(req, res, token) {
   const cookies = new Cookies(req, res, {
   keys,
 });
 return cookies.set("jwt", token, {
   domain:".vercel.app"
   secure: true,
   sameSite:"strict"
   path: "/",
   httpOnly: false,
});
 }
</code>```

Cors configuration:

```<code>   app.use(
   cors({
     credentials: true,
     origin: [
       "http://localhost:5173",
        "https://abc.vercel.app",
     ],
      methods: ["GET", "POST", "DELETE", "PATCH"],
   })
  );
</code>```

"https://abc.vercel.app" in this case is the frontend URL

I'd really appreciate any help I can get. Thanks

Body:
I'm having issues setting a cookie in a react app, In development, it works but when I switch to production the cookie is not received by the browser. I'm using a node.js/express server.
The backend and frontend are both hosted on vercel.

This is the list of things I've tried:

I've set the domain name to be the domain of the frontend(i.e ".vercel.app"),

In the request to the backend using axios, "withCredentials" is set to true

Secure is set to true

cors is enabled

Here's the code for clarification:

The code sending the cookie:

function sendCookie(req, res, token) {
   const cookies = new Cookies(req, res, {
   keys,
 });
 return cookies.set("jwt", token, {
   domain:".vercel.app"
   secure: true,
   sameSite:"strict"
   path: "/",
   httpOnly: false,
});
 }

Cors configuration:

   app.use(
   cors({
     credentials: true,
     origin: [
       "http://localhost:5173",
        "https://abc.vercel.app",
     ],
      methods: ["GET", "POST", "DELETE", "PATCH"],
   })
  );

"https://abc.vercel.app" in this case is the frontend URL

I'd really appreciate any help I can get. Thanks


问:
Configure Anti-Aliasing parameter in Arcigs Server Service in python
I need to set the anti-aliasing parameters for map services via python. Not having much luck in locating on how to configure this.

I have tried looking into the.sddraft file  as mentioned in the documentation: https://desktop.arcgis.com/en/arcmap/10.6/analyze/arcpy-mapping/createmapsddraft.htm

However, when I open the .sddraft file as a xml, I cannot find the textAntiAliasingMode or AntiAliasingMode parameter in the file. Therefore I cannot use  xml.dom.minidom to update it.

Any ideas??


问:
Issues with MediaSourceExtension
I want to livestream audio only using MSE. I would like to send data/files via websockets, therefore no HLS nor DASH.

But until I implement websockets, I thought to give it a try by statically loading the song in an array.

Here is my code so far:

```<code><audio id="ap" controls></audio>
..
<script>
  const ms = new MediaSource();
  var ae = document.getElementById("ap");
  ae.src = URL.createObjectURL(ms);
  ms.addEventListener('sourceopen', msOpen);

function msOpen(e) {
  URL.revokeObjectURL(ae.src);
  var mse = e.target;
  const sourceBuffer = mse.addSourceBuffer('audio/mp4');
  var u8A0 = new Uint8Array([0x00, 0x00, 0x00, 0x1C, 0x66, ...]);
  sourceBuffer.appendBuffer(u8A0.buffer);

  sourceBuffer.addEventListener('updateend', function() {
    if (!sourceBuffer.updating && mse.readyState === 'open') {
      mse.endOfStream();
      console.log('Audio is ready to play!');
    }
  });
}
</script>

</code>```

The result is that there are no errors in the debug window and the audio element correctly shows the duration of the song, about two min and half. However, once I click Play, the duration shows 0 (zero) and the song is not played. If I try to pause and play again, the debug window says:

*"Uncaught (in promise) DOMException: The fetching process for the media resource was aborted by the user agent at the user's request".
*
This is the ffmpeg command I used to prepare the file:

ffmpeg -i m.wav -c:a aac -b:a 32k -f mp4 output.mp4

Any help would be well appreciated.
Thank you.

Title: Issues with MediaSourceExtension

Body:
I want to livestream audio only using MSE. I would like to send data/files via websockets, therefore no HLS nor DASH.

But until I implement websockets, I thought to give it a try by statically loading the song in an array.

Here is my code so far:

<audio id="ap" controls></audio>
..

The result is that there are no errors in the debug window and the audio element correctly shows the duration of the song, about two min and half. However, once I click Play, the duration shows 0 (zero) and the song is not played. If I try to pause and play again, the debug window says:

*"Uncaught (in promise) DOMException: The fetching process for the media resource was aborted by the user agent at the user's request".
*
This is the ffmpeg command I used to prepare the file:

ffmpeg -i m.wav -c:a aac -b:a 32k -f mp4 output.mp4

Any help would be well appreciated.
Thank you.


问:
Camel : How to pull large data in batches/chunks from database using a SQL / jdpc / jpa component?
I tried to pull some large volume of data using SQL component in camel and write it into a file.
But could not find a way to pull the data in batches from data base.
The data is huge and I would not want to load it into the memory in one shot

Please suggest any possibile ways to have it implemented.
Thanks.

I have tried:
readSize, fetchSize, maxmessagesperPoll but none of the above worked out for me.
Also I can't have a flag in my table to maintain what records have been pulled (For onConsume usage reference).


问:
can't install awswrangler==2.18.0 because dependency aiohttp==3.8.1 has a known issue on windows
during build of aiohttp==3.8.1 on windows get error

aiohttp/_websocket.c(198): fatal error C1083: Cannot open include file: 'longintrepr.h': No such file or directory

this is a known bug according to
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects

trying to install awswrangler on windows 10 with python 3.11


问:
"Class XXX is not a valid entity or mapped super class" after create folder inside Entity
I am getting error  Class "App\Entity\Admin\User" is not a valid entity or mapped super class.

I have a folder Admin under Entity which includes entities required for admin.

User.php

```<code>namespace App\Entity\Admin;

use DateTime;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'user')]
#[ORM\HasLifecycleCallbacks]
class User
{
</code>```

I have made following changes in doctrine.yaml

```<code>    mappings:
        App:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'App\Entity'
            alias: App
        Admin:
            is_bundle: false
            type: attribute
            dir: '%kernel.project_dir%/src/Entity/Admin'
            prefix: 'App\Entity\Admin'
            alias: Admin
</code>```

Body:
I am getting error  Class "App\Entity\Admin\User" is not a valid entity or mapped super class.

I have a folder Admin under Entity which includes entities required for admin.

User.php

namespace App\Entity\Admin;

use DateTime;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'user')]
#[ORM\HasLifecycleCallbacks]
class User
{

I have made following changes in doctrine.yaml

    mappings:
        App:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'App\Entity'
            alias: App
        Admin:
            is_bundle: false
            type: attribute
            dir: '%kernel.project_dir%/src/Entity/Admin'
            prefix: 'App\Entity\Admin'
            alias: Admin


问:
Merge excel data sheets and add blank values if no data available for that row
Ok I have an excel workbook where there is two different sheets. Each sheet shows a students last 3 tests scores for 2 different tests. Test A and Test B. However all students have only taken one of the tests but not all students have taken the other.
For test A students may have taken the test 1-3 times.
For test B students may have
taken the test 0-3 times

For example: Test A

student ID
Test A Date

0001
07/25/2022

0001
05/05/2022

Test B

Student ID
Test B Date

0001
09/21/2022

What I want to do is I want to merge the test B date column next to the Test A column and put them all on one nice row but if there is more Test A dates than Test B dates than insert a blank value on that row for that column.

Final result should be

student ID
Test A Date
Test B Date

0001
07/25/2022
09/21/2022

0001
05/05/2022

I tried power query in excel to see if that would work but what it does is repeat the test B dates next to the Test A dates. This can get really cumbersome when there is 3 of each. It ends up making 9 total rows for that ID


问:
SpriteMask in Unity

There are many identical objects, each of which has a child.
The child object must not appear outside of the parent. I do this using SpriteMask, but with this approach, the child object sees within the boundaries of someone else's parent, as in the screenshot

Title: SpriteMask in Unity


问:
windows application Memory consumption increase while tracking browser(chorme) url using C#
Hi i have a winForms application which runs a 10 sec threading timer and in that function i am calling this function whenever active process is chrome but it start with low system memory of 28 mb and goes upto 500-600mb with in hours if i use chrome constantly can someone tell what i am doing wrong

```<code>   public  string ChromeTabItemURL()
        {
            try
            {
               // Url Tracking Enable and Disabled From Web
                if (!TrackDayWiseHelper.isTrackDayWiseActivated())
                    return string.Empty;
                if (StorageBag.isUserDisableUrlTrack)
                    return string.Empty;

                Process[] procsChrome = Process.GetProcessesByName("chrome");
                if (procsChrome.Length == 0)
                {
                    return "";
                }
                AutomationElement elm = null;
                AutomationElement elmUrlBar = null;
                AutomationPattern[] patterns = null;
                foreach (Process chrome in procsChrome)
                {
                    // the chrome process must have a window
                    if (chrome.MainWindowHandle == IntPtr.Zero)
                    {
                        continue;
                    }

                    // find the automation element
                    elm = AutomationElement.FromHandle(chrome.MainWindowHandle);
                    elmUrlBar = elm.FindFirst(TreeScope.Descendants,
                        new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));

                    // if it can be found, get the value from the URL bar
                    if (elmUrlBar != null)
                    {
                        if ((bool)elmUrlBar.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty))
                        {
                            continue;
                        }

                        patterns = elmUrlBar.GetSupportedPatterns();
                        if (patterns.Length > 0)
                        {
                            ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
                            elmUrlBar = null;
                            if (val.Current.Value != "")
                            {
                                if (Regex.IsMatch(val.Current.Value, @"^(https:\/\/)?[a-zA-Z0-9\-\.]+(\.[a-zA-Z]{2,4}).*$"))
                                {
                                    // prepend http:// to the url, because Chrome hides it if it's not SSL
                                    if (!val.Current.Value.StartsWith("http"))
                                    {
                                        string value = "http://" + val.Current.Value;
                                        Console.WriteLine(value);
                                        return value;
                                    }
                                }
                            }

                            return val.Current.Value;
                        }
                        elmUrlBar = null;
                    }
                }
                procsChrome = null;
                elm = null;
                elmUrlBar = null;
                patterns = null;
                return "";

            }
            catch (System.ComponentModel.Win32Exception ex)
            {
               ExceptionLogging.SendExcepToDB(ex); Crashes.TrackError(ex);
            }
            catch (Exception ex)
            {
               ExceptionLogging.SendExcepToDB(ex); Crashes.TrackError(ex);
            }
            return "";
        }
</code>```

code seems to be working fine i tried using jettbrains dott trace and this didnt come up as most resource consuming process but dont know why it is happening if i run application without this everything seems to be working fine

Body:
Hi i have a winForms application which runs a 10 sec threading timer and in that function i am calling this function whenever active process is chrome but it start with low system memory of 28 mb and goes upto 500-600mb with in hours if i use chrome constantly can someone tell what i am doing wrong

   public  string ChromeTabItemURL()
        {
            try
            {
               // Url Tracking Enable and Disabled From Web
                if (!TrackDayWiseHelper.isTrackDayWiseActivated())
                    return string.Empty;
                if (StorageBag.isUserDisableUrlTrack)
                    return string.Empty;

                Process[] procsChrome = Process.GetProcessesByName("chrome");
                if (procsChrome.Length == 0)
                {
                    return "";
                }
                AutomationElement elm = null;
                AutomationElement elmUrlBar = null;
                AutomationPattern[] patterns = null;
                foreach (Process chrome in procsChrome)
                {
                    // the chrome process must have a window
                    if (chrome.MainWindowHandle == IntPtr.Zero)
                    {
                        continue;
                    }

                    // find the automation element
                    elm = AutomationElement.FromHandle(chrome.MainWindowHandle);
                    elmUrlBar = elm.FindFirst(TreeScope.Descendants,
                        new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));

                    // if it can be found, get the value from the URL bar
                    if (elmUrlBar != null)
                    {
                        if ((bool)elmUrlBar.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty))
                        {
                            continue;
                        }

                        patterns = elmUrlBar.GetSupportedPatterns();
                        if (patterns.Length > 0)
                        {
                            ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
                            elmUrlBar = null;
                            if (val.Current.Value != "")
                            {
                                if (Regex.IsMatch(val.Current.Value, @"^(https:\/\/)?[a-zA-Z0-9\-\.]+(\.[a-zA-Z]{2,4}).*$"))
                                {
                                    // prepend http:// to the url, because Chrome hides it if it's not SSL
                                    if (!val.Current.Value.StartsWith("http"))
                                    {
                                        string value = "http://" + val.Current.Value;
                                        Console.WriteLine(value);
                                        return value;
                                    }
                                }
                            }

                            return val.Current.Value;
                        }
                        elmUrlBar = null;
                    }
                }
                procsChrome = null;
                elm = null;
                elmUrlBar = null;
                patterns = null;
                return "";

            }
            catch (System.ComponentModel.Win32Exception ex)
            {
               ExceptionLogging.SendExcepToDB(ex); Crashes.TrackError(ex);
            }
            catch (Exception ex)
            {
               ExceptionLogging.SendExcepToDB(ex); Crashes.TrackError(ex);
            }
            return "";
        }

code seems to be working fine i tried using jettbrains dott trace and this didnt come up as most resource consuming process but dont know why it is happening if i run application without this everything seems to be working fine


问:
Don't get subscription plan using in_app_purchase dependency flutter
enter image description here

in_app_purchase throw error [purchaseId] not found so what I do?
I am using in_app_purchase: ^3.1.1

I get all the producers from the play console but not the subscriptions.

I try both of purchasePlanId and basePlanId but get same error [id]not found


问:
Performance is 30% worse on Python 3.11.1 (vs Python 3.10.9) when using all() and to a lesser extent any()
I found that the Python 3.11.1 implementations of all() and any() are 30% slower and 23% slower respectively compared to Python 3.10.9

Any idea why this might be the case? (Unfortunately I don't have the skills to look through the underlying implementation of the CPython code)

```<code>import timeit
from functools import partial
import platform

def find_by_keys(
    keys: list[str],
    table: list[dict[str, str | int]],
    match_data: dict[str, str | int],
) -> dict[str, str | int] | None:
    for item in table:
        if all(item[k] == match_data[k] for k in keys):   # 30% slower on 3.11
        # if any(item[k] == match_data[k] for k in keys):   # 23% slower on 3.11
        # if item["id"] == match_data["id"]:   # 3% faster on 3.11
            return item
    return None

def main():
    keys: list[str] = ["id", "key_1", "key_2"]
    table: list[dict[str, str | int]] = [
        {
            "id": i,
            "key_1": "val_1",
            "key_2": "val_2",
        }
        for i in range(1, 5001)
    ]
    match_data: dict[str, str | int] = {
        "id": 3000,
        "key_1": "val_1",
        "key_2": "val_2",
    }

    # Note: used repeat=50000 for all() calls, otherwise used repeat=500000
    timeit_output = timeit.repeat(
        partial(find_by_keys, keys, table, match_data),
        repeat=50000,
        number=1
    )

    average_time = sum(timeit_output) / len(timeit_output)
    best_time = min(timeit_output)
    tps_output = 1 / average_time

    print(f"Python version = {platform.python_version()}")
    print(f"Average time = {average_time}")
    print(f"Best time = {best_time}")
    print(f"Average transactions per second = {tps_output}")

if __name__ == "__main__":
    main()
</code>```

Results

Console output using Python 3.10.9:

```<code>Python version = 3.10.9
Average time = 0.0008256170657486655
Best time = 0.0007106999401003122
Average transactions per second = 1211.2152733824669
</code>```

Console output using Python 3.11.1:

```<code>Python version = 3.11.1
Average time = 0.0011819988898839802
Best time = 0.001033599954098463
Average transactions per second = 846.0244832363215
</code>```

Body:
I found that the Python 3.11.1 implementations of all() and any() are 30% slower and 23% slower respectively compared to Python 3.10.9

Any idea why this might be the case? (Unfortunately I don't have the skills to look through the underlying implementation of the CPython code)

import timeit
from functools import partial
import platform

def find_by_keys(
    keys: list[str],
    table: list[dict[str, str | int]],
    match_data: dict[str, str | int],
) -> dict[str, str | int] | None:
    for item in table:
        if all(item[k] == match_data[k] for k in keys):   # 30% slower on 3.11
        # if any(item[k] == match_data[k] for k in keys):   # 23% slower on 3.11
        # if item["id"] == match_data["id"]:   # 3% faster on 3.11
            return item
    return None

def main():
    keys: list[str] = ["id", "key_1", "key_2"]
    table: list[dict[str, str | int]] = [
        {
            "id": i,
            "key_1": "val_1",
            "key_2": "val_2",
        }
        for i in range(1, 5001)
    ]
    match_data: dict[str, str | int] = {
        "id": 3000,
        "key_1": "val_1",
        "key_2": "val_2",
    }

    # Note: used repeat=50000 for all() calls, otherwise used repeat=500000
    timeit_output = timeit.repeat(
        partial(find_by_keys, keys, table, match_data),
        repeat=50000,
        number=1
    )

    average_time = sum(timeit_output) / len(timeit_output)
    best_time = min(timeit_output)
    tps_output = 1 / average_time

    print(f"Python version = {platform.python_version()}")
    print(f"Average time = {average_time}")
    print(f"Best time = {best_time}")
    print(f"Average transactions per second = {tps_output}")

if __name__ == "__main__":
    main()

Results

Console output using Python 3.10.9:

Python version = 3.10.9
Average time = 0.0008256170657486655
Best time = 0.0007106999401003122
Average transactions per second = 1211.2152733824669

Console output using Python 3.11.1:

Python version = 3.11.1
Average time = 0.0011819988898839802
Best time = 0.001033599954098463
Average transactions per second = 846.0244832363215


问:
Apply separate formulas to separate columns but for the same row in Multi Index Dataframe?
I'm working with a multi index dataframe and I am trying to apply two different formulas and append the calculation as a new row in the bottom ("Total").

However, because I am working with multi index dataframe, the calculation would differ depending on which sub-header it is.

Dataframe:

```<code>data = {'ID1': [1.0, 2.0,1.2,1.7,0.8,0.9], 'ID2': [5.0,3.0,7.0,2.0,1.0,6.0], 'Date': ['10-31-2022','12-31-2022','10-31-2022','12-31-2022','10-31-2022','12-31-2022'], 'Name': ['John', 'John', 'Kat', 'Kat', 'Adam','Adam']}
df1 = pd.DataFrame (data= data)
</code>```

Creating multi index:

```<code>df1 = df1.set_index(["Date", "Name"])
df1 = df1.unstack().swaplevel(0,1, axis = 1).sort_index(axis = 1, level = 0, sort_remaining = False)
</code>```

df:

In the "Total" row, I am trying to apply the cumprod function to the ID1 columns, and ID2 columns will simply be the mean.

I am able to calculate the columns by filtering to ID1 or ID2 only, however I would need to create separate rows for them.

My output:

Expected output:

Note: the numbers in the total row are random, just putting it there for visual reference.

Calculation for ID1 columns:

```<code>df_cumprod = (1 + df.filter(like='ID1')).cumprod(skipna = True) - 1

df_cumprod2 = df_cumprod.tail(1)

df_cumprod2.rename({df_cumprod2.index[-1]: 'Total'}, inplace = True)

df.append(df_cumprod2)
</code>```

Calculation for ID2 columns:

```<code>df.loc['Total'] = df.iloc[:, df.columns.get_level_values(1)=='ID2'].mean()
</code>```

This creates two "Total" rows, is there a way to merge them together so that they appear side by side in the same row (as shown in the expected output above)? Or apply two different formulas based on the condition of the column name to the same row?

Body:
I'm working with a multi index dataframe and I am trying to apply two different formulas and append the calculation as a new row in the bottom ("Total").

However, because I am working with multi index dataframe, the calculation would differ depending on which sub-header it is.

Dataframe:

data = {'ID1': [1.0, 2.0,1.2,1.7,0.8,0.9], 'ID2': [5.0,3.0,7.0,2.0,1.0,6.0], 'Date': ['10-31-2022','12-31-2022','10-31-2022','12-31-2022','10-31-2022','12-31-2022'], 'Name': ['John', 'John', 'Kat', 'Kat', 'Adam','Adam']}
df1 = pd.DataFrame (data= data)

Creating multi index:

df1 = df1.set_index(["Date", "Name"])
df1 = df1.unstack().swaplevel(0,1, axis = 1).sort_index(axis = 1, level = 0, sort_remaining = False)

df:

In the "Total" row, I am trying to apply the cumprod function to the ID1 columns, and ID2 columns will simply be the mean.

I am able to calculate the columns by filtering to ID1 or ID2 only, however I would need to create separate rows for them.

My output:

Expected output:

Note: the numbers in the total row are random, just putting it there for visual reference.

Calculation for ID1 columns:

df_cumprod = (1 + df.filter(like='ID1')).cumprod(skipna = True) - 1

df_cumprod2 = df_cumprod.tail(1)

df_cumprod2.rename({df_cumprod2.index[-1]: 'Total'}, inplace = True)

df.append(df_cumprod2)

Calculation for ID2 columns:

df.loc['Total'] = df.iloc[:, df.columns.get_level_values(1)=='ID2'].mean()

This creates two "Total" rows, is there a way to merge them together so that they appear side by side in the same row (as shown in the expected output above)? Or apply two different formulas based on the condition of the column name to the same row?


问:
EC2 AWS getting error when i try to open http://ec2-15-185-40-86.me-south-1.compute.amazonaws.com:8000/
This site can’t be reached
ec2-15-185-40-86.me-south-1.compute.amazonaws.com refused to connect.
Try:

Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED

My aws ec2 site is stopped automatically. Please help me out how to make it working.


问:
Python Error: Cannot Convert Expression to Float (Negative Square Root Problem)
I am trying to plot but it seems the square root can't work with negative number.

This is the problem I am trying to solve:

this is the errors:

```<code>RuntimeWarning: invalid value encountered in sqrt
  x2 = ((16/1)*(y-5+2))**(1/2)
/home/browni/LasthrimProjection/Python/plot.py:58: RuntimeWarning: invalid value encountered in sqrt
  Y3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.cos(V)
/home/browni/LasthrimProjection/Python/plot.py:59: RuntimeWarning: invalid value encountered in sqrt
  Z3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.sin(V)
</code>```

This is my MWE:

```<code># Compare the plot at xy axis with the solid of revolution toward x and y axis
# For region bounded by the line y = (3/16)x^2 + 3 and y = (1/16)x^2 + 5
# Plotting the revolution of the bounded region
# can be done by limiting the np.linspace of the y, u, and x_inverse values
# You can determine the limits by finding the intersection points of the two functions.

import matplotlib.pyplot as plt
import numpy as np
import sympy as sy

def r1(x):
    return (3/16)*(x**2) + 3 - 2

def r2(x):
    return (1/16)*(x**2) + 5 - 2

def r3(x):
    return ((16/3)*(x - 3 + 2)) ** (1/2)

def r4(x):
    return ((16/1)*(x - 5 + 2)) ** (1/2)

def vx(x):
    return np.pi*(r2(x)**2 - r1(x)**2)

def vy(x):
    return np.pi*(r3(x)**2 - r4(x)**2)

x = sy.Symbol("x")
vx = sy.integrate(vx(x), (x, 0, 4))
vy = sy.integrate(vy(x), (x, 0, 6))

n = 200

fig = plt.figure(figsize=(14, 7))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, projection='3d')
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224, projection='3d')

y = np.linspace(0, 6, n)

x1 = ((16/3)*y -3 + 2) ** (1/2)
x2 = ((16/1)*y - 5 + 2) ** (1/2)
t = np.linspace(0, np.pi * 2, n)

u = np.linspace(0, 4, n)
v = np.linspace(0, 2 * np.pi, n)
U, V = np.meshgrid(u, v)

X = U
Y1 = ((3/16) * (U**2) + 3 - 2) * np.cos(V)
Z1 = ((3/16) * (U**2) + 3 - 2) * np.sin(V)

Y2 = ((1/16) * (U**2) + 5 - 2) * np.cos(V)
Z2 = ((1/16) * (U**2) + 5 - 2) * np.sin(V)

Y3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.cos(V)
Z3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.sin(V)

Y4 = (((16/1)*(x - 5 + 2)) ** (1/2)) * np.cos(V)
Z4 = (((16/1)*(x - 5 + 2)) ** (1/2)) * np.sin(V)

ax1.plot(x1, y, label='$y = (3/16)x^2 + 3 - 2$')
ax1.plot(x2, y, label='$y = (1/16)x^2 + 5 - 2$')
ax1.legend()

ax1.set_title('$f(x)$')
ax2.plot_surface(X, Y3, Z3, alpha=0.3, color='red', rstride=6, cstride=12)
ax2.plot_surface(X, Y4, Z4, alpha=0.3, color='blue', rstride=6, cstride=12)
ax2.set_title("$f(x)$: Revolution around $y$ \n Volume = {}".format(vy))

# find the inverse of the function
x_inverse = np.linspace(0, 6, n)
y1_inverse = np.power((16/3)*(x_inverse - 3 + 2), 1/2)
y2_inverse = np.power((16/1)*(x_inverse - 5 + 2), 1/2)

ax3.plot(x_inverse, y1_inverse, label='Inverse of $(3/16)x^2 + 3 - 2$')
ax3.plot(x_inverse, y2_inverse, label='Inverse of $y = (1/16)x^2 + 5 - 2$')
ax3.set_title('Inverse of $f(x)$')
ax3.legend()

ax4.plot_surface(X, Y1, Z1, alpha=0.3, color='red', rstride=6, cstride=12)
ax4.plot_surface(X, Y2, Z2, alpha=0.3, color='blue', rstride=6, cstride=12)
ax4.set_title("$f(x)$: Revolution around $x$ \n Volume = {}".format(vx))

plt.tight_layout()
plt.show()

</code>```

how to fix this?

Body:
I am trying to plot but it seems the square root can't work with negative number.

This is the problem I am trying to solve:

this is the errors:

RuntimeWarning: invalid value encountered in sqrt
  x2 = ((16/1)*(y-5+2))**(1/2)
/home/browni/LasthrimProjection/Python/plot.py:58: RuntimeWarning: invalid value encountered in sqrt
  Y3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.cos(V)
/home/browni/LasthrimProjection/Python/plot.py:59: RuntimeWarning: invalid value encountered in sqrt
  Z3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.sin(V)

This is my MWE:

# Compare the plot at xy axis with the solid of revolution toward x and y axis
# For region bounded by the line y = (3/16)x^2 + 3 and y = (1/16)x^2 + 5
# Plotting the revolution of the bounded region
# can be done by limiting the np.linspace of the y, u, and x_inverse values
# You can determine the limits by finding the intersection points of the two functions.

import matplotlib.pyplot as plt
import numpy as np
import sympy as sy

def r1(x):
    return (3/16)*(x**2) + 3 - 2

def r2(x):
    return (1/16)*(x**2) + 5 - 2

def r3(x):
    return ((16/3)*(x - 3 + 2)) ** (1/2)

def r4(x):
    return ((16/1)*(x - 5 + 2)) ** (1/2)

def vx(x):
    return np.pi*(r2(x)**2 - r1(x)**2)

def vy(x):
    return np.pi*(r3(x)**2 - r4(x)**2)

x = sy.Symbol("x")
vx = sy.integrate(vx(x), (x, 0, 4))
vy = sy.integrate(vy(x), (x, 0, 6))

n = 200

fig = plt.figure(figsize=(14, 7))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, projection='3d')
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224, projection='3d')

y = np.linspace(0, 6, n)

x1 = ((16/3)*y -3 + 2) ** (1/2)
x2 = ((16/1)*y - 5 + 2) ** (1/2)
t = np.linspace(0, np.pi * 2, n)

u = np.linspace(0, 4, n)
v = np.linspace(0, 2 * np.pi, n)
U, V = np.meshgrid(u, v)

X = U
Y1 = ((3/16) * (U**2) + 3 - 2) * np.cos(V)
Z1 = ((3/16) * (U**2) + 3 - 2) * np.sin(V)

Y2 = ((1/16) * (U**2) + 5 - 2) * np.cos(V)
Z2 = ((1/16) * (U**2) + 5 - 2) * np.sin(V)

Y3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.cos(V)
Z3 = (((16/3) * (U - 3 + 2)) ** (1/2)) * np.sin(V)

Y4 = (((16/1)*(x - 5 + 2)) ** (1/2)) * np.cos(V)
Z4 = (((16/1)*(x - 5 + 2)) ** (1/2)) * np.sin(V)

ax1.plot(x1, y, label='$y = (3/16)x^2 + 3 - 2$')
ax1.plot(x2, y, label='$y = (1/16)x^2 + 5 - 2$')
ax1.legend()

ax1.set_title('$f(x)$')
ax2.plot_surface(X, Y3, Z3, alpha=0.3, color='red', rstride=6, cstride=12)
ax2.plot_surface(X, Y4, Z4, alpha=0.3, color='blue', rstride=6, cstride=12)
ax2.set_title("$f(x)$: Revolution around $y$ \n Volume = {}".format(vy))

# find the inverse of the function
x_inverse = np.linspace(0, 6, n)
y1_inverse = np.power((16/3)*(x_inverse - 3 + 2), 1/2)
y2_inverse = np.power((16/1)*(x_inverse - 5 + 2), 1/2)

ax3.plot(x_inverse, y1_inverse, label='Inverse of $(3/16)x^2 + 3 - 2$')
ax3.plot(x_inverse, y2_inverse, label='Inverse of $y = (1/16)x^2 + 5 - 2$')
ax3.set_title('Inverse of $f(x)$')
ax3.legend()

ax4.plot_surface(X, Y1, Z1, alpha=0.3, color='red', rstride=6, cstride=12)
ax4.plot_surface(X, Y2, Z2, alpha=0.3, color='blue', rstride=6, cstride=12)
ax4.set_title("$f(x)$: Revolution around $x$ \n Volume = {}".format(vx))

plt.tight_layout()
plt.show()

how to fix this?


问:
Using jimp to get hex values of pixels of an image and then find a square within it in NOde.JS
I have an image, then the goal is to detect large rectangles of the same color within an image.

So if an image is uploaded with a square picture of a duck on the left, and a square picture of another duck on top, the largest rectangle can be found toward the bottom right side.

Here is what I know so far:

```<code>Jimp.read("imagepath", function (err, image) {
    image.getPixelColor(x, y);
});
</code>```

What I think I should do somehow to accomplish this, is:

```<code>Jimp.read("imagepath", function (err, image) {
    for(var x = 0; x < Jimp.Pixel.Length?; x++) {
       for(var y...) {

           image.getPixelColor(x, y);
     }
});
</code>```

So somehow converting the image into an array of pixels that is like a 2d array. Then going through the array and using code to find patterns that match a rectangle.

Body:
I have an image, then the goal is to detect large rectangles of the same color within an image.

So if an image is uploaded with a square picture of a duck on the left, and a square picture of another duck on top, the largest rectangle can be found toward the bottom right side.

Here is what I know so far:

Jimp.read("imagepath", function (err, image) {
    image.getPixelColor(x, y);
});

What I think I should do somehow to accomplish this, is:

Jimp.read("imagepath", function (err, image) {
    for(var x = 0; x < Jimp.Pixel.Length?; x++) {
       for(var y...) {

           image.getPixelColor(x, y);
     }
});

So somehow converting the image into an array of pixels that is like a 2d array. Then going through the array and using code to find patterns that match a rectangle.


问:
client script search field saved record
i learning client script with condition that if the field at credit memo(custbody_me_credit_memo_purposes) is true and when checked in accept payment, the record will not save and give message "your record not save"

```<code>function checkCredit(custbody_me_credit_memo_purposes){
            var searchCredit = search.create({
                   type: "creditmemo",
           filters:
           [
              ["type","anyof","CustCred"],
              "AND",
              ["custbody_me_credit_memo_purposes","anyof","1"],
              "AND",
              ["mainline","is","T"],
              "AND",
              ["internalid",search.Operator.ANYOF, internalid]
           ],
           columns:
           [
              search.createColumn({name: "entity", label: "Name"}),
              search.createColumn({name: "custbody_me_credit_memo_purposes", label: "ME - Credit Memo Purposes"}),//this field has true
              search.createColumn({name: "custbody_me_list_tagihan_trans", label: "ME - List Tagihan"})
           ]
        });
            var startRow = 0;
            var pageSize = 1000;
            var listCredit = [];
        do{
            var resultSearch = searchCredit.run().getRange({
                start: startRow,
                end: startRow + pageSize
            });
        for (x = 0; x < resultSearch.length; x++){
            listCredit.push(resultSearch[x].getValue(resultSearch[x].columns[0]))
        }
        startRow += pageSize
        }while (resultSearch.length === pageSize);
        log.debug('listCredit',searchCredit)
        return listCredit;

    }

    function saveRecord(context){
        var rec = context.currentRecord;
        var numLines = rec.getLineCount({
            sublistId: 'credit'
        });
        log.debug('numLines credit',numLines)

        var checkedidCredit = []
        for (var i = 0; i > numLines; i++) {
            var pickedCred = rec.getSublistValue({
                sublistId:'credit',
                fieldId:'apply',
                line: i
            });//checkbox when i checked
            if(pickedCred == 'T' || pickedCred == true){
                var docNum = rec.getValue({

                    fieldId:'custbody_me_credit_memo_purposes'
                });

                checkedidCredit.push(docNum)
            }
        }
        log.debug('check credit',docNum)
        //validate save (true or false)
        if(checkedidCredit != ""){
            var creditVal = checkCredit(checkedidCredit)

            if(creditVal.length == 'true' || creditVal.length == 1){
                alert("your record not save"+creditVal)
                return false;
            }
        }
                else{
                    return true;
                }
        }
        return{
            saveRecord: saveRecord
        }
</code>```

i have tired but no action. even the error it now showing this field. can your tell me about this problem to coding this. thanks for your helping

Title: client script search field saved record

Body:
i learning client script with condition that if the field at credit memo(custbody_me_credit_memo_purposes) is true and when checked in accept payment, the record will not save and give message "your record not save"

function checkCredit(custbody_me_credit_memo_purposes){
            var searchCredit = search.create({
                   type: "creditmemo",
           filters:
           [
              ["type","anyof","CustCred"],
              "AND",
              ["custbody_me_credit_memo_purposes","anyof","1"],
              "AND",
              ["mainline","is","T"],
              "AND",
              ["internalid",search.Operator.ANYOF, internalid]
           ],
           columns:
           [
              search.createColumn({name: "entity", label: "Name"}),
              search.createColumn({name: "custbody_me_credit_memo_purposes", label: "ME - Credit Memo Purposes"}),//this field has true
              search.createColumn({name: "custbody_me_list_tagihan_trans", label: "ME - List Tagihan"})
           ]
        });
            var startRow = 0;
            var pageSize = 1000;
            var listCredit = [];
        do{
            var resultSearch = searchCredit.run().getRange({
                start: startRow,
                end: startRow + pageSize
            });
        for (x = 0; x < resultSearch.length; x++){
            listCredit.push(resultSearch[x].getValue(resultSearch[x].columns[0]))
        }
        startRow += pageSize
        }while (resultSearch.length === pageSize);
        log.debug('listCredit',searchCredit)
        return listCredit;

    }

    function saveRecord(context){
        var rec = context.currentRecord;
        var numLines = rec.getLineCount({
            sublistId: 'credit'
        });
        log.debug('numLines credit',numLines)

        var checkedidCredit = []
        for (var i = 0; i > numLines; i++) {
            var pickedCred = rec.getSublistValue({
                sublistId:'credit',
                fieldId:'apply',
                line: i
            });//checkbox when i checked
            if(pickedCred == 'T' || pickedCred == true){
                var docNum = rec.getValue({

                    fieldId:'custbody_me_credit_memo_purposes'
                });

                checkedidCredit.push(docNum)
            }
        }
        log.debug('check credit',docNum)
        //validate save (true or false)
        if(checkedidCredit != ""){
            var creditVal = checkCredit(checkedidCredit)

            if(creditVal.length == 'true' || creditVal.length == 1){
                alert("your record not save"+creditVal)
                return false;
            }
        }
                else{
                    return true;
                }
        }
        return{
            saveRecord: saveRecord
        }

i have tired but no action. even the error it now showing this field. can your tell me about this problem to coding this. thanks for your helping


问:
Wrong Oracle database and JDBC Driver version printed by Hibernate SettingsFactory
Our Java program has been installed on the RHEL 8.5 OS platform. And for database operations in our application, we use hibernate (version hibernate-3.2.7.ga.jar).
Additionally, we are utilizing the JDBC driver(version 19.15) and the Oracle 19c(version 19.15) database. But in the log file, we found the below details which were printed from the hibernate.jar file.

15:23:46,949 INFO  [SettingsFactory] RDBMS: Oracle, version: Oracle
Database 11g Release 11.1.0.0.0 - Production 15:23:46,949 INFO
[SettingsFactory] JDBC driver: Oracle JDBC driver, version: 10.2.0.3.0

The code part in SettingsFactory.class file from hibernate.jar is,

```<code>  ConnectionProvider connections = createConnectionProvider(props);
  Connection conn = connections.getConnection();
          try {
              DatabaseMetaData meta = conn.getMetaData();
              databaseName = meta.getDatabaseProductName();
              databaseMajorVersion = getDatabaseMajorVersion(meta);
              log.info("RDBMS: " + databaseName + ", version: " + meta.getDatabaseProductVersion() );
              log.info("JDBC driver: " + meta.getDriverName() + ", version: " + meta.getDriverVersion() );
              }
</code>```

We are confident that nowhere uses 11g, both from the code and the DB side. However, it is yet unclear how Hibernate retrieves this information.

Additionally, I've developed a Java class for the application that uses DatabaseMetaData objects to check the database information.
Here, I just received the 19c specifics of the projected results.

```<code>Product Name - Oracle
Product Version - Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.15.0.0.0
Driver Name - Oracle JDBC driver
Driver Version - 19.15.0.0.0
URL - jdbc:oracle:thin:@XX:XX:XX:XX:1521:XXXX
RDBMS: Oracle, version: Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.15.0.0.0
JDBC driver: Oracle JDBC driver, version: 19.15.0.0.0
</code>```

Please let us know the table from which hibernate retrieves the database details and how to overcome the above issue.

Thanks in advance.

Body:
Our Java program has been installed on the RHEL 8.5 OS platform. And for database operations in our application, we use hibernate (version hibernate-3.2.7.ga.jar).
Additionally, we are utilizing the JDBC driver(version 19.15) and the Oracle 19c(version 19.15) database. But in the log file, we found the below details which were printed from the hibernate.jar file.

15:23:46,949 INFO  [SettingsFactory] RDBMS: Oracle, version: Oracle
Database 11g Release 11.1.0.0.0 - Production 15:23:46,949 INFO
[SettingsFactory] JDBC driver: Oracle JDBC driver, version: 10.2.0.3.0

The code part in SettingsFactory.class file from hibernate.jar is,

  ConnectionProvider connections = createConnectionProvider(props);
  Connection conn = connections.getConnection();
          try {
              DatabaseMetaData meta = conn.getMetaData();
              databaseName = meta.getDatabaseProductName();
              databaseMajorVersion = getDatabaseMajorVersion(meta);
              log.info("RDBMS: " + databaseName + ", version: " + meta.getDatabaseProductVersion() );
              log.info("JDBC driver: " + meta.getDriverName() + ", version: " + meta.getDriverVersion() );
              }

We are confident that nowhere uses 11g, both from the code and the DB side. However, it is yet unclear how Hibernate retrieves this information.

Additionally, I've developed a Java class for the application that uses DatabaseMetaData objects to check the database information.
Here, I just received the 19c specifics of the projected results.

Product Name - Oracle
Product Version - Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.15.0.0.0
Driver Name - Oracle JDBC driver
Driver Version - 19.15.0.0.0
URL - jdbc:oracle:thin:@XX:XX:XX:XX:1521:XXXX
RDBMS: Oracle, version: Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.15.0.0.0
JDBC driver: Oracle JDBC driver, version: 19.15.0.0.0

Please let us know the table from which hibernate retrieves the database details and how to overcome the above issue.

Thanks in advance.


问:
How to define with credentials in groovy script in extended choice parameters
i need to withcredntails i am storing my AWS keys in Jenkins credentials</p>
```<code>def command = 'aws acm list-certificates --query "CertificateSummaryList[?DomainName=='*.osdemo.cf'].CertificateArn" --output text'
def proc = command.execute()
proc.waitFor()

def output = proc.in.text
def exitcode= proc.exitValue()
def error = proc.err.text

if (error) {
    println "Std Err: ${error}"
    println "Process exit code: ${exitcode}"
    return exitcode
}

//println output.split()
return output.tokenize()
</code>```

Body:
i need to withcredntails i am storing my AWS keys in Jenkins credentials

def command = 'aws acm list-certificates --query "CertificateSummaryList[?DomainName=='*.osdemo.cf'].CertificateArn" --output text'
def proc = command.execute()
proc.waitFor()

def output = proc.in.text
def exitcode= proc.exitValue()
def error = proc.err.text

if (error) {
    println "Std Err: ${error}"
    println "Process exit code: ${exitcode}"
    return exitcode
}

//println output.split()
return output.tokenize()