text:
Q: Filter the database I need to filter the sql database based on the user's input for 4 columns in an asp.net web Application. This situation, they can select or not all four columns or one column or 2 or etc. All  I have is 2^4(16) possibilities. Whats the best method to filter?
My gui screenshot:

Please guide me.
I wrote a query for selection of one of four:
SELECT acct_number AS AccountNo,
    cust_lname AS Name
FROM List
WHERE (ordr_date='" + orderdate + "'
    OR reader_code='" + rdrCode + "'
    OR dly_pack_no='" + dlyPack + "'
    OR walk_seq='" + wlkSeq + "')

A: SELECT acct_number AS AccountNo,
       cust_lname AS Name
FROM List
WHERE (ISNULL(orderdate,'')='' OR ISNULL(ordr_date,'')='' OR ordr_date='" + orderdate + "')
  AND (ISNULL(rdrCode,'')='' OR ISNULL(reader_code,'')='' OR reader_code='" + rdrCode + "')
  AND (ISNULL(dlyPack,'')='' OR ISNULL(dly_pack_no,'')='' OR dly_pack_no='" + dlyPack + "')
  AND (ISNULL(wlkSeq,'')='' OR ISNULL(walk_seq,'')='' OR walk_seq='" + wlkSeq + "')

A: try below query.
SELECT  acct_number AS AccountNo ,
    cust_lname AS Name
FROM    List
WHERE   ( ordr_date = '" + orderdate + "'
      OR " + orderdate + " = " + orderdate + "
    )
    AND ( reader_code = '" + rdrCode + "'
          OR " + rdrCode + " = " + rdrCode + "
        )
    AND ( dly_pack_no = '" + dlyPack + "'
          OR " + dlyPack + " = " + dlyPack + "
        )
    AND ( walk_seq = '" + wlkSeq + "'
          OR " + wlkSeq + " = " + wlkSeq + "
        )

A: Build your WHERE-clause dynamically and use parameters.
SqlCommand select =  new SqlCommand(@"SELECT acct_number AS AccountNo,
    cust_lname AS Name
    FROM List ");

if(!string.IsNullOrWhiteSpace(orderDate)) // use appropriate logic according to data type. I'm assuming string atm.
select.Parameters.Add(new SqlParameter() { ParameterName = "@ordr_date", Value = orderDate, SqlDbType = SqlDbType.NVarChar });

 // Repeat for each parameter and then...

 for(int i = 0; i < select.Parameters.Count; i++)
 {
     if(i == 0)
         select.CommandText += " WHERE ";
     else
         // OR as in the filter is not exclusive... depends on the filter logic you want to construct of course.
         // AND if it has to fulfill all properties
         select.CommandText += " OR ";
     select.CommandText += string.Format("{0} = {0}", select.Parameters[i].Name).Substring(1);
 }


text:
Q: String substitution within ruby array I have the following code, within which I want to change certain values to csv friendly, e.g., 'nil' to ''. I need to know how to make these changes. Thank you.
  def daily_door_schedule
    @tickets = Ticket.where(active: true).
      pluck(
        :door_manufacturer,
        :job_number,
        :door_style,
        :door_allocation_date,
        :date_doors_received_in_aub,
        :door_delivery_due_date,
        :notes
      )

    respond_to do |format|
      format.html
      format.csv { render text: @tickets.to_csv }
    end
  end

A: This should do it:
@tickets = Ticket.where(active: true).
  pluck(
    :door_manufacturer,
    :job_number,
    :door_style,
    :door_allocation_date,
    :date_doors_received_in_aub,
    :door_delivery_due_date,
    :notes
  ).map { |ticket| ticket.map(&:to_s) }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make five columns in one row in bootstrap? I gave width:20% to each columns and it make correct for the current screen size, how can i make it responsive for all screen sizes. I had created a fiddle here. Please help me to make the row responsive with five columns.
html

css
.add_more_images .grid-five{
  width:20%;
}

A: To make the images responsive you need to give them a width, in this case width: 100%
.grid-five {
  width: 20%;
}
.grid-five img {
  width: 100%;
}

Updated fiddle

.grid-five {
  width: 20%;
}

.grid-five img {
  width: 100%;
}

/* for styling this demo */

.grid-five {
  border: 2px dotted red;
  box-sizing: border-box;
}

.grid-five + .grid-five {
  border-left: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

A: Lets have a look to this fiddle: https://jsfiddle.net/ash06229/fng2zpbn/
.add_more_images .grid-five{
  min-width:320px;
  width: 20%;
}

.add_more_images .grid-five img {
  width: 100%;
}

.add_more_images {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -ms-flex-wrap: wrap;
      flex-wrap: wrap;
}


text:
Q: Why the following query return all the documents, instead of only those who pass the conditions? I have the following schema:
_id: ObjectId('631b875491b16c38eecfa4e9')
brandName: "Nick"
categories: Array
   0: ObjectId('62f3eaff3ded19dcce71081e')
   1: ObjectId('62f3eb283ded19dcce710824')
products: Array
   0: Object
      productName: "Vans Shoes dsds Old Skool"
      description: "amazing Shoes."
      categoryId: ObjectId('62f3eaff3ded19dcce71081e')
      price: 240
      _id: ObjectId(631b875491b16c38eecfa4ec)
   1: Object
   2: Object
   3: Object
__v: 0

My goal is to return only the documents greater or equal to the minPrice.
But unfortunately, all the documents are returned, even the ones with even more minimum prices.
  const products = await Brand.aggregate([
    {
      $match: {
        _id: ObjectId(brandId)
      }
    },
    {
      $project: {
        products: {
          $filter: {
            input: "$products",
            as: "product",
            cond: { $gte: ["$$product.price", +!!minPrice] },
          }
        }
      }
    }
  ])

So, what's wrong?


text:
Q: Python multiprocessing problem with dictionary as argument I have a function that parallizes another function via multiprocessing pool which takes a dictionary as input. I would expect that the code below just prints the number from 0 to 32. However, the result shows that there are many numbers being printed more than once.
Anybody an idea?
import multiprocessing as mp
import numpy as np
import functools

def test(name, t_dict):
    t_dict['a'] = name
    return t_dict

def mp_func(func, iterator ,**kwargs):
    f_args = functools.partial(func, **kwargs)
    pool = mp.Pool(mp.cpu_count())
    res = pool.map(f_args, iterator)
    pool.close()
    return res

mod =dict()

m =33
res = mp_func(func=test, iterator=np.arange(m), t_dict=mod)
for di in res:
    print(di['a'])

A: The problem is that t_dict is passed as part of the partial function f_args. Partial functions are instances of <class 'functools.partial'>. When you create the partial, it gets a reference to test and the empty dictionary in mod. Every time you call f_args, that one dictionary on the partial object is modified. This is easier to spot with a list in a single process.
>>> def foo(name, t_list):
...     t_list.append(name)
...     return t_list
...
>>> mod = []
>>> f = functools.partial(foo, t_list=mod)
>>> f(0)
[0]
>>> f(1)
[0, 1]
>>> f(2)
[0, 1, 2]
>>> mod
[0, 1, 2]

When you pool.map(f_args, iterator), f_args is pickled and sent to each subprocess to be the worker. So, each subprocess has a unique copy of the dictionary that will be updated for every iterated value the subprocess happens to get.
For efficiency, multiprocessing will chunk data. That is, each subprocess is handed a list of iterated values that it will process into a list of responses to return as a group. But since each response is referencing the same single dict, when the chunk is returned to the parent all of the responses only hold the final value set. If 0, 1, 2 were processed, the return is 2, 2, 2.
The solution will depend on your data. Its expensive to pass data back and forth between pool process and the parent, so ideally the data is generated completely in the worker. In this case, ditch the partial and have the worker create the dict.
Its likely your situation is more complicated than this.
import multiprocessing as mp
import numpy as np

def test(name):
    retrurn ('a':name}

def mp_func(func, iterator ,**kwargs):
    pool = mp.Pool(mp.cpu_count())
    res = pool.map(test, iterator)
    pool.close()
    return res

m =33
res = mp_func(func=test, iterator=np.arange(m))
for di in res:
    print(di['a'])

A: As everyone is telling you, in general, it is a bad idea to have multiple threads/processes all modifying the same location, and then expecting that location to have the value that your thread gave it.
Your code will run better if all mutating of the shared data structure happens in only one place.  So the general plan is:
def worker(key):
    ... calculate value produced by key ...
    return key, value

def runner():
    with mp.Pool() as pool:
       for key, value in pool.imap_unordered(worker, np.arange(m), chunksize=...):
           ... do fast mutation here ...


text:
Q: What does super.run() mean within a thread in Java? I don't really get the meaning of super.run();andsuper.handleMessage(msg);
Are they necessaary?
Where should my code be written? Before super.run();/super.handleMessage(msg); or after them?
new Thread(){
    @Override
    public void run() {
        super.run();
    }
}.start();

/
Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    }
};

A: Question

*

*I don't really get the meaning of super.run() and super.handleMessage(msg) Are they necessaary?

*Where should my code be written? Before super.run() or after them?

Answer - 1
This is unnecessary in the code in question.
new Thread(){
    @Override
    public void run() {
        super.run();
    }
}.start();

public class Thread implements Runnable
{
    ...
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
    ...
}

super.run is call Thread class. Therefore, it is not necessary because there is empty function.
Answer - 2
Please refer to the answer -1, you don't have to worry about it.
However, if your super.x is implemented, you will have to write code that depends on function.

A: The Thread class documentation clearly says
public void run()

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

Subclasses of Thread should override this method.

Similarly, Handler Java docs are not so clear, but if you see Handler's handleMessage method code, its empty.
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

So for both methods, calling super is not required. They both do nothing.
Your second question, answer depends on your requirement. Java does not restrict that call to super method has to be the first line of code ( except when you are writing constructors, then super constructor has to be called before any other line/ piece of code in sub class constructor).  If you need to process some logic before the super class method, you are free to do so. You could also call super method in between your method code if you want.  So you can call super method anywhere in the overridden method. You need to take a look at what super class method does and how do you need it to decide on when to call it.

A: when you are writing @Override  public void run() you are overriding the base run method so it will run what ever present on it.
In below example it will print inside run.If you pass target in constructor and call super.run() then target.run() method got called.
public static void main(String[] args) {
        new Thread(new test()){
            @Override
            public void run() {
               // super.run();
                System.out.println("inside run");
            }
        }.start();
    }

}
class test implements Runnable{

    @Override
    public void run() {
        System.out.println("inside target");

    }

 }


text:
Q: How to reduce/iterate multiple java streams of same size at once? I have multiple Java streams of the same length, and I want to perform some operation on the corresponding elements of each stream. For e.g., add 1st elements of all stream, 2nd elements of all streams and 3rd elements of all streams and so on.
How can we do this without first reducing each of the streams?
for Minimum reproducible example, I have the following test snippet
@Test
void aggregateMultipleStreams() {
    Stream<Integer> s1 = Stream.of(1, 2);
    Stream<Integer> s2 = Stream.of(4, 5);
    Stream<Integer> s3 = Stream.of(7, 8);
    assertEquals(List.of(1 + 4 + 7, 2 + 5 + 8), aggregate(s1, s2, s3, 2));
}

I can write the aggregate method as follows, by reducing all the streams first.
private List<Integer> aggregate(Stream<Integer> s1, Stream<Integer> s2, Stream<Integer> s3, int streamSize) {
    final List<List<Integer>> reduced = Stream.of(s1, s2, s3)
            .map(s -> s.collect(Collectors.toList())).collect(Collectors.toList());
    return IntStream.range(0, streamSize).mapToObj(n -> IntStream.range(0, reduced.size())
            .map(v -> reduced.get(v).get(n)).sum()).collect(Collectors.toList());
}

But this could be a storage hassle, if each stream contains numerous records, for N records, we need 3N storage here.
can we accomplish the addition of corresponding elements in different streams without first reduction? can we reduce multiple streams at once in Java?
After implementing @jb_dk's solution below, the solution code snippet became:
    private List<Integer> aggregate(Stream<Integer> s1, Stream<Integer> s2, Stream<Integer> s3, int streamSize) {

    final List<Iterator<Integer>> iterators = Stream.of(s1, s2, s3)
            .map(Stream::iterator).collect(Collectors.toList());
    return IntStream.range(0, streamSize).mapToObj(n -> IntStream.range(0, iterators.size())
            .map(v -> iterators.get(v).next()).sum()).collect(Collectors.toList());
}

A: Form an array of the input stream objects instead of 3 named variables, then create an output List or stream and use an outer loop over the stream length and an inner loop that iterates over the array of input streams and reads one element from each, adding to the output array elements.
Something like (code not tested, syntax errors may exist)
    ...
    {
        List<Integer> results; // NOT final, can be a stream builder instead
        final List<Stream<Integer>> instrms = Stream.Of(s1, s2, s3);
        Iterator<Integer>[] initers = new Iterator<Integer>[instrms.length]
        // Get the iterator (not rewindable) for each stream
        int i = 0;
        for (Stream<Integer> instrm : instrms) {
            initers[i++] = ((Iterator<Integer>)instrm::iterator);
        }
        // Actually loop over the stream elements, outputting one
        //    sum element for each element.  Assumes all input streams
        //    are same length as the first one.
        while(! initers[0].hasNext()) {
            Integer    res1 = 0;
            for (Iterator<Integer> initer : initers) {
                res1 += initer.next();
            }
            results.Add(res1);
        }
        return results;  // results.build() if a stream builder
    }


text:
Q: Don't include a JS library in webpack build (with the assumption that it'll be included in a script tag) I'm using a large library (around 1 MB) along with webpack for building. The library is just used normally - it's in package.json's dependencies, and at some point in my code I import it with an import from <lib_name> (this is in Typescript).
So right now, when I run a webpack build, the end result bundle.js contains all (or most? not sure how much webpack trims, actually) of the library's code. So even my barebones application that's only a couple lines of code and an import has that big 1MB build size.
What I would like to do is have the library not be thrown into the final build, and instead basically have in my HTML file something like this:
<script src="https://some.cdn.here/thelibrary-v0.0.0.min.js"></script>
<script src="bundle.js"></script>

In other words, the files in the build would be something like:
BEFORE:
  dist/
    bundle.js -- 1005 KB

AFTER:
  dist/
    thelibrary-v0.0.0.min.js -- 1000 KB
    bundle.js -- 5 KB

Where bundle.js becomes a very small file with just my code, and it simply expects the library to be loaded beforehand. To be clear - bundle.js would still be using things from the library and would need it to run. I'm not sure if this is actually possible or not, because I don't have a good understanding of how webpack actually handles imports and stuff (especially in conjunction with uglify/minification). Is it possible to do something like this, and if so, how?

A: It can be done with externals.
module.exports = {
  //...
  externals: {
    jquery: 'jQuery'// thelibrary in your case
  }
};


text:
Q: ServletException: JSP file not found once in three attempts on AWS bitnami Tomcat 8.5 Two WARs are built from the same commit, but not the same day. The version from June 15 was deployed on AWS (bitnami Tomcat8.5 image) and works perfectly. The version from June 23 when deployed, gives a javax.servlet.ServletException saying that file /WEB-INF/jsp/view/home.jsp is not found. It is, however, inside the deployed WAR. When trying to access the home.jsp page, 1/3 of the time, the page throws the error. The other two times are fine. This happens only with the JSP and not with the Thymeleaf pages. I compared both WARs with BeyondCompare software : they are identical except for the build datetime in git.properties. I thought maybe something changed on the server. But when I put back the version from June 15, it works again perfectly !
Here is the stack trace:

  23-06-2021 06:07:16.054 [http-nio-8080-exec-29] INFO  c.i.i.controller.HomeController - Requested Home Page
  23-06-2021 06:07:16.058 [http-nio-8080-exec-29] DEBUG c.i.i.controller.HomeController - Region for home=
  23-06-2021 06:07:16.060 [http-nio-8080-exec-29] DEBUG c.i.i.service.impl.RegionServiceImpl - No region found for name=
  23-06-2021 06:07:16.063 [http-nio-8080-exec-29] DEBUG c.i.i.s.impl.VehicleServiceImpl - Finding vehicles with useFeatured=true
  23-06-2021 06:07:16.089 [http-nio-8080-exec-29] DEBUG c.i.i.service.impl.RegionServiceImpl - No region found for name=
  23-06-2021 06:07:16.176 [http-nio-8080-exec-29] ERROR o.s.b.w.s.support.ErrorPageFilter - Forwarding to error page from request [/] due to exception [java.io.IOException: JSPException including path '/WEB-INF/jsp/view/home.jsp'.]
  org.apache.tiles.request.render.CannotRenderException: java.io.IOException: JSPException including path '/WEB-INF/jsp/view/home.jsp'.
          at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:399)
          at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:238)
          at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:221)
          at org.apache.tiles.renderer.DefinitionRenderer.render(DefinitionRenderer.java:59)
          at org.springframework.web.servlet.view.tiles3.TilesView.renderMergedOutputModel(TilesView.java:147)
          at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
          at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1393)
          at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1138)
          at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1077)
          at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
          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:231)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
          at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
          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:119)
          at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
          at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
          at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
          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.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
          at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
          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.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
          at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
          at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
          at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
          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.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
          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:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          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:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:126)
          at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:64)
          at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:101)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
          at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:119)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
          at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
          at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
          at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
          at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
          at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818)
          at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1626)
          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.io.IOException: java.io.IOException: JSPException including path '/WEB-INF/jsp/view/home.jsp'.
          at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:504)
          at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
          at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:713)
          at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:462)
          at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:387)
          at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:315)
          at org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequestDispatcher.forward(HeaderWriterFilter.java:171)
          at org.apache.tiles.request.servlet.ServletRequest.forward(ServletRequest.java:265)
          at org.apache.tiles.request.servlet.ServletRequest.doForward(ServletRequest.java:228)
          at org.apache.tiles.request.AbstractClientRequest.dispatch(AbstractClientRequest.java:57)
          at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47)
          at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259)
          at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:397)
          ... 96 common frames omitted
  Caused by: java.io.IOException: JSPException including path '/WEB-INF/jsp/view/home.jsp'.
          at org.apache.tiles.request.servlet.ServletUtil.wrapServletException(ServletUtil.java:63)
          at org.apache.tiles.request.jsp.JspRequest.doInclude(JspRequest.java:125)
          at org.apache.tiles.request.AbstractViewRequest.dispatch(AbstractViewRequest.java:47)
          at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47)
          at org.apache.tiles.request.render.ChainedDelegateRenderer.render(ChainedDelegateRenderer.java:68)
          at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259)
          at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:188)
          at org.apache.tiles.template.InsertAttributeModel.execute(InsertAttributeModel.java:132)
          at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:299)
          at org.apache.jsp.WEB_002dINF.jsp.layout.default_002dlayout_jsp._jspx_meth_tiles_005finsertAttribute_005f1(default_002dlayout_jsp.java:751)
          at org.apache.jsp.WEB_002dINF.jsp.layout.default_002dlayout_jsp._jspService(default_002dlayout_jsp.java:212)
          at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
          at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
          ... 124 common frames omitted
  Caused by: javax.servlet.ServletException: JSP file [/WEB-INF/jsp/view/home.jsp] not found
          at org.apache.jasper.servlet.JspServlet.handleMissingResource(JspServlet.java:407)
          at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:388)
          at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
          at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:713)
          at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:583)
          at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:519)
          at org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequestDispatcher.include(HeaderWriterFilter.java:177)
          at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:865)
          at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:679)
          at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:673)
          at org.apache.tiles.request.jsp.JspRequest.doInclude(JspRequest.java:123)
          ... 136 common frames omitted

And here is the pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.icimedia</groupId>
<artifactId>ici-autos</artifactId>
<version>2.2.0</version>

<packaging>war</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>11</java.version>
    <mapstruct.version>1.3.1.Final</mapstruct.version>
    <org.projectlombok.version>1.18.12</org.projectlombok.version>
    <!-- Apache Tiles -->
    <tiles.version>3.0.8</tiles.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-batch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.batch</groupId>
        <artifactId>spring-batch-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>${mapstruct.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- configuration processor to generate configuration metadata -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- Tomcat embedded container-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- JSTL for JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <!-- <scope>provided</scope> -->
    </dependency>

    <!-- Need this to compile JSP -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- Need this to compile JSP,
        tomcat-embed-jasper version is not working, no idea why -->
    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- Apache Tiles dependencies -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-core</artifactId>
        <version>${tiles.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-extras</artifactId>
        <version>${tiles.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-servlet</artifactId>
        <version>${tiles.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-api</artifactId>
        <version>${tiles.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>${tiles.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator-annotation-processor</artifactId>
    </dependency>

    <!-- FTP client -->
    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.7.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
        </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
</dependencies>

<build>
    <finalName>iciautos</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>

        <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
               <annotationProcessorPaths>
                <path>
                       <groupId>org.mapstruct</groupId>
                       <artifactId>mapstruct-processor</artifactId>
                       <version>${mapstruct.version}</version>
                   </path>
                   <!-- For JPA static metamodel generation -->
                   <path>
                       <groupId>org.hibernate</groupId>
                       <artifactId>hibernate-jpamodelgen</artifactId>
                       <version>${hibernate.version}</version>
                   </path>
                   <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${org.projectlombok.version}</version>
                    </path>
                   </annotationProcessorPaths>
                   <compilerArgs>
                       <arg>-Amapstruct.suppressGeneratorTimestamp=true</arg>
                       <arg>-Amapstruct.defaultComponentModel=spring</arg>
                   </compilerArgs>
           </configuration>
       </plugin>
       <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>add-source</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>add-source</goal>
                    </goals>
                    <configuration>
                        <sources>
                            <source>target/generated-sources/annotations</source>
                        </sources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>pl.project13.maven</groupId>
            <artifactId>git-commit-id-plugin</artifactId>
            <executions>
                <execution>
                    <phase>initialize</phase>
                    <goals>
                        <goal>revision</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <dateFormat>yyyyMMdd-HHmmss</dateFormat><!--  human-readable part of the version number -->
                <dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
                <generateGitPropertiesFile>true</generateGitPropertiesFile>
                <offline>true</offline>
            </configuration>
        </plugin>
    </plugins>
</build>

A: I found the solution to this strange intermittent problem. It had to do with clearing the Tomcat cache for compiled JSPs.
As explained in this post,
JSPs get compiled in /opt/bitnami/tomcat/work/Catalina/localhost. So we have to delete this cache, but first stop Tomcat :
sudo /opt/bitnami/ctlscript.sh stop tomcat

Then delete cache:
sudo rm -rf /opt/bitnami/tomcat/work/Catalina/localhost/iciautos

Then delete the application and copy new one:
sudo rm -rf /opt/bitnami/tomcat/webapps/iciautos
sudo rm -rf /opt/bitnami/tomcat/webapps/iciautos.war
sudo cp iciautos.war  /opt/bitnami/tomcat/webapps/

Then restart
sudo /opt/bitnami/ctlscript.sh start tomcat

Fixed !


text:
Q: getting error while multiplying two numbers in c# I am unable to find the service tax of a product. How do I get the service tax of a product? Should I use decimal or double? while using double its not giving error.
string StrVatPercentage = vatPercentage.Text;
decimal totalprice = Convert.ToDecimal(qty) * Convert.ToDecimal(price);
    // totalprice = 497080M // qty = 4 // price= 124,270.00

decimal serviceTaxPrice = totalprice * Convert.ToDecimal(StrVatPercentage)/100;
    // strVtPercentage=12.36M- getting error in this line

A: I believe the problem is in the value you have for StrVatPercentage.  You say it is equal to "12.36m-".  This will not convert because it is in the incorrect format.  I run this
 decimal totalprice = Convert.ToDecimal("4") * Convert.ToDecimal("124,270.00");
 decimal serviceTaxPrice = totalprice * Convert.ToDecimal("12.36") / 100;

And it works just fine.


text:
Q: C: why "sscanf" doesn't cut trailing characters? The following C code,
#include <stdio.h>
int main()
{
  char *source="{\"address\":\"10.10.2.130\"}";
  char ip[32];
  sscanf(source, "{\"address\":\"%s\"}", ip);
  printf("%s\n%s\n", source, ip);
  return 0;
}

I expect to extract 10.10.2.130 in ip, but the output shows 10.10.2.130"}, why?
Thanks.

A: Each part of the format string is executed without looking forward to see what's to come. So the %s matches the rest of the string. The subsequent characters in the format string just fail to match because you're trying to match characters that have already been read.
You may want something like %[^\"]s, which additionally stops reading if a quote is encountered.

A: %s stops scanning when it reaches whitespace or the end of the source string. Since the string you want to extract is terminated by a " character, you can use %[^"] to stop scanning on the first " character that is encountered, eg:
sscanf(source, "{\"address\":\"%[^\"]\"}", ip);

A: The specification of %s is:

Match a sequence of non-white-space characters.

Since the trailing "} is not whitespace, it's included in the match.
Instead, you can use the %[0-9.] format to match just numbers and dot.
sscanf(source, "{\"address\":\"%[0-9.]\"}", ip);


text:
Q: Can a GLM with exponential response distribution be transformed into a Poisson regression instead? Given the following generative model
$$T | \mathbf{x_i} \sim \operatorname{Exp}(\lambda_i)$$
$$\ln(\lambda_i) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots$$
That is: I have observations of covariate/response pairs $(\mathbf{x}_i, t_i)$, such that $t_i$ are measurements of inter-arrival time of events, and is assumed to be exponentially distributed. I would like to fit a GLM such that the response distribution is exponential and using a log link. I note that you can do it in a roundabout way using a gamma family: Fitting exponential (regression) model by MLE?
What I am wondering is whether it is possible to transform this into a Poisson regression model like the following:
$$Y | \mathbf{x_i} \sim \operatorname{Pois}(\lambda_i)$$
$$\ln(\lambda_i) = \beta_0 + \beta_1 x_1 + \dots + \beta_n x_n + \ln(t_i)$$
that is, include the time to observe one event as an offset term in the regression equation, which factors in the exposure time: Where does the offset go in Poisson/negative binomial regression?


text:
Q: ImageUploadEditor : "Uploaded file is not an image!" I have install Serenity .Net Core 3.1 on a linux centos server.
When I try to upload an image (for example a product image), I have the message :
"Uploaded file is not an image!"
The file is really an image, but the application can not create the image on the server.
The "UploadSettings" in appsettins.json seems correct.
The Directory App_Data/upload/ exists and have the good permissions.
Have you an idea how to resolve this problem ?
Thank you.

A: My solution: finally, I upgraded the framework and got a more explicit error message.
The libgdiplus library must be installed: it is used internally to make the image labels.


text:
Q: Android: dealing with spanish e accent I am working on an Android app that I would like to code in such a way so that the Spanish characters coming from the database are read as equivalent to the English ones. For instance, cafe and café would be identical.
Is there a way to do this?

A: Do you mean that you want queries to find both "cafe" and "café" when you search for "cafe"?  You should be able to use a regular expressions to do this.
If this needs to be done on the fly, you could write a function that parses the request for 'e' and generate the correct regular expression before creating the DB query.


text:
Q: Is this proof by contradiction for the Archimedean Property correct? I'm just starting to learn how to use proofs by contradiction, and I am just wondering if this works.
Theorem (Archimedean Property):
If $a$ and $b$ are any positive integers, then there exists a positive integer $n$ such that $na \geq b$.
Proof:
Suppose not. Suppose that there exists a positive integer $a$ and $b$ such that for all positive integer $n$, we have $na<b$. Let $n=b$, so $ab<b\Rightarrow \frac{ab}{b}<\frac{b}{b}\Rightarrow a<1.$ Thus, $a$ is a positive integer and $a$ is less than $1$, which is a contradiction.


text:
Q: flush printwriter on application close So I have a printwriter that will occasionally write to a file ("occasionally" here meaning "periodically after a certain number of specified events").
Now if these events happen to be too few, the log file may end up empty when the application is terminated (Ctrl + C).
I could, of course, flush after every println, but that would defeat the purpose of having a non-auto-flush printwriter (which is the only kind that can be created anyway if I want to pass a File as a constructor argument).
Is there a onApplicationKill-thing in Java I could instrument to flush the writer once when the application is terminated? Or something to detect when the current thread is killed?

A: You can use a shutdown hook:
Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
      ...
      writer.flush();
  }
});

It should also work if you kill it with Ctrl+C


text:
Q: OpenCV Video Feed Automatic Resizing with PyQt5 this is my first post on Stack Overflow so I hope I'm doing everything correctly.
I have been trying to get a video feed using OpenCV on a GUI made using PyQt5. I eventually got this to work, but it is always 640 x 480 (the size I set it to). However, I want it to automatically scale/resize (with the same aspect ratio) to fit within its parenting widget. For example, when I expand the window, the video feed should scale, too. Does anyone know a way to do this?
Here is a sample of my code for reference:
Camera Widget
class Camera(QWidget):
    def __init__(self, port):
        super().__init__()

        self.display_width = 640
        self.display_height = 480

        self.camera = QLabel(self)
        self.camera.resize(self.display_width, self.display_height)

        self.label = QLabel(f'Port {port}')

        self.label.setStyleSheet("""
            QLabel {
                color: white;
                font: bold 30px
            }
        """)

        # Layout
        self.layout = QVBoxLayout()

        self.layout.addWidget(self.label)
        self.layout.addWidget(self.camera)

        self.setLayout(self.layout)

        self.thread = VideoThread(port)
        self.thread.change_pixmap_signal.connect(self.update_image)
        self.thread.start()

    def close_event(self, event):
        self.thread.stop()
        event.accept()

    @pyqtSlot(ndarray)
    def update_image(self, cv_img):
        qt_img = self.convert_cv_qt(cv_img)
        self.camera.setPixmap(qt_img)

    def convert_cv_qt(self, cv_img):
        rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        convert_to_Qt_format = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
        p = convert_to_Qt_format.scaled(self.display_width, self.display_height, Qt.KeepAspectRatio)
        return QPixmap.fromImage(p)

Video feed Thread
class VideoThread(QThread):
    change_pixmap_signal = pyqtSignal(ndarray)

    def __init__(self, port):
        super().__init__()
        self.running = True
        self.port = port

    def run(self):
        self.capture = cv2.VideoCapture(self.port)

        while self.running:
            self.ret, self.image = self.capture.read()
            if self.ret:
                self.change_pixmap_signal.emit(self.image)

        self.capture.release()

    def stop(self):
        self.running = False
        self.wait()

A: You should get the resize event of self.camera and set it's width to self.display_width and it's height to self.display_height
and this statement p = convert_to_Qt_format.scaled(self.display_width, self.display_height, Qt.KeepAspectRatio)  will do the rest of the work

Update
Set the Minimum size to avoid recursive loop which will keep expanding window
To avoid shaking you can use a fixed size container or remove Qt.KeepAspectRatio which helps shaking the window

*

*HERE IS THE UPDATED CODE

from PyQt5 import QtCore, QtGui, QtWidgets
import cv2
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from numpy import ndarray

class Camera(QWidget):
    def __init__(self, port):
        super().__init__()

        self.display_width = 640
        self.display_height = 480

        self.camera = QLabel()
        # self.camera.setGeometry(0,0,640,480)
        self.camera.resize(self.display_width, self.display_height)

        #  Set Minimum size of camera stream to avoid going in recursive loop
        self.camera.setMinimumWidth(640)
        self.camera.setMinimumHeight(480)

        self.label = QLabel(f'Port {port}')

        self.label.setStyleSheet("""
                color: black;
                font: 30px;
        """)

        # Layout

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.camera)

        self.setLayout(self.layout)

        # Get the resize Event Callback
        self.resizeEvent = self.label_resize
        self.camera.resizeEvent = self.camera_resize

        self.thread = VideoThread(port)
        self.thread.change_pixmap_signal.connect(self.update_image)
        self.thread.start()

    # Resize Event Callback
    def label_resize(self, resizeEvent:QResizeEvent):
        self.camera.resize(resizeEvent.size())

    # Resize Event Callback
    def camera_resize(self, resizeEvent:QResizeEvent):
        self.display_width, self.display_height = self.camera.width(), self.camera.height()

    def close_event(self, event):
        self.thread.stop()
        event.accept()

    @pyqtSlot(ndarray)
    def update_image(self, cv_img):
        qt_img = self.convert_cv_qt(cv_img)
        self.camera.setPixmap(qt_img)

    def convert_cv_qt(self, cv_img):
        rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        convert_to_Qt_format = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
        p = convert_to_Qt_format.scaled(self.display_width, self.display_height, Qt.KeepAspectRatio)
        return QPixmap.fromImage(p)

class VideoThread(QThread):
    change_pixmap_signal = pyqtSignal(ndarray)

    def __init__(self, port):
        super().__init__()
        self.running = True
        self.port = port

    def run(self):
        self.capture = cv2.VideoCapture(self.port)

        while self.running:
            self.ret, self.image = self.capture.read()
            if self.ret:
                self.change_pixmap_signal.emit(self.image)

        self.capture.release()

    def stop(self):
        self.running = False
        self.wait()


text:
Q: better way to write if else statement First time writing Javascript. I just would like know if there is a shorter way of writing this:

Tried map but I couldn't get it to work.

A: There isn't really a shorter way to write an if statement in that way (which I will assume is what you're asking).  However, there could be a few different ways to write this depending on how many things you want to check.
Use a Switch statement
There is a cleaner way when dealing with multiple cases that letter could be.
This would be a switch statement and it would look like this:
var text;

switch (letter) {
    case "5544":
        text = "Abar, Marlon 1,800";
    break;
    case "5545":
        text = "Pia, Darla 1,800";
    break;

    // more cases

    default:
        text = "Incorrect Account Number";
    break;
}

This reads a little better than an if else statement in some cases.  The default keyword here acts as your else clause in an if else statement.  The case acts as your different if statements if you will.
Essentially, the switch statement above will fall through each of the cases it defines until it finds a case that matches letter (such as "5544").  If none matches, it hits the default case.  The break keyword at the end of each case stops things from falling through to the next defined case once a match is found.
This method could get cumbersome with more than 6 or 7 cases.
Create an object and look up the value
Now, a shorter way to get the value you want could be to define an object and get the value based on what has been entered like so:
var letter = document.getElementById('selector').value;
var obj = {
    '5544': 'Abar, Marlon 1,800'
};

if (letter in obj) {
   // do something if found
}
else {
   // do something if not found
}

This could be an easy way to get a value if you have many values to check.
Other thoughts
As a side note to all of this, there are short hand if statements called ternary statements which you can find here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator ... However, I would not recommend nesting these as it becomes very complicated and not very readable.
Conclusion
So, to reiterate the answer to your question: No, there isn't really a shorter way to write an if else statement with many values.  You can use a switch statement to make it cleaner.  Use the object lookup method if you have many values you would like to check.

A: JavaScript has object (map) literals.  Use them for terse code.  In your final application you'll get the data for the map from someplace else and not code it directly into your website, but if you did, it would look like this:
document.getElementById( "demo" ).innerHTML = {
    "5544" : "Abar, Marlon 1,800",
    "5445" : "Pia, Darla 1,800",
    ...
}[ document.getElementById( "myInput" ).value ];

A: you can use switch for a long if - else -if ladder:
switch(expression) {
case n:
    code block
    break;
case n:
    code block
    break;
default:
    default code block
}

This is how it works:
1)The switch expression is evaluated once.
2)The value of the expression is compared with the values of each case.
3)If there is a match, the associated block of code is executed.
if you need basic tutorials in java script then you should try w3 schools.


text:
Q: Show that this function is infinitely often differentiable I have the function $g(r):=e^{-\frac{1}{1-r}}$ for $r \in  [0,1)$ and $0$ for $r \ge 1$. Now, I want to show that $g \in C^{\infty}([0,\infty))$. I guess this can be shown somehow by finding an inductive pattern in the derivatives, but I don't see it.

A: Let $h(r)$ be a rational function. Show that the derivative of $h(r)g(r)$ still is a rational function times $g(r)$.
Additionally, you need to show that the new rational function is well defined at any point where $h$ and $g$ was.


text:
Q: How to find and replace for ranges with gsub I have text as follows:
".OESOPHAGUS: inflammation. STOMACH: Lots of information here.DUODENUM: Some more information. ENDOSCOPIC DIAGNOSIS blabla"

I would like to replace any full stop followed by a letter (upper or lower case) to be replaced by a full stop, newline and then the letter. so that the output should be:
".\nOESOPHAGUS: inflammation. .\nSTOMACH: Lots of information here. .\nDUODENUM: Some more information. .\nENDOSCOPIC DIAGNOSIS blabla"

I tried:
gsub("\\..*?([A-Za-z])","\\.\n\\1",MyData$Algo)

but this gives me:
.\nESOPHAGUS: inflammation.\nTOMACH: Lots of information here.DUODENUM: Some more information.\nNDOSCOPIC DIAGNOSIS blabla"

The problem seems to be in the matching of ranges as specified. Is there a way to do this find-replace. I am not reliant on gsub.

A: Perl Compatible Regular Expressions (PCRE) should work well in this example.
a =  ".OESOPHAGUS: inflammation. STOMACH: Lots of information here.DUODENUM: Some more information. ENDOSCOPIC DIAGNOSIS blabla"

gsub("\\..*?([A-Za-z])","\\.\n\\1", a , perl = T)
#output:
".\nOESOPHAGUS: inflammation.\nSTOMACH: Lots of information here.\nDUODENUM: Some more information.\nENDOSCOPIC DIAGNOSIS blabla"

I am unsure why the lazy matching acts as it does when perl = F.

A: I'm not sure why you want . . instead of just .\n, this works for the latter:
gsub('[.]\\s*([a-zA-Z])', '.\n\\1', str)
# [1] ".\nOESOPHAGUS: inflammation.\nSTOMACH: Lots of information here.\nDUODENUM: Some more information.\nENDOSCOPIC DIAGNOSIS blabla"

When printed to console with cat, this looks like:
cat(gsub('[.]\\s*([a-zA-Z])', '.\n\\1', str))
# .
# OESOPHAGUS: inflammation.
# STOMACH: Lots of information here.
# DUODENUM: Some more information.
# ENDOSCOPIC DIAGNOSIS blabla

I can't explain either why .*? isn't doing what you want. But there's no reason to use . in this case, since you do have restrictions on the type of character you'd like to match between the full stop and the letter (I assumed white space \s would suffice).


text:
Q: Using pyodbc with SQL join statement in Python I am trying to join 2 tables in Python. (Using Windows, jupyter notebook.)
Table 1 is an excel file read in using pandas.
TABLE_1= pd.read_excel('my_file.xlsx')

Table 2 is a large table in oracle database that I can connect to using pyodbc. I can read in the entire table successfully using pyodbc like this, but it takes a very long time to run.
sql = "SELECT * FROM ORACLE.table_2"
cnxn = odbc.connect(##########)
TABLE_2 = pd.read_sql(sql, cnxn)

So I would like to do an inner join as part of the pyodbc import, so that it runs faster and I only pull in the needed records. Table 1 and Table 2 share the same unique identifier/primary key.
sql = "SELECT * FROM ORACLE.TABLE_1 INNER JOIN TABLE_2 ON ORACLE.TABLE1.ID=TABLE_2.ID"
cnxn = odbc.connect(##########)
TABLE_1_2_JOINED = pd.read_sql(sql, cnxn)

But this doesn't work. I get this error:

DatabaseError: Execution failed on sql 'SELECT * FROM ORACLE.TABLE_1
INNER JOIN TABLE_2 ON ORACLE.TABLE1.ID=TABLE_2.ID': ('42S02', '[42S02]
[Oracle][ODBC][Ora]ORA-00942: table or view does not exist\n (942)
(SQLExecDirectW)')

Is there another way I can do this? It seems very inefficient to have to import entire table w/millions of records when I only need to join a few hundred. Thank you.

A: Something like this might work.
First do:
MyIds = set(table_1['id'])

Then:
SQL1 = "CREATE TEMPORARY TABLE MyIds ( ID int );"

Now insert your ids:
SQL2 = "INSERT INTO MyIds.ID %d VALUES %s"
for element in list(MyIds):
    cursor.execute(SQL2, element)

And lastly
SQL3 = "SELECT * FROM ORACLE.TABLE_1 WHERE ORACLE.TABLE1.ID IN (SELECT ID FROM MyIds)"

I have used MySQL not oracle and a different connector to you but the principles are probably the same. Of course there's a bit more code with the python-sql connections etc. Hope it works, otherwise try to make a regular table rather than a temporary one.


text:
Q: Get unicode script name in Go In Go, I want to get the RangeTable of a script given a specific language.
import (
    "golang.org/x/text/language"
    "unicode"
)

...

script, confidence := language.French.Script()
scriptAsString := script.String() // here scriptAsString = "Latn"
rangeTable, ok := unicode.Scripts[scriptAsString]
// here ok = false, because the Scripts map has key "Latin" and not "Latn"

The problem is that the following function returns the script code
func (s Script) String() string

Whereas the map unicode.Scripts has all of its keys using the script name
Do you know if there is a way in the native Go lib to go from a script code to a script name?
EDIT:
opened issue here: github.com/golang/go/issues/31862

A: This is the kind of mapping I was after:
var scriptCodeToScriptNames = map[string][]string {
    "Adlm": {"Adlam"},
    "Afak": {"Afaka"},
    "Aghb": {"Caucasian_Albanian"},
    "Ahom": {"Ahom"},
    "Arab": {"Arabic"},
    "Aran": {"Arabic"},
    "Armi": {"Imperial_Aramaic"},
    "Armn": {"Armenian"},
    "Avst": {"Avestan"},
    "Bali": {"Balinese"},
    "Bamu": {"Bamum"},
    "Bass": {"Bassa_Vah"},
    "Batk": {"Batak"},
    "Beng": {"Bengali"},
    "Bhks": {"Bhaiksuki"},
    "Bopo": {"Bopomofo"},
    "Brah": {"Brahmi"},
    "Brai": {"Braille"},
    "Bugi": {"Buginese"},
    "Buhd": {"Buhid"},
    "Cakm": {"Chakma"},
    "Cans": {"Canadian_Aboriginal"},
    "Cari": {"Carian"},
    "Cham": {"Cham"},
    "Cher": {"Cherokee"},
    "Copt": {"Coptic"},
    "Cpmn": {"Cypro-Minoan"},
    "Cprt": {"Cypriot"},
    "Cyrl": {"Cyrillic"},
    "Cyrs": {"Cyrillic"},
    "Deva": {"Devanagari"},
    "Dogr": {"Dogra"},
    "Dsrt": {"Deseret"},
    "Dupl": {"Duployan"},
    "Egyd": {"Egyptian_Demotic"},
    "Egyh": {"Egyptian_Hieratic"},
    "Egyp": {"Egyptian_Hieroglyphs"},
    "Elba": {"Elbasan"},
    "Ethi": {"Ethiopic"},
    "Geok": {"Khutsuri"},
    "Geor": {"Georgian"},
    "Glag": {"Glagolitic"},
    "Gong": {"Gunjala_Gondi"},
    "Gonm": {"Masaram_Gondi"},
    "Goth": {"Gothic"},
    "Gran": {"Grantha"},
    "Grek": {"Greek"},
    "Gujr": {"Gujarati"},
    "Guru": {"Gurmukhi"},
    "Hanb": {"Han", "Bopomofo"},
    "Hang": {"Hangul"},
    "Hani": {"Han"},
    "Hano": {"Hanunoo"},
    "Hans": {"Han"},
    "Hant": {"Han"},
    "Hatr": {"Hatran"},
    "Hebr": {"Hebrew"},
    "Hira": {"Hiragana"},
    "Hluw": {"Anatolian_Hieroglyphs"},
    "Hmng": {"Pahawh_Hmong"},
    "Hmnp": {"Nyiakeng_Puachue_Hmong"},
    "Hrkt": {"Hiragana", "Katakana"},
    "Hung": {"Old_Hungarian"},
    "Inds": {"Indus_(Harappan)"},
    "Ital": {"Old_Italic"},
    "Jamo": {"Hangul"},
    "Java": {"Javanese"},
    "Jpan": {"Han", "Hiragana", "Katakana"},
    "Jurc": {"Jurchen"},
    "Kali": {"Kayah_Li"},
    "Kana": {"Katakana"},
    "Khar": {"Kharoshthi"},
    "Khmr": {"Khmer"},
    "Khoj": {"Khojki"},
    "Kitl": {"Khitan_large_script"},
    "Kits": {"Khitan_small_script"},
    "Knda": {"Kannada"},
    "Kore": {"Hangul", "Han"},
    "Kpel": {"Kpelle"},
    "Kthi": {"Kaithi"},
    "Lana": {"Tai_Tham"},
    "Laoo": {"Lao"},
    "Latf": {"Latin"},
    "Latg": {"Latin"},
    "Latn": {"Latin"},
    "Leke": {"Leke"},
    "Lepc": {"Lepcha"},
    "Limb": {"Limbu"},
    "Lina": {"Linear_A"},
    "Linb": {"Linear_B"},
    "Lisu": {"Lisu"},
    "Loma": {"Loma"},
    "Lyci": {"Lycian"},
    "Lydi": {"Lydian"},
    "Mahj": {"Mahajani"},
    "Maka": {"Makasar"},
    "Mand": {"Mandaic"},
    "Mani": {"Manichaean"},
    "Marc": {"Marchen"},
    "Maya": {"Mayan_hieroglyphs"},
    "Mend": {"Mende_Kikakui"},
    "Merc": {"Meroitic_Cursive"},
    "Mero": {"Meroitic_Hieroglyphs"},
    "Mlym": {"Malayalam"},
    "Modi": {"Modi"},
    "Mong": {"Mongolian"},
    "Mroo": {"Mro"},
    "Mtei": {"Meetei_Mayek"},
    "Mult": {"Multani"},
    "Mymr": {"Myanmar"},
    "Narb": {"Old_North_Arabian"},
    "Nbat": {"Nabataean"},
    "Newa": {"Newa"},
    "Nkoo": {"Nko"},
    "Nshu": {"Nushu"},
    "Ogam": {"Ogham"},
    "Olck": {"Ol_Chiki"},
    "Orkh": {"Old_Turkic"},
    "Orya": {"Oriya"},
    "Osge": {"Osage"},
    "Osma": {"Osmanya"},
    "Palm": {"Palmyrene"},
    "Pauc": {"Pau_Cin_Hau"},
    "Perm": {"Old_Permic"},
    "Phag": {"Phags_Pa"},
    "Phli": {"Inscriptional_Pahlavi"},
    "Phlp": {"Psalter_Pahlavi"},
    "Phlv": {"Book_Pahlavi"},
    "Phnx": {"Phoenician"},
    "Plrd": {"Miao"},
    "Prti": {"Inscriptional_Parthian"},
    "Rjng": {"Rejang"},
    "Rohg": {"Hanifi_Rohingya"},
    "Roro": {"Rongorongo"},
    "Runr": {"Runic"},
    "Samr": {"Samaritan"},
    "Sara": {"Sarati"},
    "Sarb": {"Old_South_Arabian"},
    "Saur": {"Saurashtra"},
    "Sgnw": {"SignWriting"},
    "Shaw": {"Shavian"},
    "Shrd": {"Sharada"},
    "Shui": {"Shuishu"},
    "Sidd": {"Siddham"},
    "Sind": {"Khudawadi"},
    "Sinh": {"Sinhala"},
    "Sogd": {"Sogdian"},
    "Sogo": {"Old_Sogdian"},
    "Sora": {"Sora_Sompeng"},
    "Soyo": {"Soyombo"},
    "Sund": {"Sundanese"},
    "Sylo": {"Syloti_Nagri"},
    "Syrc": {"Syriac"},
    "Syre": {"Syriac"},
    "Syrj": {"Syriac"},
    "Syrn": {"Syriac"},
    "Tagb": {"Tagbanwa"},
    "Takr": {"Takri"},
    "Tale": {"Tai_Le"},
    "Talu": {"New_Tai_Lue"},
    "Taml": {"Tamil"},
    "Tang": {"Tangut"},
    "Tavt": {"Tai_Viet"},
    "Telu": {"Telugu"},
    "Teng": {"Tengwar"},
    "Tfng": {"Tifinagh"},
    "Tglg": {"Tagalog"},
    "Thaa": {"Thaana"},
    "Thai": {"Thai"},
    "Tibt": {"Tibetan"},
    "Tirh": {"Tirhuta"},
    "Ugar": {"Ugaritic"},
    "Vaii": {"Vai"},
    "Visp": {"Visible_Speech"},
    "Wara": {"Warang_Citi"},
    "Wcho": {"Wancho"},
    "Wole": {"Woleai"},
    "Xpeo": {"Old_Persian"},
    "Xsux": {"Cuneiform"},
    "Yiii": {"Yi"},
    "Zanb": {"Zanabazar_Square"},
    "Zinh": {"Inherited"},
    "Zyyy": {"Common"},
}


text:
Q: android - static var is killed but activity is brought to foreground let's say I have 2 activities A and B. I go to B from A then hit the Home button. there are a few static vars being initialized in A.
after a few hours or days or until activity is being killed, I launch the app again from the Recent button. activity B becomes the new entry point of this app, but static vars are no longer holding any value and has no chance of getting initialized unless I redirect back to A.
my launchMode for both activities are singleTop. not sure if that matters but I've tried singleTop, singleInstance and standard none of them work. I guess my expected behavior would be the entry point is always A or any other activities if is not being killed and of course static vars are still holding value.
Thanks!

A: the problem may be because when your application is in background the android o.s must have cleaned the memory to free resources for other application

A: *

*I hope those static variables are of primitive datatypes.

*Even if the Application is in background Android system kills the process after some time.

*So you can do is pass those primitive variables through Intent to ActivityB.

*Now if the Application is killed from background and brought it to Foreground same intent is used to launch the ActivityB and you can still get the passed variables.

Pass variable to ActivityB instead of static variable.
Intent intent = new Intent();
intent.putExtras("Id", 1);
intent.putExtras("Name", "kevz");
startActivity(intent, ActivityB.class);

Now in ActivityB get the passed variable values-
int Id = getIntent().getIntExtra("Id", -1); // -1 is default value.
String Name = getIntent().getStringExtra("Name", "unknown"); // unknown is default value

A: If static variables doesn't work, you can try using getter() and setter() methods for variables.


text:
Q: Why does python logging package not support printing variable length args? When I first learned Python, I got used to doing this:
  print "text", lineNumber, "some dictionary", my_dict

When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:
def error(*args):
   print ERR_PREFIX,
   for _x in args:
      print _x,
   print "\r\n",

error("text", lineNumber, "some dictionary", my_dict)

Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort.  Overall it looks like a clean design that can do a lot.  But I'm stymied by the fact that you can no longer present it with the same list of items for it to print.  Instead, I must change all my calls to something more like this:
error("text %d some dictionary %s" % (lineNumber, my_dict))

Or, I could do something really silly like this:
error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))

The question is, why omit such an obvious usage case?  If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier?
As a follow-up question, can you think of a way to override the Logger class to perform this?

A: I would suggest that it would be better to update the existing logging messages to the style that the logging module expects as it will be easier for other people looking at your code as the logging module will not longer function as they expect.
That out of the way, the following code will make the logging module behave as you desire.
import logging
import types

class ExtendedLogRecord(logging.LogRecord):

    def getMessage(self):
        """
        Return the message for this LogRecord.

        Return the message for this LogRecord after merging any user-supplied
        arguments with the message.
        """
        if not hasattr(types, "UnicodeType"): #if no unicode support...
            msg = str(self.msg)
        else:
            try:
                msg = str(self.msg)
            except UnicodeError:
                msg = self.msg      #Defer encoding till later
        if self.args:
            msg +=' '+' '.join(map(str,self.args))
        return msg

#Patch the logging default logging class
logging.RootLogger.makeRecord=lambda self,*args: ExtendedLogRecord(*args)

some_dict={'foo':14,'bar':15}
logging.error('text',15,'some dictionary',some_dict)

Output:
ERROR:root:text 15 some dictionary {'foo': 14, 'bar': 15}

A: Patching the logging package (as one answer recommended) is actually a bad idea, because it means that other code (that you didn't write, e.g. stuff in the standard library) that calls logging.error() would no longer work correctly.
Instead, you can change your existing error() function to call logging.error() instead or print:
def error(*args):
  logging.error('%s', ' '.join(map(str, args)))

(If there might be unicode objects you'd have to be a bit more careful, but you get the idea.)

A: Your claim about logging is not completely true.
log= logging.getLogger( "some.logger" )
log.info( "%s %d", "test", value )
log.error("text %d some dictionary %s", lineNumber, my_dict)

You don't need to explicitly use the string formatting operator, %

Edit
You can leverage your original "error" function.
def error( *args ):
    log.error( " ".join( map( str, args ) ) )

Which will probably make the transition less complex.
You can also do this.
class MyErrorMessageHandler( object ):
    def __init__( self, logger ):
        self.log= logger
    def __call__( self, *args ):
        self.log.error( " ".join( map( str, args ) ) )
error= MyErrorMessageHandler( logging.getLogger("some.name") )

Which might be palatable, also.

A: Well, printing and logging are two very different things.  It stands to reason that as such their usages could potentially be quite different as well.

A: It's relatively easy to add a method to a class dynamically.  Why not just add your method to Logging.


text:
Q: What is the purpose of the lower lens on some laptops? I have tried reading the HP EliteBook 2540p manual but it does not seem to label it anywhere.
I've noticed that this model in particular isn't the only one, there are quite a few models that have it and I'm not entirely sure what it is, my first thought is that it's a webcam but the webcam is at the top of the screen on this model?

A: I'm guessing that its an ambient light sensor - which the specifications confirms it has. Apparently they arn't terribly good, and there's a quite of information on how to turn them off, but I'm reasonably certain that's what it is.


text:
Q: Defining the ground state energy of a QFT
*

*I would like to hear of some general discussion on how is the ground state and its energy defined in QFT and how does one go about finding it. (..at least in some simple cases I have seen the use of Bogulibov transformation to make the theory look like a free-field theory to be able to identify the vacuum - but does every theory have a generalized Bogulibov transformation?..)

To initiate let me point out one specific formalism which I am confused about.
If one takes the Lagrangian as $L = \frac{1}{2}\left(\partial _\mu \phi\right)^2 - V(\phi)$ then in an expansion in powers of $\hbar$ gives the first term of the partition function as,
$Z \approx \frac{1}{\sqrt{\mathrm{det}\left[-\partial^2 - V^{\prime\prime}\left(\phi_c\right)\right]}} e^{iS\left[\phi_c\right]}$
where $S$ is the action of the theory and $\phi _c$ is the classical extrema of that action.
Then one sees that if $E_0$ is the energy of the classical solution and the action is evaluated for a time interval $T$ then one has the relation $S\left[\phi_c\right] = -T\,E_0$
In the footsteps of the above identity one wants to define $E_G$ as the true quantum groundstate energy as $E_G = \lim_{T\rightarrow \infty} \frac{i \ln Z}{T}$.
If one used the above definition to the same order of perturbation as $Z$ is given and one replaces the value of $E_0$ before one takes the limit of $T \rightarrow \infty$ then one one has the relation,
$E_G \approx E_0 - \lim_{T \rightarrow \infty} \frac{i}{2T} \ln \left\{ \det \left[-\partial ^2 - V^{\prime\prime}\left(\phi_c\right)\right]\right\}$

*

*Now I am not sure as to how to interprete the second term of the above expression since naively that seems to go to $0$ since the determinant doesn't depend on the time-interval. But I guess I am wrong and I would want to know how at least this way of thinking works out.

A: My answer is based on the book "Quantum field theory in a nutshell, by A. Zee, Chapter IV.3 : Effective Potential"
Take a scalar field theory $(\phi)$, when you have a classical potential $V(\phi)$, you can find the state V.E.V. (vacuum expectation value) $\phi_0$ by minimizing this potential $V(\phi)$.
But quantum fluctuations change this potential, so to calculate the modifyed  state  V.E.V. $\phi_{eff}$, you have first to calculate the modifyed potential $V_{eff}(\phi)$.
Define $W(J) = i log Z(J)$, You have V.E.V. $\phi(x) = \frac{\delta W(J)}{\delta J(x)}$ (a particular example of Green function obtained by diffentiating $W$ by the source $J$ repeatedly).
By using a Legendre transformation, define $\Gamma(\phi) = W(J) - \int d^4x J(x) \phi(x)$.
Note that there is an implicite dependence of $J$ on $\phi$, and you have $-J(x) = \frac{\delta \Gamma(\phi)}{\delta \phi(x)}$.
You may define $V_{eff}$ by  : $\Gamma(\phi) =  \int d^4x (- V_{eff}(\phi) + Z(\phi) (\partial\phi)^2) + ...$, which is justifyed because you can show that $V^\prime_{eff}(\phi) = J$ (rigourously when $\phi$ and $J$ do not depend on x). This means, that without source, $V^\prime_{eff}(\phi) = 0$, so $V_{eff}$ is the correct potential which, minimized, gives the ground state.
With step descent approximation applyied to $Z$, around the step descent point field $\phi_s$, where $V^{\prime}(\phi_s) = 0$ you will find, with explicit $\hbar$:
$$Z(J) = \int D\phi\;e^{(i/\hbar)[S(\phi)+ J\phi]}$$
$$Z(J) \approx e^{(i/\hbar)[S(\phi_s)+ J\phi_s]} \int D\phi\;e^{(i/\hbar)\int d^4x\,\frac{1}{2}
[(\partial\phi)^2) - V^{\prime\prime}(\phi_s)\phi^2]}$$
In the previous expression, the new integration variable is $\phi= \phi-\phi_s$.
$$Z(J) \approx e^{(i/\hbar)[S(\phi_s)+ J\phi_s] - \frac{1}{2} (Tr\, log (\partial^2 +V^{\prime\prime}(\phi_s)) - Tr\, log (\partial^2))}$$
Note that the appearance of the term $Tr\, log (\partial^2))$ may be seen as a renormalization factor.
$$W(J)  = S(\phi_s) + J\phi_s + i\frac{\hbar}{2} (Tr\, log (\partial^2 +V^{\prime\prime}(\phi_s)) - Tr\, log (\partial^2)) +O(\hbar^2)$$
$$\Gamma(\phi) =  S(\phi)  + i\frac{\hbar}{2} (Tr\, log (\partial^2 +V^{\prime\prime}(\phi)) - Tr\, log (\partial^2)) +O(\hbar^2)$$
With $\phi$ independant of x, you can write : $$Tr\, log (\partial^2 +V^{\prime\prime}(\phi))  = \frac{1}{(2\pi)^4}\int d^4x \int d^4k \,\,log \frac{(-k^2 + V^{\prime\prime}(\phi))}{-k^2}$$
So, finally, by the definition of $V_{eff}(\phi)$ from $\Gamma(\phi)$  $$V_{eff}(\phi) = V(\phi) - i\frac{\hbar}{2} \frac{1}{(2\pi)^4} \int d^4k \,\,log \frac{(k^2 - V^{\prime\prime}(\phi))}{k^2} + O(\hbar^2)$$
In practice, this integral is quadratically divergent, so you have to put a cut-off $\Lambda$, and you get : $$V_{eff}(\phi) = V(\phi) +  \frac{\Lambda^2}{32\pi^2}V^{\prime\prime}(\phi) - \frac{1}{64\pi^2}[V^{\prime\prime}(\phi)]^2 log\frac{e^{1/2}\Lambda^2}{V^{\prime\prime}(\phi)}$$
So, by minimizing this effective potential $V_{eff}$, you can find the new state V.E.V. $\phi_{eff}$.
Now, in 3+1 dimensions, a scalar like $\phi_{eff}$ has the dimension of a mass (or energy), so  by some Higgs mechanism, it can give mass to spin 1 gauge bosons, but the minimum of the effective potential $V_{eff}$ and the effective V.E.V. field $\phi_{eff}$ are 2 different things.


text:
Q: Check if file/blob object is valid UTF-8 I need a function that can check if a file or blob object is valid UTF-8. I can get the text and check for � characters, but if the string has that character to begin with, the function would mark it as invalid.

function isUTF8(blob) {
  return new Promise(async resolve => {
    const text = await blob.text();
    resolve(!~text.indexOf("�"));
  });
}

// "�" is valid utf-8 but the function returns false
isUTF8(new Blob(["�"])).then(console.log);

// returns true
isUTF8(new Blob(["example"])).then(console.log);

A: You can use the TextDecoder API:

async function isUTF8(blob) {
  const decoder = new TextDecoder('utf-8', { fatal: true });
  const buffer = await blob.arrayBuffer();
  try {
    decoder.decode(buffer);
  } catch (e) {
    if (e instanceof TypeError)
      return false;
    throw e;
  }
  return true;
}

(async () => {

console.log(await isUTF8(new Blob(
  [new Uint8Array([0x80])]))); // false
console.log(await isUTF8(new Blob(
  [new Uint8Array([0xef, 0xbf, 0xbd])]))); // true
console.log(await isUTF8(new Blob(
  ["\ufffd"]))); // true
console.log(await isUTF8(new Blob(
  ["example"]))); // true

})().catch(e => console.warn(e));

The above loads the entire Blob into an ArrayBuffer for simplicity.  If memory-efficiency becomes an issue, you may look into using the .stream() method to process the Blob in parts, without holding it in memory in its entirety.


text:
Q: Get img source from js Object I have a js object slider.controlNav, that contains DOM elements. I need to save in variable source of image, that contains in link with class 'flex-active'.
 jQuery.each(slider.controlNav, function(i, val) {
   var  dom_object = slider.controlNav.get(i);
      console.log(dom_object)
  });

Top code returns:

My code:
jQuery.each(slider.controlNav, function(i, val) {
   var  dom_object = slider.controlNav.get(i).find('img').attr('src');
      console.log(dom_object)
  });

After that in console i have error:

Uncaught TypeError: slider.controlNav.get(...).find is not a function

A: get function gives you the underlying DOM object. You need to convert it to jQuery object.
Try $(slider.controlNav.get(i)).find('img').attr('src');

A: Please check with this code.
jQuery("slider.controlNav a").each(function() {
    var  dom_object = jQuery(this).find('img').attr('src');
    console.log(dom_object)
});

A: You do want to use this or val, which refers to the current element in the iteration:
jQuery.each(slider.controlNav, function(i, val) {
    var  src = jQuery(this).eq(i).find('img').attr('src');
    console.log( src )
});

Alternatively, just use plain JS as follows:
slider.controlNav.forEach(function(val) {
    var src = val.querySelector( 'img' ).src;
    console.log( src );
});

A: See this jsbin
var flexActiveControlNavs = slider.controlNav.find(".flex-active");

jQuery.each(flexActiveControlNavs, function(i, val) {
   var dom_object = flexActiveControlNavs.eq(i).find('img').attr('src');
   console.log(dom_object);
});

This will return only the image sources that are a child of elements with class "flex-active".


text:
Q: can a method call be chained to the 'set()' built-in? (and why not?) If I try:
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list)
mi_set.remove('small')
print mi_set

I get:
set(['three', 'words'])

which is what I expect. Whereas If I try:
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list).remove('small')
print mi_set

I get:
None

Why?
I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:
KeyError: 'big'

A: There is a general convention in python that methods which cause side-effects return None.  Examples include list.sort, list.append, set.add, set.remove, dict.update, etc.
This is essentially to help you avoid bugs.  Say you had a set called mi_set.  If you could write:
mi_set2 = mi_set.remove('small')

then a reader might think: "mi_set2 is different from mi_set".  But this would not be the case!  And the confusion might lead to subtle bugs caused by mistakenly sharing data structures.  So by returning None, python forces you to remember that methods like those I listed above modify objects, rather than creating new ones.
See also long discussion here.  Although note that methods like sorted() and reversed() have been added since that thread.
[note that list.pop is an exception to this rule, for historical reasons – it lets you use a list like a stack.  And even then, it returns the object removed, rather than the list.]

A: set.remove returns nothing (None).
Your code assigns the return value of set.remove to the variable mi_set. Therefore, mi_set is None.

A: The way to go, in your case, would be to use the difference member:
>>> a = set(["a", "b", "c"])
>>> a = a.difference(["a"])
>>> print a
set(['c', 'b'])

The difference is that remove acts on the current set (python library object member functions that modify an instance usually return None), whereas difference creates and returns a new set.

A: Why does it return None? Because .remove, .add, etc. return None :) That's it. They do not support chaining.
set is using methods that change it in place. You could create your own version of set that uses chaining, but that can cause some problems:
class chain_set(set):
   def chain_add(self, x):
      newself = self.copy()
      newself.add(x)
      return newself

cs = chain_set([1,2,3,4])
cs.chain_add(5)
# chain_set([1, 2, 3, 4, 5])
cs.chain_add(7)
# chain_set([1, 2, 3, 4, 7])
cs.chain_add(7).chain_add(8)
# chain_set([1, 2, 3, 4, 7, 8])

The problem is - do you expect cs itself to change?
Do you always want to modify the original set (might create some hard to find bugs) or do you want to copy the set every time (might be slow with bigger sets). If you know what behaviour you need and you remember about it - just go ahead with your own set implementation.

A: Are you sure that the remove function returns a value?

A: remove modifies the original set without returning anything (or rather, it returns None). This example shows what happens to the original object when you call remove on it:
Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = [1,2,3]
>>> s1 = set(lst)
>>> s1
{1, 2, 3}
>>> s2 = s1.remove(2)  # instead of reassigning s1, I save the result of remove to s2
>>> s1
{1, 3}  # *** 2 is not an element in the original set ***
>>> s2  # s2 is not a set at all!
>>>

To answer the other part of your question, the exception indicates that remove tried to remove the argument from the set, but couldn't because the argument is not in the set. Conversely, remove returns None to indicate success.


text:
Q: Problem with universal enveloping algebra generated by a single element (Jacobson) Jacobson's book on "Lie algebras" has the following definition of enveloping algebra generated by a subset (Definition 2, Chap II) : Start with an unital associative algebra $A$ (over a field $F$) and $S \subset A$. The enveloping algebra $S^{\ast}$ is simply the associative subalgebra of $A$ containing $1_A$ generated by $S$. The way I see it as $S^{\ast} = \sum_{n \geq 0} S^n$ where $S^n$ is the $F$-submodule generated by the set $\{ s_1 \dotsc s_n ~:~ s_1, \dotsc, s_n \in S \}$ of $n$-fold monomials  (of course $S^{0} := F$). Since we require $1_A \in S^{\ast}$, we need $n=0$ in the sum.
Now while describing the subsequent properties, it says for $w \in A$ we have $\{ w \}^{\ast}$ is the algebra of polynomials in $w$ with constant term $0$. How can we have the constant terms $0$ if I need $1_A \in \{ w \}^{\ast}$?

A: You've misread Jacobson (p32 in his Dover book).
In a unital associative algebra $A$, he defines $S^*$ as the non-unital subalgebra generated by $S$ and calls it "enveloping associative algebra of $S$ in $A$", and $S^\dagger$ as the unital subalgebra generated by $S$ and calls it "enveloping algebra of $S$ in $A$". This is consistent with his description of $S^*$ as polynomials with 0 constant term.
(This is terrible terminology! But mathematicians from the XXth century built an irreversibly messy terminology with rings and algebras...)


text:
Q: Setting boto3 dynamodb endpoint_url globaly I want to use dynamodb local for local (unit) testing of my python/boto3 based application.
Now I can do something like this
if test_mode:
    client = boto3.client("dynamodb", endpoint_url="localhost:8000")
    resource = boto3.resource("dynamodb", endpoint_url="localhost:8000")
else:
    client = boto3.client("dynamodb")
    resource = boto3.resource("dynamodb")

But I would like to avoid the test_mode check.
Can I somehow "prepare" boto3 so the dynamodb endpoint URL is set globally?
Update
To further explain what I want. I want some sort of function, where I can say:
boto3.setGlobalDynamodbEndpoint("http://localhost:8000")

such that when, after calling this function, I do:
client = boto3.client("dynamodb")
resource = boto3.resource("dynamodb")

The endpoint will automatically be set to "http://localhost:8000"

A: As far as I know, there's no built-in function in the boto3 library that will do this for you, but you could achieve a similar result using the functools.partial utility in the Python standard library. This tool takes a Python callable and one or more arguments, and returns a new callable that does the same thing, but with those arguments "pre-set". In functional programming jargon, this is called "partially applying" a function (hence the name partial).
For example,
import functools
import boto3

URL = "http://localhost:8000"
boto3.client = functools.partial(botot3.client, endpoint_url=URL)
boto3.resource = functools.partial(boto3.resource, endpoint_url=URL)

By redefining boto3.client and boto3.resource to be our new partial, instead of the original versions from the library, we're monkey-patching boto3.
Later on in your code, when you call:
client = boto3.client("dynamodb")
resource = boto3.resource("dynamodb")

You won't need to explicitly pass endpoint_url because the client and resource objects will be automatically instantiated with the previously-set URL value in the partial object.

A: I've just submitted a PR to the boto3 project to use an env var to override the endpoint_url, which might be useful for this.
https://github.com/boto/boto3/pull/2746
https://github.com/rwillmer/boto3


text:
Q: C++ Factory Pattern With Templates I'm trying to code an abstract factory using c++ templates. Due to the fact I've never done things like that before I'm encountering troubles. The code I wrote, as you can verify by yourself, is wrong and I have no idea on how to correct it. My idea is that there are two templated classes that will contain the base_class and the derived_class, so this class can be used with any type of class. It is templated the key too for the same reason.
#ifndef _t_factory_h_
#define _t_factory_h_

#include <iostream>
#include <map>

template < class T >
class base_creator
{
  public:
   virtual ~base_creator(){ };
   virtual T* create() = 0;
};

template < class derived_type , class base_type >
class derived_creator : public base_creator<base_type>
{
  public:
  base_type* create()
  {
   return new derived_type;
  }
};

template <class _key, class base >
class factory
{
   public:
     void register_type(_key id , derived_creator<derived_type,base_type>* _fn)
  {
    _function_map[id] = _fn;
  }

  base* create(_key id)
  {
    return _function_map[id]->create();
  }

 ~factory()
 {
   auto it = _function_map.begin();
   for(it ; it != _function_map.end() ; ++it)
   {
     delete (*it).second;
   }
  }

  private:
     std::map<_key , derived_creator<derived_type,base_type>*> _function_map;
   };

#endif /* defined _t_factory_h_ */

If somenone can help me to correct this code I would be grateful.

A: Problem solved.
Here is the code:
#ifndef _t_factory_h_
#define _t_factory_h_

#include <iostream>
#include <map>

template < class T >
class base_creator
{
  public:
  virtual ~base_creator(){ };
  virtual T* create() = 0;
};

template < class derived_type , class base_type >
class derived_creator : public base_creator<base_type>
{
 public:
 base_type* create()
 {
  return new derived_type;
 }
};

template <class _key, class base_type >
class factory
{
 public:
   void register_type(_key id , base_creator<base_type>* _fn)
   {
     _function_map[id] = _fn;
   }

   base_type* create(_key id)
   {
      return _function_map[id]->create();
   }

  ~factory()
  {
    auto it = _function_map.begin();
    for(it ; it != _function_map.end() ; ++it)
    {
      delete (*it).second;
    }
}

 private:
   std::map<_key , base_creator<base_type>*> _function_map;
};

#endif /* defined _t_factory_h_ */


text:
Q: R: Abbreviate state names in strings I have strings with state names in them. How do I efficiently abbreviate them? I am aware of state.abb[grep("New York", state.name)] but this works only if "New York" is the whole string. I have, for example, "Walmart, New York". Thanks in advance!
Let's assume this input:
x = c("Walmart, New York", "Hobby Lobby (California)", "Sold in Sears in Illinois")

Edit: desired outputs will be a la "Walmart, NY", "Hobby Lobby (CA)", "Sold in Sears in IL". As you can see from here, state can appear in many ways in a string

A: Here's a base R way, using gregexpr(), regmatches(), and regmatches<-(), :
abbreviateStateNames <- function(x) {
    pat <- paste(state.name, collapse="|")
    m <- gregexpr(pat, x)
    ff <- function(x) state.abb[match(x, state.name)]
    regmatches(x, m) <- lapply(regmatches(x, m), ff)
    x
}

x <- c("Hobby Lobby (California)",
       "Hello New York City, here I come (from Greensboro North Carolina)!")

abbreviateStateNames(x)
# [1] "Hobby Lobby (CA)"
# [2] "Hello NY City, here I come (from Greensboro NC)!"

Alternatively -- and quite a bit more naturally -- you can accomplish the same thing using the gsubfn package:
library(gsubfn)

pat <- paste(state.name, collapse="|")
gsubfn(pat, function(x) state.abb[match(x, state.name)], x)
[1] "Hobby Lobby (CA)"
[2] "Hello NY City, here I come (from Greensboro NC)!"


text:
Q: TypeError: createWorker is not a constructor const worker = new createWorker({
^
TypeError: createWorker is not a constructor
I'm having this error every time, I have changed from TesseractWorker to createWorker but I'm still having this issue.
Package:
"tesseract.js": "2.1.4"