Q: ElasticSearch group by documents field and count occurences My ElasticSearch 6.5.2 index look likes:
      {
    "_index" : "searches",
    "_type" : "searches",
    "_id" : "cCYuHW4BvwH6Y3jL87ul",
    "_score" : 1.0,
    "_source" : {
      "querySearched" : "telecom",
    }
  },
  {
    "_index" : "searches",
    "_type" : "searches",
    "_id" : "cSYuHW4BvwH6Y3jL_Lvt",
    "_score" : 1.0,
    "_source" : {
      "querySearched" : "telecom",
    }
  },
  {
    "_index" : "searches",
    "_type" : "searches",
    "_id" : "eCb6O24BvwH6Y3jLP7tM",
    "_score" : 1.0,
    "_source" : {
      "querySearched" : "industry",
    }

And I would like a query that return this result:
"result":
{
"querySearched" : "telecom",
"number" : 2
},
{
"querySearched" : "industry",
"number" : 1
}

I just want to group by occurence and get number of each, limit to ten biggest numbers. I tried with aggregations but bucket is empty.
Thanks!

A: Case your mapping
PUT /index
{
  "mappings": {
    "doc": {
      "properties": {
        "querySearched": {
          "type": "text",
          "fielddata": true
        }
      }
    }
  }
}

Your query should looks like
GET index/_search
{
  "size": 0,
  "aggs": {
    "result": {
      "terms": {
        "field": "querySearched",
        "size": 10
      }
    }
  }
}

You should add fielddata:true in order to enable aggregation for text type field more of that
    "size": 10, => limit to 10

After a short discussion with @Kamal i feel obligated to let you know that if you choose to enable fielddata:true you must know that
it can consume a lot of heap space.
From the link I've shared:

Fielddata can consume a lot of heap space, especially when loading high cardinality text fields. Once fielddata has been loaded into the heap, it remains there for the lifetime of the segment. Also, loading fielddata is an expensive process which can cause users to experience latency hits. This is why fielddata is disabled by default.

Another alternative (a more efficient one):
PUT /index
{
  "mappings": {
    "doc": {
      "properties": {
        "querySearched": {
          "type": "text",
          "fields": {
           "keyword": {
             "type": "keyword",
             "ignore_above": 256
           }
         }
        }
      }
    }
  }
}

Then your aggregation query
GET index/_search
{
  "size": 0,
  "aggs": {
    "result": {
      "terms": {
        "field": "querySearched.keyword",
        "size": 10
      }
    }
  }
}

Both solutions works but you should take this under consideration.
Hope it helps

A: What did you tried?
POST
/searches/_search
   {
      "size": 0,
      "aggs": {
        "byquerySearched": {
          "terms": {
            "field": "querySearched",
             "size": 10
          }
        }
      }
    }


Q: What is the algorithm to copy a region of one bitmap, into a region in another? In my project (and I am sure many others), I need to copy a subset (R2) of one bitmap image (R1), into a region (R3) in another, where the destination region can be any size (stretching and scaling where necessary).

I am sure this is a solved problem but I cannot find any examples; what is the most straightforward algorithm for performing this operation? (Linear interpolation would be sufficient for filling in the pixels when the source is scaled upwards, if that is the quickest (computationally) method)

A: Perhaps the mechanism you seek is the BitBlt algorithm?

Bit blit (also written BITBLT, BIT BLT, BitBLT, Bit BLT, Bit Blt etc., which stands for bit-level block transfer) is a computer graphics operation in which several bitmaps are combined into one using a raster operator.
The operation involves at least two bitmaps, a source and destination, possibly a third that is often called the "mask" and sometimes a fourth used to create a stencil. The pixels of each are combined bitwise according to the specified raster operation (ROP) and the result is then written to the destination. The ROP is essentially a boolean formula. The most obvious ROP overwrites the destination with the source. Other ROPs may involve AND, OR, XOR, and NOT operations...

A: In order to resize an image properly (particularly, to reduce the size of an image), you need an interpolation filter scaled to the smaller of the source and destination sizes.
Unfortunately, if your destination buffer really is a bitmap, you have no way to store the grayscale pixels you will get from your filter.  The best you can do (short of extraordinary measures) is threshold the results at 50%, in order to get a binary pixel value to store in your output buffer.

In many cases, a quick & dirty program won't bother to try resizing an arbitrarily-scaled bitmap properly at all -- they will simply grab the source pixel closest to the interpolated target location, as you describe.  This is certainly fast, but it looks quite ugly, especially for size reduction (as your question suggests), or for dynamic stretching (animated or interactive).
However, if you're doing everything with bitmaps, maybe that particular kind of ugly could be useful for a bit of 8-bit cred...

A: Here's C-like pseudocode. You can figure how to handle the edge cases (e.g. clipping, mirroring, etc). I'll leave it to you to also figure out how to make this use integer or fixed point math if performance is an issue.
struct {
    bitmap bmp;
    float x, y, width, height;
} xfer_param;

scaled_xfer(xfer_param src, xfer_param det)
{
    float src_dx = dst.width / src.width;
    float src_dy = dst.height / src.height;
    float src_maxx = src.x + src.width;
    float src_maxy = src.y + src.height;
    float dst_maxx = dst.x + dst.width;
    float dst_maxy = dst.y + dst.height;
    float src_cury = src.y;

    for (float y = dst.y; y < dst_maxy; y++)
    {
        float src_curx = src.x;
        for (float x = dst.x; x < dst_maxx; x++)
        {
            // Point sampling - you can also impl as bilinear or other
            dst.bmp[x,y] = src.bmp[src_curx, src_cury];
            src_curx += src_dx;
        }

        src_cury += src_dy;
    }
}

To do sub-pixel interpolation, you can sample the 4 pixels around the floating-point src_curx, src_cury, and take a weighted average. One of the highest quality methods is to effectively take a sample rectangle in the source image that corresponds to a single pixel in the dest image. Then you just average all the values in that and write the destination pixel. However, that rect will likely not fall on clean pixel boundaries, so you will want to take the clipped edge pixels and weight them accordingly.

A: Generally the best way is to work on a grid in the destination and interpolate the source pixel. That way you are sure that there are no gaps or aliasing effects in the destination.


Q: NetworkStream.Write returns immediately - how can I tell when it has finished sending data? Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background.
This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network).
    bool done;
    void SendData(TcpClient tcp, byte[] data)
    {
        NetworkStream ns = tcp.GetStream();
        done = false;
        ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns);
        while (done == false) Thread.Sleep(10);
    }

    public void myWriteCallBack(IAsyncResult ar)
    {
        NetworkStream ns = (NetworkStream)ar.AsyncState;
        ns.EndWrite(ar);
        done = true;
    }

How can I tell when the data has actually been sent to the client?
I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card.
The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond.
I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?

A: TCP is a "reliable" protocol, which means the data will be received at the other end if there are no socket errors.  I have seen numerous efforts at second-guessing TCP with a higher level application confirmation, but IMHO this is usually a waste of time and bandwidth.
Typically the problem you describe is handled through normal client/server design, which in its simplest form goes like this...
The client sends a request to the server and does a blocking read on the socket waiting for some kind of response.  If there is a problem with the TCP connection then that read will abort.  The client should also use a timeout to detect any non-network related issue with the server.  If the request fails or times out then the client can retry, report an error, etc.
Once the server has processed the request and sent the response it usually no longer cares what happens - even if the socket goes away during the transaction - because it is up to the client to initiate any further interaction.  Personally, I find it very comforting to be the server.  :-)

A: I'm not a C# programmer, but the way you've asked this question is slightly misleading.  The only way to know when your data has been "received", for any useful definition of "received", is to have a specific acknowledgment message in your protocol which indicates the data has been fully processed.
The data does not "leave" your network card, exactly.  The best way to think of your program's relationship to the network is:

your program -> lots of confusing stuff -> the peer program

A list of things that might be in the "lots of confusing stuff":

*

*the CLR

*the operating system kernel

*a virtualized network interface

*a switch

*a software firewall

*a hardware firewall

*a router performing network address translation

*a router on the peer's end performing network address translation

So, if you are on a virtual machine, which is hosted under a different operating system, that has a software firewall which is controlling the virtual machine's network behavior - when has the data "really" left your network card?  Even in the best case scenario, many of these components may drop a packet, which your network card will need to re-transmit.  Has it "left" your network card when the first (unsuccessful) attempt has been made?  Most networking APIs would say no, it hasn't been "sent" until the other end has sent a TCP acknowledgement.
That said, the documentation for NetworkStream.Write seems to indicate that it will not return until it has at least initiated the 'send' operation:

The Write method blocks until the requested number of bytes is sent or a SocketException is thrown.

Of course, "is sent" is somewhat vague for the reasons I gave above.  There's also the possibility that the data will be "really" sent by your program and received by the peer program, but the peer will crash or otherwise not actually process the data.  So you should do a Write followed by a Read of a message that will only be emitted by your peer when it has actually processed the message.

A: In general, I would recommend sending an acknowledgment from the client anyway. That way you can be 100% sure the data was received, and received correctly.

A: If I had to guess, the NetworkStream considers the data to have been sent once it hands the buffer off to the Windows Socket. So, I'm not sure there's a way to accomplish what you want via TcpClient.

A: I can not think of a scenario where NetworkStream.Write wouldn't send the data to the server as soon as possible.  Barring massive network congestion or disconnection, it should end up on the other end within a reasonable time.  Is it possible that you have a protocol issue?  For instance, with HTTP the request headers must end with a blank line, and the server will not send any response until one occurs -- does the protocol in use have a similar end-of-message characteristic?
Here's some cleaner code than your original version, removing the delegate, field, and Thread.Sleep.  It preforms the exact same way functionally.
void SendData(TcpClient tcp, byte[] data) {
    NetworkStream ns = tcp.GetStream();
    // BUG?: should bytWriteBuffer == data?
    IAsyncResult r = ns.BeginWrite(bytWriteBuffer, 0, data.Length, null, null);
    r.AsyncWaitHandle.WaitOne();
    ns.EndWrite(r);
}

Looks like the question was modified while I wrote the above.  The .WaitOne() may help your timeout issue.  It can be passed a timeout parameter.  This is a lazy wait -- the thread will not be scheduled again until the result is finished, or the timeout expires.

A: I try to understand the intent of .NET NetworkStream designers, and they must design it this way. After Write, the data to send are no longer handled by .NET. Therefore, it is reasonable that Write returns immediately (and the data will be sent out from NIC some time soon).
So in your application design, you should follow this pattern other than trying to make it working your way. For example, use a longer time out before received any data from the NetworkStream can compensate the time consumed before your command leaving the NIC.
In all, it is bad practice to hard code a timeout value inside source files. If the timeout value is configurable at runtime, everything should work fine.

A: How about using the Flush() method.
ns.Flush()

That should ensure the data is written before continuing.

A: Bellow .net is windows sockets which use TCP.
TCP uses ACK packets to notify the sender the data has been transferred successfully.
So the sender machine knows when data has been transferred but there is no way (that I am aware of) to get that information in .net.
edit:
Just an idea, never tried:
Write() blocks only if sockets buffer is full. So if we lower that buffers size (SendBufferSize) to a very low value (8? 1? 0?) we may get what we want :)

A: Perhaps try setting
tcp.NoDelay = true


Q: how to close MessageBox in RCP plugin development? I have created a MessageBox while developing Eclipse plugin which opens when you perform some action...however even after i say "OK" on that messageBox the dialog MessageBox occurs again and again..
Can anyone tell me how to close MessageBox once it is shown to user..
To open dialog box i wrote following code:
    MessageBox dialog = new MessageBox(new Shell(), SWT.OK);
    dialog.setMessage("Some message");
    dialog.setText("Title");
    dialog.open();

A: Your Problem has nothing to do with the code you posted. Please provide us with additional information. Also consider to set the shell of the currently active widget as parent shell in the MessageBox constructor (e.g. new MessageBox(swtControl.getShell(), SWT.OK). Otherwise the dialog might not be modal. This depends on the modal style of the Shell.

A: After research i found that you need to dispose component that you need no longer once specific action has been completed. So once my MessageDialog appears and user clicks
OK... i need to dispose my MessageDialog using Display.getCurrent().dispose()


Q: Finding the degree of an undirected graph I am trying to find the degree distribution of an undirected graph. And I tried the following code:
graph = { "a" : ["c"],
          "b" : ["c", "e"],
          "c" : ["a", "b", "d", "e"],
          "d" : ["c"],
          "e" : ["c", "b"],
          "f" : []
        }

def generate_edges(graph):
    edges = []
    for node in graph:
        for neighbour in graph[node]:
            edges.append((node, neighbour))

    return edges

print(generate_edges(graph))

And my output is something like this :
[('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('b', 'c'), ('b', 'e'), ('a', 'c'), ('e', 'c'), ('e', 'b'), ('d', 'c')]

I am trying to find the degree but I am not getting it. I need my output to be [1,2,2,0,1] which is a list, where the index value range from 0 to maximum degree in the graph(i.e in the above graph 4 is the maximum degree for "c") and the index values are number of nodes with degree equal to that index. ( in the above above graph, there is 1 node with 0 degrees,2 with 1 degree and again 2 with 2 degrees,none with 3 degree and finally 1 with 4 degree). Hence [1,2,2,0,4]. Can anyone help me with this without using NetworkX ?

A: graph = { "a" : ["c"],
          "b" : ["c", "e"],
          "c" : ["a", "b", "d", "e"],
          "d" : ["c"],
          "e" : ["c", "b"],
          "f" : [] }

def max_length(x):
    return len(graph[x])

# Determine what index has the longest value
index = max(graph, key=max_length)
m = len(graph[index])

# Fill the list with `m` zeroes
out = [0 for x in range(m+1)]

for k in graph:
    l = len(graph[k])
    out[l]+=1

print(out)

Outputs [1, 2, 2, 0, 1]

A: Another solution using Counter :
from collections import Counter
a = Counter(map(len, graph.values())) # map with degree as key and number of nodes as value
out = [a[i] for i in range(max(a)+1)] # transform the map to a list

A: You can find the degrees of individual nodes by simply finding lengths of each element's list.
all_degrees = map(len, graph.values())

This, in your case produces the individual degrees, not necessarily in same order as the elements.
[1, 4, 2, 2, 1, 0]

Next thing is simply frequency count in the list.
from collections import defaultdict
freq = defaultdict(int)
for i in all_degrees:
    freq[i] += 1
print freq
Out: defaultdict(<type 'int'>, {0: 1, 1: 2, 2: 2, 4: 1})

As expected, freq now gives count of each values which you can then print, append to list etc. You can simply print values of the dictionary freq as
print freq.values()

Returns the desired list [1, 2, 2, 0, 1]. Or you can create an empty list and append values to it as
out = list()
for i in range(max(all_degrees)+1):
   out.append(freq[i])

Again returns out = [1,2,2,0,1] - the required output.


Q: Quick and Efficient way to generate random numbers in Java I am writing a multi-threaded Java program that generates lot of random numbers.
Additional Details:
These numbers are used to create a list of random numbers from 0-99 without repetition and such that every number in the range 0-99 exists in the list (In other words, the list contains 100 unique elements in the range 0-99).
Generating Random Numbers [Things already tried!]

*

*I have an ArrayList of numbers from 0-100. I generate a random number and use it as an index which is used to pop out an element from the ArrayList.

*I have used Collections.shuffle().

Here is the code for approach 1:
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < N; i++){
 arr.add(i, i);
}

for(int i=0; i<N; i++){
  int indx = rand.nextInt(arr.size());
  res.add(arr.get(indx));
  arr.remove(indx);
}

For second approach, I replaced the second for loop with Collections.shuffle(arr).
As generating list of random numbers is the most expensive part of my algorithm, I want to optimize it. This brings me to the questions:

*

*What is the fastest way to generate random numbers?

*What is the fastest way to generate the list of random numbers as described above?

PS:

*

*I found Collections.shuffle() to be slower than the first approach

*Someone suggested me using rngd to generate random numbers from hardware in Unix. Has anyone tried this before? How do you do that?

A: I think the problem with Collections.shuffle() is that is uses default Random instance which is a thread-safe singleton. You say that your program is multi-threaded, so I can imagine synchronization in Random being a bottle-neck.
If you are happily running on Java 7, simply use ThreadLocalRandom. Look carefully, there is a version of shuffle() taking Random instance explicitly:
Collections.shuffle(arr, threadLocalRandom);

where threadLocalRandom is created only once.
On Java 6 you can simply create a single instance of Random once per thread. Note that you shouldn't create a new instance of Random per run, unless you can provide random seed every time.

A: Part of the problem might be the overhead of the Integer boxing and unboxing.  You might find it helpful to reimplement the Fisher-Yates shuffle directly on an int[].

A: My approach woul be to generate the numbers with the Math.random() method as in the example here and initialize the list via a static init block like this:
private static List<int> list = new ArrayList<int>();
static {
  for(int i = 0; i < 100; i++) {
    // randomize number
    list.add(number);
  }
}

Hope this helped, have Fun!

A: To shuffle an array a of n elements (indices 0..n-1):
for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

Check Fischer and Yattes algorithm.


Q: Is this sentence correct as a title ? Social media's weak signals scanning, for future strategical decisions taking
I'm trying here to write the title of an article.
the article I'm trying to write is a research topic to apply for a scholarship. (English is my third language)
My article is about detecting the small changes in profiles behaviour on linkedin to predict the changes in a given company.(Eventually where the profile works).
So I thought :

Social media's weak signals scanning, for future strategical decisions taking

Would be a good title.
What do you guys think?

A: Try instead: Scanning social media's weak signals for future strategic decisions
The syntax of your proposed title isn't correct.  You shouldn't divide the title with a comma since it doesn't contain a subjugated clause.  Also, Strategical isn't a commonly used word, and the simpler Strategic is more appropriate.


Q: With hive's complex struct data type, how to write query with where clause I've have following hive table with complex data type, STRUCT. Can you please help writing hive query with where clause for specific city?
CREATE EXTERNAL TABLE user_t (
 name      STRING,
 id        BIGINT,
 isFTE     BOOLEAN,
 role      VARCHAR(64),
 salary    DECIMAL(8,2),
 phones    ARRAY<INT>,
 deductions MAP<STRING, FLOAT>,
 address   ARRAY<STRUCT<street:STRING, city:STRING, state:STRING, zip:INT>>,
 others    UNIONTYPE<FLOAT,BOOLEAN,STRING>,
 misc      BINARY
 )

I'm able to use STRUCT data type in select clause but not able to use same in where clause.
Working:
select address.city from user_t;

Not working:
select address.city from user_t where address.city = 'XYZ'

Documentation says it has limitation while using group by or where clause and gave a solution as well. But I didn't understand it clearly.
Link: Documentation
Please suggest. Thank you.

A: Demo
create table user_t
(
    id        bigint
   ,address   array<struct<street:string, city:string, state:string, zip:int>>
)
;

insert into user_t

    select  1
           ,array
            (
                named_struct('street','street_1','city','city_1','state','state_1','zip',11111)
               ,named_struct('street','street_2','city','city_1','state','state_1','zip',11111)
               ,named_struct('street','street_3','city','city_3','state','state_3','zip',33333)
            )

    union all

    select  2
           ,array
            (
                named_struct('street','street_4','city','city_4','state','state_4','zip',44444)
               ,named_struct('street','street_5','city','city_5','state','state_5','zip',55555)
            )
;

Option 1: explode
select  u.id
       ,a.*

from    user_t as u
        lateral view explode(address) a as details

where   details.city = 'city_1'
;

+----+---------------------------------------------------------------------+
| id |                               details                               |
+----+---------------------------------------------------------------------+
|  1 | {"street":"street_1","city":"city_1","state":"state_1","zip":11111} |
|  1 | {"street":"street_2","city":"city_1","state":"state_1","zip":11111} |
+----+---------------------------------------------------------------------+

Option 2: inline
select  u.id
       ,a.*

from    user_t as u
        lateral view inline(address) a

where   a.city = 'city_1'
;

+----+----------+--------+---------+-------+
| id |  street  |  city  |  state  |  zip  |
+----+----------+--------+---------+-------+
|  1 | street_1 | city_1 | state_1 | 11111 |
|  1 | street_2 | city_1 | state_1 | 11111 |
+----+----------+--------+---------+-------+

Option 3: self join
select  u.*

from            user_t as u

        join   (select  distinct
                        u.id

                from    user_t as u
                        lateral view inline(address) a

                where   a.city = 'city_1'
                ) as u2

        on      u2.id = u.id
;

+----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id |                                                                                address                                                                                |
+----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  1 | [{"street":"street_1","city":"city_1","state":"state_1","zip":11111},{"street":"street_2","city":"city_1","state":"state_1","zip":11111},{"street":"street_3","city":"city_3","state":"state_3","zip":33333}] |
+----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+


Q: A/B testing for React SSR app with chunking Versions:
webpack: 4.30.0,
react: 16.8.6,
react-loadable: 5.5.0,

I'm having one entry JS in webpack. Other chunks are currently created using react-loadable and vendor JS is created using splitChunks.
Idea of my application:
SSR and chunking is working with react-loadable for route-level components. And dynamic-components chunk can be made using either webpack's import promise or react Loadable.

Now, I want to introduce A/B testing to these dynamic components.
I've 2 approaches:

*

*First approach: Wrap dynamic-import statement inside if-else to import A/B variation of that dynamic-component. And at server level, I would know that for a given user, I would set a flag in Redux store, in order to select A/B variation.
(This approach can be followed for whether app is SSR and SPA.)
Notes for this approach:
a. Seems doable :P
b. Can't scale for A/B/C very easily. In this case, I would have to introduce a 3rd else condition to dynamically import C variation. It'll bust the browser caching for the route-level component's chunk(containing these variations) because hash in file name is changed. And same will happen to all the route-level components which takes effect for adding additional C testing.
c. Have to unnecessarily pollute code with if-conditions. If A/B testing is completed, then code again will have to modified, which busts the browser cache again.

*Second Approach: I'll have only 1 dynamic import in code but I want 3 different chunks for the same component A, B and C, like A/some_chunk[hash].js, B/some_chunk[hash].js and C/some_chunk[hash].js. And at server level, I would use same logic for segmenting the user for A/B/C testing as in approach 1, but instead of setting flag in redux store, **I'll serve some_chunk[hash].js from A, B or C folder as per user's segment.
Notes for this approach:
a. I need to ask how we can create chunks for dynamic-component without they being actually imported in a file.
b. Can very easily scale for A/B/C testing, since now A/B testing is now dependent upon which variation of file server is serving.
c. No polluting of code with if-else conditions in client code. No issues of browser cache busting.
d. Will need separate wrapper component for server code for ReactDOMServer.renderToString to know which variation to pick for server side rendering.
Questions:

*

*So, I need to know how we can create chunk as per 2nd approach? Because webpack would ignore creating chunk for the file if not reachable (i.e not imported by any other file)

*Would you recommend this approach. What's the right micro FE app approach of doing AB testing?
PS:
If this is doable, then my roadmap would be to chunk for base layouts as well. Where I can avoid if-else conditions in code and entire layout can be changed as per which A/B variation server sends to browser.

A: This can be done using webpack's weak resolve
Example from webpack docs:
const page = 'Foo'; // Trick: Can be taken from props
__webpack_modules__[require.resolveWeak(`./page/${page}`)];

My use case:
Suppose, we're doing A/B testing on component D which has variations D1, D2 and D3.
We can make folder D/ with D1.js D2.js and D3.js variations inside this folder. Now, require.resolveWeak('./D/${variation}') will pack chunks for D1, D2 and D3 in the build folder. Now, on runtime, passing the props to pick the particular variation will dynamically load that JS.
Note: For eg: to pick D2 variation, experiment name also must be D2 (or else you must store mapping of experiment name to component name) to be passed as props. Generally, people do A/B testing by just having multiple if-elses. So, in the loadVariationOfD.js, instead of having weak resolve import statement, if-else is used with dynamic imports(I'm using loadable-components for this).


Q: How do I send a parameter list to be used as arguments when a delegate is invoked? I've implemented a simple extension method in my asp.net mvc 3 app to pull objects out of session using generics:
public static T GetVal<T>(this HttpSessionStateBase Session, string key, Func<T> getValues)
    {
        if (Session[key] == null)
            Session[key] = getValues();

        return (T)Session[key];
    }

This works great if getValues() doesn't require any arguments.
I was attempting to write an overload that takes in params object[] args to allow me to pass arguments if necessary to the getValues() function, but I don't know what the syntax is to apply those variables to the function.
Is this even possible? Thanks in advance for your advice.

A: I would argue that you shouldn't need to do this - the caller can handle that with a lambda expression. For example:
int x = session.GetVal<int>("index", () => "something".IndexOf("o"));

Here we're capturing the idea of calling IndexOf on "something" passing in the argument "o". All of that is captured in a simple Func<int>.

A: You can add an overload to your function
public static T GetVal<T>(this HttpSessionStateBase Session, string key, Func<IList<object>,T> getValues, IList<object> args)
{
    if (Session[key] == null)
        Session[key] = getValues(args);

    return (T)Session[key];
}

A: You'll have to define your own delegate rather than Func.  The following will work perfectly here:
public delegate TResult ParamsFunc<TResult>(params object[] args);


Q: WPF - Binding IsMouseOver to Visibility I have a window which overrides a RadioButton's ControlTemplate to show a custom control inside of it. Inside the custom control, I have a button's visibility tied to IsMouseOver, which works correctly in showing the button only when the mouse is hovering over the control. However, when I click on the RadioButton, the Button disappears. After some debugging and reading, it seems that the RadioButton is capturing the mouse on click, and this makes IsMouseOver for the UserControl false.
I tried binding the Button's visibility to FindAncestor {x:Type RadioButton} and it works, but it seems a bit fragile to me to have the UserControl depend on who is containing it. The code for the window and the user control is below. Any suggestions?
<Window x:Name="window" x:Class="WPFTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WPFTest="clr-namespace:WPFTest"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type RadioButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RadioButton}">
                        <WPFTest:TestUC />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Border BorderBrush="Black" BorderThickness="2">
        <StackPanel>
            <RadioButton x:Name="OptionButton" Height="100" />
            <TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}" />
        </StackPanel>
    </Border>
</Window>

<UserControl x:Name="_this" x:Class="WPFTest.TestUC"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </UserControl.Resources>
    <StackPanel>
        <TextBlock Text="SomeText" />
        <TextBlock Text="{Binding ElementName=_this, Path=IsMouseOver}" />
        <Button x:Name="_cancelTextBlock" Content="Cancel" Visibility="{Binding ElementName=_this, Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}" />
    </StackPanel>
</UserControl>

A: I seemed to have fixed the problem by setting a trigger in the control template, which binds to the RadioButton's IsMouseOver, and sets a custom DependencyProperty on the UserControl.
Something like:
<ControlTemplate TargetType="{x:Type RadioButton}">
    <WPFTest:TestUC x:Name="UC" />
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="ShowCancel" Value="True" TargetName="UC"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

I'm still confused as to why the Mouse Capture falsifies IsMouseOver on the UserControl child of the RadioButton however. Can anyone shed some light on this?

A: After the event is handled by the RadioButton , it is only set as handled but in reality it still bubbles up. So you just need to specify that you want to handle handled events too.
For that you need to look at handledEventsToo.
Unfortunately I don't think it can be set in xaml. only code.

A: Very interesting problem. I myself would like to know more of why the UserControl IsMouseOver changes to false when the TextBlock(s) in its visuals are mouse downed upon.
However, here is another way to solve it ... maybe you will like this approach better.
Instead of using RadioButton (since you are retemplating it) why don't you just use Control? (I think IsMouseOver is getting changed to false due to the fact that it is a Button derived control.)
Following is the xaml for the Window ...
<Window
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1"
    Width="300"
    Height="300"
>
    <Window.Resources>
        <Style TargetType="{x:Type Control}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Control}">
                        <local:UserControl1/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <Border BorderBrush="Black" BorderThickness="2">
        <StackPanel>
            <Control x:Name="OptionButton" Height="100"/>
            <TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}"/>
        </StackPanel>
    </Border>
</Window>

EDIT:
I just wanted to add ... that if you're okay with the above approach ... then, the right thing to do is probably to just use the UserControl in the Window's visual tree versus retemplating a Control. So ... like this:
<Window
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1"
    Width="300"
    Height="300"
>
    <Border BorderBrush="Black" BorderThickness="2">
        <StackPanel>
            <local:UserControl1 x:Name="OptionButton" Height="100"/>
            <TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}"/>
        </StackPanel>
    </Border>
</Window>


Q: React app, API call that fetches routes for app Hello I am using react and redux, i have my action creator that fetches the routes of the page and i creat the routing with them this way:
First in app.js im calling the action creator (using mapDispatchToProps) in UseEffect and passing the result (mapStateToProps) to the Routes component:
    useEffect(() => {
    fetchMenu();
}, []);

<Routes menu={menu} />

Then in Routes.js:
            {menu.map((item) => (
            <PrivateRoute
                key={item.id}
                exact
                path={item.link}
                parentClass="theme-1"
                component={(props) => selectPage(item.linkText, props)}
            />
        ))}

The problem is that if I refresh the page, there is a little delay between the api call and the render of the page, so for one second the browser shows "NOT FOUND PAGE" and then instantly redirect to the route. How can I make it work properly? Thank you !

A: Basically what you want is to be able to know that the data hasn't been loaded yet, and render differently based on that.  A simple check would be see if the menu is empty. Something like this:
export const Menu = ({ menu, fetchMenu }) => {
  useEffect(() => {
    fetchMenu();
  }, []);

  if ( menu.length > 0 ) {
    return <Routes menu={menu} />
  } else {
    return <MenuLoading />
  }
}

A more advanced setup would be able to tell the difference between an empty menu due to an API error and a menu that's empty because it's still loading, but to do that you would need to store information about the status of the API call in the state.


Q: PyQt: Overriding QGraphicsView.drawItems I need to customize the drawing process of a QGraphicsView, and so I override the drawItems method like this:
self.graphicsview.drawItems=self.drawer.drawItems

where self.graphicsview is a QGraphicsView, and self.drawer is a custom class with a method drawItems.
In this method I check a few flags to decide how to draw each item, and then call item.paint, like this:
def drawItems(self, painter, items, options):
    for item in items:
        print "Processing", item
        # ... Do checking ...
        item.paint(painter, options, self.target)

self.target is the QGraphicsView's QGraphicsScene.
However, once it reaches item.paint, it breaks out of the loop - without any errors. If I put conditionals around the painting, and for each possible type of QGraphicsItem paste the code that is supposed to be executed (by looking at the Qt git-sources), everything works.
Not a very nice solution though... And I don't understand how it could even break out of the loop?

A: There is an exception that occurs when the items are painted, but it is not reported right away. On my system (PyQt 4.5.1, Python 2.6), no exception is reported when I monkey-patch the following method:
def drawItems(painter, items, options):
    print len(items)
    for idx, i in enumerate(items):
        print idx, i
        if idx > 5:
            raise ValueError()

Output:
45
0 <PyQt4.QtGui.QGraphicsPathItem object at 0x3585270>
1 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356ca68>
2 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356ce20>
3 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cc88>
4 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cc00>
5 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356caf0>
6 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cb78>

However, once I close the application, the following method is printed:
Exception ValueError: ValueError() in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored

I tried printing threading.currentThread(), but it returns the same thread whether it's called in- or outside the monkey-patched drawItems method.
In your code, this is likely due to the fact that you pass options (which is a list of style options objects) to the individual items rather than the respective option object. Using this code should give you the correct results:
def drawItems(self, painter, items, options):
    for item, option in zip(items, options):
        print "Processing", item
        # ... Do checking ...
        item.paint(painter, option, self.target)

Also, you say the self.target is the scene object. The documentation for paint() says:

This function, which is usually called by QGraphicsView, paints the contents of an item in local coordinates. ... The widget argument is optional. If provided, it points to the widget that is being painted on; otherwise, it is 0. For cached painting, widget is always 0.

and the type is QWidget*. QGraphicsScene inherits from QObject and is not a widget, so it is likely that this is wrong, too.
Still, the fact that the exception is not reported at all, or not right away suggests some foul play, you should contact the maintainer.

A: The reason why the loop suddenly exits is that an Exception is thrown. Python doesn't handle it (there is no try: block), so it's passed to the called (Qt's C++ code) which has no idea about Python exceptions, so it's lost.
Add a try/except around the loop and you should see the reason why this happens.
Note: Since Python 2.4, you should not override methods this way anymore.
Instead, you must derive a new class from QGraphicsView and add your drawItems() method to this new class. This will replace the original method properly.
Don't forget to call super() in the __init__ method! Otherwise, your object won't work properly.


Q: ViewPager and Fragments: Why do I always see the same thing? I have created a ViewPager with three "pages". The code is this
MainActivity.java
public class MainActivity extends FragmentActivity {

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);
        FragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
                getSupportFragmentManager());

        viewPager.setAdapter(fragmentPagerAdapter);
        pagerTabStrip.setDrawFullUnderline(true);
        pagerTabStrip.setTabIndicatorColor(Color.DKGRAY);
    }

}

MyFragmentPageAdapter.java
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    private String[] pageTitle = {
            "Page1", "Page2", "Page3"
    };

    public MyFragmentPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = new PageFragment();
        Bundle arguments = new Bundle();
        arguments.putString("pageIndex", Integer.toString(position + 1));
        fragment.setArguments(arguments);
        return fragment;
    }

    @Override
    public int getCount() {
        return pageTitle.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return pageTitle[position];
    }

}

PageFragment.java
public class PageFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);

    return view;

    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <android.support.v4.view.PagerTabStrip
        android:id="@+id/pager_tab_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33B5E5"
        android:textColor="#FFFFFF"
        android:paddingTop="10dp"
        android:paddingBottom="10dp" />

    </android.support.v4.view.ViewPager>

</RelativeLayout>

fragment_page.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:textSize="16sp"
        android:textStyle="italic"
        android:gravity="center_horizontal"
        android:textColor="@color/red"
        android:text="@string/inf" />

        <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="60dp"
        android:textSize="28sp"
        android:gravity="center_horizontal"
        android:textStyle="bold"
        android:text="@string/ben" />

                <TextView
        android:id="@+id/textView3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="130dp"
        android:gravity="center_horizontal"
        android:textSize="18sp"
        android:text="Prova"
         />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:layout_centerInParent="true"
            android:text="@string/verifica" />

</RelativeLayout>

But now i visualize in all three pages the same thing. If I for example on page 2 I want a TextView with the text "This is the 2 page" and on the third page a TextView with the text "This is the page 3" and in the first page  two TextView with the button ... how can I? I'm going crazy, please let pass me the code to do this thing. Please.

A: Once you inflate PageFragment's layout you need to get a reference of the TextView so you can display the position on it via the Bundle you are passing using setArguments(). Use your view variable inside onCreateView() to get a reference of the TextView. (i.e. view.findViewById()). Then use getArguments() in your PageFragment to retrieve the Bundle with that has position, and set the TextView to that value.

A: this is a good example for what you want.

A: Just create a function in your page fragment class to configure elements and modify onCreateView to attach childs.
public class PageFragment extends Fragment {

        TextView tv1 ;
        // ...

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
            /// Attach your childs
            tv1 = view.findViewById(R.id.textView1);

        return view;

        }

        public void configure(int position) {
            tv1 .setText("This is "+ position);
        }
    }

Then just call the function configure in getItem function
  @Override
        public Fragment getItem(int position) {
            PageFragment fr = new PageFragment();
            fr.configure(position + 1);
            return fr;
        }


Q: What is difference between the KFP SDK v2, v2 namespace, and v2 compatible mode? What is the difference between KFP SDK v2, the v2 namespace in KFP SDK v1, and v2 compatible mode?

A: The KFP SDK has two major versions: v1.8.x and v2.x.x (in pre-release at the time of writing this).
KFP SDK v2.x.x compiles pipelines and components to IR YAML [example], a platform neutral pipeline representation format. It can be run on the KFP open source backend or on other platforms, such as Google Cloud Vertex AI Pipelines.
KFP SDK v1.8.x, by default, compiles pipelines and components to Argo Workflow YAML. Argo Workflow YAML is executed on Kubernetes and is not platform neutral.
KFP SDK v1.8.x provides two ways to author pipelines using v2 Python syntax:
KFP SDK v2-compatible mode is a feature in KFP SDK v1.8.x which permits using v2 Python authoring syntax within KFP SDK v1 but compiles to Argo Workflow YAML. v2-compatible mode is deprecated and should not be used.
The KFP SDK v2 namespace in KFP SDK v1.8.x (from kfp.v2 import dsl, compiler) permits using v2 Python authoring syntax within KFP SDK v1 and compiles to IR YAML [usage example]. While this mode is not deprecated, users should prefer authoring IR YAML via the pre-released KFP SDK v2.x.x.


Q: Using the split function in Python I am working with the CSV module, and I am writing a simple program which takes the names of several authors listed in the file, and formats them in this manner: john.doe
So far, I've achieved the results that I want, but I am having trouble with getting the code to exclude titles such as "Mr."Mrs", etc. I've been thinking about using the split function, but I am not sure if this would be a good use for it.
Any suggestions? Thanks in advance!
Here's my code so far:
import csv

books = csv.reader(open("books.csv","rU"))

for row in books:

     print '.'.join ([item.lower() for item in [row[index] for index in (1, 0)]])

A: It depends on how much messy the strings are, in worst cases this regexp-based solution should do the job:
import re
x=re.compile(r"^\s*(mr|mrs|ms|miss)[\.\s]+", flags=re.IGNORECASE)
x.sub("", text)

(I'm using re.compile() here since for some reasons Python 2.6 re.sub doesn't accept the flags= kwarg..)
UPDATE: I wrote some code to test that and, although I wasn't able to figure out a way to automate results checking, it looks like that's working fine.. This is the test code:
import re
x=re.compile(r"^\s*(mr|mrs|ms|miss)[\.\s]+", flags=re.IGNORECASE)
names = ["".join([a,b,c,d]) for a in ['', ' ', '   ', '..', 'X'] for b in ['mr', 'Mr', 'miss', 'Miss', 'mrs', 'Mrs', 'ms', 'Ms'] for c in ['', '.', '. ', ' '] for d in ['Aaaaa', 'Aaaa Bbbb', 'Aaa Bbb Ccc', ' aa ']]
print "\n".join([" => ".join((n,x.sub('',n))) for n in names])

A: Depending on the complexity of your data and the scope of your needs you may be able to get away with something as simple as stripping titles from the lines in the csv using replace() as you iterate over them.
Something along the lines of:
titles = ["Mr.", "Mrs.", "Ms", "Dr"] #and so on

for line in lines:
    line_data = line
    for title in titles:
        line_data = line_data.replace(title,"")
    #your code for processing the line

This may not be the most efficient method, but depending on your needs may be a good fit.
How this could work with the code you posted (I am guessing the Mr./Mrs. is part of column 1, the first name):
import csv

books = csv.reader(open("books.csv","rU"))

for row in books:
     first_name = row[1]
     last_name = row[0]
     for title in titles:
          first_name = first_name.replace(title,"")
     print '.'.(first_name, last_name)


Q: Cannot reach spring-boot-starter-parent dependencies I'm using https://start.spring.io/ to create Spring Boot project and in development I can't reach spring boot starters these dependencies:
<dependency>
    <groupId>org.springframework.ws</groupId>
    <artifactId>spring-ws-support</artifactId>
        <version>3.0.10.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
        <version>5.3.2</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
</dependency>

<dependency>
    <groupId>com.sun.xml.messaging.saaj</groupId>
    <artifactId>saaj-impl</artifactId>
        <version>1.5.2</version>
</dependency>

I get warning messages:
Overriding managed version 5.3.1 for spring-oxm
Overriding managed version 5.3.1 for spring-oxm
Duplicating managed version 4.5.13 for httpclient
Duplicating managed version 1.5.2 for saaj-impl

I've searched for how to fix it, one of the workaround some people refers to use <!--$NO-MVN-MAN-VER$ --> at the end of the </version> tag to ignore the warning.
My question is how to make these (and other future dependencies) be seen from spring boot?
EDIT #1: pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>xx.xx.xxx</groupId>
    <artifactId>yyyy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>yyyy</name>
    <description>zzzzz</description>

    <properties>
        <java.version>11</java.version>

        <apache.cxf.version>3.4.1</apache.cxf.version>
        <apache.httpcomponents.version>4.5.13</apache.httpcomponents.version>
        <jaxb2.maven2.version>0.14.0</jaxb2.maven2.version>

        <springframework.version>5.3.2</springframework.version>
        <springframework.ws.version>3.0.10.RELEASE</springframework.ws.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </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>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${apache.cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>${jaxb2.maven2.version}</version>
            <type>maven-plugin</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-support</artifactId>
            <version>${springframework.ws.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${apache.httpcomponents.version}</version>
        </dependency>
    </dependencies>
</project>

A: Solution is to remove <version>...</version>, let Spring boot handle the versions.
Thanks to tgdavies.


Q: Why is "a lot" written as two words even though "ahead" is written as one word? So I know "alot" should be written "a lot" and I have seen this amusing post on the treatment: http://hyperboleandahalf.blogspot.co.nz/2010/04/alot-is-better-than-you-at-everything.html
However, why is a word like "ahead" OK? Surely they are doing the same thing, aren't they?
I have read the question
Why is writing "alot" such a common mistake? but it doesn't answer my question.
Why is "ahead" a valid word and "alot" not?
Any information would be appreciated.

A: The flip answer is that (per the OED) starting in the 1600s, ahead became a nautical term meaning forward, as in full speed ahead, and a head couldn't be used because that was already the term for the forepart of the ship. (Since that's the place for the ship's toilets, head survives today as slang for the loo.)
The real answer is that a string of letters becomes a word when enough people incorporate that string in their vocabulary. Consider alright, which has become an acceptable substitute for all right, possibly influenced by words like almost and altogether.

A: No, they aren’t doing the same thing.
It's because these a- words are mostly ancient prepositional phrases in origin that eventually got squished together — but into adverbs, not quantifiers or adjectives.  Consider aback, abroad, above, afoot, across, afar, ahead, ajar, akin, alike, aloud, amid, apart, atop, away.
That a- portion was an unstressed version of the word on way back in Old English, according to Oxford Dictionaries Online. As a prefix it most often means on or to something, or in that manner.
So the process that created all these fused prepositional phrases turned to adverbs is not one that would give rise to such things as *alot, *alittle, *abit, *abig, *afat, *acool, *abad, *anold.
Articles and prepositions aren’t the same thing, so to‑day you aren’t going to get an adjective by fusing an article to an adjective.
For that we have a newt, an orange, an apron, a nickname. :)
More seriously, this very thing did once happen aforetimes to give us another.   Then again, whether other counts as an adjective is dubious in modern analysis.
In any event, it is not a productive process now‑a‑days.

A: Lot means a large number or great amount. It's a standalone word. You wouldn't say I like you lot. You would say l Ike you lots or I like you a lot. Lot holds its same meaning with or without the a.
Head and ahead are 2 completely separate words.

A: The origins of 'ahead', 'astern', 'aboard', 'abroad' etc have been explained eruditely in previous posts and the distinction between them and 'a lot', 'a little' and so on pointed out. However there is the verb 'to allot' and its synonym 'to apportion'.
It seems to me that these are also examples of the a- prefix being used but in these cases to create verbs rather than adverbs and adjectives. In the case of 'to allot' we even have an adjective derived from its past tense as in 'allotted time'. I feel the pull of a linguistic black hole!

A: The answer is spelling convention. While there is an explanation for how "ahead" differs from "a lot", there is absolutely no reason that we should spell a lot "a lot", while we also spell awhile "awhile" and another "another". The words are certainly not separated in speech by an audible gap, which is what word spacing is supposed to represent. I can't prove it but I suspect that a lot has not become "alot" due to class-obsessed quasi-intellectual pedants, who like telling people they're wrong.


Q: XCode 6 infinite building I have really strange problem. I'm writing swift ios project. It has some swift files. One of them is internet requester, which contains some small methods (5-6 rows). If i write 8 methods, my project builds in a second and runs well. But if i add extra method (it can be empty), builder stucks at "compiling swift files" for an inifinite time, PC starts lagging hardly and sometimes "source kit service" terminates. Can you help me?


Q: Shim config not supported in Node, may or may not work I am working on a project which works fine on browser , now we are trying to run it on server side using nodejs.
I have below configurations :

*

*node : v4.2.1

*npm : v2.14.7

and when I am trying to run my project on nodejs , getting the error as :
Shim config not supported in Node, may or may not work

Since the modules and dependencies (AMD) are working fine on browser I assume the shims config are correct .
Please let me know if I am missing something ?
https://github.com/jrburke/requirejs/issues/1443
Regards
Manish

A:
Since the modules and dependencies (AMD) are working fine on browser I assume the shims config are correct .

That's an incorrect assumption. The problem is that Node.js operates with a set of basic assumptions that are very different from how browsers work. Consider this statement:
var foo = "something";

If you execute this at the top of your scope in Node.js, you've created a variable which is local to the file Node is executing. If you really want to make it global, then you have to explicitly shove it into global.
Now, put the same statement at the top of the scope of a script you load in a browser with the script element. The same statement creates a global variable. (The variable is global whether or not var is present.)
RequireJS' shim configuration is used for scripts that expect the second behavior. They expect a) that anything they declare at the top of their scope is leaked to the global space and b) that anything that has been leaked to the global space by scripts they depend on is available in the global space. Both expectations are almost always false in Node. (It would not be impossible for a module designed for node to manipulate global but that's very rare.)
The author of RequireJS explained in this issue report that he does not see it advisable for RequireJS to try to replicate the browser behavior in Node. I agree with him. If you want to run front-end code in the back-end you should replace those modules that need shim in the browser with modules that are designed to run in Node.


Q: Authentication not working with Supabase and Node.js I am not sure even this is possible but I am trying to use Supabase with Node.js. I get the code from a React front-end, this link, which works okay.
Below is my code
client.js
const { createClient } = require('@supabase/supabase-js')

const supabaseUrl = "MY_URL"
const public_anon_key = "MY_ANON_KEY"
const supabase = createClient(supabaseUrl,public_anon_key)

exports.supabase = supabase

app.js
const { supabase }  = require('./client')

async function signOut() {
        /* sign the user out */
        await supabase.auth.signOut();
}

async function signInWithGithub() {
        /* authenticate with GitHub */
        await supabase.auth.signIn({
                provider: 'github'
        });
}

async function printUser() {
        const user = supabase.auth.user()
        console.log(user.email)
}

signInWithGithub()
printUser()
signOut()

I am new to Node.js and I suspect something wrong with Promises is missing.
Is it possible to retrieve the user data from Supabase, if so, what is my code missing?
Thanks
Edit : title

A: I don't know what Supabase does but the problem seems to be Promise related
Try to change your app.js as follow
const { supabase }  = require('./client')

function signOut() {
        /* sign the user out */
        supabase.auth.signOut();
}

function signInWithGithub() {
        /* authenticate with GitHub */
        return  supabase.auth.signIn({
                provider: 'github'
        });
}
function printUser() {
        const user = supabase.auth.user()
        console.log(user.email)
}

signInWithGithub().then(() => {
   printUser()
   return signOut()

})


Q: C++ and member function pointers
I'm trying to send an address of a member function to my "Thread" class so I can activate it from there.
I read that I can use functors but I want it to be generic in a way that I can send it to my "Thread" constructor and functors need templates, so it won't be enough for me...
Does anybody know a way to do this?
thanks :)

A: If I may suggest a different approach: derive from your thread class and make a virtual Run() function.
The reason is that although it is possible to call a function pointer from the static thread entry function, you face problem after problem. For example, you can solve the problem of having the right function signature with templates and variadic parameters, but it is not of much avail, because the entry function won't know what to send to your function.
On the other hand, deriving from Thread is easy and straightforward. You put into the contructor whatever the thread needs to know. Or, optionally, you can call any number of other functions and set any number of members before you create the thread. Once you do create the thread, the static thread entry function will simply call the virtual Run function. Now... the Run function is part of the thread object, so it knows anything the class knows -- no problem.
The extra overhead of a single virtual function call and of one pointer in the vtable is also ridiculously small compared to how easy it is.

A: I suggest you look at the treatment of this topic in the C++ FAQ Lite. In short, pointers to member functions are problematic, but there are several work-arounds, as well as a number of reasons why they should be avoided for certain purposes.

A: Finally I decided to use a stub function as suggested in this thread:
Create thread is not accepting the member function
thanks everbody :)


Q: Why does (ps -f) create no subshell but a separate process? I need some help because I don't get something. From what I read from Internet, a subshell is created when we execute a shell script or if we run command in brackets: ( )
I tried to test this with a script which contains only the following command:
ps -f

When I run it I see the following result:
ID      PID  PPID  C STIME TTY          TIME CMD
me     2213  2160  0 08:53 pts/14   00:00:00 bash
me     3832  2213  0 18:41 pts/14   00:00:00 bash
me     3833  3832  0 18:41 pts/14   00:00:00 ps -f

Which is good, because I see that my bash process has spawned another bash process for my script.
But when I do:
( ps -f )

it produces:
UID     PID  PPID  C STIME TTY          TIME CMD
me     2213  2160  0 08:53 pts/14   00:00:00 bash
me     3840  2213  0 18:46 pts/14   00:00:00 ps -f

So if brackets spawn a subshell why it is not shown in the processes? And why does ps -f is counted as another process? Does every command run as a separate process?

A: It seems you've caught bash in a little bit of an optimization.  if a subshell contains only a single command, why really make it a subshell?
$ ( ps -f )
UID        PID  PPID  C STIME TTY          TIME CMD
jovalko  29393 24133  0 12:05 pts/10   00:00:00 bash
jovalko  29555 29393  0 12:07 pts/10   00:00:00 ps -f

However, add a second command, say : (the bash null command, which does nothing) and this is the result:
$ ( ps -f ; : )
UID        PID  PPID  C STIME TTY          TIME CMD
jovalko  29393 24133  0 12:05 pts/10   00:00:00 bash
jovalko  29565 29393  0 12:08 pts/10   00:00:00 bash
jovalko  29566 29565  0 12:08 pts/10   00:00:00 ps -f

One of the main reasons to use a subshell is that you can perform operations like I/O redirection on a group of commands instead a single command, but if your subshell contains only a single command there's not much reason to really fork a new bash process first.
As to ps counting as a process, it varies. Many commands you use like ls, grep, awk are all external programs. But, there are builtins like cd, kill, too.
You can determine which a command is in bash using the type command:
$ type ps
ps is hashed (/bin/ps)
$ type cd
cd is a shell builtin

A: The main part of the question is:

Does every command run as a separate process?

YES!. Every command what isn't built-in into bash (like declare and such), runs as separate process. How it is works?
When you type ps and press enter, the bash analyze what you typed, do usual things as globbing, variable expansionas and such, and finally when it is an external command

*

*the bash forks itself.

The forking mean, than immediatelly after the fork, you will have two identical bash processes (each one with different process ID (PID)) - called as "parent" and "child", and the only difference between those two running bash programs is, than the "parent" gets (return value from the fork) the PID of the child but the child don't know the PID of the parent. (fork for the child returns 0).

*

*after the fork, (bash is written this way) - the child replaces itself with the new program image (such: ps) - using the exec call.

*after this, the child bash of course doesn't exist anymore, and running only the newly executed command - e.g. the ps.

Of course, when the bash going to fork itself, do many other things, like I/O redirections, opens-closes filehandles, changes signal handling for the child and many-many other things.


Q: customizing the NSPredicateEditor I want to customize the NSPredicateEditorRowTemplate, but I needn't the subtraction sign in the first RowTemplate, the second, and the third, like the Finder application.

A: If you tell the NSPredicateEditor that it cannot remove all the rows in the editor, then the editor will automatically remove the (-)  button when necessary.
You can do this by unchecking the "Can Remove All Rows" checkbox when editing the predicate editor in a xib, or by doing it programmatically with the -setCanRemoveAllRows: method.


Q: Python Selenium: How can I print the link? How can I print the value of the href attribute?

How can I print the link aaaaa.pdf with python selenium?
HTML:

A: You can do like this:
print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href'))

A: Try the below:
   pName = driver.find_element_by_css_selector(".xxxx").text
    print(pName)

or
   pName = driver.find_element_by_css_selector(".xxxx").get_attribute("href")
   print(pName)

A: div.xxxx a

first, check if this CSS_SELECTOR is representing the desired element.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the css and see, if your desired element is getting highlighted with 1/1 matching node.
If yes, then use explicit waits:
wait = WebDriverWait(driver, 20)
print(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.xxxx a"))).get_attribute('href'))

Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: The value of the href attribute i.e. aaaaa.pdf is within the  tag which is the only descendant of the
 tag.

Solution
To print the value of the href attribute you can use either of the following locator strategies:

*

*Using css_selector:
print(driver.find_element(By.CSS_SELECTOR, "div.xxxx > a").get_attribute("href"))

*Using xpath:
print(driver.find_element(By.XPATH, "//div[@class='xxxx']/a").get_attribute("href"))

To extract the value ideally you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.xxxx > a"))).get_attribute("href"))

*Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='xxxx']/a"))).get_attribute("href"))

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


Q: How to get Cartesian product from different group member? As the title mentioned, I have some problems in C++.
If I have a std::vector<std::vector<int> >tmpvec
vector < vector <int> > tmpvec = {
    {1,2,3},
    {4,5},
    {6,7,8,9},
    {10,11}
};

how can I generate all possible combination of a vector of vector
1,4,6,10

1,4,6,11

1,4,7,10

1,4,7,11

......

There are at most 48 different combination.

A: You may do
bool increase(const std::vector<std::vector<int>>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] >= v[index].size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}

void do_job(const std::vector<std::vector<int>>& v,
            const std::vector<std::size_t>& it)
{
    for (std::size_t i = 0; i != it.size(); ++i) {
        // TODO: manage case where v[i] is empty if relevant.
        std::cout << v[i][it[i]] << " ";
    }
    std::cout << std::endl;
}

void iterate(const std::vector<std::vector<int>>& v)
{
    std::vector<std::size_t> it(v.size(), 0u);

    do {
        do_job(v, it);
    } while (increase(v, it));
}

Live Demo


Q: How to correctly move ownership from raw pointer to std::unique_ptr? My approach is:
class SomeClass
{
    std::vector<std::unique_ptr<MyObject>> myObjects;
public:
    void takeOwnership(MyObject *nowItsReallyMyObject)
    {
        myObjects.emplace_back(std::move(nowItsReallyMyObject));
    }
};

Am I doing everything correctly or are there any better solutions?

A: You should accept the unique_ptr from the get-go:
class SomeClass
{
    std::vector<std::unique_ptr<MyObject>> myObjects;
public:
    // tells the world you 0wNz this object
    void takeOwnership(std::unique_ptr<MyObject> myObject)
    {
        myObjects.push_back(std::move(myObject));
    }
};

This way you make it clear you take ownership and you also help other programmers to avoid using raw pointers.
Further reading: CppCoreGuidelines R.32

A: The move is redundant.
Myself, I'd do this:
void takeOwnership(std::unique_ptr<MyObject> nowItsReallyMyObject)
{
    myObjects.emplace_back(std::move(nowItsReallyMyObject));
}

because I would want to move the unique_ptr ownership semantics as far "out" as possible.
I might write this utility function:
template<class T>
std::unique_ptr<T> wrap_in_unique( T* t ) {
  return std::unique_ptr<T>(t);
}

so callers can:
foo.takeOwnership(wrap_in_unique(some_ptr));

but even better, then can push the borders of unique_ptr semantics out as far as they reasonably can.
I might even do:
template<class T>
std::unique_ptr<T> wrap_in_unique( T*&& t ) {
  auto* tmp = t;
  t = 0;
  return std::unique_ptr<T>(tmp);
}
template<class T>
std::unique_ptr<T> wrap_in_unique( std::unique_ptr<T> t ) {
  return std::move(t);
}

which lets callers transition their T* into unique_ptrs easier.  All of their T*->unique_ptr<T> is now wrapped in a std::move, and zeros the source pointer.
So if they had
struct I_am_legacy {
  T* I_own_this = 0;
  void GiveMyStuffTo( SomeClass& sc ) {
    sc.takeOwnership( wrap_in_unique(std::move(I_own_this)) );
  }
};

the code can be transformed into:
struct I_am_legacy {
  std::unique_ptr<T> I_own_this;
  void GiveMyStuffTo( SomeClass& sc ) {
    sc.takeOwnership( wrap_in_unique(std::move(I_own_this)) );
  }
};

and it still compiles and works the same.  (Other interaction with I_own_this may have to change, but part of it will already be unique_ptr compatible).


Q: Email is not firing for feeditem records inserted through DataLoader When I am Inserting feed item records through dataLoader, the standard salesforce chatter email is not firing.
But When I insert a record through UI, I am getting the mail. Also, the email is coming when doing through the Batch Apex.
I could not find the root cause of this or I am missing any setting for the same. Correct Me..!!

A: Referring to the Knowledge Article Chatter post does not trigger Chatter email notifications
, it is the expected behavior not to trigger emails during data migration.

This feature is available for data migration purposes so that when you migrate posts from an external or legacy system, the chatter users are not sent emails for the migrated posts. This can be accomplished by setting the InsertedById to a different value than the CreatedById.

In your case, I assume the InsertedById and CreatedById are different and thus no emails are triggered. The article further mentions, if you still want to trigger emails, you can do so by making sure that both the ids are same.

If you want the Chatter post to send notifications to users that have their account configured to receive notifications, make sure while inserting Chatter posts or FeedItems the CreatedById == InsertedById (that is these fields must not be different).


Q: Delete a record in MySql database by clicking a dynamically generated button in Winforms I'm new to programming and hoping someone will help me with my problem. I'm developing an e-commerce application and looking to add buttons to a dynamically generated list of items in the cart. I used a loop statement to go through each row of the table and show the results but I don't know how to remove a record once the user clicks a button. Here is the code for the cart. Please advise. end result screenshot
 private void CartPage_Load(object sender, EventArgs e)
    {

        DB db = new DB();

        DataTable table = new DataTable();
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlCommand command = new MySqlCommand("SELECT * FROM `Product_Info` WHERE `Cart_Number` = @cart", db.getConnection());

        command.Parameters.Add("@cart", MySqlDbType.Int32).Value = Global.cart;

        adapter.SelectCommand = command;
        adapter.Fill(table);

        int rowcount = table.Rows.Count;

        if (rowcount > 0)
        {

            //MessageBox.Show("You have products");
            int Left = 45;
            int Top = 100;
            int rownumb = 0;

            for (int i = 0; i < rowcount; i++)
            {

                Label ProdName_label = new Label();
                this.Controls.Add(ProdName_label);
                Label Name_label = new Label();
                this.Controls.Add(Name_label);

                Label ProdNo_label = new Label();
                this.Controls.Add(ProdNo_label);
                Label No_label = new Label();
                this.Controls.Add(No_label);

                Label ProdQty_label = new Label();
                this.Controls.Add(ProdQty_label);
                Label Qty_label = new Label();
                this.Controls.Add(Qty_label);

                Label ProdPrice_label = new Label();
                this.Controls.Add(ProdPrice_label);
                Label Price_label = new Label();
                this.Controls.Add(Price_label);

                Label PrdSub_label = new Label();
                this.Controls.Add(PrdSub_label);
                Label Sub_label = new Label();
                this.Controls.Add(Sub_label);

                Button Remove_button = new Button();
                this.Controls.Add(Remove_button);

                Panel Product_panel = new Panel();
                this.Controls.Add(Product_panel);

                Product_panel.BackColor = System.Drawing.Color.White;
                Product_panel.Controls.Add(Remove_button);
                Product_panel.Controls.Add(PrdSub_label);
                Product_panel.Controls.Add(Sub_label);
                Product_panel.Controls.Add(ProdNo_label);
                Product_panel.Controls.Add(No_label);
                Product_panel.Controls.Add(ProdQty_label);
                Product_panel.Controls.Add(Qty_label);
                Product_panel.Controls.Add(ProdPrice_label);
                Product_panel.Controls.Add(Price_label);
                Product_panel.Controls.Add(ProdName_label);
                Product_panel.Controls.Add(Name_label);
                Product_panel.Location = new System.Drawing.Point(Left, Top);
                Product_panel.Name = "Product_panel";
                Product_panel.Size = new System.Drawing.Size(200, 200);
                Product_panel.TabIndex = 2;

                //
                // ProdName_label
                //

                ProdName_label.AutoSize = true;
                ProdName_label.Location = new System.Drawing.Point(28, 25);
                ProdName_label.Name = "ProdName_label";
                ProdName_label.Size = new System.Drawing.Size(195, 32);
                ProdName_label.TabIndex = 3;
                ProdName_label.Text = "Product Name:";

                Name_label.AutoSize = true;
                Name_label.Location = new System.Drawing.Point(145, 25);
                Name_label.Name = "Name_label";
                Name_label.Size = new System.Drawing.Size(195, 32);
                Name_label.TabIndex = 3;
                Name_label.Text = table.Rows[rownumb]["Prod_Name"].ToString();

                ////
                //// ProdNo_label
                ////
                ProdNo_label.AutoSize = true;
                ProdNo_label.Location = new System.Drawing.Point(28, 45);
                ProdNo_label.Name = "ProdNo_label";
                ProdNo_label.Size = new System.Drawing.Size(220, 32);
                ProdNo_label.TabIndex = 4;
                ProdNo_label.Text = "Product Number:";

                No_label.AutoSize = true;
                No_label.Location = new System.Drawing.Point(145, 45);
                No_label.Name = "No_label";
                No_label.Size = new System.Drawing.Size(220, 32);
                No_label.TabIndex = 4;
                No_label.Text = "1";
                No_label.Text = table.Rows[rownumb]["Prod_Number"].ToString();

                //
                // ProdPrice_label
                //
                ProdPrice_label.AutoSize = true;
                ProdPrice_label.Location = new System.Drawing.Point(28, 65);
                ProdPrice_label.Name = "ProdPrice_label";
                ProdPrice_label.Size = new System.Drawing.Size(80, 32);
                ProdPrice_label.TabIndex = 4;
                ProdPrice_label.Text = "Price:";

                Price_label.AutoSize = true;
                Price_label.Location = new System.Drawing.Point(145, 65);
                Price_label.Name = "Price_label";
                Price_label.Size = new System.Drawing.Size(80, 32);
                Price_label.TabIndex = 4;
                Price_label.Text = table.Rows[rownumb]["Prod_Price"].ToString();

                ////
                //// ProdQty_label
                ////
                ProdQty_label.AutoSize = true;
                ProdQty_label.Location = new System.Drawing.Point(28, 85);
                ProdQty_label.Name = "ProdQty_label";
                ProdQty_label.Size = new System.Drawing.Size(173, 32);
                ProdQty_label.TabIndex = 4;
                ProdQty_label.Text = "Product Q-ty:";

                Qty_label.AutoSize = true;
                Qty_label.Location = new System.Drawing.Point(145, 85);
                Qty_label.Name = "ProdQty_label";
                Qty_label.Size = new System.Drawing.Size(173, 32);
                Qty_label.TabIndex = 4;
                Qty_label.Text = table.Rows[rownumb]["Prod_Qty"].ToString();

                ////
                //// PrdSub_label
                ////
                PrdSub_label.AutoSize = true;
                PrdSub_label.Location = new System.Drawing.Point(28, 105);
                PrdSub_label.Name = "PrdSub_label";
                PrdSub_label.Size = new System.Drawing.Size(226, 32);
                PrdSub_label.TabIndex = 5;
                PrdSub_label.Text = "Product Subtotal:";

                Sub_label.AutoSize = true;
                Sub_label.Location = new System.Drawing.Point(145, 105);
                Sub_label.Name = "Sub_label";
                Sub_label.Size = new System.Drawing.Size(226, 32);
                Sub_label.TabIndex = 5;
                Sub_label.Text = table.Rows[rownumb]["Prod_Subtotal"].ToString();

                ////
                //// Remove_button
                ////
                Remove_button.BackColor = System.Drawing.Color.LightGreen;
                Remove_button.Location = new System.Drawing.Point(40, 150);
                Remove_button.Name = "Remove_button" + Convert.ToString(rownumb);
                Remove_button.Size = new System.Drawing.Size(120, 34);
                Remove_button.TabIndex = 3;
                Remove_button.Text = "Remove";
                Remove_button.UseVisualStyleBackColor = false;
                Remove_button.Click += new System.EventHandler(Remove_button_Click);

                Top += 220;
                rownumb += 1;
            }

        }

        else
        {
            MessageBox.Show("You don't have any products in your cart");
        }

    }

    private void Remove_button_Click(object sender, EventArgs e)
    {

        MessageBox.Show("Are you sure you want to remove this item?", "Remove", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

    }

A: Your issue apparently is "how do I know which button was clicked?".
You already know how to create a button, add it to the form and attach a click-handler:
   Button Remove_button = new Button();
   this.Controls.Add(Remove_button);

   Remove_button.Name = "Remove_button" + Convert.ToString(rownumb);
   Remove_button.Click += new System.EventHandler(Remove_button_Click);

To know which button was clicked, you can set its .Tag property:
   Remove_button.Tag = Convert.ToString(rownumb); // or whatever the primary key for this row is

Next, in the click handler, you need to read that property.
Fortunately, when the button calls the handler, it uses (a reference to) itself as the sender parameter.
So when you cast that sender to a Button, you get the real button that originated the command and you can access all its properties, such as .Tag:
    private void Remove_button_Click(object sender, EventArgs e)
    {
        Button clickedButton = (Button)sender;
        string rownumb = clickedButton.Tag;

        DialogResult selection = MessageBox.Show("Are you sure you want to remove item #" + rownumb + "?",
              "Remove", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

        // TODO execute a DELETE command for this row when the user clicked OK
    }


Q: determining the character set to use my delphi 2009 app has a basic translation system that uses GNUGetText.  i had used some win API calls to prepare the fonts.  i thought it was working correctly until recently when someone from Malta had a problem with my app failing precisely in this area.  my app is used globally.  some of this code may have become obsolete since d2009 uses unicode.
is all of this truly necessary in order for my app to work in all locales?
TForm.Font.Charset
it's been my understanding i must set the TForm instance's Font.Charset according to the user's locale.  is this correct?
TranslateCharsetInfo( ) win API function
delphi 2009's windows.pas says:
function TranslateCharsetInfo(var lpSrc: DWORD; var lpCs: TCharsetInfo;
dwFlags: DWORD): BOOL;

delphi 5's windows.pas says:
function TranslateCharsetInfo(var lpSrc: DWORD; var lpCs: TCharsetInfo;
dwFlags: DWORD): BOOL; stdcall;

from microsoft's MSDN:
BOOL TranslateCharsetInfo(
  __inout  DWORD FAR *lpSrc,
  __out    LPCHARSETINFO lpCs,
  __in     DWORD dwFlags
);

back when this code was written (back in delphi 5 days), the word was the inport of the function was incorrect and the correct way was:
function TranslateCharsetInfo(lpSrc: Pointer; var lpCs: TCharsetInfo;
dwFlags: DWORD): BOOL; stdcall; external gdi32;

notice that the d2009 windows.pas file copy is not stdcall.  which declaration of TranslateCharsetInfo should i be using?
The code
that aside, essentially i've been doing the following:
var
  Buffer : PChar;
  iSize, iCodePage : integer;
  rCharsetInfo: TCharsetInfo;
begin
  // SysLocale.DefaultLCID = 1802
  iSize := GetLocaleInfo(SysLocale.DefaultLCID, LOCALE_IDefaultAnsiCodePage,
              nil, 0);
  // size=14
  GetMem(Buffer, iSize);
  try
    if GetLocaleInfo(SysLocale.DefaultLCID, LOCALE_IDefaultAnsiCodePage, Buffer,
      iSize)=0 then
        RaiseLastOSError;

    // Buffer contains 0 so codepage = 0
    iCodePage:=Result := StrToInt(string(Buffer));
  finally
    FreeMem(Buffer);
  end;

  // this function is not called according to MSDN's directions for
  // TCI_SRCCODEPAGE and the call fails.
  if not TranslateCharsetInfo(Pointer(iCodePage), rCharsetInfo,
    TCI_SRCCODEPAGE) then
      RaiseLastOSError;

  // acts upon the form
  Font.Charset:= rCharsetInfo.ciCharset;
end;

i just don't know enough about this...strangely enough, years ago when i wrote this, i was persuaded that it was working correctly.  the results of...failing to check API call return code...
isn't there a smarter way to do all this?  doesn't the RTL/VCL do most/all of this automatically?  my instincts tell me i'm working too hard on this...
thank you for your help!

A: Actually, I'm not sure about Delphi 2009, but MSDN says:

Note that DEFAULT_CHARSET is not a real charset; rather, it is a constant akin to NULL that means "show characters in whatever charsets are available."

So my guess is that you just need to remove all the code that you mentioned, and it should work.

A: Not a really answer to this question, but 'small' note on possible memory corruption with this code under D2009+. Function GetLocaleInfo "MSDN: Returns the number of characters retrieved in the locale data buffer..." not BYTES, so under D2009+ you MUST allocate 2 bytes for each characters. Best way to do this is write:
GetMem(Buffer, iSize * SizeOf(Char)); //This will be safe for all delphi versions

Without this you can lead to unpredicted AVs (D2009+), function GetLocaleInfo can overwrite your memory, because you have allocated too small buffer.
Also I don't understant why you're trying change charset to user locale one, I think that you should change charset to your destination translation (like, your program is set to be translated to Russian language, but running on English OS, then you need change charset to RUSSIAN_CHARSET, not ANSI_CHARSET). And under D2009+ I not sure if this is needed, but I might be wrong.


Q: .net windows service local application data is different then in normal app In normal console app I have this
Environment.SpecialFolder.LocalApplicationData is C:\Users\Simon\AppData\Local\
In Windows service
Environment.SpecialFolder.LocalApplicationData is C:\Windows\system32\config\systemprofile\AppData\Local\
How can I specify same path in both type of application?

A: Remember that the services run under a different user profile (can be a LOCAL_SERVICE, NETWORK_SERVICE, etc.) If you'd like them to be the same, run the service under your user profile (You can specify this ServiceProcessInstaller.Account property when you create the installer, or in the Services manager of windows).


Q: What does the BluetoothGATTSetCharacteristicValue ReliableWriteContext parameter actually do? Using C++ VS2017 Win10...
I am testing some code to set a characteristic value on a BLE device.  I had originally had the default function call
HRESULT hr = BluetoothGATTSetCharacteristicValue(
                hBleService.get(),
                _pGattCharacteristic,
                gatt_value,
                NULL,
                BLUETOOTH_GATT_FLAG_NONE);

I had to switch the flag to BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE to get any sets to take place even though IsWritable and IsReadable were the only 2 properties set showing true but that is a different story and another topic.
Anyway,  before I found the problem with the flag I had tried to use the ReliableWriteContext parameter so the code changed to
    HANDLE hDevice = _bleDeviceContext.getBleDeviceHandle();
    BTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext = NULL;
    HRESULT hr1 = BluetoothGATTBeginReliableWrite(hDevice,
        &ReliableWriteContext,
        BLUETOOTH_GATT_FLAG_NONE);

    HRESULT hr = BluetoothGATTSetCharacteristicValue(
        hBleService.get(),
        _pGattCharacteristic,
        gatt_value,
        ReliableWriteContext,
        BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE);

    if (NULL != ReliableWriteContext) {
        BluetoothGATTEndReliableWrite(hDevice,
            ReliableWriteContext,
            BLUETOOTH_GATT_FLAG_NONE);
    }

Once I fixed the flag issue my BluetoothGATTSetCharacteristicValue() function would work with either the NULL or the ReliableWriteContext parameters.  No difference that I could see.
My question is,then, what does the ReliableWriteContext do exactly?  MS docs only say:

The BluetoothGATTBeginReliableWrite function specifies that reliable
writes are about to begin.

Well that doesn't tell me anything.  So should I keep the reliable writes because the word "Reliable" sure sounds like it is something that I want? Or do I not use it because it does not seem to be necessary>
Any insight would be appreciated.
Ed


Q: Raster display issue in ArcMap? A client of ours is having trouble with some raster tiles in ArcMap. They gave me a sample, and I was able to get it looking right with the following workflow:
All you have to do is go into each of your loaded raster images, right-click, Properties, Symbology tab. Under Stretch, change the drop-down to None, and unselect Apply Gamma Stretch. Then it should look normal.
They tried this, and got it to work on partial tiles, but not entire ones. Is there any better solution? Attached is a tile sample.  I'm using ArcGIS 10.2.2 for Desktop.

A: You should be able to set your default rendering options from ArcMap so that any images you load will be rendered in a specified way.  To do this, go to "Customize", select "ArcMap Options", select the "Raster" tab, and then the "Raster Layer" secondary tab.  In this menu you will find many options for rendering any newly loaded rasters.

The section labeled "Enable Custom Rendering Defaults" should do the trick once the settings are set the way you need for the type of rasters you are trying to load.


Q: Create a list of selected objects from S3 bucket with Boto3 I have a S3 bucket with this structure:
data/date=1900-01-01-00/id=abc123def/file1.parquet
data/date=1900-01-01-00/id=ghi456jkl/file2.parquet
data/date=2021-07-11-00/id=mno789pqr/file3.parquet
data/date=2021-07-11-00/id=stu123vwy/file4.parquet
.
.
.

the files in the folder date=1900-01-01-00 are dummy files, the others are "real file" coming from data acquisition.
I would like to create a list of S3Objects containing just the first dummy file and the first real file.
This is the code I wrote:
def __data_list(self):
    datastore_bucket = s3_resource.Bucket(S3_DATASTORE_BUCKET)

    len_dummy_file = len(
        list(
            datastore_bucket.objects.filter(
                Prefix="data/date=1900-01-01-00/"
            )
        )
    )

    data_list = list(
        datastore_bucket.objects.filter(
            Prefix="data/"
        ).limit(len_dummy_file + 1)
    )

    return [data_list[0], data_list[-1]]

I can't know the number of dummy files and I could have thousands of real files, so read all the bucket could take a lot of time and I want to avoid it.
Does anyone know a better way to create the list?

A: You can do logic on the Key returned from the object list:
first_dummy = None
first_real = None

for object in s3_resource.Bucket(BUCKET_NAME).objects.filter(Prefix='data/'):
  if not first_dummy and 'date=1900-01-01-00' in object.key:
    first_dummy = object.key
  elif not first_real and 'date=1900-01-01-00' not in object.key:
    first_real = object.key

  if first_dummy and first_real:
    break

print(first_dummy, first_real)