Thursday, October 21, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to post a Json with a base64 file using python request?

Posted: 21 Oct 2021 09:02 AM PDT

Right now I am programming an API with python, and I have the following problem: I have to POST the following JSON to an url:

prescription = {  "Name": "file_name", # This is a string  "Body" : "xxx",# (File in base64 format)  "ParentId" : "xxxxxxxxxxxxxxxxxx", # This is a string  "ContentType" : "xxxxx/xxx" # This is a string  }  

But when I try to do the following request:

requests.post(url, prescription)  

I am getting the following error:

TypeError: Object of type bytes is not JSON serializable  

How can I make a request for posting that JSON? Is it even possible?

Thanks for your help.

Can we use Relu activation fuction with linear regression?

Posted: 21 Oct 2021 09:02 AM PDT

Relu is non-linear regression. Today, someone say we can apply ReeLu with House price prediction. I think House price prediction is linear regression and how we can apply it?

Query to find three instances the same in one column, but must be have three different results in another column

Posted: 21 Oct 2021 09:02 AM PDT

I have a table like the following:

InspectDate | Serial Number | Reference | Error | PartNumber

I need to find the data of errors that occurred in the last 10 days. I can get that, but then I need to find only those problems that occurred on the same reference, but only if they happen to be on three or more different serial numbers.

Please let me know if I need to provide any more info. I have tried using count and filtering by those with more than 3, but that only shows me any one serial number that has more than three errors on that reference.

1 million concurrent database connections

Posted: 21 Oct 2021 09:02 AM PDT

In https://cloud.google.com/sql/docs/quotas, it mentioned that "Cloud Run services are limited to 100 connections to a Cloud SQL database.". Assume I deploy my service as Cloud Run, what's the right way to handle 1 million concurrent connections? Can cloud spanner enables this - I can't find documentation discussing maximum concurrent connections on cloud spanner maximum concurrent connection with Cloud Run.

Python to rename files in a directory/folder to csv

Posted: 21 Oct 2021 09:02 AM PDT

I have written a small script to hopefully iterate through my directory/folder and replace act with csv. Essentially, I have 11 years worth of files that have a .act extension and I just want to replace it with .csv

'''  import os    files = os.listdir("S:\\folder\\folder1\\folder2\\folder3")    path = "S:\\folder\\folder1\\folder2\\folder3\\"    #print(files)    for x in files:        new_name = x.replace("act","csv")        os.rename(path+x,path+new_name)        print(new_name)    '''  

When I execute this, it worked for the first five files and then failed on the sixth with the following error: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'S:\folder\folder1\folder2\folder3\file_2011_06.act' -> 'S:\folder\folder1\folder2\folder3\file_2011_06. csv'

When I searched for "S:\folder\folder1\folder2\folder3\file_2011_06.act" in file explorer, the file opens. Are there any tips on what additional steps I can take to debug this issue?

Admittedly, this is my first programming script. I'm trying to do small/minor things to start learning. So, I likely missed something... Thank you!

How to change the entry point name in a simple assembly program?

Posted: 21 Oct 2021 09:02 AM PDT

Having such a simple Win32 assembly program

.386  .model flat, c  option casemap :none    ;includelib C:\Users\Darek\Dev\VC\lib\libcmt.lib  ;includelib C:\Users\Darek\Dev\VC\lib\legacy_stdio_definitions.lib    EXTERN printf :PROC ; declare printf    .data      HelloWorld db "Hello j World!:-)", 0    .code  main PROC    push offset HelloWorld    call printf      add esp, 4    ret  main ENDP  END  

I'd like to change the entry point name from the standard main to say my_start, so I've changed the name of the main function to my_start

...  my_start PROC  ...  my_start ENDP  ...  

and then linked like below

link /ENTRY:my_start /SUBSYSTEM:CONSOLE HelloWorld.obj libcmt.lib  

but getting the linker error:

undefined external symbol _main called in _mainCRTStartup Why does the linker ingres the ENTRY option? What I'm doing wrong and what to do to get it working?

P.S.

I'm using the ml and link provided with my MSVC 2019

React initialise state based on object

Posted: 21 Oct 2021 09:02 AM PDT

If my data is in this structure from an api:

{    title: "Title",     id: 1,    description: "example desc"  }  

What would I pass in as the initial value to the state object? i.e

interface ObjectData {      title: string,      id: number,      description: string  }    const [fetchData, setFetchData] = React.useState<ObjectData>(?// here);  

Android Studio - Setting up a Project hierarchy that checks source files in real time (Ant style)

Posted: 21 Oct 2021 09:01 AM PDT

I've got two Android applications (not libraries) on Android Studio:

  • App A can be built and run on its own;
  • App B can be built and run on its own, but needs App A as a dependency.

I've currently set up the hierarchy as instructed in this question (and similar ones), but the result is that the current state of App A was copied inside the App B project folder as a module, so any changes I make inside the actual source files in the project folder of App A are never visible from App B.

What I'd like to achieve is for App B to reference the source files in the App A project folder, and possibly take notice of the changes I make to App A source files in real time without having to manually rebuild/resync anything (i.e. if I delete a referenced variable in App A and save, Android Studio should immediately show the error in App B, etc...).

Basically how an extremely basic Ant project hierarchy you can set up in a couple clicks in Java IDEs would work.

How would I accomplish that in Android Studio?

Which ER-model notation does Elasticsearch default to?

Posted: 21 Oct 2021 09:01 AM PDT

As asked in the title I'd like to know which ER-model notation Elasticsearch defaults to. In terms of context, I've received a database schema which I cannot openly share, but the following screenshot shows one of the obscure looking relations.

An obscure looking relation, is this Crow's Foot Notation or something else?

After a few quick Google searches I was surprised at the fact that I couldn't find any official statement about Elasticsearch's default notation. While searching I came across this post where the OP showed a similar screenshot, but without the obscure double-dashed-line notation: https://discuss.elastic.co/t/convert-relational-schema-to-elasticsearch-mapping/72291

Is this Crow's Foot Notation, or something else?

Linking <option> with onclick [duplicate]

Posted: 21 Oct 2021 09:02 AM PDT

I am building my own shopping website, and I got stuck in this part:

<label for="option">Option</label>  <select id="option">      <optgroup>          <option onclick="changeValueA()">Option A</option>          <option onclick="changeValueB()">Option B</option>      </optgroup>  </select>    <p>You choosed Option <span id="option-value"></span></p>    <script>            function changeValueA(){                   document.getElementById("option-value").innerHTML = "Option A";        }        function changeValueB(){                   document.getElementById("option-value").innerHTML = "Option B";        }    </script>

I want to make "option-value" display "Option A" if changeValueA() is called by clicking the Option A from <select>, and I want to make "option-value" display "Option B" if changeValueB() is called by clicking the Option B from <select>.

However, the code doesn't work. It would be really grateful if you help me this part!

CSS Variable Sometimes Is All Lowercase in Browser but Hump Case in the Varables.css File

Posted: 21 Oct 2021 09:02 AM PDT

We have a web application and we just implemented CSS variables. The variables are defined in a "variables.css" file and are hump case in the file. When the user is on the same network where the website is hosted everything works fine. When the user is outside the network and hitting the web application from the internet the variables are sent to the browser in all lower case which does not apply the desired styling since the variable is hump case on the control (verified using Chrome debugger) but now lowercase in the variables sent to the browser. If I open the Chrome debugger and change the variable name back to the hump case version the styling is applied.

This is very strange behavior and I can't understand what could be causing the variables to be sent to the browser as all lower case.

Any help would be greatly appreciated.

Thanks!

variables.css:

:root {      /* Header Colors (also used for site tour popups) */      --headerBackground: #E5E5DF;      --headerTextColor: #003D79;      /* This is used for hoverable items in the header (benefit picker, fund picker, and user account)      Typically should be slightly lighter than the 'headerBackground' color */      --headerBackgroundLighten: #578d9c;      /* Navigation Menu Colors (also affects drop down menus in the header - benefit picker, fund picker, and user account) */      --menuBackground: #f7f7f7;      --menuLinkColor: #003D79;      /* Hover colors for menu links (also affects drop down menus in the header - benefit picker, fund picker, and user account)*/      --menuLinkHoverColor: #343434;      --menuLinkHoverBackgroundColor: #e1e1e1;      /* Background color of the highlighted menu item for the current page (typically should be slighlty darker than the 'menuLinkHoverBackgroundColor') */      --menuLinkSelectedBackgroundColor: rgba(34, 153, 110, 0.33);      /* Grid Header, Footer and Pager colors (also controls date picker header colors and menu data list colors) */      --gridHeaderBackgroundColor: #627482;      --gridHeaderColor: white;      /* Link Colors */      --linkColor: #007B94;      --linkHoverColor: #000308;      /* Primary Button Colors */      --primaryButtonBackgroundColor: #6c757d;      --primaryButtonTextColor: white;      --primaryButtonHoverBackgroundColor: #5a6268;      --primaryButtonHoverTextColor: white;      /* Secondary Button Colors*/      --secondaryButtonBackgroundColor: #989898;      --secondaryButtonTextColor: #212529;      --secondaryButtonHoverBackgroundColor: #858585;      --secondaryButtonHoverTextColor: white;      /* Footer Colors */      --footerBackgroundColor: #E5E5DF;      --footerColor: #003D79;  }  

ASP.NET Styling From Page:

 <style>          .popover-title {              background-color: #E5E5DF;              background-color: var(--headerBackground);              color: #003D79;              color: var(--headerTextColor);              font-weight: 400 !important;          }            .elementCover {              position: absolute;              width: 100%;              height: 100%;              left: 0;              top: 0;              z-index: 1000;          }      </style>  

RoR: devise gem after edit password

Posted: 21 Oct 2021 09:02 AM PDT

I'm looking for a similar function after_sending_reset_password_instructions_path_for but for the password change password_path

after filling the password it is redirected to the url password_path (edit password token)

it connects me to the page as if I were logging in but I would like to make a page that redirects and tells it that the password has been changed without logging in

java.lang.NullPointerException: Cannot invoke "service" because "this.contentService" is null

Posted: 21 Oct 2021 09:02 AM PDT

Hey When i am making a get request to my spring microservice i am recieving this error and same from my other microservices as well i am sorry i am new with microservices and spring i think its something related to my jwt filter can someone help me with this

2021-10-21 21:10:31.006 ERROR 10252 --- [nio-8082-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "com.bloggie.contentservice.service.contracts.ContentService.getAccessibleContent()" because "this.contentService" is null] with root cause    java.lang.NullPointerException: Cannot invoke "com.bloggie.contentservice.service.contracts.ContentService.getAccessibleContent()" because "this.contentService" is null      at com.bloggie.contentservice.controller.ContentController.getPublicContent(ContentController.kt:27) ~[classes/:na]      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[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:567) ~[na:na]      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.10.jar:5.3.10]      at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.10.jar:5.3.10]      at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.53.jar:4.0.FR]      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.10.jar:5.3.10]      at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.53.jar:4.0.FR]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113) ~[spring-web-5.3.10.jar:5.3.10]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at com.bloggie.contentservice.configurations.filters.JwtRequestFilter.doFilterInternal(JwtRequestFilter.kt:41) ~[classes/:na]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.5.2.jar:5.5.2]      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.3.10.jar:5.3.10]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.10.jar:5.3.10]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.10.jar:5.3.10]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.10.jar:5.3.10]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.10.jar:5.3.10]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.53.jar:9.0.53]      at java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]  

JWT Request filter

package com.bloggie.contentservice.configurations.filters    import com.axisbank.server.utils.JwtUtil  import com.bloggie.contentservice.service.DefaultUserDetailService  import org.springframework.security.authentication.UsernamePasswordAuthenticationToken  import org.springframework.security.core.context.SecurityContextHolder  import org.springframework.security.web.authentication.WebAuthenticationDetailsSource  import org.springframework.stereotype.Component  import org.springframework.web.filter.OncePerRequestFilter  import javax.servlet.FilterChain  import javax.servlet.http.HttpServletRequest  import javax.servlet.http.HttpServletResponse    @Component  class JwtRequestFilter(      private val defaultUserDetailService: DefaultUserDetailService,  ) : OncePerRequestFilter() {      override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {          val authorizationHeader = request.getHeader("Authorization")            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {              println(authorizationHeader)              val jwt = authorizationHeader.substring(7)                val userName = JwtUtil.extractUsername(jwt)              val claims = JwtUtil.extractAllClaims(jwt)                if (claims["authorities"] != null && SecurityContextHolder.getContext().authentication == null) {                  val userDetails = defaultUserDetailService.loadUserByUsername(userName)                  println(userDetails.authorities)                  if (JwtUtil.validateToken(jwt, userDetails)) {                      val userNamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken(                          userDetails, null, userDetails.authorities                      )                      userNamePasswordAuthenticationToken                          .details = WebAuthenticationDetailsSource().buildDetails(request)                      SecurityContextHolder.getContext().authentication = userNamePasswordAuthenticationToken                  }              }          }          chain.doFilter(request, response)      }  }  

Content Service

package com.bloggie.contentservice.service.contracts    import com.bloggie.contentservice.dto.Messages  import com.bloggie.contentservice.dto.blog.Blog  import org.springframework.stereotype.Service    @Service  interface ContentService {      fun getSearchedContent(personalizedSearchRequest: Messages.PersonalizedSearchRequest): MutableList<Blog>      fun getAccessibleContent(): MutableList<Blog>      fun getPrivateContent(): MutableList<Blog>  }  

please let me know if anything else is required

Edited*

Conroller

package com.bloggie.contentservice.controller    import com.bloggie.contentservice.dto.Messages  import com.bloggie.contentservice.dto.blog.Blog  import com.bloggie.contentservice.service.contracts.ContentService  import org.springframework.http.ResponseEntity  import org.springframework.validation.annotation.Validated  import org.springframework.web.bind.annotation.GetMapping  import org.springframework.web.bind.annotation.PostMapping  import org.springframework.web.bind.annotation.RequestBody  import org.springframework.web.bind.annotation.RestController    @RestController  @Validated  open class ContentController(      val contentService: ContentService  ) {      @PostMapping("/search")      fun getSearchedContent(          @RequestBody personalizedSearchRequest: Messages.PersonalizedSearchRequest      ): ResponseEntity<MutableList<Blog>> {          return ResponseEntity.ok(contentService.getSearchedContent(personalizedSearchRequest))      }        @GetMapping      fun getPublicContent(): ResponseEntity<MutableList<Blog>> {          return ResponseEntity.ok(contentService.getAccessibleContent())      }        @GetMapping("/private")      fun getPrivateContent(): ResponseEntity<MutableList<Blog>> {          return ResponseEntity.ok(contentService.getPrivateContent())      }  }  

Can a singleton class have a non-singleton dependency? [duplicate]

Posted: 21 Oct 2021 09:03 AM PDT

I'm wondering how IServiceCollection.AddDbContext() adds my ApplicationDbContext. My guess is that it is not added as a singleton, and that a new instance is created with each request.

I'm implementing a custom ILoggerProvider, which requires an instance of ApplicationDbContext.

My question is: what happens if my ILoggerProvider is configured as a singleton, but it has a dependency on an ApplicationDbContext that is not a singleton?

Getting a Pine-script error when trying to get lowest or highest values

Posted: 21 Oct 2021 09:02 AM PDT

Hi I'm new to Pine Script, so please bear with me on the amateur level of the question I was playing, in Version 5, with some Public Library Darvas box code (from Version 3) and the code is as follows:

boxp=input(5, "BOX LENGTH")    LL=lowest (low,boxp)  k1=highest(high,boxp)  k2=highest(high,boxp-1)  k3=highest(high,boxp-2)  

The keyword "input" is in blue but the "lowest" and "highest" functions are not recognized and I get an error "Could not find function or function reference 'lowest'." (same for highest).

These lines of code are used in several other Public Library functions..

Please guide me how I can get around this – I looked up the migration manuals but did not find anything useful.

Thanks!

C# regex for conditional operators example eq:2 , ne:3

Posted: 21 Oct 2021 09:02 AM PDT

I wanted to write an regex in C# for strings which can comprise of any operator and operand value. These operators are string characters like eq for equals , ct = contains & bt for between , eq for equals.

i get strings into backend like eq=4. But during test someone tested my code with garbage values to my API and the string was eq:**+4.

Now i want to build an regex such that it will validate string against regex values like eq:5 or bt:8-9.

i have done this @"^\b(eq | ne | gt | lt | ge | le | ct | bt)\w\b : ? (\d | - ) ? \d"

seems im close but need some guidance to get this properly working.

Any help or suggestion is welcome.

how to write this function in C++ using meta programming

Posted: 21 Oct 2021 09:03 AM PDT

What are you trying to achieve

generally, I want to convert RetType ClassA::MemberFunc(Args...) to mem_fn(&ClassA::MemberFunc) but it is like a function in order to avoid write lambda or function for every member functions

What did you get out (include error messages)

no matching function for call to 'regisAdd(std::_Mem_fn<int (ABC::*)(int, int)>)'

What else have you tried?

I tried other ways, no clue, still think it is doable or not.

What do you think is causing it?

because I am too lazy to write every lambda for each member function

Why do you need to make a new question for it? Why is your problem different to other, similar questions on here?

I searched, did not find any answers like this.

why you write so long F&Q

because stackoverflow complains It looks like your post is mostly code; please add some more details

here is my code..

#include <functional>  #include <iostream>    using namespace std;    struct ABC {      int value;      int add(int a, int b) {          return a + b * value;      }      int other(int a) {          return a * value;      }  };    int doAdd(void* data, int a, int b) {      ABC* p = (ABC*)data;      return p->add(a, b);  }    typedef int (*TYPE_ADD)(void* data, int a, int b);  TYPE_ADD gAdd = nullptr;  void regisAdd(TYPE_ADD a) {      gAdd = a;  }    void callAdd() {      if (!gAdd) return;      ABC abc;      abc.value = 10;      cout << gAdd(&abc, 1, 2) << endl;  }    typedef int (*TYPE_OTHER)(void* data, int a);  TYPE_OTHER gOther = nullptr;  void regisAdd(TYPE_OTHER a) {      gOther = a;  }  void callOther() {      if (!gOther) return;      ABC abc;      abc.value = 10;      cout << gOther(&abc, 12) << endl;  }    int main() {      regisAdd(doAdd);                               // this is GOOD      callAdd();                                     // call      regisAdd([](void* data, int a, int b) {        // < this is also GOOD          return static_cast<ABC*>(data)->add(a, b); // < GOOD      });                                            // < GOOD      callAdd();                                     // call        // how to write a general function work like mem_fn      // to avoid write doAdd and lambda for every function signatures      // regisAdd(mem_fn(&ABC::add));      // regisOther(mem_fn(&ABC::other));      // callAdd();      return 0;  }  

Powershell Display rows only if column 2 -cge column 3 for a group based on column 1

Posted: 21 Oct 2021 09:01 AM PDT

I have a csv like this:

MPN,Per_Pallet,Customer_Order,Customer_Order_Date,Backordered_by_Pallet,Reserved_Sum  501,116.82,12055,4/28/2021,3.18,1.02  501,116.82,12421,6/7/2021,2.36,1.02  501,116.82,12424,6/7/2021,3.91,1.02  2243,30,12014,4/26/2021,1.4,1  2243,30,12425,6/7/2021,4.8,1  2243,30,12817,7/21/2021,0.4,1  2243,30,13359,9/29/2021,0.6,1  2435,50.22,12014,4/26/2021,1,2  2435,50.22,13311,9/24/2021,1.14,2  218,40,13236,9/15/2021,3,5  218,40,13382,10/4/2021,3,5  7593,64,12670,7/2/2021,5,5  484,8,12582,6/22/2021,0.38,2  484,8,12798,7/16/2021,1.38,2  484,8,13255,9/18/2021,1,2  484,8,13288,9/22/2021,1,2  5647,87,13304,9/23/2021,0.01,1  

I need to group by the MPN column then check the oldest order first to see if Backordered_by_Pallet is greater than or equal to Reserved_Sum.

If it is -cge display only that row for that group. if its not, then check to see if the next order plus the first order is and display both of them and so on. until the backorered total is greater than Reserved_Sum

This is what it looks like in my head:

look at oldest order first for matching MPN if oldest orders Backordered > Reserved Sum Then only display oldest order Else if oldest order + second oldest order > Reserved Sum then display both orders Else If Less Than, Add Next Order etc

To look like this:

MPN,Per_Pallet,Customer_Order,Customer_Order_Date,Backordered_by_Pallet,Reserved_Sum  501,116.82,12055,4/28/2021,3.18,1.02  2243,30,12014,4/26/2021,1.4,1  2435,50.22,13311,9/24/2021,1.14,2  218,40,13236,9/15/2021,3,5  218,40,13382,10/4/2021,3,5  7593,64,12670,7/2/2021,5,5  484,8,12582,6/22/2021,0.38,2  484,8,12798,7/16/2021,1.38,2  484,8,13255,9/18/2021,1,2  5647,87,13304,9/23/2021,0.01,1  

I have gotten different pieces to work, but i cant figure out how to put it all together:

returning if its greater or not is easy enough:

$Magic | ForEach-Object {          If ($_.Backordered_by_Pallet -cge $_.Reserved_Sum) {$_}          Else {"Nothing To Order"}          }  

and i have tried adding in a group by

$Magic | Group-Object MPN | ForEach-Object {          If ($_.group.Backordered_by_Pallet -cge $_.group.Reserved_Sum) {$_}          Else {"Nothing_Left_To_Order"}          }   

but that displays the whole group or nothing and im not sure how to combine it all, not to mention how to add the previous rows amount if needed.

I believe i need to do a several layer deep for-each so i group the MPN, make an array for just that one mpn, then a for each on that array (sorted by oldest) (not sure how to pull the previous row to add) then export just the results, then the loop moves on to the next group and so on.

Like this? I know this is not real, i jut cant figure it out

 $Magic_Hash = $Magic_File | Group-Object -Property MPN -AsHashTable | Sort $_.group.Customer_Order_Date                    ForEach ($item in $Magic_Hash) {             If ($item.group.Backordered_by_Pallet -cge $_.group.Reserved_Sum) {$_}          Elseif ($item.group.Backordered_by_Pallet + $item.group.Backordered_by_Pallett["2nd oldest order"] -cge $_.group.Reserved_Sum) {$_}          else {"Nothing_Left"}          }           ```  Thank you so much for all your help this community is amazing  

Google Apps Script to support multiple Google Forms feeding one Google Sheet

Posted: 21 Oct 2021 09:02 AM PDT

I have a Google Sheet with many different "sheet tabs" across the bottom. Several of them are tied to a Google Form, so that when that form is populated the entries show on that "tab".

I'm trying to also inject those entries into a MySQL database. I have gotten this to work successfully using a single Google Sheet/Form pairing using a Google Apps Script tied to the Sheet, which listens for onFormSubmit. That code follows:

// These are the Database connections values  var user = 'dbUsername';  var userPwd = 'dbPassword';  var db = 'databaseName';    var dbUrl = 'jdbc:mysql://192.168.0.0:3306/' + db;    /**   * @param {Object} e The event parameter for form submission to a spreadsheet;   *     see https://developers.google.com/apps-script/understanding_events   */  function onFormSubmit(e) {    console.log(e);    var color = e.namedValues['Color1'][0]; // these names ('Color', 'Number') come from the Form's Question     var number = e.namedValues['Number1'][0];    writeColor(color, number);  }    /**   * Write one row of data to a table.   */  function writeColor(color, number) {    var conn = Jdbc.getConnection(dbUrl, user, userPwd); // this connects to the database      var stmt = conn.prepareStatement('INSERT INTO test_google_forms '        + '(`color`, `number`) values (?, ?)');    stmt.setString(1, color);    stmt.setString(2, number);    stmt.execute(); // this performs the SQL that was "prepared" in the previous 3 lines  }  

However it appears Google triggers that function whenever ANY of the attached Forms is submit. So if I have two Forms feeding different tabs of the same Sheet, it executes this code regardless of which Form was submit (or which tab it was writing to).

Further, I don't see any information in the passed event object about which form it came from (or tab it was writing to), so I don't know how I can triage these responses to go to the correct MySQL tables.

Is there some way I can filter these calls, or do I NEED to break up my Sheet into 1-tab-per-Sheet to avoid this conflict?

Need the children of an XPATH parent that has another specific children without direct correlation

Posted: 21 Oct 2021 09:01 AM PDT

I need to get a specific set of elements with XPATH. I need to get all spans that have the class objective as long as the ancestor div they're in has a children with the span class "objective-is-useful".

Unfortunately the spans are not direct children and they're contained among lots of containers in-between.

I attached an example like so:

<div class="superparent">     <div class="parent">       <div class="container">         <span class="objective">Data 1</span>       </div>       <div class="key">         <span class="objective-is-useful">Approved</span>       </div>     </div>     <div class="parent">       <div class="container">         <span class="objective">Data 2</span>       </div>       <div class="key">       </div>     </div>     <div class="parent">       <div class="container">         <span class="objective">Data 3</span>       </div>       <div class="key">         <span class="objective-is-useful">Approved</span>       </div>     </div>  </div>  

Is there any way to make an XPATH that'd return Data 1 and Data 3 but not Data 2?

How to create an indicator column of the first occurrence of a variable of groupby ID sorted by date?

Posted: 21 Oct 2021 09:01 AM PDT

I have some hospital visit healthcare data in a dataframe of the form:

CLIENT_ID DATE_ENCOUNTER DATE_COUNSELLING COUNSELLING_COUNT
54950 2017-11-24 NaN 0
54950 2018-01-19 NaN 0
54950 2018-03-13 NaN 0
54950 2018-05-11 2018-04-30 1
54950 2018-12-17 2018-06-25 3
67777 2015-09-01 NaN 0
67777 2015-12-01 NaN 0
67777 2016-02-28 2016-02-28 1
70000 2019-06-07 2019-06-07 1
70000 2019-08-09 2019-06-07 1

I want to create a column COUNSELLING_STARTED which indicates whether a client CLIENT_ID has started counselling, but only the first time. i.e. The first occurence when COUNSELLING_COUNT == 1 for each CLIENT_ID which should result in the dataframe below:

CLIENT_ID DATE_ENCOUNTER DATE_COUNSELLING COUNSELLING_COUNT COUNSELLING_STARTED
54950 2017-11-24 NaN 0 0
54950 2018-01-19 NaN 0 0
54950 2018-03-13 NaN 0 0
54950 2018-05-11 2018-04-30 1 1
54950 2018-12-17 2018-06-25 3 0
67777 2015-09-01 NaN 0 0
67777 2015-12-01 NaN 0 0
67777 2016-02-28 2016-02-28 1 1
70000 2019-06-07 2019-06-07 1 1
70000 2019-08-09 2019-06-07 1 0

below is the code to generate the dataframe:

data = {'CLIENT_ID':[54950,54950,54950,54950,54950,67777,67777,67777,70000,70000],  'DATE_ENCOUNTER':['2017-11-24','2018-01-19','2018-03-13','2018-05-11','2018-12-17','2015-09-01','2015-12-01','2016-02-28','2019-06-07','2019-08-09'],  'DATE_COUNSELLING':[np.nan,np.nan,np.nan,'2018-04-30','2018-06-25',np.nan,np.nan,'2016-02-28','2019-06-07','2019-06-07'],  'COUNSELLING_COUNT':[0,0,0,1,3,0,0,1,1,1]}    df = pd.DataFrame(data)  

AVG Query after SUM in mongodb

Posted: 21 Oct 2021 09:01 AM PDT

I would like to make a simple "avg" result from a "sum" result like in this sql example:

SELECT       AVG(a.kaga), a.hashString   FROM (      SELECT             SUM(p.lookingSeconds) kaga,             p.hashString        FROM             lookingPage p        WHERE            p.hashString IN(1,2,3)        GROUP BY p.hashString  ) a   GROUP BY a.hashString  

A could create a simple AVG query with mongoose:

if (!!hashStrings && !!hashStrings.length) {    filter.hashString = { $in: hashStrings };  }    const avg = await PageModel.aggregate([  { $match: filter },  { $group: { _id: null, pop: { $avg: '$lookingSeconds' } } }]).exec();  

I couldn't create a "Query in query" solution in mongo.

ib_insync outside RTH orders

Posted: 21 Oct 2021 09:02 AM PDT

I am using a custom algo based on the ib_insync framework to trade Future Options. The problem is that some of the orders won't execute outside RTH. I submitted a ticket in IB and they told me that the problem was the Market type orders. I changed them to Limit (as they advised) but still the same (in the meantime I have re-opened the ticket).

All setting in TWS are correct (about allowing outside RTH trades) and the code has been included the outsideRth=True declaration.

Uploading files to Shared drive without credentials

Posted: 21 Oct 2021 09:02 AM PDT

I want to upload some files to shared Drive that was opened for me by another person. I have a small project that uploads files to my Google Drive, it was developed with credentials from json and google.apis.auth.oauth2.

But now I didn't receive any credentials, only link to the folder. It is meant that I don't need anything else.

So my question is:

  • is it possible to upload something to Shared Drive without any credentials? Or they should provide me all the credentials (project_id, private_key, token etc..)?

Thank you!

Conditional div with blazor server

Posted: 21 Oct 2021 09:02 AM PDT

Here is what I want to do:

@if (condition)  {    <div class="test">  }  <span class="test2">...</span>  @if (condition)  {    </div>  }  

This does not work because the Blazor compiler thinks the div is never closed.

So I need to do this:

@if (condition)  {    <div class="test">          <span class="test2">...</span>    </div>  }  else  {     <span class="test2">...</span>  }  

It works fine, but I have a big code redundancy with the span.

How can I do this properly?

Please note div and span are examples. In reality, my code is bigger.

Thanks

categoricalToNumeric function in R with indefinite quantity of variables (Variadic function)

Posted: 21 Oct 2021 09:02 AM PDT

I would like to do the following with a function:

categoricalToNumeric <- function(data,...) {      for(i in list(...)) {        data$i <- as.numeric(as.factor(data$i))      }    summary(data)  }  

Then call,

categoricalToNumeric(data, 'school', 'sex', 'address', 'famsize', 'Pstatus', 'Mjob', 'Fjob', 'reason', 'nursery', 'internet', 'guardian.x', 'schoolsup.x', 'famsup.x', 'paid.x', 'activities.x', 'higher.x', 'romantic.x', 'guardian.y', 'schoolsup.y', 'famsup.y', 'paid.y', 'activities.y', 'higher.y', 'romantic.y')  

Currently, there is no error, but the data variable does not mutate upon the categoricalToNumeric call.

The data: https://archive.ics.uci.edu/ml/machine-learning-databases/00320/student.zip

The setup:

data_mat=read.table("./data/csv/student-mat.csv",sep=";",header=TRUE)  data_por=read.table("./data/csv/student-por.csv",sep=";",header=TRUE)      data=merge(data_mat,data_por,by=c("school","sex","age","address","famsize","Pstatus","Medu","Fedu","Mjob","Fjob","reason","nursery","internet"))  print(nrow(data)) # 382 data    head(data,5)  

Scala Month function throwing error No enum constant java.time.Month.UNDEFINED

Posted: 21 Oct 2021 09:01 AM PDT

I am writing a scala month function that will return an Integer month number when called. This function is passing the compilation stage but throwing error while being called at run time.

import java.time.Month  import java.util.Calendar  object Test {    val FINAL_MONTH_NBR = 12      def main(args: Array[String])    {      month()    }    def month(): Int = {      val month = System.getProperty("month")      if(month == null) {        Calendar.getInstance().get(Calendar.MONTH)      }      else {        val monthValue = Month.valueOf(month)        if (monthValue == Month.JANUARY) {          FINAL_MONTH_NBR        }        else {          monthValue.getValue - 1        }      }    }  }  

This is throwing error: java.lang.IllegalArgumentException: No enum constant java.time.Month.UNDEFINED The error is at below line

val monthValue = Month.valueOf(month)

can anybody suggest how to fix this.

Expose UDP port using traits and make it accessible outside of the pod

Posted: 21 Oct 2021 09:02 AM PDT

Update: The question had been answered under Camel K GitHub Issues: https://github.com/apache/camel-k/issues/2693

I have a Camel K project and it uses port 4739. Now I am only able to send data to the port when log into the pod container.

I am trying to send data outside of the container, does anyone know how to configure?

The following command has been tried but seems not working...

// Split commands into multiple lines for easy read  kamel run   --trait container.enabled=true    --trait container.expose=true   --trait container.port=4739   --trait service.node-port=true   SyslogBasic.java --dev  

My understanding is container is living inside of a pod. Firstly we need to expose the container port to pod and then use service to expose the port to outside, unfortunately I haven't find any command line related to service port.

(base) ➜  ~ kamel describe integration syslog-basic  Name:                syslog-basic  Namespace:           camel-basic  Creation Timestamp:  Fri, 08 Oct 2021 15:31:27 -0600  Phase:               Running  Runtime Version:     1.9.0  Kit:                 camel-basic/kit-c59mu55np3m8mfiq07hg  Image:               10.100.204.194/camel-basic/camel-k-kit-c59mu55np3m8mfiq07hg@sha256:06d02dbdda3a58fa0428b9d7cccab9d0708a0172ebe1a9c37e9c1ad114d46769  Version:             1.6.0  Dependencies:    camel:log    camel:netty    mvn:com.fasterxml.jackson.core:jackson-databind:2.12.5    mvn:io.quarkus:quarkus-logging-json    mvn:org.apache.camel.k:camel-k-runtime    mvn:org.apache.camel.quarkus:camel-quarkus-java-joor-dsl    mvn:org.apache.camel:camel-syslog:3.11.2  Sources:    Name              Language  Compression  Ref  Ref Key    SyslogBasic.java  java      false  Conditions:    Type                          Status  Reason                        Message    IntegrationPlatformAvailable  True    IntegrationPlatformAvailable  camel-basic/camel-k    IntegrationKitAvailable       True    IntegrationKitAvailable       kit-c59mu55np3m8mfiq07hg    CronJobAvailable              False   CronJobNotAvailableReason     different controller strategy used (deployment)    DeploymentAvailable           True    DeploymentAvailable           deployment name is syslog-basic    ServiceAvailable              False   ServiceNotAvailable           no http service required    ExposureAvailable             False   IngressNotAvailable           no host or service defined    Ready                         True    ReplicaSetReady  Traits:    Container:      Configuration:  map[enabled:true expose:true port:4739]    Service:      Configuration:  map[enabled:true nodePort:true]  

unique pointer vs raw pointer

Posted: 21 Oct 2021 09:02 AM PDT

Trying to understand the unique_pointer vs raw pointer access

#include <iostream>  #include <memory>    int main() {      int a = 10;      int *x = &a;      int *y = &a;      std::unique_ptr<int> p1 = std::make_unique<int>(a);      std::cout<<*x<<*p1<<*y<<"\n";      // prints 101010      *p1 = 20;      std::cout<<*x<<*p1<<*y<<"\n";      // prints 102010      *x =30;      std::cout<<*x<<*p1<<*y<<"\n";      // 302030      return 0;  }  

Output

101010  102010  302030    Program ended with exit code: 0  

In the above code x, y,p1 are all pointing to variable a; so change of value a should have reflected to all the pointers dereferencing .

Please do help me to understand the behaviour I am few of the guys who all are now moving from use of raw pointers to smart pointers.

Angular 2 show mixed elements array

Posted: 21 Oct 2021 09:02 AM PDT

What I want to accomplish is to show all elements from an array. This array contains various types of components (yes, components), and all these components extends from an abstract class. Here's my code:

Abstract Class Plugin

export abstract class Plugin {  constructor() { }  }  

Watch Component

@Component({  selector: 'watch',  template: `      {{clock | async | date:'medium'}}    `  })    export class WatchCmpt extends Plugin {      clock = Observable.interval(1000).map(() => new Date())      constructor() {        super();      }  }  

Demo Component

@Component({  selector: 'demo',  template: `      <h1>Hello {{name}}</h1>  `  })    export class DemoCmpt extends Plugin {       name: string = "Jose";       constructor() {          super();       }  }  

I'm using this code in my view to display it in my html file:

<? *ngFor="let target of targetList; let x = index">{{target}} </?>  

What should I use in the <?> ?

targetList is an array like this: [demo, watch]

EDIT:

@Component({      selector: 'dndPanel',      templateUrl: 'dragNdropPanel.cmpt.html'   })    export class DragNDropPanelCmpt {     @ViewChild(DemoCmpt) demo1: DemoCmpt;     @ViewChild(WatchCmpt) watch: WatchCmpt;       constructor() {     }       targetList: Plugin[] = [        this.demo1,        this.watch,     ];       addTo($event: any) {        this.targetList.push($event.dragData);    }  }  

This is the complete HTML

   div class="col-sm-6">      <div class="panel panel-info" dnd-sortable-container [sortableData]="targetList">          <div class="panel-heading">Target List</div>          <div class="panel-body" dnd-droppable (onDropSuccess)="addTo($event)" [dropZones]="['source-dropZone']">              <ul class="list-group">                  <li *ngFor="let target of targetList; let x = index" class="list-group-item" dnd-sortable [sortableIndex]="x" [dragEnabled]="true">                      {{target}}                  </li>              </ul>          </div>      </div>  </div>  

No comments:

Post a Comment