Saturday, March 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Different results when using the st.gumbel_r.ppf()

Posted: 20 Mar 2021 08:10 AM PDT

I want to calculate the value for a given probability using the st.gumbel_r.ppf(). I'm comparing it with the analytical solution and it is giving me completely different results, anyone knows why? I obtained the values for the scale and location using the moment of methods

P_class = [0.14285714, 0.28571429, 0.42857143, 0.57142857, 0.71428571, 0.85714286, 0.999999]    u = 8.590342451210152  alpha = 0.1841827435642898    h_class1 = st.gumbel_r.ppf(P_class, scale = u, loc = alpha)  h_class = u-np.log(-np.log(P_class))/alpha    Results  h_class1 = [ -5.53466431,  -1.7516637 ,   1.6076281 ,   5.17091797, 9.54112426,  16.24661736, 118.86414528]  h_class = [4.97583548,  7.36682128,  9.49000861, 11.74212971, 14.50424958, 18.74235061, 83.60013865]  

I'm want to get the same h_class results when using the scipy function

How does Lex/Flex match multiple user defined regex

Posted: 20 Mar 2021 08:09 AM PDT

I am new to the compiler and I am learning to implement a scanner using the algorithm provided by the Dragon Book (Compiler Principles). I have implemented the algorithm 3.36 that translates a regex directly to a DFA.

As a scanner uses many regexes to define different tokens, I am interested in how Flex deals with the multiple DFAs after translation. A very intuitive thought would be to try every DFA and simulate the DFA. If a token reaches the end state in the DFA then returns the corresponding token identifier.

However, I would also argue that this method is might be more computationally intensive than the regex-to-NFA and then NFA-to-DFA approach even if the trials can be done using concurrent threads. Because in that method one can just combine all the NFAs generated with the $\epsilon$ action from the start state and run the algorithm to form a complete DFA.

Thanks a lot for your help!

Node js ftp uploading from form

Posted: 20 Mar 2021 08:09 AM PDT

I need to upload files through ftp to a server. I have the code to upload files but how can I get form files selected from user to upload thenm?

Thanks in advance

How can you modify nginx config file to work 2 projects on different platform?

Posted: 20 Mar 2021 08:09 AM PDT

I have a node project hosted with Nginx on an AWS server(Ubuntu). Now I want to deploy a PHP project in a folder of that project. Is it possible to do so?

Example: My node project is on the domain - dummydomain.com I want to host a PHP project on - dummydomain.com/testing/

This is my config file.

server {        listen 80 default_server;          server_name abc.com;          return 301 https://$host$request_uri;    }  server {          listen 443;          server_name abc.com;            root /var/www/html;            index index.html index.htm index.php;            #this is where node project runs          location / {                  proxy_set_header   X-Forwarded-For $remote_addr;                  proxy_set_header   Host $http_host;                  proxy_pass         "http://127.0.0.1:5000";          }          # I want to run PHP project in this directive          location /testing {                  #alias /var/www/html;                  #index index.html index.php;                  try_files $uri $uri/ /index.php$is_args$args;          }          location ~ \.php$ {                  fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;                  include snippets/fastcgi-php.conf;                  fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;          }          location ~ /\.ht {                  deny all;          }  }  

By these settings, I have achieved to run dummydomain.com/testing/ but can't run dummydomain.com/testing/index.php or dummydomain.com/testing/testing.php or any sort of PHP file.

R - How to use a variable created in a for loop as a column name in a data frame?

Posted: 20 Mar 2021 08:09 AM PDT

I have 2 questions; In first FOR, I create a variable name called "column", and in each loop I want to use this column name as a grouping variable. In second FOR, I want to assign some values to dataframe variables by using again "column" variable. Lets say in first loop I want "df$var1 <- 999", but it does not work. Thank you.

# Dataset  df <- tibble(    var1 = c(rep("a", 5), rep("b", 5)),    var2 = c(rep("c", 3), rep("d", 7)),    var3 = rnorm(10)  )    # First Loop  for(x in 1:2) {    column <- paste0("var", x)    df2 <- df %>% group_by(column) %>% summarize(total = n())  }    # Second Loop  for(x in 1:2) {    column <- paste0("var", x)    df$column <- 999  }  

React-Virtualized Table onRowClick highlight row

Posted: 20 Mar 2021 08:08 AM PDT

I am working on React-Virtualized Table, on row selection or on row click I want to highlight the selected row/rows and also provide the unselect option(remove the highlight), it should work how a checkbox row selection works but I don't want to use a Checkbox, any work around for this?

How to display user friendly error messages from python - SQlAlchemy SQL server to display in the front end

Posted: 20 Mar 2021 08:08 AM PDT

I am using Flask and SQLAlchemy - SQL Server. I get the below error message:

"(pyodbc.IntegrityError) ('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Violation of UNIQUE KEY constraint 'UQ__Model__67DC63B54CA06362'. Cannot insert duplicate key in object 'dbo.Models'. The duplicate key value is (model111111111t). (2627) (SQLExecDirectW); [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)")\n[SQL: INSERT INTO [Models] ([ModelName], [Description], [DateCreated]) OUTPUT inserted.[ModelID] VALUES (?, ?, ?)]\n[parameters: ('model111111111t', 'test description', datetime.datetime(2021, 3, 20, 20, 36, 9, 290718))]\n(Background on this error at: http://sqlalche.me/e/14/gkpj)"

But i just want to show only "Name already exists" or "Duplicate Name Error" to display in the front end.

How do I extract that from the exception.?

In a do..while loop is the word "do" a keyword? And what is the purpose of "do"?

Posted: 20 Mar 2021 08:09 AM PDT

What exactly is the function of do in the following code?

public class DoWhileLoop {      public static void main(String[] args) {          int i=0;              do {                          System.out.println("The value is "+ i);              i++;          }          while(i<5);       }  }  

React resend request to server on page reload

Posted: 20 Mar 2021 08:08 AM PDT

I have a table the gets a data using Fetch requests,everything works fine and the code is implemented using react hooks and function,the problem is when the user hits "F5" and refresh the page all the data is removed and I don't know how to detect the refresh and resend the request to the servers,If there a way to fetch the request again on page refresh using react functions/hooks? by the way I am a beginner to react any help is appreciated

filling missing value code error in pyspark

Posted: 20 Mar 2021 08:09 AM PDT

I am trying two ways of filling out missing value, one works the other doesn't. (i'm on google colab), with following version of pyspark

!pip install pyspark==3.0.1 py4j==0.10.9  

Code works:

data.na.fill(value=0, subset=["data", "open"]).na.fill(value='unknown', subset=["high"]).show(5)  

Code that not work

data.na.fill({'high':0}).show(5)  

Returns me error:

/usr/local/lib/python3.7/dist-packages/pyspark/sql/utils.py in raise_from(e)    AnalysisException: Cannot resolve column name "market.cap" among (_c0, symbol, data, open, high, low, close, volume, adjusted, market.cap, sector, industry, exchange); did you mean to quote the `market.cap` column?;  

A friendly guest left a comment just now (but then quickly deleted for some reason) that the error is due to the col name "market.cap". Thank him for pointing it out. I should be more clearer about my major concern here. Why the "market.cap" col causing issue with the 2nd line of the command but not the first line of command. And how may I fix this col name?

covert Timestamp obj to float

Posted: 20 Mar 2021 08:09 AM PDT

I am trying to convert a datetime to float, but I'm getting an error

the code:

import pandas as pd  NameD = "03/02/2021 0:00"  NameD = pd.to_datetime(NameD).values.astype(float)  

the error:

AttributeError: 'Timestamp' object has no attribute 'values'  

can you please help me to solve that error?

Restyling Bootstrap with Typescript styled component

Posted: 20 Mar 2021 08:08 AM PDT

I have the whole Navbar basically copied from React Bootstrap. I am using Typescript's styled components in my app and I came to the point where I actually don't know how to restyle default style from Bootstrap.

Example (React Bootstrap navabar):

<Navbar bg="light" expand="lg">    <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>    <Navbar.Toggle aria-controls="basic-navbar-nav" />    <Navbar.Collapse id="basic-navbar-nav">      <Nav className="mr-auto">        <Nav.Link href="#home">Home</Nav.Link>        <Nav.Link href="#link">Link</Nav.Link>        <NavDropdown title="Dropdown" id="basic-nav-dropdown">          <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>          <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>        </NavDropdown>      </Nav>    </Navbar.Collapse>  </Navbar>  

Of course each component has to be imported form Bootstrap e.g.

import Navbar from 'react-bootstrap/Navbar';  

So I can not import it again from my style.ts, where I would normally styled it. If I would use css, then of course I would give it a className and style based on that, but here is totally different system, in which I am new.

Is there any way how can I customise Bootstrap ?

I also tried React styling style={{color: "pink"}} to implement in elements e.g to Nav.Link, but obviously it doesn't work.

Detecting mouse cursor type change over element

Posted: 20 Mar 2021 08:08 AM PDT

It is possible to get the current cursor type without predefined cursor style, like when the mouse pass over text, link..

Something like that :

document.addEventListener('mouseover', (e) => {    console.log(e.'cursorType')  });  

I would like to get in the console.log the state of the cursor like : pointer, text, move, wait...

I find some kind of solution in jQuery but I am looking for one in pure vanilla JS

Thank for your answer

How do I add a new key-value pair in a smart way to a dict if the key is already contained in the dict?

Posted: 20 Mar 2021 08:08 AM PDT

As the title says, I want to write a function that automatically detects, when adding a key value pair, if this key is already included in the dict.

If this is the case, an ascending number should be added to the key and the slightly changed key value pair should be added to the dict.

As seen in the following example, my current horrible approach is to query each case individually, how can I do that in a smart way for any number of keys with the same name.

            if "begin time" in day_dict.keys():                  if "begin time2" in day_dict.keys():                      if "begin time3" in day_dict.keys():                          day_dict["begin time4"] = value                      else:                          day_dict["begin time3"] = value                   else:                      day_dict["begin time2"] = value              else:                  day_dict["begin time"] = value  

write mode in python not creating new file

Posted: 20 Mar 2021 08:09 AM PDT

  • I was executing a program for creating a folder consisting multiplication table of 2 to 20, and for that, I am opening files of a folder that don't exist, and I am opening that with write mode, which ideally should create those folders and files if it doesn't exist but its giving error: FileNotFoundError: [Errno 2] No such file or directory: 'tables/mul_2.txt'
  • Program:
   #multiplication folder  for i in range(2,21):     with open(f"tables/mul_{i}.txt", 'w') as f:         for j in range(1,11):             f.write(f"{i}X{j}={i*j}")  
  • Python version: 3.8.5

Typescript infer type by sibling property

Posted: 20 Mar 2021 08:09 AM PDT

I'm trying to make a framework with typescript.
and I need a compile time data check.

My typescript interface code

type TypeInfo = 'string' | 'number' | 'boolean';    type GetType<T extends PrimitiveTypeInfo> = T extends 'string'    ? string    : T extends 'number'    ? number    : T extends 'boolean'    ? boolean    : never;    interface StateInfo {    // TypeInfo    type: TypeInfo;    default: GetType<this['type']>;  }  

Expected (compile time)

// OK  const test1: StateInfo = {    type: 'number',    default: 1,  };    // Bad ('default' property is not number or 'type' property is not 'string')   const test2: StateInfo = {    type: 'number',    default: 'test',  };  

But, the typescript compile the code without any errors.
How can I declare type of 'default' property correctly?

Get the message content into a command [discord.py]

Posted: 20 Mar 2021 08:07 AM PDT

I'm searching to create a bot which create private text channels and then delete them. But with my actual code everyone can delete and rename other peolple's rooms. So, I'd like to create a message that contains the author ID when the bot create the room, and then when someone try to delete or rename the room, the bot goes to search the message and checks if the message author is the same who created the room.

In a few words, I'd like to know what there's in a past message, read and compare it with the message author.

For now I have this:

@client.command()  async def getmsg(ctx):      guild = ctx.guild      channel = ctx.channel      bot = client.user        msg = get(await channel.history(limit=100).flatten(), author=bot)  

This isn't convincing me because I'd like to have directly the message content (if it's possible).

Thanks in advance.

Anomaly detection and explanation

Posted: 20 Mar 2021 08:08 AM PDT

I was given a dataset with 500 features after OHE wich looks like this: dataset

Class = 1 means "anomaly", class = 0 is "normal". So basicly my task is simple ML classification. But another part of this task is to explain, why this data (wich has class = 1) is anomaly. I wanted to build some graphs detect anomalies on pictures, but the problem is that OHE is used and I can't do anything about it.

I've started with using feature_importances_, but they don't give enough information specifically about class = 1.

rf = RandomForestClassifier()  rf.fit(X,y)  plt.plot(rf.feature_importances_)  

Could you please tell me, what statistic methods (or maybe something else) should I use to explain why some of my data are anomalous?

Wrap Object.entries(myObject) output inside html tags

Posted: 20 Mar 2021 08:08 AM PDT

I need to output the key-value pairs of a large object on the web page. I was relieved to find that Object.entries() can do just that. But I would need some control over the formatting so I would like to wrap the keys inside a span tag with a a special class and the values with a span tag with a special class.

Is there any easy way of wrapping the output of Object.entries with html tags?

This is the code I used for writing the object on the page:

$('.mycontainer').html(Object.entries(myObject));  

How to get and set environment variable from mingw, c++ (or c)

Posted: 20 Mar 2021 08:09 AM PDT

I am writing a program that needs to set environment variables for the current process from mingw (to be available for subprocesses when using system(...)-call).

I know how to do in linux, and windows with msvc and clang. However, I cannot find any goood examples on how to do it with mingw-g++.

How do I implement functions that has this kind of behaviour?

// Example usage:  void setVar(std::string name, std::string value) {      // How to do this  }    std::string getVar(std::string name) {      // ... and this  }  

If you want to answer in c, feel free to omit std::string :)

Edit:

When using setenv (the linux way) i get:

src/env.cpp: In function 'void appendEnv(std::string, std::string)':  src/env.cpp:46:5: error: 'setenv' was not declared in this scope; did you mean 'getenv'?     46 |     setenv(name.c_str(), value.c_str(), 1);        |     ^~~~~~        |     getenv  

When using _putenv_s (the way i have used for msvc and clang on windows) I get.

src/env.cpp: In function 'int setenv(const char*, const char*, int)':  src/env.cpp:16:12: error: '_putenv_s' was not declared in this scope; did you mean '_putenv_r'?     16 |     return _putenv_s(name, value);        |            ^~~~~~~~~        |            _putenv_r  

How to get sql dump for a oracle sql query from Oracle SQL Developer?

Posted: 20 Mar 2021 08:10 AM PDT

I am writing an sql query in Oracle 12c Database which is returning around 500K records. I need to take dump or export it in a readable format in a faster way.

I am connecting using Oracle Sql Developer for running the query.

Appreciate your help in advance.

how do I check if a number can be expressed as x raised to power y?

Posted: 20 Mar 2021 08:08 AM PDT

I need x^y == integer (input) cant figure out how to do so I CANT USE MATH IMPORT tried to do something like this:

a = int(input("Please Enter any Positive Integer:"))   power = 1   i = 1     while(i <= a):       power = power * a      i = i + 1  

for example the input is 8 i need the program to find x^y==8 in this case the output needs to be: x=2 y=3 hope its clear thanks in advance.

Servlet.service() for servlet [dispatcherServlet] in context with path

Posted: 20 Mar 2021 08:09 AM PDT

I am getting below error while creating spring maven rest webservice. It works fine when i use postman to test post request on the api for ocbc. But when i tried to do post request for citi, i got the following error: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause. And in my postman it shows error: "Internal Server Error", Status :"500"

Error:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause    java.lang.NullPointerException: null          at com.example.service.impl.PaymentServiceImpl.addCitiPayment(PaymentServiceImpl.java:22) ~[classes/:na]          at com.example.controller.PaymentController.addCitiPayment(PaymentController.java:25) ~[classes/:na]          at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]          at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]          at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]          at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]          at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.4.jar:5.3.4]          at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.4.jar:5.3.4]              at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060) ~[spring-webmvc-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962) ~[spring-webmvc-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.4.jar:5.3.4]          at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.4.jar:5.3.4]          at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.43.jar:4.0.FR]          at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.4.jar:5.3.4]          at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.43.jar:4.0.FR]          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.43.jar:9.0.43]          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.4.jar:5.3.4]          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.4.jar:5.3.4]          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.4.jar:5.3.4]          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]          at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]          at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.43.jar:9.0.43]          at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]  

Here is my code:

BankOCBCDAO

package com.example.repository;    import com.example.model.BankOCBC;    import org.springframework.data.jpa.repository.JpaRepository;  import org.springframework.stereotype.Repository;    @Repository  public interface BankOCBCDAO extends JpaRepository<BankOCBC, Integer>{    }  

BankCitiBankDAO

package com.example.repository;    import com.example.model.BankCitiBank;    import org.springframework.data.jpa.repository.JpaRepository;  import org.springframework.stereotype.Repository;    @Repository  public interface BankCitiBankDAO extends JpaRepository<BankCitiBank, Integer>{    }  

PaymentController

package com.example.controller;    import com.example.model.BankCitiBank;  import com.example.model.BankOCBC;  import com.example.service.PaymentService;  import com.example.dto.ApiResponse;    import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.web.bind.annotation.PostMapping;  import org.springframework.web.bind.annotation.RequestBody;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RestController;      @RestController  @RequestMapping(path="/payment")  public class PaymentController {            @Autowired      private PaymentService paymentService;              @PostMapping("/citi")      public ApiResponse addCitiPayment(@RequestBody BankCitiBank bankCitiBank) {          return paymentService.addCitiPayment(bankCitiBank);      }        @PostMapping("/ocbc")      public ApiResponse addOCBCPayment(@RequestBody BankOCBC bankOCBC) {          return paymentService.addOCBCPayment(bankOCBC);      }  }  

PaymentService

package com.example.service;    import com.example.model.BankCitiBank;  import com.example.model.BankOCBC;  import com.example.dto.ApiResponse;    public interface PaymentService {      ApiResponse addCitiPayment(BankCitiBank bankCitiBank);      ApiResponse addOCBCPayment(BankOCBC bankOCBC);  }  

PaymentServiceImpl

package com.example.service.impl;    import com.example.dto.ApiResponse;  import com.example.model.BankCitiBank;  import com.example.model.BankOCBC;  import com.example.service.PaymentService;  import com.example.repository.BankCitiBankDAO;  import com.example.repository.BankOCBCDAO;    import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Service;      @Service  public class PaymentServiceImpl implements PaymentService{      @Autowired      private BankOCBCDAO bankOCBCDAO;      private BankCitiBankDAO bankCitiBankDAO;            @Override      public ApiResponse addCitiPayment(BankCitiBank bankCitiBank) {          bankCitiBankDAO.save(bankCitiBank);          return new ApiResponse(200, "CitiBank Payment Successful", null);       }        @Override      public ApiResponse addOCBCPayment(BankOCBC bankOCBC) {          bankOCBCDAO.save(bankOCBC);          return new ApiResponse(200, "OCBC Payment Successful", null);                 }        }  

Please advise what is wrong in my code. Thanks in advance.

Also can i ask if there any recommendation ways to encrypt the data value obtained from api before added into the database.

strtof() function misplacing decimal place

Posted: 20 Mar 2021 08:08 AM PDT

I have a string "1613894376.500012077" and I want to use strtof in order to convert to floating point 1613894376.500012077 . The problem is when I use strtof I get the following result with the decimal misplaced 1.61389e+09 . Please help me determine how to use strof properly.

Discord.js UnhandledPromiseRejectionWarning: TypeError: message.guild.channels.cache.array.forEach is not a function

Posted: 20 Mar 2021 08:08 AM PDT

I'm trying to create a ticket function for my discord.js bot, but when I click on an emoji, it throws an error. Here is the code:

let messageEmbed = await message.channel.send(ticketEmbed);  messageEmbed.react("1️⃣");  messageEmbed.react("2️⃣");  messageEmbed.react("3️⃣");  messageEmbed.react("4️⃣");    client.on('messageReactionAdd', async (reaction, user) => {    if (reaction.message.partial) await reaction.message.fetch();    if (reaction.partial) await reaction.fetch();    if (user.bot) return;    if (!reaction.message.guild) return;        if (reaction.emoji.name === firstreaction) {      const categoryId = "822577084223586364"      var username =  reaction.message.guild.members.cache.get(user.id)      var userDiscriminator =  reaction.message.guild.members.cache.get(user.id).discriminator      var ticketExists = false        message.guild.channels.cache.array.forEach(channel => {        if(channel.name == userName.toLowerCase() + "-" + userDiscriminator){          var ticketExists = true          message.username.send("You already have an open ticket!")            return        }      })      if (ticketExists) return        message.guild.channels.create("Playerreport-" +username.toLowerCase + userDiscriminator, {type: "text"})  

React Native cannot find Android Studio or SDK

Posted: 20 Mar 2021 08:08 AM PDT

OS: Ubuntu

Running npx react-native doctor yields:

results

As you can see react native does not recognise the existence of android studio or sdk.

I have configured my environment variables to the following:

export ANDROID_HOME=$HOME/opt/Android/Sdk  export PATH=$PATH:$ANDROID_HOME/emulator  export PATH=$PATH:$ANDROID_HOME/tools  export PATH=$PATH:$ANDROID_HOME/tools/bin  export PATH=$PATH:$ANDROID_HOME/platform-tools  

Exact path of Android studio:

/opt/android-studio-ide/android-studio/bin  

Exact path of Android Sdk:

/opt/Android/Sdk  

Android studios is installed and working, and by extension so is the sdk. I have followed the instructions on how to setup react and ensured all the correct packages have been added. See here:

Snippets from Android Studio

SDK Platforms

SDK Tools 1 SDK Tools 2

EF Core - Populate an UnMapped column from raw SQL?

Posted: 20 Mar 2021 08:10 AM PDT

I have a query where I'm doing a Count on a specific join/column - If I run this code with the "Clicks" [NotMapped] attribute removed, all the values populate properly - but then inserts fail since "Clicks" is not a valid column name. When I mark the column as [NotMapped] then it's not populating from this statement. How can I use raw SQL and populate a [NotMapped] column?

Code:

var query = db.URLs.FromSqlRaw(          @"SELECT [u].[Key], [u].[Url], COUNT(c.Id) AS [Clicks]            FROM[URLs] AS[u]            LEFT JOIN[Clicks] AS[c] ON[u].[Key] = [c].[ShortUrlKey]            GROUP BY[u].[Key], [u].[Url]")            .AsQueryable<ShortURL>();                var urls = query.ToList();  

Model (works for inserts, but doesn't populate Clicks property):

public class ShortURL  {      public string Key { get; set; }      public string Url { get; set; }        [NotMapped()]      public int Clicks { get; set; } // doesn't populate from raw query  }  

Model (works for queries, but fails on inserts)

    public class ShortURL  {     public string Key { get; set; }     public string Url { get; set; }     public int Clicks { get; set; } // not in DB  }  

SCIKIT FastICA Maximum Number of Iterations

Posted: 20 Mar 2021 08:09 AM PDT

I'm getting the following error: "FastICA did not converge. Consider increasing tolerance or the maximum number of iterations".

So, considering the documentation here: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.FastICA.html , what is the maximum number of iterations that I can plug into the max_iter parameter?

Squash first N commits of git history / keep the rest as is [duplicate]

Posted: 20 Mar 2021 08:09 AM PDT

Consider the following problem:

  • Private Project containing some credentials in the early stages
  • We want to go open source
  • We need to get rid of the credentials in the history
  • credentials are not in single files but in code
  • Complicated history with several merges, pull requests etc.

What I want to do:

Squash all commits from root up to an arbitrary commit with clean state to one big 'Initial commit'.

When I do:

git rebase -i --root  

And squash the first commits together:

pick Initial commit \  fixup dirty1        |  fixup dirty2        | Squash these to one, to remove credentials.  fixup dirty3        |  fixup clean1        /  pick clean2  pick clean3  ...  ...  

I have to rebase everything and resolve all merge conflicts again after that.

How can I just squash the first N commits without having to resolve the entire history including the merge conflicts after the N + 1 commit.

Node require absolute path

Posted: 20 Mar 2021 08:09 AM PDT

I have a directory that looks like this:

-- app/     |- models/        |- user.js     |- config.json  

I want my user.js file to require config.json. Right now I'm using require('/config') but this is not working. What am I doing wrong? I'd like to avoid using require('../config').

No comments:

Post a Comment