Saturday, May 14, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How sklearn.metrics.r2_score works

Posted: 14 May 2022 05:44 AM PDT

I tried to implement formula from Wikipedia but results are different. Why is it so?

y_true = np.array([1, 1, 0])  y_pred = np.array([1, 0, 1])    r2 = r2_score(y_true, y_pred)  print(r2)    y_true_mean = statistics.mean(y_true)  r2 = 1 - np.sum((y_true - y_pred) ** 2) / np.sum((y_true - y_true_mean) ** 2)  print(r2)  

-1.9999999999999996
0.0

Closing a PostGreSQL Client Connection in Rust

Posted: 14 May 2022 05:44 AM PDT

I am new to Rust and I am using the postgres crate. I am trying to create a wrapper around the postgresql client, and I have defined this Struct:

pub struct PostGresSqlClient {          user_name: String,          host_name: String,          port: String,          client: Client,      }  

Later, I am trying to implement the Drop trait on this Struct. Right now, it just tries to close the connection to the Client, but later it may do different things.

impl Drop for PostGresSqlClient {          fn drop(&mut self) {              self.client.close();          }      }  

However, I am running into this issue:

error[E0507]: cannot move out of `self.client` which is behind a mutable reference     --> data_lib/src/lib.rs:106:13      |  106 |             self.client.close();      |             ^^^^^^^^^^^ move occurs because `self.client` has type `Client`, which does not implement the `Copy` trait  

I do not know how to resolve this and any help would be appreciated.

How can i solved in cnn, weight error slope of kernel

Posted: 14 May 2022 05:44 AM PDT

i can't solved my class study question

what is the answer?\n

this is question

In CNN, when there are two adjacent layers (i,j), layer I consists of 12 nodes, filter size is 3 and stride is 3. The output vectors of the nodes of the layer I are [1,2,3,1,2,3,1,2,3,1,2,3]. The names of the filters are w1, w2, and w3, respectively, and the error slopes of the nodes of the layer J are [1, 2, 3, 4]. In this case, what is the weighted error slope of w2?

i tried search how solved but i cant' find

VBA code for recalling the SelHeight Property Value of a subform is not working - syntax error?

Posted: 14 May 2022 05:44 AM PDT

My aim: I have a subform in a form and I want to pick up the value of one field in a user selected record in the subform and populate a field in my form using that value. I am using .Selheight to determine the number of records selected in the subform. the code goes like this:

    If Me.Frm_ICD10CMCodes.Form.SelHeight = 0 Then          MsgBox "Please select one record. You have selected " & Me.Frm_ICD10CMCodes.Form.SelHeight & " records.", vbOKOnly, "Dr Talking:"      ElseIf Me.Frm_ICD10CMCodes.Form.SelHeight = 1 Then          'Copy the diagnosis in the diagnosis box      ElseIf Me.Frm_ICD10CMCodes.Form.SelHeight > 1 Then          MsgBox "Please select only one record.", vbOKOnly, "Dr Talking:"      End If  

Now the problem is that the Form.SelHeight Property keeps returning the Value 0 no matter how many records I select when I run the code.

I must be doing something wrong. , but the I'm not getting an error.

Find first and last value greater than 0 in a list in python

Posted: 14 May 2022 05:44 AM PDT

It is a list based on a solar measurement system so in the first hours of the day it will be 0 and in the last hours of the day it will be 0, so I am interested in obtaining the minimum and maximum value greater than 0; example:

total_solar=[0,0,0,0,0,100,200,200,300,200,200,120,0,0,0,0,0]

Runtime complexity of insertion sort for half sorted array and half reversed sorted

Posted: 14 May 2022 05:44 AM PDT

Wondering what is the average runtime complexity for half sorted and half reverse sorted array. For example the array: [0,7,2,5,4,3,6,1], number on every even index is sorted and number on odd index is reverse sorted. Would the runtime be O(n) or O(n^2)? Thanks!

Having trouble choosing what to use for modern desktop GUI with a C++ backend [closed]

Posted: 14 May 2022 05:43 AM PDT

I want to create a gui for my C++ application that's modern and simple, with animated prompts, "bouncy" buttons etc. A good example of what I want it to look like is the Spotify desktop client. Basically the modern electron app look and feel but with something that's compatible with c++ and reasonably fast. Are there any frameworks/libraries/languages that could help me achieve this modern non-native look specifically on windows or am I forced to draw the ui from the ground up? If that's my only option, do you have any resources on how to do so?

Python: What am i suppose to do to have a value of 0 inside a square bracket

Posted: 14 May 2022 05:43 AM PDT

How can I put value of 0 in the square bracket below?

'SARIMAX(3, 0, 2)x(1, 0, [], 4)'  

This is my desired output

'SARIMAX(3, 0, 2)x(1, 0, [0], 4)'  

What should I do to make this possible.

Split an array to chunks by parameter (JavaScript)

Posted: 14 May 2022 05:44 AM PDT

I got this array:

const arr = [    { level: 1, name: 'Steph Curry' },    { level: 2, name: 'Ja Morant' },    { level: 2, name: 'Luka Doncic' },    { level: 3, name: 'Chris Paul' },    { level: 3, name: 'Devin Booker' },    { level: 4, name: 'Nikola Jokic' }  ]  

I need to split it to chunks but not by chunk length (found many answers to that) but by parameter - in this case level.

Meaning the output should be:

[['Steph Curry'], ['Ja Morant', 'Luka Doncic'], ['Chris Paul', 'Devin Booker'], ['Nikola Jokic']]

How can I do this?

Auto-scroll in div with React

Posted: 14 May 2022 05:43 AM PDT

Having a div with dynamic logs content (props.logs), How can I auto scroll to the bottom?

  <div className='rc_logsContent' ref={logsRef}>      <Collapse isOpened={isOpened} >         <p           dangerouslySetInnerHTML={{__html: formatNote(props.logs)}}         />      </Collapse>    </div>   

WSL2 run e2fsck on startup

Posted: 14 May 2022 05:43 AM PDT

I have a WSL2 Ubuntu image running on Win11.

I'd like to run e2fsck on the root filesystem of that image.

Funning fsck on a mounted filesystem is not recommended.

I've found instructions for making changes to the file system config for Ubuntu where grub is managing the initial boot-up process. Those instructions don't seem to be working for WSL2...

Looking at the output from dmesg I can see a recommendation to run e2fsck:

[    1.787637] sd 0:0:0:0: [sda] Attached SCSI disk  [    1.792078] EXT4-fs (sda): mounted filesystem with ordered data mode. Opts: (null)  [    2.967150] Adding 4194304k swap on /swap/file.  Priority:-2 extents:3   across:4210688k  [    3.737253] scsi 0:0:0:1: Direct-Access     Msft     Virtual Disk     1.0  PQ: 0   ANSI: 5  [    3.738205] sd 0:0:0:1: Attached scsi generic sg1 type 0  [    3.738490] scsi 0:0:0:2: Direct-Access     Msft     Virtual Disk     1.0  PQ: 0   ANSI: 5  [    3.739060] sd 0:0:0:1: [sdb] 695784 512-byte logical blocks: (356 MB/340 MiB)  [    3.739078] sd 0:0:0:2: Attached scsi generic sg2 type 0  [    3.739138] sd 0:0:0:1: [sdb] Write Protect is on  [    3.739139] sd 0:0:0:1: [sdb] Mode Sense: 0f 00 80 00  [    3.739355] sd 0:0:0:1: [sdb] Write cache: disabled, read cache: enabled, doesn't   support DPO or FUA  [    3.739661] sd 0:0:0:2: [sdc] 536870912 512-byte logical blocks: (275 GB/256 GiB)  [    3.739662] sd 0:0:0:2: [sdc] 4096-byte physical blocks  [    3.739713] sd 0:0:0:2: [sdc] Write Protect is off  [    3.739714] sd 0:0:0:2: [sdc] Mode Sense: 0f 00 00 00  [    3.739820] sd 0:0:0:2: [sdc] Write cache: enabled, read cache: enabled, doesn't   support DPO or FUA  [    3.741712] sd 0:0:0:2: [sdc] Attached SCSI disk  [    3.741758] sd 0:0:0:1: [sdb] Attached SCSI disk  [    3.743742] EXT4-fs (sdb): mounted filesystem without journal. Opts: (null)  [    3.748036] EXT4-fs (sdc): warning: maximal mount count reached, running e2fsck is   recommended  [    3.749945] EXT4-fs (sdc): mounted filesystem with ordered data mode. Opts:   discard,errors=remount-ro,data=ordered  

Any suggestions on how to actually get e2fsck to run gratefully received.

String to DataFrame using split and for syntax?

Posted: 14 May 2022 05:44 AM PDT

How this DataFrame make to below table?

pd.DataFrame({'a':['COD21C0517_1~519_1/526_1/527_1/541_1/581_1/582_1/585_1/586_1']},index=['AAA'])

index a
AAA COD21C0517_1
AAA COD21C0518_1
AAA COD21C0519_1
AAA COD21C0526_1
AAA COD21C0527_1
AAA COD21C0541_1
AAA COD21C0581_1
AAA COD21C0582_1
AAA COD21C0585_1
AAA COD21C0586_1

getting NoSuchWindowException while scrapping twitter usernames using Selenium

Posted: 14 May 2022 05:43 AM PDT

I have been trying to scrape twitter usernames by going inside the followers page but the issue is if I leave my pc there after some time I get this exception and also If I look into the browser it shows me this error browser error check screenshot here

I am attaching my code here but I think it has some issue with scrolling when I scroll to much the memory of browser goes small. but still thinking of knowing the actual reason.

while scrolling:          sleep(1)          page_cards = driver.find_elements_by_xpath('.//div[@data-testid="primaryColumn"]//section//span[contains(text(), "@")]')          print('cards length:',len(page_cards))          for card in page_cards[-20:]:              count = count + 1              tweet = get_tweet_data(card)              if tweet:                  tweet_id = ''.join(tweet)                  if tweet_id not in tweet_ids:                      tweet_ids.add(tweet_id)                      data.append(tweet)                      writer.writerow([tweet])                      print(count, 'username: ', tweet)      #                 postgres_insert_query = """ INSERT INTO tbl_username (id, u_name) VALUES (%s,%s)"""      #                 record_to_insert = (count, tweet)      #                 cursor.execute(postgres_insert_query, record_to_insert)      #                 connection.commit()      scroll_attempt = 0      while True:          driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')          sleep(2)          curr_position = driver.execute_script("return window.pageYOffset;")          if last_position == curr_position:              scroll_attempt += 1                if scroll_attempt >= 3:                  scrolling = False                  break              else:                  sleep(2)           else:              last_position = curr_position              break  

How to fetch only CH_PAY_MODE loan_id from this table?

Posted: 14 May 2022 05:44 AM PDT

enter image description here

There is two loan_id given in the table, per month collection using CH or CL, so i wanted to fetch loan_id wich is not paying in CL in any month.

strip all strings in list of specific character

Posted: 14 May 2022 05:44 AM PDT

I have been looking for an answer to this for a while but keep finding answers about stripping a specific string from a list.

Let's say this is my list of strings

stringList = ["cat\n","dog\n","bird\n","rat\n","snake\n"]

But all list items contain a new line character (\n)

How can I remove this from all the strings within the list?

RegExp constructor adding unexpected comma to pattern

Posted: 14 May 2022 05:44 AM PDT

trigoOperators is an array containing some trigonometric operations.

The goal is to create a regular expression that parses a string equation into an array.

The problem is that the resulting regular expression is adding an unexpected comma to the pattern as shown in the example below

const trigoOperators = ['abs', 'sqrt']    const rexExp = new RegExp('\\W|(-?\\d+)' + `${(trigoOperators.map(o => `|(${o})`))}`, 'g')    console.log(rexExp)

The expected result is /\W|(-?\d+)|(abs)|(sqrt)/g while the current result is /\W|(-?\d+)|(abs),|(sqrt)/g (notice the added comma)

Hello I have a problem with this assembly program

Posted: 14 May 2022 05:43 AM PDT

I have a problem with this assembly program:

.model small  .code  start :   mov ax , [1100h]   mov bx , [1101h]  add ax , bx   JS Negative   JZ Nul   mov [2000h] , ax   JMP fin  Negative :   mov [3000h] , ax  JMP fin  Nul :  mov bx , ax  JMP fin   fin :  mov ax , 4c00h  int 21h  end start  

please describe the problem you have with the code
once done that, delete these (bold) comments

Distribution function of the linear combination of standardized student-t quantiles

Posted: 14 May 2022 05:44 AM PDT

here to submit the following question to you.

Assume to observe 2 quantiles, x and y, associated with the z% probability. These quantiles are generated by 2 non-independent standardized student-t distributions X and Y.

In case of linear combination of x and y with the Correlation matrix, its distribution function is known?

Can I assume any initial condition on x and y in order to have a known distribution function of the linear combination?

MySQL Get same yesterday day of previous week data

Posted: 14 May 2022 05:44 AM PDT

Let say yesterday is Wednesday, I need to get all records from same day (Wednesday) of previous week. How to achieve this in MySQL statement condition?

How to display Images from Internet in JavaFX(not working)?

Posted: 14 May 2022 05:43 AM PDT

I want to take the url of a image from a API, which I did. I also get the URL of the image that I want, but the image doesn't display in the JavaFX Scene.

String json2=readUrl("https://imsea.herokuapp.com/api/1?q=moon");  images.Images i=gson.fromJson(json2,images.Images.class);  System.out.println(i.getResult1());  String path = i.getResult1();  Image image = new Image(new FileInputStream(i.getResult1()));  img_spaceObject.setImage(image);  

RestSharp baseUrl with a space

Posted: 14 May 2022 05:44 AM PDT

I google it and I pass hours try figure how to do it and I can't figure: I try get Response from web Api with RestSharp v107 in .net 5 Is works well when I do the baseUrl with out space but when I try the one I need with space don't works, I got 404 not found: Same issue in postman. But when I do in Chrome or in edge with the code encoding (%20) works perfectly the browser return the expected Json

example : new Resclient("https://thedomain.name.com/local") works well but if I try new Resclient("https://thedomain.name.com/my User") or

new Resclient("https://thedomain.name.com/my%20User")  

I try the with the .AddUrlSegment("elemement", "my%20User" ) or .AddUrlSegment("elemement", "my%20User" )

I think the issue is the url get decode/encode and the space have been remove...

I see we have

UseUrlEncoder(Func<string,string>)  

but I don't how to use it... And if that will solve my issue

Please helps

Thanks in advance

SPARK SHELL when executing in windows getting error: not found: value spark

Posted: 14 May 2022 05:44 AM PDT

I am actually new to spark and I want to configure spark in my system so I can learn it. I saw tutorial online and installed it but when I am running spark shell I get this


Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties  Setting default log level to "WARN".  To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).  Welcome to        ____              __       / __/__  ___ _____/ /__      _\ \/ _ \/ _ `/ __/  '_/     /___/ .__/\_,_/_/ /_/\_\   version 3.2.1        /_/    Using Scala version 2.13.5 (Java HotSpot(TM) 64-Bit Server VM, Java 18)  Type in expressions to have them evaluated.  Type :help for more information.  22/05/13 23:38:19 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable  java.lang.IllegalAccessError: class org.apache.spark.storage.StorageUtils$ (in unnamed module @0x2d2ffcb7) cannot access class sun.nio.ch.DirectBuffer (in module java.base) because module java.base does not export sun.nio.ch to unnamed module @0x2d2ffcb7    ... 61 elided                ^         error: not found: value spark                ^         error: not found: value spark  

can you please help me out

Add the result of a Powershell Start-Process to a file instead of replacing it with -RedirectStandardOutput

Posted: 14 May 2022 05:44 AM PDT

I use the following command in Powershell to convert files in the background but would like to log the results all in one file. Now the -RedirectStandardOutput replaces the file each run.

foreach ($l in gc ./files.txt) {Start-Process -FilePath "c:\Program Files (x86)\calibre2\ebook-convert.exe" -Argumentlist "'$l' '$l.epub'" -Wait -WindowStyle Hidden -RedirectStandardOutput log.txt}  

I tried with a redirect but then the log is empty. If possible I would like to keep it a one-liner.

foreach ($l in gc ./files.txt) {Start-Process -FilePath "c:\Program Files (x86)\calibre2\ebook-convert.exe" -Argumentlist "`"$l`" `"$l.epub`"" -Wait -WindowStyle Hidden *> log.txt}  

Websocket error when using a proxy_pass to CRA development server using Nginx and Docker

Posted: 14 May 2022 05:44 AM PDT

I am trying to proxy_pass in Nginx to my React dev server at localhost:3000. It currently works but I am seeing an error in my console which I am unsure will cause any issues down the road:

WebSocketClient.js:16 WebSocket connection to 'ws://localhost/ws' failed:

Nginx.conf:

upstream backend {      server backend:8000;  }    upstream frontend {      server frontend:3000;  }    server {      listen 80;            location / {          proxy_pass http://frontend$request_uri;          proxy_set_header Host $http_host;      }            location /api/ {          proxy_pass http://backend;          proxy_set_header Host $http_host;      }        location /admin/ {          proxy_pass http://backend;          proxy_set_header Host $http_host;      }  }  

I have tried adding WDS_SOCKET_PORT=0 to the frontend .env file also tried adding:

    proxy_http_version 1.1;      proxy_set_header Upgrade $http_upgrade;      proxy_set_header Connection "Upgrade";  

...as suggested in other SO posts. Neither worked.

What is this error? How can I fix it?

Is there any way to update value in Redis?

Posted: 14 May 2022 05:43 AM PDT

I use Redis Desktop Manager in windows 10 for caching in ASP.Net Core 3.1 by StackExchange.Redis library.

Except delete and then again add new Key-Value in Redis, is there any way for updating value by key?

SwiftUI update navigation bar title color

Posted: 14 May 2022 05:44 AM PDT

How to change the navigation bar title color in SwiftUI

NavigationView {              List{                  ForEach(0..<15) { item in                      HStack {                          Text("Apple")                              .font(.headline)                              .fontWeight(.medium)                              .color(.orange)                              .lineLimit(1)                              .multilineTextAlignment(.center)                              .padding(.leading)                              .frame(width: 125, height: nil)                              Text("Apple Infinite Loop. Address: One Infinite Loop Cupertino, CA 95014 (408) 606-5775 ")                              .font(.subheadline)                              .fontWeight(.regular)                              .multilineTextAlignment(.leading)                              .lineLimit(nil)                          }                  }              }              .navigationBarTitle(Text("TEST")).navigationBarHidden(false).foregroundColor(.orange)              }  

I have tried with .foregroundColor(.orange) but it is not working

also tried .navigationBarTitle(Text("TEST").color(.orange))

Any help ?

How to remove/adjust the space between RadioListTiles inside ListView?

Posted: 14 May 2022 05:43 AM PDT

I have created a ListView of RadioListTiles, however there is too much space between the RadioListTiles. How can I remove them? There is no property of padding inside its constructor.

This is my code

 @override Widget build(BuildContext context) {        Column taskView = Column(          children: <Widget>[            ...,          Expanded(            child: ListView.builder(              padding: EdgeInsets.all(0.0),              itemCount: tasks.length,              itemBuilder: (context, index) {                return RadioListTile<String>(                  title:  Text(tasks[index]),                  value: tasks[index],                  groupValue: selectedRadio,                  onChanged: (val){                      setSelectedRadio(val);                  }                );              },            ),          ),        ],      );      return Scaffold(        body: taskView,      );    }  

enter image description here

How can I remove internal padding on a RadioListTile so I can use 3 RadioListTiles in a row?

Posted: 14 May 2022 05:44 AM PDT

I am pretty new to Flutter and Dart and I can't seem to find any hints for this particular topic. I am trying to put 3 RadioListTiles in a Row like so:

Row(          children: [            Expanded(              child:RadioListTile<GoalSelection>(                title: Text(                  'Net',                  style: Theme.of(context).textTheme.body1,                ),                value: GoalSelection.net,                groupValue: _goalSelection,                onChanged: (GoalSelection value) {                  setState(() {                    _goalSelection = value;                  });                },              ),            ),            Expanded(              child: RadioListTile<GoalSelection>(                title: Text(                  'Gross',                  style: Theme.of(context).textTheme.body1,                ),                value: GoalSelection.gross,                groupValue: _goalSelection,                onChanged: (GoalSelection value) {                  setState(() {                    _goalSelection = value;                  });                },              ),            ),            Expanded(              child: RadioListTile<GoalSelection>(                title: Text(                  'Salary',                  style: Theme.of(context).textTheme.body1,                ),                value: GoalSelection.salary,                groupValue: _goalSelection,                onChanged: (GoalSelection value) {                  setState(() {                    _goalSelection = value;                  });                },              ),            ),          ],        ),  

The buttons layout fine, but there seems to be a lot of wasted space for the label. I put a screenshot of what it currently looks like below. I have tried wrapping the Expanded, the RadioListTile, and the Text in Padding widgets (all one at a time) to manually set the padding to 0, but it didn't do anything. I have also tried to change Expanded to Flexible even though I didn't think that would change anything. I am at a loss now. Is there any way to get this layout to work? I am kind of assuming it is something really dumb that I am doing.

Layout inspector showing padding

Why do we add an _ (underscore) before a variable name? [duplicate]

Posted: 14 May 2022 05:43 AM PDT

Why do we add an _ (underscore) before a variable name in Java while variable declaration?

I have tried on Google Search, but I actually couldn't find the exact answer for it.

Is it just a type of declaration as the user wants or is there any proper mechanism and reason to do so?

MVC Return Partial View as JSON

Posted: 14 May 2022 05:44 AM PDT

Is there a way to return an HTML string from rendering a partial as part of a JSON response from MVC?

    public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)      {          if (ModelState.IsValid)          {              if(Request.IsAjaxRequest()                  return PartialView("NotEvil", model);              return View(model)          }          if(Request.IsAjaxRequest())          {              return Json(new { error=true, message = PartialView("Evil",model)});          }          return View(model);      }  

No comments:

Post a Comment