问:
How does a smart contract being expended over the block chain?
Alert: Beginners question.
I am searching about solving this question. Once we deploy a smart contract, how on the block chain does other nodes know about my smart contract? If any one have some suggestions on how to understand this part. I can understand that my question may require a lot of explanations. I appreciate any links to resources that would help me the prerequisites.

答:
When you compile a Solidity code, it results in a bytecode executable by the EVM (Ethereum Virtual Machine).

Deployment is nothing else than sending a transaction to "no recipient" (literally the to field is empty) containing the bytecode in its data field.

After this transaction has been broadcasted to the network (through a node that your wallet software or custom app is connected to), it waits in the mempool to be picked by a miner and mined in a block.

When a miner produces a block, they execute each transaction locally in the own EVM instance to generate state changes (for example storing the deployed contract bytecode in the EVM storage) that they'll include later in the block.

During execution of this transaction (on the miner local machine), the EVM generates a new pseudorandom address (by deterministic rules) for the contract and copies the bytecode to this address.

The miner includes all mined transaction in the block, and broadcasts this block (including the new state of your contract) to the rest of the network. Other nodes learn about this new block and reflect the state changes (e.g. new bytecode on the address of your contract) on their end as well.

You can find more info about the mining process in the ETH wiki page Mining.


来源: stackexchange

问:
NoSuchMethodError: org.springframework.boot.web.servlet.error.ErrorController.getErrorPath() in latest spring-cloud-starter-netflix-zuul
My application use spring-boot version 2.5.0 and spring-cloud-starter-netflix-zuul 2.2.8.RELEASE

With latest spring-boot version 2.5.0, getErrorPath() API is removed from ErrorController, but latest spring-cloud-starter-netflix-zuul 2.2.8.RELEASE still calls this API and causes this error

Has anyone got the same issue and resolved already

```<code>2021-06-23 19:36:31 o.a.c.c.C.[.[localhost] [ERROR] Exception Processing ErrorPage[errorCode=0, location=/error]
org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: 'java.lang.String org.springframework.boot.web.servlet.error.ErrorController.getErrorPath()'
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1078)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:106)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:87)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:710)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:398)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:257)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:352)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoSuchMethodError: 'java.lang.String org.springframework.boot.web.servlet.error.ErrorController.getErrorPath()'
    at org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping.lookupHandler(ZuulHandlerMapping.java:87)
    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.getHandlerInternal(AbstractUrlHandlerMapping.java:152)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:498)
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1257)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
    ... 72 common frames omitted
</code>```

答:
Downgrading spring cloud version solved issue.

<spring-cloud.version>Hoxton.SR6</spring-cloud.version>

Properties also changed as Below

```<code>zuul.routes.serviceone.path=/user/**

zuul.routes.serviceone.url=USERSERVICE
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My application use spring-boot version 2.5.0 and spring-cloud-starter-netflix-zuul 2.2.8.RELEASE

With latest spring-boot version 2.5.0, getErrorPath() API is removed from ErrorController, but latest spring-cloud-starter-netflix-zuul 2.2.8.RELEASE still calls this API and causes this error

Has anyone got the same issue and resolved already

2021-06-23 19:36:31 o.a.c.c.C.[.[localhost] [ERROR] Exception Processing ErrorPage[errorCode=0, location=/error]
org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: 'java.lang.String org.springframework.boot.web.servlet.error.ErrorController.getErrorPath()'
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1078)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:106)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:87)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:710)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:398)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:257)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:352)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoSuchMethodError: 'java.lang.String org.springframework.boot.web.servlet.error.ErrorController.getErrorPath()'
    at org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping.lookupHandler(ZuulHandlerMapping.java:87)
    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.getHandlerInternal(AbstractUrlHandlerMapping.java:152)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:498)
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1257)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
    ... 72 common frames omitted

Body:
Downgrading spring cloud version solved issue.

<spring-cloud.version>Hoxton.SR6</spring-cloud.version>

Properties also changed as Below

zuul.routes.serviceone.path=/user/**

zuul.routes.serviceone.url=USERSERVICE


问:
Is it allowed to associate specific file types to installed UWP app?
I have a PDF viewer which is an UWP app, is it possible to register to Windows platform so that this app can be launched by Windows when Desktop App calls shell API (ShellExecute with open verb) to open the PDF document?</p>

答: Yes, add a file type association in the AppxManifest. If you're using Visual Studio there is a graphical editor that will guide you (open the file package.appxmanifest)


问:
How to Compare Two Column as Condition in Eloquent Laravel
I want to compare two column as condition in Eloquent Laravel.
For example:
I have 3 columns, qty_1, qty_2, and price.
I wanto to get product which price under 1000 if column qty_1 and qty_2 are equal.
I have tried these codes but not working:

Product::whereColumn('qty_1','=','qty_2', function($query){
    return $query->where('price','<', 1000);
});
```

How to do that?
Thank you.

答:
Try this :</p>
```<code>Product::whereColumn('qty_1','qty_2')
  ->where('price','<',1000)
  ->get();
</code>```

Body:
I want to compare two column as condition in Eloquent Laravel.
For example:
I have 3 columns, qty_1, qty_2, and price.
I wanto to get product which price under 1000 if column qty_1 and qty_2 are equal.
I have tried these codes but not working:

Product::whereColumn('qty_1','=','qty_2', function($query){
    return $query->where('price','<', 1000);
});

How to do that?
Thank you.

Body:
Try this :

Product::whereColumn('qty_1','qty_2')
  ->where('price','<',1000)
  ->get();


问:
Argument passed in must be a string of 24 hex characters - I think it is
I have a method to find a document in my database based on its ObjectID:

```<code>      console.log('id: ' + id + ' type: ' + typeof id);
      collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
        if (error) {
          callback(error);
        } else {
           callback(null, doc);
        }
      });
</code>```

When I run it I get the following error:

```<code>/myPath/node_modules/monk/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;
          ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/myPath/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:38:11)
at /myPath/collectionDriver.js:134:41
</code>```

This refers to the collection.findOne() line above.

The console log I have before that call outputs the id as a string of 24 hex characters:

```<code>id: "55153a8014829a865bbf700d" type: string
</code>```

Before this I convert the id from an object to a string using JSON.stringify() but it appears to work successfully as shown in my console.log.

Running db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")}) in Robomongo brings back the expected result.

答:
I got the same error. Later I found that I have included a whitespace while sending the values to the server.

```<code><input type="checkbox" name="checkbox" value="<%= item._id %>" onchange="this.form.submit()" />

</code>```

In the value attribute I had typed as value="<%= item._id %> " . A whitespace after the ID. It caused to that error. After I removed it(value="<%= item._id %>" ), the problem solved.

The below code worked for me.

```<code>item.findOne({'_id':id} , (err)=>{

if(err){
  console.log(err);
}
else{
  console.log("Item Found");
}
</code>```

});

ContentLicense: CC BY-SA 3.0

Body:
I have a method to find a document in my database based on its ObjectID:

      console.log('id: ' + id + ' type: ' + typeof id);
      collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
        if (error) {
          callback(error);
        } else {
           callback(null, doc);
        }
      });

When I run it I get the following error:

/myPath/node_modules/monk/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;
          ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/myPath/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:38:11)
at /myPath/collectionDriver.js:134:41

This refers to the collection.findOne() line above.

The console log I have before that call outputs the id as a string of 24 hex characters:

id: "55153a8014829a865bbf700d" type: string

Before this I convert the id from an object to a string using JSON.stringify() but it appears to work successfully as shown in my console.log.

Running db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")}) in Robomongo brings back the expected result.

Body:
I got the same error. Later I found that I have included a whitespace while sending the values to the server.

<input type="checkbox" name="checkbox" value="<%= item._id %>" onchange="this.form.submit()" />

In the value attribute I had typed as value="<%= item._id %> " . A whitespace after the ID. It caused to that error. After I removed it(value="<%= item._id %>" ), the problem solved.

The below code worked for me.

item.findOne({'_id':id} , (err)=>{

if(err){
  console.log(err);
}
else{
  console.log("Item Found");
}

});


问:
How to get winform fullpath?
I have a winform and its fullpath is C:\test.exe

How do I get the winform fullpath at run time? For example, the user may move the winform to other places. Thanks.

答:
As you are using WinForms, there are two simple properties to choose from on the Application class:

Application.StartupPath will get you the directory in which the application started.

Application.ExecutablePath will get you the full path to the application (including the filename).

Title: How to get winform fullpath?


问:
Send webRTC video over RTMP to server for live broadcasting?
I am implementing a live broadcasting in my android app. I am using webRTC for real-time video chat. Now I would like to broadcast live chat to many people.I would like to use Mpeg-DASH.For that video stream can be sent to the server over RTMP and then will be broadcasted using Mpeg-DASH.

So I would like to know how to capture media stream of both local and remote user and then send it over RTMP. I have a working prototype for sending camera captured video to the server over RTMP. But I don't know how to send same media stream to the server which is being used by webRTC.
Possible solutions

Record/Capture screen of live chat and then send it to the server over RTMP.

Make server a peer in webRTC and manipulate stream and broadcast it via Mpeg-DASH.

I would like to do it in client side.Is there any other way to do this?
Thanks.

答:
You should use a WebRTC SFU to forward packets to app, and to covert WebRTC to RTMP. It works like this:

```<code>android app --WebRTC--> Server -+--WebRTC--> android app
                                |
                                +--RTMP--> live streaming platform
                                +--HLS/DASH--> player
</code>```

Because WebRTC is always encrypted by DTLS, so you should covert the stream by a SFU server, rather than hacking the stream of client.

Please read more in this post.

Body:
You should use a WebRTC SFU to forward packets to app, and to covert WebRTC to RTMP. It works like this:

android app --WebRTC--> Server -+--WebRTC--> android app
                                |
                                +--RTMP--> live streaming platform
                                +--HLS/DASH--> player

Because WebRTC is always encrypted by DTLS, so you should covert the stream by a SFU server, rather than hacking the stream of client.

Please read more in this post.


问:
Error in passing a constant argument to mapply() function
I have created a function that run FastICA on a dataset with different number of components and it returns ICA signals (S matrix) but in a long format.

```<code>compute_ICA <- function(r)

{
   res_ICA <- fastICA(df, r, alg.typ = "parallel", fun = "logcosh", alpha = 1,
             method = "R", row.norm = FALSE, maxit = 200,
             tol = 0.0000001, verbose = FALSE)
   df_long<-reshape2::melt(as.data.frame(res_ICA$S))
   return(df_long)
}
</code>```

Now I want to repeat this function 100 times for one specific r (number of components) and keep track of the iteration number.
So I tried this :

```<code>iterate_ICA <- function(r,t)
{for (i in r)
{
  res<-mapply(compute_ICA, t, SIMPLIFY = FALSE)
  res_unzip<-do.call(rbind, res)
  res_unzip$iteration <- i
  return(res_unzip)
}
  }
</code>```

But when I try applying the iterate_ICA() function like this I get this error:

```<code>res_zip<-mapply(iterate_ICA, 1:100, 3, SIMPLIFY = FALSE)
</code>```
```<code>Error in dots[[1L]][[1L]] : object of type 'closure' is not subsettable
</code>```

Does anyone know what's wrong with this function?

Thanks in advance!

答:
I cannot reproduce the error, however, I think you misunderstood what
mapply does.

When you apply mapply to a function FUN, with arguments that are
lists or vectors (consider that R basic types like numbers or characters are always vectors), the function FUN is called iteratively on the first element of all the arguments, then on the second, etc. Arguments are recycled if necessary.

For instance:

fn <- function(num, let) {
  data.frame(num = num, let = let)
}

mapply(FUN = fn, 1:5, letters[1:5], SIMPLIFY = FALSE)

##> [[1]]
##>   num let
##> 1   1   a
##>
##> [[2]]
##>   num let
##> 1   2   b
##>
##> [[3]]
##>   num let
##> 1   3   c
##>
##> [[4]]
##>   num let
##> 1   4   d
##>
##> [[5]]
##>   num let
##> 1   5   e
```
<p>To comply with the expected behavior you described, the <code>iterate_ICA</code>
function should read like this:</p>
<pre class="lang-r prettyprint-override"><code>iterate_ICA<-function(r,t) {
  res <-  compute_ICA(t)
  return(cbind(res, iteration = r))
}
</code>```

Then you iterate it using mapply:

res <- mapply(iterate_ICA, 1:100, 3, SIMPLIFY = FALSE)
```
<p>Finally, you merge all the replicates:</p>
<pre class="lang-r prettyprint-override"><code>res_unzip <- do.call(rbind, res)
</code>```

Body:
I have created a function that run FastICA on a dataset with different number of components and it returns ICA signals (S matrix) but in a long format.

compute_ICA <- function(r)

{
   res_ICA <- fastICA(df, r, alg.typ = "parallel", fun = "logcosh", alpha = 1,
             method = "R", row.norm = FALSE, maxit = 200,
             tol = 0.0000001, verbose = FALSE)
   df_long<-reshape2::melt(as.data.frame(res_ICA$S))
   return(df_long)
}

Now I want to repeat this function 100 times for one specific r (number of components) and keep track of the iteration number.
So I tried this :

iterate_ICA <- function(r,t)
{for (i in r)
{
  res<-mapply(compute_ICA, t, SIMPLIFY = FALSE)
  res_unzip<-do.call(rbind, res)
  res_unzip$iteration <- i
  return(res_unzip)
}
  }

But when I try applying the iterate_ICA() function like this I get this error:

res_zip<-mapply(iterate_ICA, 1:100, 3, SIMPLIFY = FALSE)

Error in dots[[1L]][[1L]] : object of type 'closure' is not subsettable

Does anyone know what's wrong with this function?

Thanks in advance!

Body:
I cannot reproduce the error, however, I think you misunderstood what
mapply does.

When you apply mapply to a function FUN, with arguments that are
lists or vectors (consider that R basic types like numbers or characters are always vectors), the function FUN is called iteratively on the first element of all the arguments, then on the second, etc. Arguments are recycled if necessary.

For instance:

fn <- function(num, let) {
  data.frame(num = num, let = let)
}

mapply(FUN = fn, 1:5, letters[1:5], SIMPLIFY = FALSE)

##> [[1]]
##>   num let
##> 1   1   a
##>
##> [[2]]
##>   num let
##> 1   2   b
##>
##> [[3]]
##>   num let
##> 1   3   c
##>
##> [[4]]
##>   num let
##> 1   4   d
##>
##> [[5]]
##>   num let
##> 1   5   e

To comply with the expected behavior you described, the iterate_ICA
function should read like this:

iterate_ICA<-function(r,t) {
  res <-  compute_ICA(t)
  return(cbind(res, iteration = r))
}

Then you iterate it using mapply:

res <- mapply(iterate_ICA, 1:100, 3, SIMPLIFY = FALSE)

Finally, you merge all the replicates:

res_unzip <- do.call(rbind, res)


问:
Android LiveData is always null in instrumented test
In my app, I have a ViewModel looks like that:

```<code>public class MyExampleViewModel {

   private LiveData<MyEntity> myLiveData;

   @Inject
   MyRepository myRepository;

   @Inject
   public MyExampleViewModel() {
   }

   public void init(final Long id) {
      if (this.myLiveData == null) {
         this.myLiveData = myRepository.getById(id);
      }
   }

   public void toggleStar() NullPointerException {
      final MyEntity myValue = this.myLiveData.getValue();
      myValue.setStar(!myValue.getStar());
      myRepository.save(myValue);
   }
}
</code>```

Also the code of MyRepository#getById (myDao is a room DAO and it is injected):

```<code>    public LiveData<MyEntity> getById(final Long id) {
        return myDao.getById(id);
    }
</code>```

The code of MyDao#getById:

```<code>    @Query(
            "SELECT * FROM myTable WHERE id=:id"
    )
    LiveData<MyEntity> getById(final Long id);
</code>```

I also try to test this ViewModel using

```<code>myExampleViewModel.init(myId);
myExampleViewModel.toggleStar();
</code>```

but after the init call my LiveData value is always null.

My first question is: is it a best practice to use getValue() on my LiveData or should I use Transformation.map?

My second question is: in my test, how can I have a LiveData populated? I tried to use CountingTaskExecutorRule and InstantTaskExecutorRule but without any success.

Thank you for your help!

答:
I understood why myLiveData is not populated in my test. According to the documentation "LiveData objects that are lazily calculated on demand." and LiveData#getValue only get the value if the LiveData is already populated but doesn't calculate the value.

So I fixed my test adding a getter on my LiveData and an observer on my LiveData to force the calculation like that LiveDataUtil.getValue(myExampleViewModel.getMyLiveData()); with LiveDataUtil#getValue:

```<code>public class LiveDataUtil {

    public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
        final Object[] data = new Object[1];
        final CountDownLatch latch = new CountDownLatch(1);
        Observer<T> observer = new Observer<T>() {
            @Override
            public void onChanged(@Nullable T o) {
                data[0] = o;
                latch.countDown();
                liveData.removeObserver(this);
            }
        };
        new Handler(Looper.getMainLooper()).post(() -> liveData.observeForever(observer));
        latch.await(2, TimeUnit.SECONDS);

        //noinspection unchecked
        return (T) data[0];
    }
}
</code>```

After this fix, MyExampleViewModel class looks like:

```<code>public class MyExampleViewModel {

   private LiveData<MyEntity> myLiveData;

   @Inject
   MyRepository myRepository;

   @Inject
   public MyExampleViewModel() {
   }

   public void init(final Long id) {
      if (this.myLiveData == null) {
         this.myLiveData = myRepository.getById(id);
      }
   }

   public void toggleStar() NullPointerException {
      final MyEntity myValue = this.myLiveData.getValue();
      myValue.setStar(!myValue.getStar());
      myRepository.save(myValue);
   }

   public LiveData<MyEntity> getMyLiveData() {
       return myLiveData;
   }
}
</code>```

And my test method:

```<code>myExampleViewModel.init(myId);
LiveDataUtil.getValue(myExampleViewModel.getMyLiveData());
myExampleViewModel.toggleStar();
</code>```

I fixed my test but I still don't know if using LiveData.getValue is a best practice and I found few documentation on this topic. So, I'm interested in this topic if you have more information.

Body:
In my app, I have a ViewModel looks like that:

public class MyExampleViewModel {

   private LiveData<MyEntity> myLiveData;

   @Inject
   MyRepository myRepository;

   @Inject
   public MyExampleViewModel() {
   }

   public void init(final Long id) {
      if (this.myLiveData == null) {
         this.myLiveData = myRepository.getById(id);
      }
   }

   public void toggleStar() NullPointerException {
      final MyEntity myValue = this.myLiveData.getValue();
      myValue.setStar(!myValue.getStar());
      myRepository.save(myValue);
   }
}

Also the code of MyRepository#getById (myDao is a room DAO and it is injected):

    public LiveData<MyEntity> getById(final Long id) {
        return myDao.getById(id);
    }

The code of MyDao#getById:

    @Query(
            "SELECT * FROM myTable WHERE id=:id"
    )
    LiveData<MyEntity> getById(final Long id);

I also try to test this ViewModel using

myExampleViewModel.init(myId);
myExampleViewModel.toggleStar();

but after the init call my LiveData value is always null.

My first question is: is it a best practice to use getValue() on my LiveData or should I use Transformation.map?

My second question is: in my test, how can I have a LiveData populated? I tried to use CountingTaskExecutorRule and InstantTaskExecutorRule but without any success.

Thank you for your help!

Body:
I understood why myLiveData is not populated in my test. According to the documentation "LiveData objects that are lazily calculated on demand." and LiveData#getValue only get the value if the LiveData is already populated but doesn't calculate the value.

So I fixed my test adding a getter on my LiveData and an observer on my LiveData to force the calculation like that LiveDataUtil.getValue(myExampleViewModel.getMyLiveData()); with LiveDataUtil#getValue:

public class LiveDataUtil {

    public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
        final Object[] data = new Object[1];
        final CountDownLatch latch = new CountDownLatch(1);
        Observer<T> observer = new Observer<T>() {
            @Override
            public void onChanged(@Nullable T o) {
                data[0] = o;
                latch.countDown();
                liveData.removeObserver(this);
            }
        };
        new Handler(Looper.getMainLooper()).post(() -> liveData.observeForever(observer));
        latch.await(2, TimeUnit.SECONDS);

        //noinspection unchecked
        return (T) data[0];
    }
}

After this fix, MyExampleViewModel class looks like:

public class MyExampleViewModel {

   private LiveData<MyEntity> myLiveData;

   @Inject
   MyRepository myRepository;

   @Inject
   public MyExampleViewModel() {
   }

   public void init(final Long id) {
      if (this.myLiveData == null) {
         this.myLiveData = myRepository.getById(id);
      }
   }

   public void toggleStar() NullPointerException {
      final MyEntity myValue = this.myLiveData.getValue();
      myValue.setStar(!myValue.getStar());
      myRepository.save(myValue);
   }

   public LiveData<MyEntity> getMyLiveData() {
       return myLiveData;
   }
}

And my test method:

myExampleViewModel.init(myId);
LiveDataUtil.getValue(myExampleViewModel.getMyLiveData());
myExampleViewModel.toggleStar();

I fixed my test but I still don't know if using LiveData.getValue is a best practice and I found few documentation on this topic. So, I'm interested in this topic if you have more information.


问:
array datatype from database to eloquent laravel
I have data stored in a database with a column data type of array. I can get the value in PostgreSQL as follows:

```<code>select id, student, subject[1] as first_subject, subject[array_length(subject, 1)] as last_subject
from tableinfo
</code>```

So, I need to get the first and last value of the array in the Laravel eloquent query. But using select in eloquent doesn't seem to work.

Eloquent query:

```<code>DB::Table('tableinfo')
->select('id', 'name', 'subject[array_length(subject, 1)] as last_subject')
->get();
</code>```

Error message I got:

答:
You can not use custom/raw select using select method, but you can use selectRaw method like below:

```<code>DB::Table('tableinfo')
->select('id', 'name')
->selectRaw('subject[array_length(subject, 1)] as last_subject')
->get();
</code>```

above code will generate query like below:

```<code>select "id", "name", subject[array_length(subject, 1)] as last_subject from "tableinfo"
</code>```

Body:
I have data stored in a database with a column data type of array. I can get the value in PostgreSQL as follows:

select id, student, subject[1] as first_subject, subject[array_length(subject, 1)] as last_subject
from tableinfo

So, I need to get the first and last value of the array in the Laravel eloquent query. But using select in eloquent doesn't seem to work.

Eloquent query:

DB::Table('tableinfo')
->select('id', 'name', 'subject[array_length(subject, 1)] as last_subject')
->get();

Error message I got:

Body:
You can not use custom/raw select using select method, but you can use selectRaw method like below:

DB::Table('tableinfo')
->select('id', 'name')
->selectRaw('subject[array_length(subject, 1)] as last_subject')
->get();

above code will generate query like below:

select "id", "name", subject[array_length(subject, 1)] as last_subject from "tableinfo"


问:
how to turn off / Disable Tab Change on Swype (import from react-native-elements) in react native
i am new in react-native and i am using this react native tab elements in my application like this

```<code><Tab value={index} onChange={setIndex}>
  <Tab.Item title="recent" />
  <Tab.Item title="favorite" />
  <Tab.Item title="cart" />
</Tab>

<TabView value={index} onChange={setIndex} >
   <TabView.Item style={{ backgroundColor: 'red', width: '100%' }}>
     <Text h1>Recent</Text>
   </TabView.Item>
   <TabView.Item style={{ backgroundColor: 'blue', width: '100%' }}>
     <Text h1>Favorite</Text>
   </TabView.Item>
   <TabView.Item style={{ backgroundColor: 'green', width: '100%' }}>
     <Text h1>Cart</Text>
    </TabView.Item>
</TabView>
</code>```

but default Tab Change On Swype is active
how to Disable Swype Tab Change ?
i want only tab change while click on tab title how to do that ?

答:
You must use this property</p>
```<code><TabView swipeEnabled={false} />
</code>```

Body:
i am new in react-native and i am using this react native tab elements in my application like this

<Tab value={index} onChange={setIndex}>
  <Tab.Item title="recent" />
  <Tab.Item title="favorite" />
  <Tab.Item title="cart" />
</Tab>

<TabView value={index} onChange={setIndex} >
   <TabView.Item style={{ backgroundColor: 'red', width: '100%' }}>
     <Text h1>Recent</Text>
   </TabView.Item>
   <TabView.Item style={{ backgroundColor: 'blue', width: '100%' }}>
     <Text h1>Favorite</Text>
   </TabView.Item>
   <TabView.Item style={{ backgroundColor: 'green', width: '100%' }}>
     <Text h1>Cart</Text>
    </TabView.Item>
</TabView>

but default Tab Change On Swype is active
how to Disable Swype Tab Change ?
i want only tab change while click on tab title how to do that ?

Body:
You must use this property

<TabView swipeEnabled={false} />


问:
remove digits NOT between brackets - regex
I am trying to write a regular expression in python to remove digits except those between brackets
here is an example : "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."

I would like : "[Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from .."

答:
You can use the following code.

```<code>import re

s = "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."

pattern = r"\[.*?\]|(\d+)"

print(re.sub(pattern, lambda x: '' if x.group(1) else x.group(), s))
  -> [Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from ..
</code>```

Demo

The regular expression reads, "Match a left bracket followed by one or more characters matched lazily, followed by a right bracket, or match one or more digits and save the match to capture group 1."

Matching characters lazily prevents a right bracket from being matched. We could alternatively write the first part of the alternation \[[^\]]*\], where [^\]]* matches zero or more characters other than a right bracket.

The lambda reads, "If a string has been captured to group 1, replace the match with an empty string; else replace the match with itself".

Note that the order of the alternation is important; r"(\d+)|\[.*?\]" will not work.

Body:
You can use the following code.

import re

s = "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."

pattern = r"\[.*?\]|(\d+)"

print(re.sub(pattern, lambda x: '' if x.group(1) else x.group(), s))
  -> [Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from ..

Demo

The regular expression reads, "Match a left bracket followed by one or more characters matched lazily, followed by a right bracket, or match one or more digits and save the match to capture group 1."

Matching characters lazily prevents a right bracket from being matched. We could alternatively write the first part of the alternation \[[^\]]*\], where [^\]]* matches zero or more characters other than a right bracket.

The lambda reads, "If a string has been captured to group 1, replace the match with an empty string; else replace the match with itself".

Note that the order of the alternation is important; r"(\d+)|\[.*?\]" will not work.


问:
jQuery change doesn't work in bootstrap 5 tabs
I add an input form in bootstrap 5 tabs like this:

```<code><div class="container">
  <div class="row justify-content-center my-5">
    <div class="col-auto">
      <ul class="nav bg-dark">
        <li class="nav-item">
          <a class="nav-link link-secondary" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" href="#">HOME</a>
        </li>
        <li class="nav-item">
          <a class="nav-link link-secondary" id="about-tab" data-bs-toggle="tab" data-bs-target="#about" href="#">ABOUT</a>
        </li>
        <li class="nav-item">
          <a class="nav-link link-secondary active" id="album-tab" data-bs-toggle="tab" data-bs-target="#album" href="#">ALBUM</a>
        </li>
      </ul>

      <div class="tab-content" id="tabContent">
        <div class="tab-pane fade" id="home" role="tabpanel" aria-labelledby="home-tab">
          <img class="img-fluid" src="https://fakeimg.pl/800x300/?text=home" />
        </div>
        <div class="tab-pane fade" id="about" role="tabpanel" aria-labelledby="about-tab">
          <img class="img-fluid" src="https://fakeimg.pl/800x300/?text=about" />
        </div>
        <div class="tab-pane fade show active" id="album" role="tabpanel" aria-labelledby="album-tab">
          <input id="searchDateFrom" type="text" class="form-control search-by-date" data-name="searchDateFrom">
          <img class="img-fluid" src="https://fakeimg.pl/800x300/?text=album" />
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Js:

```<code>var dateFrom = $('#searchDateFrom').val();
$('#searchDateFrom').change(function() {
  console.log(dateFrom);
});
</code>```

Now, In action, I need to get input value using jQuery change method. But, after change the value I can't see any result. (into console log in case)

How do can I fix this problem?!

DEMO Here

Image:

答:
The problem is, that you don't refresh the value of your variable "dateFrom" on change.

dateFrom keeps its initial value, which is "". On change, it logs this value.

You should change your code to:

```<code>var dateFrom;
$('#searchDateFrom').change(function() {
  dateFrom = $('#searchDateFrom').val();
  console.log(dateFrom);
});
</code>```

This will update the value of the variable on change and log it afterwards.

Body:
I add an input form in bootstrap 5 tabs like this:

          HOME

          ABOUT

          ALBUM

          <input id="searchDateFrom" type="text" class="form-control search-by-date" data-name="searchDateFrom">

Js:

var dateFrom = $('#searchDateFrom').val();
$('#searchDateFrom').change(function() {
  console.log(dateFrom);
});

Now, In action, I need to get input value using jQuery change method. But, after change the value I can't see any result. (into console log in case)

How do can I fix this problem?!

DEMO Here

Image:

Body:
The problem is, that you don't refresh the value of your variable "dateFrom" on change.

dateFrom keeps its initial value, which is "". On change, it logs this value.

You should change your code to:

var dateFrom;
$('#searchDateFrom').change(function() {
  dateFrom = $('#searchDateFrom').val();
  console.log(dateFrom);
});

This will update the value of the variable on change and log it afterwards.


问:
Why is memset() incorrectly initializing int?
Why is the output of the following program 84215045?

```<code>int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}
</code>```

答:
Well, the memset writes bytes, with the selected value. Therefore an int will look something like this:

```<code>00000101 00000101 00000101 00000101
</code>```

Which is then interpreted as 84215045.

Body:
Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}

Body:
Well, the memset writes bytes, with the selected value. Therefore an int will look something like this:

00000101 00000101 00000101 00000101

Which is then interpreted as 84215045.


问:
Remove desktop shortcut after uninstall uwp on windows
I install uwp app and place a shorcut to desktop via "shell:AppsFolder" and choosing right icon app and "Create shortcut", but after uninstall the app, the desktop shortcut remains...is it possible somehow from uwp side to remove all shortcuts to the uninstalled app?</p>

答: No, it's not even possible for non-UWP apps to locate and remove arbitrary shortcuts. They are a 1-way link.</p>


问:
Group anagrams Leetcode question (python)
I'm looking at this leetcode question Leetcode. I'm trying to understand the provided solution which is:

```<code>class Solution:
    def groupAnagrams(strs):
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            ans[tuple(count)].append(s)
        return ans.values()
</code>```

I know we are creating a character count tuple as the key and adding the words that match the tuple as values to the map.

The thing that I'm confused about is this line  ans[tuple(count)].append(s). Why isn't it
 ans[tuple(count)]=s. Is the append(s) adding values to the map? I thought maps don't have the append() method?

Can anyone clarify this specific line?
Thank you

答:
If ans = collections.defaultdict(list) confuses you, you could write like this:

```<code>class Solution:
   # your question does not have `self`  "def groupAnagrams(strs):"
    def groupAnagrams(self,strs):
        # ans = collections.defaultdict(list)
        ans={}
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            # defaultdict already sets this for us
            if tuple(count) not in ans:
                ans[tuple(count)]=[]
            ans[tuple(count)].append(s)
        return ans.values()
</code>```

Body:
I'm looking at this leetcode question Leetcode. I'm trying to understand the provided solution which is:

class Solution:
    def groupAnagrams(strs):
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            ans[tuple(count)].append(s)
        return ans.values()

I know we are creating a character count tuple as the key and adding the words that match the tuple as values to the map.

The thing that I'm confused about is this line  ans[tuple(count)].append(s). Why isn't it
 ans[tuple(count)]=s. Is the append(s) adding values to the map? I thought maps don't have the append() method?

Can anyone clarify this specific line?
Thank you

Body:
If ans = collections.defaultdict(list) confuses you, you could write like this:

class Solution:
   # your question does not have `self`  "def groupAnagrams(strs):"
    def groupAnagrams(self,strs):
        # ans = collections.defaultdict(list)
        ans={}
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            # defaultdict already sets this for us
            if tuple(count) not in ans:
                ans[tuple(count)]=[]
            ans[tuple(count)].append(s)
        return ans.values()


问:
Multiple worker to same queue messages
I have a task to migrate keys (S3 objects) from one S3 account to another S3 account as soon as possible. I would like to publish keys in a single queue but want multiple workers(Running on different EC2 instances) to consume keys from the same queue in parallel manner.

Let's say I am publishing 1000 keys continuously in the queue and there are 5 workers consuming keys from queue. I want each 1000 to be picked by each different worker and all process keys parallely.

I am not sure how to do it and distinguish which worker has already picked keys and which one yet to pick.

答:
You should create:

An Amazon SQS queue

An AWS Lambda function that is configured to Trigger when a message is sent to the SQS queue, and which will process the keys mentioned in the message(s)

Something that will 'push' the keys as messages into the SQS queue

The Amazon SQS queue will automatically trigger the AWS Lambda function when a message is available. It can pass up to 10 messages to each Lambda function being invoked and the default is a maximum of 1000 concurrently-running Lambda functions.

Each 'message' could contain a single key or multiple keys -- that is up to you to decide. The Lambda function simply needs to know how to process the message that you have sent.

The Lambda function will receive the message(s) in the event['Records'] list (array). It should process those messages and then exit the function. This will cause those messages to be deleted from the queue. If the function does not exit successfully (eg if there is an error generated), the messages will automatically reappear on the queue for re-processing.

Title: Multiple worker to same queue messages


问:
Multiple commands produce error in Xcode 13
I have been stuck on this bug for quite a while now so any help would be appreciated. When I try to build my app I keep getting the following build error:

Multiple commands produce '/Users/my_user_name/Library/Developer/Xcode/DerivedData/Expense_Tracker_Final-aujeprcwgnjmizeaueitvhpegrzf/Build/Products/Debug-iphonesimulator/Expense Tracker Final.app':

Target 'Expense Tracker Final' has create directory command with output '/Users/my_user_name/Library/Developer/Xcode/DerivedData/Expense_Tracker_Final-aujeprcwgnjmizeaueitvhpegrzf/Build/Products/Debug-iphonesimulator/Expense Tracker Final.app'

That command depends on command in Target 'Expense Tracker Final': script phase “[CP] Copy Pods Resources”

I have tried solution that have been recommended on other stack overflow questions such as deleting certain files from the [CP] Copy Pods Resources, but nothing seems to be working. Could someone please help me I'm really lost.

答:
Looks like there's a duplicate code in your script under Build Phase >  [CP] Copy Pods Resources
Remove the duplicate and re-run the project.


问:
How to SELECT / Query Whole Numbers only
Would you know If i can select only whole numbers?
I don't want to round off the values.

For example this is select * from Table_1 below

Numbers
Team

10.5
A

12.12
B

23
C

I would do like
select * from Table_1
where NUMBERS is ;

Expected output below

Numbers
Team

23
C

Thank you very much!

答:
The function TRUNC() truncates a number without rounding:

```<code>SELECT *
FROM Table_1
WHERE TRUNC("Numbers") = "Numbers";
</code>```

See the demo.

Body:
The function TRUNC() truncates a number without rounding:

SELECT *
FROM Table_1
WHERE TRUNC("Numbers") = "Numbers";

See the demo.


问:
radio and radiolist flutter andriod studio
Anyone can help me to solve this problem in the code, so I want to answer and correct the code in the android studio" home.dart named of file

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Color val;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: val,
      appBar: AppBar(
        title: Text('Flutter forms lesson 5'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Green'),
            Radio(
              value: Colors.green,
              groupValue: val,
              onChanged: (newValue) {
                setState(() {
                  val = newValue;
                });
              },
            ),
            Text('Red'),
            Radio(
              value: Colors.red,
              groupValue: val,
              onChanged: (newValue) {
                setState(() {
                  val = newValue;
                });
              },
            ),
            RadioListTile(
              title: Text('Orange'),
              value: Colors.orange,
              groupValue: val,
              onChanged: (newValue) {
                setState(() {
                  val = newValue;
                });
              },
            ),
            RadioListTile(
              title: Text('Yellow'),
              value: Colors.yellow,
              groupValue: val,
              onChanged: (newValue) {
                setState(() {
                  val = newValue;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}
```

答:
In dart everything should be typed if at all possible. You can write it without typing but issues like this one will crop up. The problem you are seeing here is because your radio button is not typed. Here is an example of a radio button from the docs:

Radio<SingingCharacter>(
  value: SingingCharacter.lafayette,
  groupValue: _character,
  onChanged: (SingingCharacter newValue) {
    setState(() {
      _character = newValue;
    });
  },
)
```
<p>In this case you can see in the declaration the <code>Radio</code> is typed as a <code>SingingCharacter</code> by writing <code>Radio<SingingCharacter></code>. This lets the analyzer know that the <code>onChanged</code> value will also be a <code>SingingCharacter</code>.</p>
<p>In your code, it should be pretty simple to fix:</p>
<pre class="lang-dart prettyprint-override"><code>Radio<Color>(
  value: Colors.red,
  groupValue: val,
  onChanged: (Color? newValue) {
    if (newValue != null) {
      setState(() {
        val = newValue;
      });
    } else {
      throw Exception('Null newValue received!');
    }
  },
),
</code>```

Body:
In dart everything should be typed if at all possible. You can write it without typing but issues like this one will crop up. The problem you are seeing here is because your radio button is not typed. Here is an example of a radio button from the docs:

Radio<SingingCharacter>(
  value: SingingCharacter.lafayette,
  groupValue: _character,
  onChanged: (SingingCharacter newValue) {
    setState(() {
      _character = newValue;
    });
  },
)

In this case you can see in the declaration the Radio is typed as a SingingCharacter by writing Radio<SingingCharacter>. This lets the analyzer know that the onChanged value will also be a SingingCharacter.

In your code, it should be pretty simple to fix:

Radio<Color>(
  value: Colors.red,
  groupValue: val,
  onChanged: (Color? newValue) {
    if (newValue != null) {
      setState(() {
        val = newValue;
      });
    } else {
      throw Exception('Null newValue received!');
    }
  },
),


问:
(Python)Unable to import excel file using colab
i have tried to import an excel csv file from my local disk but failed

```<code>import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")
</code>```

error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'
</code>```

答:
Try uploading files on drive first.
Then read.
Go to file.
Copy path.
Try following code.</p>
```<code>from google.colab import files
Upload= files.upload
Df= pd.read_csv("file_path_file_name")
df.head
</code>```

Body:
i have tried to import an excel csv file from my local disk but failed

import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")

error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'

Body:
Try uploading files on drive first.
Then read.
Go to file.
Copy path.
Try following code.

from google.colab import files
Upload= files.upload
Df= pd.read_csv("file_path_file_name")
df.head


问:
Django media files not showing with Debug = False on production - Django 1.10
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed. I get a 404 not found error.
My quuestion is how do I display media content in production environment when DEBUG = False. With DEBUG= True everything seems to work fine ? I read the following page and tried these things out.

1-Tried creating a separate folder for static media just like static content.
Currently my static content is being managed by the collectstatic command. I am using apache on webfaction.I have a static folder called static_content when I ran ./manage.py collectstatic all of my content in static folder was copied to the static_content folder.I tried creating another static folder called static_media. However when I ran ./manage.py collectstatic the content of my media folder got copied to static_content and not to static_media like it should have. Can anyone tell me why the collectstatic command did not paste the content to static_media instead ?

This is what my configuration looks like

```<code>ALLOWED_HOSTS = [
   "*",
   'mywebsite.com',
   'www.mywebsite.com.com',
]

STATIC_URL = 'http://mywebsite.com.com/static/'
STATIC_ROOT = '/home/admin/webapps/static_content'
STATICFILES_DIRS = (
                        '/home/admin/webapps/mainfolder/mainapp/static',
                        '/home/admin/webapps/mainfolder/mainapp/media',
                   )
PROJECT_PATH = os.path.join(BASE_DIR, 'static')

MEDIA_URL = 'http://mywebsite.com.com/media/'
MEDIA_ROOT = '/home/admin/webapps/static_media'
</code>```

This is what my urls.py looks like

```<code>admin.autodiscover()
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Am I using the correct approach creating a separate folder for managing my media content just like for my static content for when DEBUG=False ? If so then why is collectstatic command dumping all my media content into my static_content folder instead of static_media folder ? Also if I use a static folder for managing my media content when a user uploads data where will that be uploaded to media or static_media.

答:
this helps me a lot

settings.py

```<code>STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

MEDIA_URL =  '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

INSTALLED_APPS = [

    'django.contrib.staticfiles',

    'whitenoise.runserver_nostatic',

]
</code>```

in url.py import URL and give static and media file URL

```<code>from django.views.static import serve

from django.conf.urls import url
</code>```

Body:
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed. I get a 404 not found error.
My quuestion is how do I display media content in production environment when DEBUG = False. With DEBUG= True everything seems to work fine ? I read the following page and tried these things out.

1-Tried creating a separate folder for static media just like static content.
Currently my static content is being managed by the collectstatic command. I am using apache on webfaction.I have a static folder called static_content when I ran ./manage.py collectstatic all of my content in static folder was copied to the static_content folder.I tried creating another static folder called static_media. However when I ran ./manage.py collectstatic the content of my media folder got copied to static_content and not to static_media like it should have. Can anyone tell me why the collectstatic command did not paste the content to static_media instead ?

This is what my configuration looks like

ALLOWED_HOSTS = [
   "*",
   'mywebsite.com',
   'www.mywebsite.com.com',
]

STATIC_URL = 'http://mywebsite.com.com/static/'
STATIC_ROOT = '/home/admin/webapps/static_content'
STATICFILES_DIRS = (
                        '/home/admin/webapps/mainfolder/mainapp/static',
                        '/home/admin/webapps/mainfolder/mainapp/media',
                   )
PROJECT_PATH = os.path.join(BASE_DIR, 'static')

MEDIA_URL = 'http://mywebsite.com.com/media/'
MEDIA_ROOT = '/home/admin/webapps/static_media'

This is what my urls.py looks like

admin.autodiscover()
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Am I using the correct approach creating a separate folder for managing my media content just like for my static content for when DEBUG=False ? If so then why is collectstatic command dumping all my media content into my static_content folder instead of static_media folder ? Also if I use a static folder for managing my media content when a user uploads data where will that be uploaded to media or static_media.

Body:
this helps me a lot

settings.py

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

MEDIA_URL =  '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

INSTALLED_APPS = [

    'django.contrib.staticfiles',

    'whitenoise.runserver_nostatic',

]

in url.py import URL and give static and media file URL

from django.views.static import serve

from django.conf.urls import url


问:
mysql_query return TRUE on empty table

$rs = mysql_query("SELECT user, userid FROM House WHERE
  userid='$userid'");

This return Resource id #37
The table House is empty, shouldn't it return FALSE?
According to the manual http://php.net/manual/en/function.mysql-query.php

I have always gotten FALSE on error, but not this time.
Can someone explain, thanks!

答:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or false on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc it returns trueon success or false on error.

Title: mysql_query return TRUE on empty table


问:
Is there a way to add clickable icons on weebly nav bars?
Using weebly to create a website and I have come across this webpage(https://editortricks.weebly.com/how-to-add-icons-to-your-weebly-navigation.html) to add icons to the navigation bar. Here`s the code,

```<code>/* External Fonts */
@font-face {
  font-family: 'dashicons';
  src: url('fonts/dashicons.eot');
  src: url('fonts/dashicons.eot?#iefix');
  src: url('fonts/dashicons.woff');
  src:url('fonts/dashicons.svg#svgdashicons');
  src: url('fonts/dashicons.ttf');
}
.wsite-nav-1:before,
.wsite-nav-2:before,
.wsite-nav-3:before,
.wsite-nav-4:before,
.wsite-nav-5:before {
  font-family: 'dashicons';
  position: relative;
  top: 1px; /* Changes the icons' vertical position */
  margin-right: 0px; /* Changes the icons' horizontal position */
  color: #000000; /* Changes the icons' color */
  font-size: 1em; /* Changes the icons' size */
}
</code>```

This allows the page to have icons in the navigation bar but they cannot be hyperlinked to another page. I have done a bit of HTML/CSS but I have no clue what I`m doing on Weebly's .less format. Please help, would really appreciate it.

答:
You should be able to do id without HTML from the editor - choose the icon and then right-click it - from the menu, choose the "chain link" icon and paste the URL there.

if that didn't work you can use HTML tags within Weebly, so you can do something like this (the simplest way):

```<code><a href="insert destination URL here"><img src="insert image location here" title="insert title" alt="insert description here"></a>
</code>```

Body:
Using weebly to create a website and I have come across this webpage(https://editortricks.weebly.com/how-to-add-icons-to-your-weebly-navigation.html) to add icons to the navigation bar. Here`s the code,

/* External Fonts */
@font-face {
  font-family: 'dashicons';
  src: url('fonts/dashicons.eot');
  src: url('fonts/dashicons.eot?#iefix');
  src: url('fonts/dashicons.woff');
  src:url('fonts/dashicons.svg#svgdashicons');
  src: url('fonts/dashicons.ttf');
}
.wsite-nav-1:before,
.wsite-nav-2:before,
.wsite-nav-3:before,
.wsite-nav-4:before,
.wsite-nav-5:before {
  font-family: 'dashicons';
  position: relative;
  top: 1px; /* Changes the icons' vertical position */
  margin-right: 0px; /* Changes the icons' horizontal position */
  color: #000000; /* Changes the icons' color */
  font-size: 1em; /* Changes the icons' size */
}

This allows the page to have icons in the navigation bar but they cannot be hyperlinked to another page. I have done a bit of HTML/CSS but I have no clue what I`m doing on Weebly's .less format. Please help, would really appreciate it.

Body:
You should be able to do id without HTML from the editor - choose the icon and then right-click it - from the menu, choose the "chain link" icon and paste the URL there.

if that didn't work you can use HTML tags within Weebly, so you can do something like this (the simplest way):

<a href="insert destination URL here"><img src="insert image location here" title="insert title" alt="insert description here"></a>


问:
How to call component on onclick of node from react-d3-tree
```<code>        class WorkflowDesign extends React.PureComponent {
          state = {};

          componentDidMount() {
            const dimensions = this.treeContainer.getBoundingClientRect();
            this.setState({
              translate: {
                x: dimensions.width / 2,
                y: dimensions.height / 2
              }
            });
          }

          render() {
            return (
              <div style={containerStyles} ref={tc => (this.treeContainer = tc)}>
                <Tree
                  data={this.props.data}
                  translate={this.state.translate}
                  orientation={'vertical'}
                  collapsible={false}
                  directed={false}
                  onClick={(nodeData, evtData) => {
                    if (nodeData.type === 'FLOW') {
                      this.props.getFlowNodeStartId(nodeData);
                    }
                    return;
                  }}

                  allowForeignObjects
                  nodeLabelComponent={{
                    render: <CollapsedBreadcrumbs data={this.props.breadcrumbtartNodeId} />,
                    foreignObjectWrapper: {
                      y: 24
                    }
                  }
                  }

                />
              </div>
            );
          }
        }
</code>```

I have tried with [react-d3-tee][1] but its not allowing me to call component inside onclick, So please help me out how to call component on onclick with some conditions, I have mention on the above code

I wanted to call component on onclick which I have wrote onclick function with some condition

```<code>      [1]: https://www.npmjs.com/package/react-d3-tree
</code>```

答:
I guess the props that you are looking for is onNodeClick

```<code><Tree
    data = {this.props.data}
    onNodeClick = {this.handleClick.bind(this)}
/>
</code>```

and you can use it like:

```<code>handleClick(nodeData, evtData){
    // your code
    if (nodeData.type === 'FLOW') {
         this.props.getFlowNodeStartId(nodeData);
    }
    return;
}
</code>```

You can find out more in the documentation here.

Body:
        class WorkflowDesign extends React.PureComponent {
          state = {};

          componentDidMount() {
            const dimensions = this.treeContainer.getBoundingClientRect();
            this.setState({
              translate: {
                x: dimensions.width / 2,
                y: dimensions.height / 2
              }
            });
          }

          render() {
            return (

 (this.treeContainer = tc)}>
                <Tree
                  data={this.props.data}
                  translate={this.state.translate}
                  orientation={'vertical'}
                  collapsible={false}
                  directed={false}
                  onClick={(nodeData, evtData) => {
                    if (nodeData.type === 'FLOW') {
                      this.props.getFlowNodeStartId(nodeData);
                    }
                    return;
                  }}

                  allowForeignObjects
                  nodeLabelComponent={{
                    render: <CollapsedBreadcrumbs data={this.props.breadcrumbtartNodeId} />,
                    foreignObjectWrapper: {
                      y: 24
                    }
                  }
                  }

                />

            );
          }
        }

I have tried with [react-d3-tee][1] but its not allowing me to call component inside onclick, So please help me out how to call component on onclick with some conditions, I have mention on the above code

I wanted to call component on onclick which I have wrote onclick function with some condition

      [1]: https://www.npmjs.com/package/react-d3-tree

Body:
I guess the props that you are looking for is onNodeClick

<Tree
    data = {this.props.data}
    onNodeClick = {this.handleClick.bind(this)}
/>

and you can use it like:

handleClick(nodeData, evtData){
    // your code
    if (nodeData.type === 'FLOW') {
         this.props.getFlowNodeStartId(nodeData);
    }
    return;
}

You can find out more in the documentation here.


问:
Creating a Google Doc with 2 tables in Google Apps Script
Reference to this question see link I would to have the possibility to put 2 tables in my Google Doc from the Spreadsheet. In the code below I can put only 1 table (from col C to col E). My need is to put also a second table from col H to col N.

What I could add to the script?

```<code>function generateDoc() {
  var tableColumn = [3,5]; // Table1 header is in column 3C to 5E
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var TEMPLATE_ID = 'xxx';
  var ui = SpreadsheetApp.getUi();
  if (TEMPLATE_ID === '') {
    ui.alert('TEMPLATE_ID needs to be defined in code.gs')
    return
  }
  var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy();
  var copyId = copyFile.getId();
  var copyDoc = DocumentApp.openById(copyId);
  var FILE_NAME = ui.prompt('Insert doc name:', ui.ButtonSet.OK);
  copyDoc.setName(FILE_NAME.getResponseText());
  var copyBody = copyDoc.getBody();
  var lastColumn = sheet.getLastColumn();
  var activeRowIndex = sheet.getActiveRange().getRowIndex();
  var activeRow = sheet.getRange(activeRowIndex, 1, 1, lastColumn).getDisplayValues()[0];
  var headerRow = sheet.getRange(1, 1, 1, lastColumn).getDisplayValues()[0];
  for (var columnIndex = 0; columnIndex < headerRow.length; columnIndex++) {
    if (columnIndex === tableColumn[0] - 1) { // Check if column corresponds to table data
      try {
        var tableValues = sheet.getRange(2, tableColumn[0], sheet.getLastRow()-1,tableColumn[1]-tableColumn[0]+1).getDisplayValues();
        var placeholder = `%${headerRow[tableColumn[0]-1]}%`;
        var rangeElement = copyBody.findText(placeholder);
        var element = rangeElement.getElement();
        console.log(element.asText().getText())
        var childIndex = copyBody.getChildIndex(element.getParent());
        console.log(childIndex)
        const elementText = copyBody.getChild(childIndex).asText().getText();
        const [beforeText, afterText] = elementText.split(placeholder);
        copyBody.getChild(childIndex).asText().setText('');
        copyBody.insertParagraph(childIndex, beforeText);
        copyBody.insertTable(childIndex+1, tableValues).setColumnWidth(0, 215).setColumnWidth(1, 85).setColumnWidth(2, 150);
        copyBody.insertParagraph(childIndex+2, afterText);
      } catch(err) {
        continue;
      }
    } else if (columnIndex < tableColumn[0] - 1 || columnIndex > tableColumn[1] - 1) {
      var nextValue = formatString(activeRow[columnIndex]);
      copyBody.replaceText('%' + headerRow[columnIndex] + '%', nextValue);
    }
  }
  copyDoc.saveAndClose();
  SpreadsheetApp.getUi().alert('doc created!!')
}
</code>```

答:
My Solution:

```<code>function creategoogledoc() {
  var tableColumn = [3,5]; // Table1 header is in column 3C to 5E
  var tableColumn2 = [7,12]; // Table2
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var TEMPLATE_ID = 'xxx';
  var ui = SpreadsheetApp.getUi();
  if (TEMPLATE_ID === '') {
    ui.alert('TEMPLATE_ID needs to be defined in code.gs')
    return
  }
  var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy();
  var copyId = copyFile.getId();
  var copyDoc = DocumentApp.openById(copyId);
  var FILE_NAME = ui.prompt('Insert google doc name:', ui.ButtonSet.OK);
  copyDoc.setName(FILE_NAME.getResponseText());
  var copyBody = copyDoc.getBody();
  var lastColumn = sheet.getLastColumn();
  var activeRowIndex = sheet.getActiveRange().getRowIndex();
  var activeRow = sheet.getRange(activeRowIndex, 1, 1, lastColumn).getDisplayValues()[0];
  var headerRow = sheet.getRange(1, 1, 1, lastColumn).getDisplayValues()[0];
  for (var columnIndex = 0; columnIndex < headerRow.length; columnIndex++) {
    if (columnIndex === tableColumn[0] - 1) { // Check if column corresponds to table data
      try {
        var tableValues = sheet.getRange(2, tableColumn[0], 6,tableColumn[1]-tableColumn[0]+1).getDisplayValues();
        var placeholder = `%${headerRow[tableColumn[0]-1]}%`;
        var rangeElement = copyBody.findText(placeholder);
        var element = rangeElement.getElement();
        console.log(element.asText().getText())
        var childIndex = copyBody.getChildIndex(element.getParent());
        console.log(childIndex)
        const elementText = copyBody.getChild(childIndex).asText().getText();
        const [beforeText, afterText] = elementText.split(placeholder);
        copyBody.getChild(childIndex).asText().setText('');
        copyBody.insertParagraph(childIndex, beforeText);
        copyBody.insertTable(childIndex+1, tableValues).setColumnWidth(0, 255).setColumnWidth(1, 100).setColumnWidth(2, 165);
        copyBody.insertParagraph(childIndex+2, afterText);
      } catch(err) {
        continue;
      }
    } else if (columnIndex < tableColumn2[0] - 1 || columnIndex > tableColumn2[1] - 1) {
      var nextValue = formatString(activeRow[columnIndex]);
      copyBody.replaceText('%' + headerRow[columnIndex] + '%', nextValue);
    }
  }
    for (var columnIndex = 0; columnIndex < headerRow.length; columnIndex++) {
    if (columnIndex === tableColumn2[0] - 1) { // Check if column corresponds to table data
      try {
        var tableValues = sheet.getRange(2, tableColumn2[0], sheet.getLastRow()-1,tableColumn2[1]-tableColumn2[0]+1).getDisplayValues();
        var placeholder = `%${headerRow[tableColumn2[0]-1]}%`;
        var rangeElement = copyBody.findText(placeholder);
        var element = rangeElement.getElement();
        console.log(element.asText().getText())
        var childIndex = copyBody.getChildIndex(element.getParent());
        console.log(childIndex)
        const elementText = copyBody.getChild(childIndex).asText().getText();
        const [beforeText, afterText] = elementText.split(placeholder);
        copyBody.getChild(childIndex).asText().setText('');
        copyBody.insertParagraph(childIndex, beforeText);
        copyBody.insertTable(childIndex+1, tableValues).setColumnWidth(0, 135).setColumnWidth(1, 80).setColumnWidth(2, 63).setColumnWidth(3, 95).setColumnWidth(4, 50).setColumnWidth(5, 100).setColumnWidth(6, 155);
        copyBody.insertParagraph(childIndex+2, afterText);
      } catch(err) {
        continue;
      }
    } else if (columnIndex < tableColumn2[0] - 1 || columnIndex > tableColumn2[1] - 1) {
      var nextValue = formatString(activeRow[columnIndex]);
      copyBody.replaceText('%' + headerRow[columnIndex] + '%', nextValue);
    }
  }
  copyDoc.saveAndClose();
  SpreadsheetApp.getUi().alert('google doc created!!')
}
</code>```

Now, I would to find a way to display the link of the google doc created by the script, in the dialog box.

Body:
Reference to this question see link I would to have the possibility to put 2 tables in my Google Doc from the Spreadsheet. In the code below I can put only 1 table (from col C to col E). My need is to put also a second table from col H to col N.

What I could add to the script?

function generateDoc() {
  var tableColumn = [3,5]; // Table1 header is in column 3C to 5E
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var TEMPLATE_ID = 'xxx';
  var ui = SpreadsheetApp.getUi();
  if (TEMPLATE_ID === '') {
    ui.alert('TEMPLATE_ID needs to be defined in code.gs')
    return
  }
  var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy();
  var copyId = copyFile.getId();
  var copyDoc = DocumentApp.openById(copyId);
  var FILE_NAME = ui.prompt('Insert doc name:', ui.ButtonSet.OK);
  copyDoc.setName(FILE_NAME.getResponseText());
  var copyBody = copyDoc.getBody();
  var lastColumn = sheet.getLastColumn();
  var activeRowIndex = sheet.getActiveRange().getRowIndex();
  var activeRow = sheet.getRange(activeRowIndex, 1, 1, lastColumn).getDisplayValues()[0];
  var headerRow = sheet.getRange(1, 1, 1, lastColumn).getDisplayValues()[0];
  for (var columnIndex = 0; columnIndex < headerRow.length; columnIndex++) {
    if (columnIndex === tableColumn[0] - 1) { // Check if column corresponds to table data
      try {
        var tableValues = sheet.getRange(2, tableColumn[0], sheet.getLastRow()-1,tableColumn[1]-tableColumn[0]+1).getDisplayValues();
        var placeholder = `%${headerRow[tableColumn[0]-1]}%`;
        var rangeElement = copyBody.findText(placeholder);
        var element = rangeElement.getElement();
        console.log(element.asText().getText())
        var childIndex = copyBody.getChildIndex(element.getParent());
        console.log(childIndex)
        const elementText = copyBody.getChild(childIndex).asText().getText();
        const [beforeText, afterText] = elementText.split(placeholder);
        copyBody.getChild(childIndex).asText().setText('');
        copyBody.insertParagraph(childIndex, beforeText);
        copyBody.insertTable(childIndex+1, tableValues).setColumnWidth(0, 215).setColumnWidth(1, 85).setColumnWidth(2, 150);
        copyBody.insertParagraph(childIndex+2, afterText);
      } catch(err) {
        continue;
      }
    } else if (columnIndex < tableColumn[0] - 1 || columnIndex > tableColumn[1] - 1) {
      var nextValue = formatString(activeRow[columnIndex]);
      copyBody.replaceText('%' + headerRow[columnIndex] + '%', nextValue);
    }
  }
  copyDoc.saveAndClose();
  SpreadsheetApp.getUi().alert('doc created!!')
}

Body:
My Solution:

function creategoogledoc() {
  var tableColumn = [3,5]; // Table1 header is in column 3C to 5E
  var tableColumn2 = [7,12]; // Table2
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var TEMPLATE_ID = 'xxx';
  var ui = SpreadsheetApp.getUi();
  if (TEMPLATE_ID === '') {
    ui.alert('TEMPLATE_ID needs to be defined in code.gs')
    return
  }
  var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy();
  var copyId = copyFile.getId();
  var copyDoc = DocumentApp.openById(copyId);
  var FILE_NAME = ui.prompt('Insert google doc name:', ui.ButtonSet.OK);
  copyDoc.setName(FILE_NAME.getResponseText());
  var copyBody = copyDoc.getBody();
  var lastColumn = sheet.getLastColumn();
  var activeRowIndex = sheet.getActiveRange().getRowIndex();
  var activeRow = sheet.getRange(activeRowIndex, 1, 1, lastColumn).getDisplayValues()[0];
  var headerRow = sheet.getRange(1, 1, 1, lastColumn).getDisplayValues()[0];
  for (var columnIndex = 0; columnIndex < headerRow.length; columnIndex++) {
    if (columnIndex === tableColumn[0] - 1) { // Check if column corresponds to table data
      try {
        var tableValues = sheet.getRange(2, tableColumn[0], 6,tableColumn[1]-tableColumn[0]+1).getDisplayValues();
        var placeholder = `%${headerRow[tableColumn[0]-1]}%`;
        var rangeElement = copyBody.findText(placeholder);
        var element = rangeElement.getElement();
        console.log(element.asText().getText())
        var childIndex = copyBody.getChildIndex(element.getParent());
        console.log(childIndex)
        const elementText = copyBody.getChild(childIndex).asText().getText();
        const [beforeText, afterText] = elementText.split(placeholder);
        copyBody.getChild(childIndex).asText().setText('');
        copyBody.insertParagraph(childIndex, beforeText);
        copyBody.insertTable(childIndex+1, tableValues).setColumnWidth(0, 255).setColumnWidth(1, 100).setColumnWidth(2, 165);
        copyBody.insertParagraph(childIndex+2, afterText);
      } catch(err) {
        continue;
      }
    } else if (columnIndex < tableColumn2[0] - 1 || columnIndex > tableColumn2[1] - 1) {
      var nextValue = formatString(activeRow[columnIndex]);
      copyBody.replaceText('%' + headerRow[columnIndex] + '%', nextValue);
    }
  }
    for (var columnIndex = 0; columnIndex < headerRow.length; columnIndex++) {
    if (columnIndex === tableColumn2[0] - 1) { // Check if column corresponds to table data
      try {
        var tableValues = sheet.getRange(2, tableColumn2[0], sheet.getLastRow()-1,tableColumn2[1]-tableColumn2[0]+1).getDisplayValues();
        var placeholder = `%${headerRow[tableColumn2[0]-1]}%`;
        var rangeElement = copyBody.findText(placeholder);
        var element = rangeElement.getElement();
        console.log(element.asText().getText())
        var childIndex = copyBody.getChildIndex(element.getParent());
        console.log(childIndex)
        const elementText = copyBody.getChild(childIndex).asText().getText();
        const [beforeText, afterText] = elementText.split(placeholder);
        copyBody.getChild(childIndex).asText().setText('');
        copyBody.insertParagraph(childIndex, beforeText);
        copyBody.insertTable(childIndex+1, tableValues).setColumnWidth(0, 135).setColumnWidth(1, 80).setColumnWidth(2, 63).setColumnWidth(3, 95).setColumnWidth(4, 50).setColumnWidth(5, 100).setColumnWidth(6, 155);
        copyBody.insertParagraph(childIndex+2, afterText);
      } catch(err) {
        continue;
      }
    } else if (columnIndex < tableColumn2[0] - 1 || columnIndex > tableColumn2[1] - 1) {
      var nextValue = formatString(activeRow[columnIndex]);
      copyBody.replaceText('%' + headerRow[columnIndex] + '%', nextValue);
    }
  }
  copyDoc.saveAndClose();
  SpreadsheetApp.getUi().alert('google doc created!!')
}

Now, I would to find a way to display the link of the google doc created by the script, in the dialog box.


问:
Check table row number on button click
Hi i've this code and in for each part i create a table with 3 cells (name, timestamp and operation with a button view). I see some elements in this table, but when i click the button "VIEW" i want to know the id or number of the row clicked.
This is the code:</p>
```<code>  protected void Page_Load(object sender, EventArgs e)
        {
            List<myproject> items = new List<myproject>();
            string session = (string)Session["username"];
            string id_login = "";

            using (SqlConnection sqlCon = new SqlConnection(@"Data Source=DESKTOP-9UN2C31;Initial Catalog=projectdatabase;Integrated Security=True"))
            {
                sqlCon.Open();
                string query1 = "SELECT id FROM dbo.login WHERE username=@username";
                SqlCommand sqlCmd1 = new SqlCommand(query1, sqlCon);
                sqlCmd1.Parameters.AddWithValue("@username", session);
                SqlDataReader rdr1 = sqlCmd1.ExecuteReader();

                    while (rdr1.Read())
                    {
                        id_login = rdr1.GetString(0);
                    }
                     rdr1.Close();

                    string query = "SELECT nome, timestamp FROM dbo.project WHERE id_login=@id_login";
                    SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                    sqlCmd.Parameters.AddWithValue("@id_login", id_login);

                    using (var rdr = sqlCmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            items.Add(new myproject { nome = (string)rdr["nome"], timestamp = (string)rdr["timestamp"]});

                        }
                        rdr.Close();

                    }
                }

                foreach (var element in items)
                {
                    Button b = new Button();
                    b.Text = "VIEW";
                    TableRow tr = new TableRow();
                    TableCell tc1 = new TableCell();
                    TableCell tc2 = new TableCell();
                    TableCell tc3 = new TableCell();
                    tc1.Controls.Add(new LiteralControl("<span>" + element.nome + "</span>"));
                    tc2.Controls.Add(new LiteralControl(element.timestamp));
                    tc3.Controls.Add(b);

                    tr.Controls.Add(tc1);
                    tr.Controls.Add(tc2);
                    tr.Controls.Add(tc3);
                    Table1.Controls.Add(tr);
                    System.Diagnostics.Debug.WriteLine(element.nome + " " + element.timestamp);

                }
</code>```

答:
I would suggest using a grid view, or even a list view.

so, say you have this markup:

```<code>        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
          cssclass="table"  width="30%">
            <Columns>
                <asp:BoundField DataField="Nome" HeaderText="Nome"  />
                <asp:BoundField DataField="timestamp" HeaderText="timestamp" />

                <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Button ID="cmdView" runat="server" Text="View"  CssClass="btns"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
</code>```

And now your code can be this:

```<code>           string query = "SELECT nome, timestamp FROM dbo.project";
            SqlCommand sqlCmd = new SqlCommand(query, sqlCon);

            DataTable rstData = new DataTable();
            rstData.Load(sqlCmd.ExecuteReader());

            GridView1.DataSource = rstData;
            GridView1.DataBind();
</code>```

(I left out the parameter's - but you do want to keep them as you have).

So, now we see this:

Ok, so now add a event to the button click:

And our button code click is thus:

```<code>   protected void cmdView_Click(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        GridViewRow gRow = btn.NamingContainer as GridViewRow;

        Debug.Print("Row index click = " + gRow.RowIndex.ToString());
        Debug.Print("First column value = " + gRow.Cells[0].Text);
        DateTime? myDt = DateTime.Parse(gRow.Cells[1].Text);
        Debug.Print("2nd column value = " +  myDt.ToString());
    }
</code>```

OutPut:

```<code>Row index click = 3
First column value = SR-71A.jpg
2nd column value = 2022-02-05 7:22:00 PM
</code>```

Title: Check table row number on button click

Body:
Hi i've this code and in for each part i create a table with 3 cells (name, timestamp and operation with a button view). I see some elements in this table, but when i click the button "VIEW" i want to know the id or number of the row clicked.
This is the code:

  protected void Page_Load(object sender, EventArgs e)
        {
            List<myproject> items = new List<myproject>();
            string session = (string)Session["username"];
            string id_login = "";

            using (SqlConnection sqlCon = new SqlConnection(@"Data Source=DESKTOP-9UN2C31;Initial Catalog=projectdatabase;Integrated Security=True"))
            {
                sqlCon.Open();
                string query1 = "SELECT id FROM dbo.login WHERE username=@username";
                SqlCommand sqlCmd1 = new SqlCommand(query1, sqlCon);
                sqlCmd1.Parameters.AddWithValue("@username", session);
                SqlDataReader rdr1 = sqlCmd1.ExecuteReader();

                    while (rdr1.Read())
                    {
                        id_login = rdr1.GetString(0);
                    }
                     rdr1.Close();

                    string query = "SELECT nome, timestamp FROM dbo.project WHERE id_login=@id_login";
                    SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                    sqlCmd.Parameters.AddWithValue("@id_login", id_login);

                    using (var rdr = sqlCmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            items.Add(new myproject { nome = (string)rdr["nome"], timestamp = (string)rdr["timestamp"]});

                        }
                        rdr.Close();

                    }
                }

                foreach (var element in items)
                {
                    Button b = new Button();
                    b.Text = "VIEW";
                    TableRow tr = new TableRow();
                    TableCell tc1 = new TableCell();
                    TableCell tc2 = new TableCell();
                    TableCell tc3 = new TableCell();
                    tc1.Controls.Add(new LiteralControl("" + element.nome + ""));
                    tc2.Controls.Add(new LiteralControl(element.timestamp));
                    tc3.Controls.Add(b);

                    tr.Controls.Add(tc1);
                    tr.Controls.Add(tc2);
                    tr.Controls.Add(tc3);
                    Table1.Controls.Add(tr);
                    System.Diagnostics.Debug.WriteLine(element.nome + " " + element.timestamp);

                }

Body:
I would suggest using a grid view, or even a list view.

so, say you have this markup:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
          cssclass="table"  width="30%">
            <Columns>
                <asp:BoundField DataField="Nome" HeaderText="Nome"  />
                <asp:BoundField DataField="timestamp" HeaderText="timestamp" />

                <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Button ID="cmdView" runat="server" Text="View"  CssClass="btns"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

And now your code can be this:

           string query = "SELECT nome, timestamp FROM dbo.project";
            SqlCommand sqlCmd = new SqlCommand(query, sqlCon);

            DataTable rstData = new DataTable();
            rstData.Load(sqlCmd.ExecuteReader());

            GridView1.DataSource = rstData;
            GridView1.DataBind();

(I left out the parameter's - but you do want to keep them as you have).

So, now we see this:

Ok, so now add a event to the button click:

And our button code click is thus:

   protected void cmdView_Click(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        GridViewRow gRow = btn.NamingContainer as GridViewRow;

        Debug.Print("Row index click = " + gRow.RowIndex.ToString());
        Debug.Print("First column value = " + gRow.Cells[0].Text);
        DateTime? myDt = DateTime.Parse(gRow.Cells[1].Text);
        Debug.Print("2nd column value = " +  myDt.ToString());
    }

OutPut:

Row index click = 3
First column value = SR-71A.jpg
2nd column value = 2022-02-05 7:22:00 PM


答:
In Google Collab you have to upload it in sample_data folder. But the file will lost after you close it. Other alternatives are jupyter notebook where you can do everything in google collab but offline.

But if you want to use google collab here's where you need to upload

```<code>Files >> sample_data >> upload files
</code>```

Title: (Python)Unable to import excel file using colab

Body:
In Google Collab you have to upload it in sample_data folder. But the file will lost after you close it. Other alternatives are jupyter notebook where you can do everything in google collab but offline.

But if you want to use google collab here's where you need to upload

Files >> sample_data >> upload files


问:
Some emojis dont render properly for flutter textfield
I'm using a textfield widget:

```<code>TextField(
  controller: _taskNamecontroller,
  focusNode: _focus,
  textInputAction: TextInputAction.done,
  maxLines: null,
  decoration: InputDecoration(
      border: InputBorder.none,
      hintText: SC.current.taskHeaderTaskName),
  style: const TextStyle(
      fontSize: 18,
      fontWeight: FontWeight.bold,
      height: 1.25),
),
</code>```

and when adding this emoji 1⃣ from the keyboard, it renders very strangely, it shows the 1 followed by a weird symbol:

Why is Flutter failing to render this emoji appropriately?

答: use  GoogleFonts.notoColorEmojiCompat() for style</p>

Body:
I'm using a textfield widget:

TextField(
  controller: _taskNamecontroller,
  focusNode: _focus,
  textInputAction: TextInputAction.done,
  maxLines: null,
  decoration: InputDecoration(
      border: InputBorder.none,
      hintText: SC.current.taskHeaderTaskName),
  style: const TextStyle(
      fontSize: 18,
      fontWeight: FontWeight.bold,
      height: 1.25),
),

and when adding this emoji 1⃣ from the keyboard, it renders very strangely, it shows the 1 followed by a weird symbol:

Why is Flutter failing to render this emoji appropriately?