text:
Q: Way to implement "Get all strings with Levenshtein distance less than X" I'm wondering whether there's an efficient data structure to perform "Retrieve all strings with levenshtein distance less than X".
Few things I'm interested in:

*

*Explanation of the algorithm.

*Is there an existing implementation in existing database / programming langauge?

*Paper / article that I can refer to?

A: this is nearest neighborer search in a metric space with levenshtein distance as the metric (or distance) function
a VP-tree is one of the ways of solving that problem
this Python VP-tree implementation is a working demo that shows how a VP-tree works run it on say a word list it provides an interactive shell where you type a word and it returns the words in that list that are no more then X distance from the word you typed

A: Sounds like a simple breadth-first search with each generation being just one 'edit' away from the previous - and with checks in place to ensure that a string appears in one-and-only-one level.
This would be easily implemented using a couple of hashsets / hashtables in a pair of loops.


text:
Q: Not able to find the Losshitory plots using saveplot in deepxde [Tensorflow] I am running a deep learning model using the deepxde library link. I am trying to plot the losshistory (i.e MSE loss in Train, Test data vs epochs) in order to analyse my simulations. As I am performing a parametric study by varying many parameters, I am trying to save all the loss history while my simulation is running and then later on plot them one after the other at the end of the simulation!
Currently, the code is plotting them after every loop of each parameter (i.e if I have 10*5 parameters , then I am getting 50 plots periodically after each simulation (end of epochs)! This is becoming very crumble-some for me to wait and attend all the 50 plots one after the other during the run-time! That's why I want to look at these after all my simulations have finished! For that I enabled the issave=True. But was not bale to locate the plots!

*

*I am not able to know where are my dde.saveplot files are being saved?

*And what will be the name of these files? (Name or extension; such that I can find them easily in the folder)?

*While keeping the isplot=True; Can there be anyway in which my terminal does not pauses to show the plots? That is, it can plot the error figures and also run in the background, hence all the plots are plotted without me going and closing each one of them one by one and then the program restarting?

I am using the deepxde module link for this simulation. It is based on tensorflow.
Code:
    model = dde.Model(data, net)
    model.compile("adam", lr=lr, metrics=[mean_squared_error])
    checker = dde.callbacks.ModelCheckpoint(
        "/Users/anshumansinha/Desktop/Project/model/"+save_str+"model.ckpt", save_better_only=False, period=100
    )

    print('check done 1')

    # Training for different input points from 2^4 to 2^11.
    # Trainng will be done for 10,000 epochs.
    # isplot = True will generate 10 plots for each simulation.

    losshistory, train_state = model.train(epochs=epochs, callbacks=[checker]) #Training Model batch_size = 10000
    # For plotting the residuals and the training history: isplot=True will plot
    dde.saveplot(losshistory, train_state, issave=True, isplot=True)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - taking most frequent element from array/converting numpy array to std array I'm in the process of implementing a K-nearest neighbour algorithm in Python (for those of you that don't know about learning, it's an algorithm used to classify objects based on data that is already classified, using Euclidean distance).
I've got my distances computed, and I can take the k nearest distances, and find the classes of those objects. My problem is, if K is greater than 1, say 3 or 5, I'm not sure how I can get the most frequent element in the list.
For example, my output is:
[10, 9, 7, 10]

10 occurs the most, so I'd like to return this number. In case of a tie (2 or more elements occuring the same frequency), it returns an error (I can deal with this myself). I'd just like some opinion on how to return the maximum of the above list. (Using python 2.6.6 so I can't use the collections imports).
Second question:
I'm attempting to convert a numpy array to a normal array. My code looks like this:
def getClassesOfIndexes(l):
    tmp1 = []
    for i in l:
        tmp1.append(classes[i])
    return tmp1

print(getClassesOfIndexes([1024, 9128, 394, 39]))

This prints something like: [array([10], dtype=uint8), array([7], dtype=uint8), array([10], dtype=uint8), array([9], dtype=uint8)]
What could I do for it to simply return [10, 7, 10, 9]?
Thanks for any help.

A: Question 2 is the easier (though in the future, please post unrelated questions as two separate questions on SO).  The tolist function automatically converts numpy arrays to regular lists http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html
Question 1 is also pretty straightforward. You say you want "the most frequent element in the list". Here's a complete discussion Python most common element in a list. One solution is to map each element to a dictionary of its frequency, and then grab the key corresponding to the largest value in the map. This might look like
...
freq_map = {my_list.count(val):val for val in set(my_list)}
return freq_map[max(freq_map.keys())]

A: Following-up on the comments given in en_Knight's good answer (upvoted for the reference to the existing threads, but beware the dict comprehension does not work under Python2.6.6!): if you want a list of the most common elements (so those with equal frequency), you could do the following:
>>> arr = [10,9,9,7,10]
>>> counter = {}
>>> for elm in arr:
...     try:
...         counter[elm] += 1
...     except KeyError:
...         counter[elm] = 1
...
>>> counter
{9: 2, 10: 2, 7: 1}
>>> srt = sorted(counter.items(), key=lambda x: x[1], reverse=True)
>>> maxitem, maxcount = srt[0]
>>> most_frequents = [maxitem]
>>> for rec in srt[1:]:
...     if rec[1] == maxcount:
...         most_frequents.append(rec[0])
...     else:
...         break
...
>>> most_frequents
[9, 10]

Tested under Python2.6.6.


text:
Q: Is it ok to change Microsoft.Phone.Controls.Toolkit's behavior and use it in the app I have to change toolkit's implementations for slide transitions a little bit. Is there any legal issue in changing the toolkit's code and using it in my app.
Thanks
-Abhinav-

A: You are free to modify and use the toolkit`s code. Check this : Community Source Licensing
Microsoft Public License (Ms-PL) - The Ms-PL is the least restrictive of the Microsoft source code licenses. It allows licensees to view, modify, and redistribute the source code for either commercial or non-commercial purposes. Under the Ms-PL, licensees may change the source code and share it with others. Licensees may also charge a licensing fee for their modified work if they so wish. Microsoft uses this license most commonly for its developer tools, applications, and components.


text:
Q: Sed doesn't process all script lines I have problem with my sed script. I process this data using the above script.
The problem is that, the lines from script:
/^$/d
s/ $/ajes/g

doesn't work. Of course it will work if I process data again.
This doesn't work:
sed -f script.sed -i data.file

but this will work (double procesing):
sed -f script.sed -i data.file
sed -f script.sed -i data.file

Why is that? Where is problem? Why I can't process it once with all results?

A: The real problem is that you have just one line. And sed reads it once and tries execute each command one by one, while the whole line is in the patterns space. When you substitute something to \n it is still just one string and it is in the pattern space. It wasn't divided in multiple strings and reread one by one.
Obviously /^$/ doesn't match to your \n\n and s/ $/ajes/g doesn't match to your any space before \n. That's the reason why that doesn't work the way you expect.
You can solve the problem with modifying "non working" commands to
s/\n\+/\n/g # equals to /^$/d
s/ \n/ajes\n/g # equals to s/ $/ajes/g

A: You have many substitutions there. Let's say you have substitutions

*

*Rule A

*Rule B

*Rule C.

So, the problem here is if Rule A initially does not match and then Rule B or C matches resulting in a pattern that would match again with A after replacement, then Rule A would not come into effect for that line. So, you need to analyze the order in which the substitutions would be processed and hopefully you'll find the mistake.
Hope this helps you in the proper direction.


text:
Q: How to write to a Spark SQL table from a Panda data frame using PySpark? The pandas.DataFrame.to_sql() method will let you write out to a database the result of your data frame. This works fine in the context of a standard RDBMS. How to use this with Spark SQL though, using PySpark ?
I need a connection parameter for this method - what can that be ?
thanks,
Matt

A: SparkSQL has nothing to do with the to_sql() which connects to a SQL engine.
If sc is your SparkContext
import pandas as pd
df = pd.DataFrame({'Name':['Tom','Major','Pete'], 'Age':[23,45,30]})

from pyspark import SQLContext
sqlc = SQLContext(sc)

spark_df = sqlc.createDataFrame(df)


text:
Q: Add new keys and values to an existing dictionary where the keys are matched I would like to calculate the cost of product c = 20 $ and d = 30$. Since I have meta data and df as separated data frame I need to join them somehow where I can then get the price and the number of items bought for each product (e.g. c:5) in a dictionary for each individual id, and then calculated the price of each product (e.g. for product c 1 * 20)

*

*My First data frame
Metadata  = {'product_name': ["c", "d"], 'product_price': [20, 30]}
Metadata = pd.DataFrame(data=Metadata )

*My second data frame
df = pd.DataFrame({'id':[1,2,3], 'product':[{'c':1}, {'d':3}, {'c':5,
'd':6}]})

Edited

*My attempts:
So I thought I need to get access to the keys and then use them for later for matching.
I start with converting the Metadata table into a dictionary:
def get_product_price_dictionary(Metadata):
    product_info = Metadata
    product_price_dict = dict()
    for d in product_info.to_dict('records'):
        p_name = d["product_name"]
        p_price = d["product_price"]
        product_price_dict[p_name] = p_price
    return product_price_dict
test = get_product_price_dictionary(Metadata)
test

Output:
{'c': 20, 'd': 30}

Then I get the keys inside my data frame.
list_keys = []
df_dic = df['product']
for i in range(len(df_dic)):
    if df_dic.iloc[i] is not None:
        each_dic = df_dic.iloc[i]
    for key, value in each_dic.items():
        list_keys.append(key)
list_keys_uique = list(set(list_keys))
list_keys_uique[0:5]

Output
['c', 'd']

I have recently get started working with python and now, I am really stuck in working with dictionary! to get the column called product_cost in the df data frame.
And now I do not know how to precede with it!!!

A: I would not turn everything to dict as Pandas is already very fast. You can search for certain values within a database using double equators together with the row name:
df[df['row']==key].value

I added a little piece of code which walks your database and calculates the total money of each transaction:
Metadata  = {'product_name': ["c", "d"], 'product_price': [20, 30]}
Metadata = pd.DataFrame(data=Metadata )

df = pd.DataFrame({'id':[1,2,3], 'product':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})

print (Metadata)
print (df)

for action in df['product']:
  print ('action:', action)
  total = 0
  for product in action:
    price = float(Metadata[Metadata['product_name']==product].product_price)
    print ('  product: %s, price: %.2f' % (product, price))
    print ('    count: %i, sum: %.2f' % (action[product], price * action[product]))
    total += price * action[product]
  print ('  total: %.2f' % total)

Console output of the above code:
  product_name  product_price
0            c             20
1            d             30
   id           product
0   1          {'c': 1}
1   2          {'d': 3}
2   3  {'c': 5, 'd': 6}
action: {'c': 1}
  product: c, price: 20.00
    count: 1, sum: 20.00
  total: 20.00
action: {'d': 3}
  product: d, price: 30.00
    count: 3, sum: 90.00
  total: 90.00
action: {'c': 5, 'd': 6}
  product: c, price: 20.00
    count: 5, sum: 100.00
  product: d, price: 30.00
    count: 6, sum: 180.00
  total: 280.00


text:
Q: Redirect broken 404 pages with .htaccess and regular expressions I have been unpublishing old pages on my website. To avoid 404 pages, I'd like to redirect these pages to a generic page.
So for example this page:
https://www.portal-gestao.com/artigos/7380-7-t%C3%A1cticas-de-sobreviv%C3%AAncia-%C3%A0-crise-nas-vendas.html

Should redirect to:
https://www.portal-gestao.com/artigos/

I'm not very skilled with .htaccess or regular expressions, I've bee trying to redirect the pages with:
RewriteRule ^artigos/(.*)$ /artigos/$1 [R=301,L]

But something isn't working, can anyone help?

A:
Late information... the site uses a Joomla CMS. See the UPDATE below.

To redirect requests for physical files that no longer exist you need to actually check that the file no longer exists, otherwise it will indeed "redirect everything" (as mentioned in comments).
For example, to redirect any requests of the form /artigos/<something>, that do not map to physical files, to /artigos/ you can do the following:
RewriteEngine On

REwriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(artigos/). /$1 [R=302,L]

The $1 backreference simply prevents you having to repeat the directory name.
The first condition that checks against the REDIRECT_STATUS environment is intended to ensure that only direct requests are redirected. This is probably only required if you are still on Apache 2.2 (as opposed to 2.4) since mod_dir will execute first, rewriting the redirected request to index.php (if it exists) and causing a rewrite loop. On Apache 2.4, mod_dir executes later.
Test with a 302 and only change to a 301 when you are sure it's working OK - to prevent caching issues.
You will need to clear your browser cache before testing.
However, a 404 would generally be a better response. The search engines will likely see the redirect to a common root as a soft-404 and users are more likely to be "confused" when they don't see the information they requested.

RewriteRule ^artigos/(.*)$ /artigos/$1 [R=301,L]

By itself, this would result in a redirect loop, as it simply redirects to itself.

UPDATE: it's not a file, it is an article in a Joomla CMS

If valid URLs do not map to physical files then you can't do this in .htaccess. In your case, a valid URL is determined by the Joomla CMS (as stored in the Joomla database). .htaccess is processed at the very start of the request, before control passes to PHP/Joomla. Directives in .htaccess can only look at the HTTP request and the physical filesystem.
Joomla uses a front-controller pattern. All URLs, that do not map to physical files (to exclude static resources like CSS, JS and images), are internally rewritten to index.php (the "front-controller"), this effectively "routes" the URL and decides what content should be returned.
What you are asking could only be done on a static website where URLs map to physical files on the file system.
You need to perform this redirect in Joomla itself, when Joomla has determined that the requested URL does not exist. (This is actually more efficient anyway as you only need to execute your code after a 404 has been determined, rather than on every single request, as it would be if you used .htaccess.)


text:
Q: Replace specific file in a zip file using java I would like to replace a specific file (README.MD) in prj-basics-final.zip with the external file of the same name.
The code below doesn't replace README.MD in prj-basics-final.zip. It doesn't throw any error also.
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class UpdateZipFile {
    public static void main(String[] args) {
        Path zipFilePath = Paths.get("/Users/pradeepjonnalagadda/ZipFile/prj-basics-final.zip");
        Path externalFile = Paths.get("/Users/pradeepjonnalagadda/ZipFile/README.md");;
        try {
            FileSystem fs = FileSystems.newFileSystem(zipFilePath, null);
            Path fileInsideZipPath = fs.getPath("/README.md");
            Files.copy(externalFile, fileInsideZipPath,StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Finished processing");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
Q: Grade of a maximal prime ideal in a Noetherian UFD Here is an another problem in Commutative Rings by Kaplansky, p. 103, no. 15.

Let $R$ be a Noetherian UFD. Let $(a,b) \not= R$ where $a,b \in R.$ Prove that any maximal prime of $(a,b)$ has grade of at most $2.$

Note: By a maximal prime of $I=(a,b)$, I assumed a maximal prime ideal $\mathfrak{p} \in \text{Ass}(I).$ In other words, an embedded prime ideal associated with $I.$

A: Since $R$ is noetherian, a maximal prime of $(a,b)$ is nothing but a maximal prime in the set $\operatorname{Ass}_R(R/(a,b))$. We can localize and reduce the problem to the following:

Let $(R,\mathfrak m)$ be a local noetherian UFD, and $a,b\in R\setminus\{0\}$ such that $(a,b)\ne R$. If $\mathfrak m\in\operatorname{Ass}_R(R/(a,b))$, then $\operatorname{depth}R\le 2$.

We have an exact sequence of $R$-modules $$0\to R/(a)\cap (b)\to R/(a)\oplus R/(b)\to R/(a,b)\to0.$$ Since $R$ is a UFD, $(a)\cap (b)$ is a principal ideal (generated by $ab/\gcd(a,b)$), and thus the projective dimension of $R/(a)\cap (b)$ is one. Now we get $\operatorname{pd}_R(R/(a,b))\le 2$. Applying the Auslander-Buchsbaum formula we obtain $\operatorname{depth}R=\operatorname{pd}_R(R/(a,b))\le 2$.


text:
Q: Vulcan biology and Pon Farr In Star Trek: Enterprise (S2ep25, "Bounty") Dr. Phlox and other crew found themselves being seduced by T'Pol, who said that if she didn't have sex soon she'd die because of an artifically induced Pon Farr.

Spock also gave this story to the crew of Star Trek TOS.
Is there any reasonable medical explanation for how a humanoid could just up and die unless they had sex?
Based on a literal interpretation of the statements by T'Pol and Spock, the biological pathway whereby sure death would occur from lack of sex would have to be something which could only be satiated by intercourse and which could not be "tricked" by a self gratification.
This leads me to my hypothesis. Is it possible that they would not literally up and die if they didn't find a partner, but rather they meant it metaphorically, like "if I don't get some soon I'll just die!", because they wanted it so badly?

A: Background
According to Memory Alpha, the pon farr could lead to the plak tow (blood fever), which would literally result in death if not abated within 8 days.
The plak tow was initiated by telepathic contact, which would normally involve another vulcan of the opposite sex, but it was possible to engage it with other species (Ensign Vorik did this with B'Ellana Torres, in the Blood Fever, Voyager). There's no canon evidence I know of to suggest plak tow can or can't be initiated with someone of the same sex.
If the plak tow was initiated, it could be stopped by one of two methods: either mating successfully or engaging in kal if fee, a ritualistic fight to the death (although none of the kal if fee rituals shown in any series resulted in death that I recall).
Holograms
Tuvok satiated his pon farr using a hologram of his wife, though he commented it was lacking compared to the real thing, and it doesn't seem he ever initiated the plak tow. (Body and Soul, Voyager.)
Vorik attempted to use a hologram of a vulcan female, but it was unsuccessful. I don't know if this is because he had already mind-linked with B'Ellana, because the hologram wasn't accurate enough, because he had no prior connection to the holographic female, or because he simply didn't attempt it (he expressed disdain for the idea to Tom Paris before the attempt, so maybe he just went in, waited for Tom to leave, then shut the hologram down).
Inevitability
Spock in TOS (Amok Time) suggested he would die if he couldn't satiate his pon farr. Tuvok, on the other hand, mentioned it could be avoided by intense meditation, though Vorik was unable to meditate successfully, so it may be something only some vulcans can achieve.
Tuvok had access to medicine that Spock didn't, so it could be a matter of advances in medicine between TOS and Voyager, but Vorik had the same medicine available which didn't help (though he also refused to complete the treatments so it may have helped if he wasn't so stubborn).
Given that fighting to the death can cause the pon farr to end, it seems logical to come up with some method of beating the crap out of a vulcan with the pon farr to end it, but that's not canon. Also, beating the crap out of a vulcan is a problem unto itself. So the holodeck method is probably better if it works.


text:
Q: Is modular approach in Drupal good for performance? Suppose I have to create functionalities A, B and C through custom coding in Drupal using hooks.
Either I can club three of them in custom1.module or I can create three separate modules for them, say custom1.module, custom2.module and custom3.module.
Benefits of creating three modules:

*

*Clean code

*Easily searchable

*Mutually independent

*Easy to commit in multi-developer projects

Cons:

*

*Every module entry gets stored in the database and requires a query.

To what extent does it mar the performance of the site?
Is it better to create a single large custom module file for the sake of reducing database queries or break it into different smaller ones?
This issue might be negligible for small scale websites, let the case be for large scale performance oriented sites.

A: I would code it based on how often do I need function A , B and C
Actual example:
I made a module which had two needs
1) Send periodic emails based on user preference. Lets call this function A
2) Custom content made in a module . Lets call this function B
3) Social integration . Lets call this function C
So what I did is as Function A is only called once a week I made a separate module for it.
As for Function B and C I put it all together as they would always be called together.
If you have problems with performance then check  out this link . Its a good resource  for performance improvement.
http://www.vmirgorod.name/10/11/5/tuning-drupal-performance
It lists a nice module called boost. I have not used it but I have heard good things about it.
cheers,
Vishal

A: i'm actually interested in:

Is it better to create a single large custom module file for the sake of reducing database queries or break it into different smaller ones?

I was poking around and found a few things regarding benchmarking the database. Maybe the suggestion here is to fire up the dev version and test. check out db benchmarking
now i understand that doesn't answer specifically but i'd have to say its unique to each environment. I hate to use that type of answer but i truly believe it is. Depends on modules installed, versions used, hardware and os tunables among many other things.

A: Drupal .module files are all loaded with every page load.  There is very little performance related that can be gained or lost simply by separating functions into different .module files.   If you are not using an op code cache, then you can get improved performance by creating .inc files and referencing those files in the menu items in hook_menu, such that those files only get loaded when the menu items are accessed.  Then infrequently called functions do not take up memory space.
File separation in general is a very small performance issue compared to how the module is designed with respect to caching, memory use, and/or database access and structure. Let the code maintenance and dependency issues drive when you do or do not create separate modules.


text:
Q: Trying to find a geometry algorithm, that calculates geometry depending on which path is closer
I'm trying to figure out an algorithm:
So there are 2 paths, and paths have hitboxes (outer line). When the cursor is inside one of the hitboxes, event is sent to the respective path.
But when the cursor is inside both hitboxes, I want to send the event only to the one that is closer to the cursor.
So I want to find an algorithm that will modify the hitbox, instead of me checking which one is closer to the mouse - since I don't want to execute extra functions on mousemove.


text:
Q: InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty I have 2 certificates that I am using to make a GET request. The certificates are certs.pem and key.pem and these 2 certs when I am using with Python code it is giving me response. Below is Python code snippet that I am using -
url = "https://example.com"
cert = (certs.pem, key.pem)
response = requests.get(url, cert=cert, verify=False)

Now same GET call I want to use in java. And since Java mostly accept .jks file. So, I am trying to convert both .pem files to single .jks file.
To convert to jks file I am first combining both .pem file using command- cat certs.pem key.pem > combined.pem.
After generating combined pem I am converting it to .p12 file using command-  openssl pkcs12 -export -in combined.pem -out cert.p12. I am not using any password while creating p12 file.
After generating .p12 file I am converting it to .crt file using command- openssl pkcs12 -in cert.p12 -clcerts -nokeys -out out_cert.crt
And finally I am converting to .jks file using below code snippet -
   private static Certificate readCert(String path) throws IOException, CertificateException {
        try (FileInputStream fin = new FileInputStream(path)) {
            return CertificateFactory.getInstance("X.509").generateCertificate(fin);
        }
    }

    // To convert into jks
    public static void generateCert() {
        try {
            // Reading the cert
            Certificate cert = readCert("out_cert.crt");

            // Creating an empty JKS keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);

            // Adding the cert to the keystore
            keystore.setCertificateEntry("somecert", cert);

            // Saving the keystore with a zero length password
            FileOutputStream fout = new FileOutputStream("final_cert.jks");
            keystore.store(fout, new char[0]);
        } catch (GeneralSecurityException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Since I want to generate .jks file without password so I am using above code snippet. We can not generate .jks file without password with keytool.
Now finally after generating the .jks file, I am using below code snippet to make GET call -
    private static final String GET_API = "https://example.com";

    private static Client getClient() throws Exception {

        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream tsStream = getClass.getResourceAsStream(Constants.JKS_FILE_PATH);  //jks file that I have genearted from pem
        keystore.load(tsStream, null);
        TrustManagerFactory tmg = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmg.init(keystore);
        TrustManager[] trustManager = tmg.getTrustManagers();

        SSLContext sslContext = null;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManager, null);

        return ClientBuilder.newBuilder()
                .sslContext(sslContext)
                .hostnameVerifier((s1, s2) -> true)
                .build();
    }

    public static void getAPI() {
        try {
            String response = getClient().target(GET_API)
                    .request(MediaType.APPLICATION_JSON)
                    .get(String.class);
            System.out.println("Response is "+response)
        } catch (Exception e) {
            logger.error("Error in calling get api , Exception {}",e);
        }
    }

When I am running above code snippet to call getAPI(), I am getting error as -
javax.ws.rs.ProcessingException: javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:269) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:297) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:675) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.call(JerseyInvocation.java:697) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.lambda$runInScope$3(JerseyInvocation.java:691) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:390) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.runInScope(JerseyInvocation.java:691) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:674) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:422) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:318) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
Caused by: javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.ssl.Alert.createSSLException(Alert.java:133) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:348) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:291) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:286) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1589) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:452) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:104) ~[?:1.8.0_312]
    at sun.security.validator.Validator.getInstance(Validator.java:181) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:302) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:189) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369) ~[?:1.8.0_312]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182) ~[?:1.8.0_312]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:156) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1418) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1324) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:439) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[?:1.8.0_312]
    at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[?:1.8.0_312]
    at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[?:1.8.0_312]
    at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:102) ~[?:1.8.0_312]
    at sun.security.validator.Validator.getInstance(Validator.java:181) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:302) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:189) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369) ~[?:1.8.0_312]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182) ~[?:1.8.0_312]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:156) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1418) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1324) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:439) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more

Can someone have any idea what is going wrong in my complete process?
Thanks in Advance :-)


text:
Q: Kendo grid datetime picker , how to get timestamp? I would like to get the timestamp value from datetime picker placed in a grid data table.
I tried to do it this way:
  columns: ["id",
            "username",
            "email",
           {
                          field :"created",
                          title : "Created at",
                          format: "{0:dd-MM-yyyy}",
                          parseFormats: ["dd-MM-yyyy"],
                          type: "date"
           },

But it always returns a value like this:
created: "+046300-12-08T07:40:00.000Z"

How can I get timestamp from date picker?
Thanks for any advice.


text:
Q: Log 4 net not logging to file Probably a very simple setup, but I've tried to setup Log4Net. In my web.config I have:
<log4net>
    <appender name="File" type="log4net.Appender.RollingFileAppender">
      <file value="Logs\\Log4Net.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd-HHmm" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>

    <logger name="File">
      <level value="All" />
      <appender-ref ref="LogFileAppender" />
    </logger>
    <root>
      <level value="ALL"/>
      <appender-ref ref="FileAppender"/>
    </root>
  </log4net>

I have added the following to my configsections:
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

The following in global.asax:
 log4net.Config.XmlConfigurator.Configure();

The following is on my default.aspx:
ILog alog = log4net.LogManager.GetLogger(typeof(_Default));
log4net.ILog logger = log4net.LogManager.GetLogger("File");

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        SetupSeo();
    }
    alog.Error("this test");
    logger.Error("Front page loaded for ip " + Request.UserHostAddress);
}

What is wrong?

A: I guess it is a Permission issue. The relevant directory do not have sufficent permissions so that ASP.NET can write to that.
To verify that, Enable log4net internal debugging by adding the below item to the <appSettings> section in the webconfig.
<add key="log4net.Internal.Debug" value="true"/>

Now add the below to the webconfig as well
<system.diagnostics>
  <trace autoflush="true">
    <listeners>
      <add
        name="textWriterTraceListener"
        type="System.Diagnostics.TextWriterTraceListener"
        initializeData="C:\myLogFolder\log4net.txt" />
    </listeners>
  </trace>
</system.diagnostics>

Make sure that myLogFolder folder in C drive have permissions so that ASP.NET can write to that. This will write the internal debugging message to this file. Run the app and see what happens.


text:
Q: DataFrame : Get the top n value of each type I have a group of data like below
ID  Type    value_1 value_2
1   A   12  89
2   A   13  78
3   A   11  92
4   A   9   79
5   B   15  83
6   B   34  91
7   B   2   87
8   B   3   86
9   B   7   85
10  C   9   83
11  C   3   85
12  C   2   87
13  C   12  88
14  C   11  82

I want to get the top 3 member of each Type according to the value_1 . The only solution occurs to me is that: first , get each Type data into a dataframe and sorted according to the value_1 and get the top 3; Then, merge the result together.
But is ther any simple method to solve it ? For easy discuss , I have codes below
#coding:utf-8
import pandas as pd
_data = [
    ["1","A",12,89],
    ["2","A",13,78],
    ["3","A",11,92],
    ["4","A",9,79],
    ["5","B",15,83],
    ["6","B",34,91],
    ["7","B",2,87],
    ["8","B",3,86],
    ["9","B",7,85],
    ["10","C",9,83],
    ["11","C",3,85],
    ["12","C",2,87],
    ["13","C",12,88],
    ["14","C",11,82]
]
head= ["ID","type","value_1","value_2"]
df = pd.DataFrame(_data, columns=head)

A: Then we using groupby tail with sort_values
newdf=df.sort_values(['type','value_1']).groupby('type').tail(3)
newer
    ID type  value_1  value_2
2    3    A       11       92
0    1    A       12       89
1    2    A       13       78
8    9    B        7       85
4    5    B       15       83
5    6    B       34       91
9   10    C        9       83
13  14    C       11       82
12  13    C       12       88

A: Sure! DataFrame.groupby can split a dataframe into different parts by the group fields and apply function can apply UDF on each group.
df.groupby('type', as_index=False, group_keys=False)\
    .apply(lambda x: x.sort_values('value_1', ascending=False).head(3))


text:
Q: Why does a Task within a @MainActor not block the UI? Today I refactored a ViewModel for a SwiftUI view to structured concurrency. It fires a network request and when the request comes back, updates a @Published property to update the UI. Since I use a Task to perform the network request, I have to get back to the MainActor to update my property, and I was exploring different ways to do that. One straightforward way was to use MainActor.run inside my Task, which works just fine. I then tried to use @MainActor, and don't quite understand the behaviour here.
A bit simplified, my ViewModel would look somewhat like this:
class ContentViewModel: ObservableObject {

    @Published var showLoadingIndicator = false

    @MainActor func reload() {
        showLoadingIndicator = true

        Task {
            try await doNetworkRequest()
            showLoadingIndicator = false
        }
    }

    @MainActor func someOtherMethod() {
        // does UI work
    }

}

I would have expected this to not work properly.
First, I expected SwiftUI to complain that showLoadingIndicator = false happens off the main thread. It didn't. So I put in a breakpoint, and it seems even the Task within a @MainActor is run on the main thread. Why that is is maybe a question for another day, I think I haven't quite figured out Task yet. For now, let's accept this.
So then I would have expected the UI to be blocked during my networkRequest - after all, it is run on the main thread. But this is not the case either. The network request runs, and the UI stays responsive during that. Even a call to another method on the main actor (e.g. someOtherMethod) works completely fine.
Even running something like Task.sleep() within doNetworkRequest will STILL work completely fine. This is great, but I would like to understand why.
My questions:
a) Am I right in assuming a Task within a MainActor does not block the UI? Why?
b) Is this a sensible approach, or can I run into trouble by using @MainActor for dispatching asynchronous work like this?

A: await is a yield point in Swift. It's where the current Task releases the queue and allows something else to run. So at this line:
        try await doNetworkRequest()

your Task will let go of the main queue, and let something else be scheduled. It won't block the queue waiting for it to finish.
This means that after the await returns, it's possible that other code has been run by the main actor, so you can't trust the values of properties or other preconditions you've cached before the await.
Currently there's no simple, built-in way to say "block this actor until this finishes." Actors are reentrant.


text:
Q: Differences between strings.Contains and strings.ContainsAny in Golang In the source code:
// Contains returns true if substr is within s.
func Contains(s, substr string) bool {
    return Index(s, substr) >= 0
}

// ContainsAny returns true if any Unicode code points in chars are within s.
func ContainsAny(s, chars string) bool {
    return IndexAny(s, chars) >= 0
}

the only difference seems to be substr and the Unicode code points in chars. I wrote some test to test both of them. Their behaviors seem to be identical. I don't understand when to use which.

A: I think two functions are totally different. Contains are used to detect if a string contains a substring. ContainsAny are used to detect if a string contains any chars in the provided string.

A: Contains function reports whether a sub-string is within the string. Whereas ContainsAny function reports whether any Unicode code points in chars are within the string. Look at the documentation.
 func main() {
     fmt.Println(strings.Contains("seafood", "aes"))
     fmt.Println(strings.ContainsAny("seafood", "aes"))
     fmt.Println(strings.Contains("iiii", "ui"))
     fmt.Println(strings.ContainsAny("iiii", "ui"))
 }

The output is;
false
true
false
true


text: Q: Source of background data usage - Flutter I noticed that the app I'm working on has some background data usage, I wanted to investigate the source of this usage, so I used the DevTools, but there were no requests happening while the app was in the background, is there any other way that can help me know the source of this usage?


text:
Q: Looping in Render() function of ReactJS I have an array of objects that I need to loop output on but am getting stuck. I tried using jQuery's .each() without success.
render: function() {
  return (
  $.each(events, function(k, e) {

e.Date

e.Title

e.Price

#professional

#livejazz

#courtet

     });
  );
}

My array contains simple Javascript objects with keys and values. How can I render them in React?

A: Here is a example of how looping is usually done in Reactjs
var List = React.createClass({
   render: function() {
     return (
    { this.props.data.map(function(e) {
            var eventStyle = {
              backgroundImage:e.Image
            };

            return (

{e.Date}

{e.Title}

{e.Price}

#professional

#livejazz

#courtet

            )
        })
    }
    );
 }
});

React.render(<List data={ (Array goes here) }  />, document.body);

A: I totally agree with Dominic Tobias answer about, forgetting about jQuery, since we won't be manipulating the dom nor do we need to. For all other helpers use native functions or _. or give (es6 a shot) but in addition to the answer given by eugene safronov. I would like to recommend not to create the loop within the return itself, for readability and also for flexibility purposes. See example and the example below.
    var List = React.createClass({
        render: function () {
            var eventItems = this.props.data.map(function (item) {
            var itemStyle = {
              backgroundImage:item.Image
            };
                return (

{item.Date}

{item.Title}

{item.Price}

#professional

#livejazz

#courtet

                );
            });

            return (

                    { eventItems }

            );
        }
    });

    React.render(<List data={ (itemsArray) }  />, document.body);

-- example with no data --
    var List = React.createClass({
        render: function () {

            var eventItems;

            if(_.isEmpty(this.props.data)) { // i used lodash/underscore _. for this example)
                eventItems = (
                    No items to display
                );
            } else {
                eventItems = this.props.data.map(function (item) {
                    var itemStyle = {
                      backgroundImage:item.Image
                    };
                    return (

{item.Date}

{item.Title}

{item.Price}

#professional

#livejazz

#courtet

                    );
                });
            }

            return (

                    { eventItems }

            );
        }
    });

    React.render(<List data={ (itemsArray) }  />, document.body);

it adds some extra flexibility, and readibility. I hope this helps u a bit, success with ReactJs!
(update: btw, now i used _. to check if data was empty, but u could also have checked if map returned nothing, and then show the different content, saves 1 extra function :D)


text:
Q: Just bought an ultrawide monitor, but it looks borderline blury, what am I doing wrong? So I either bought the wrong thing, or just don't know how to configure it correctly.  I bought a Acer XR342CK bmijqphuzx , and have it hooked up to a Macbook Pro w Touchbar 2016 via a Caldigit TS3 plus dock using displayport.
Basically the fonts looked jagged and borderline blurry.  At first I thought there was something wrong with my eyes and I kept squinting.  I missed with the font smoothing effects in MacOS and don't notice any changes.
Are these ultrawide monitors just not as high resolution as the retina or the 4k Monitors I'm currently used to ( I have an HP Z27 at work, and a Dell 2715Q on my mac mini at home)
Thanks for the help, was looking forward to this super wide 34 inch for video editing, but I didn't expected it to be annoyingly less sharp.  I'm definitely open to the possibility that I've done something stupid!


text:
Q: Como não aparecer valor de lixo quando puxar um dado do banco com PHP que seja nulo Estou puxando um valor VARCHAR do banco , que eu converto ele para aparecer em formato de DATA , contanto quando o valor é branco no meu banco, ele me puxa um numero "31/12/1969" . Como posso solucionar isso ?
Como eu estou transformando esse valor :

*CONEXÃO COM O BANCO + SQL DO SELECT

Data

<?php while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { ?>

 ?php echo date("d/m/Y",strtotime($row['DT_FATURAMENTO']??'')); ?>

<?php     }   ?>

A: Verificando se o valor de $row['DT_FATURAMENTO'] é vazio antes de passá-lo para a função strtotime.
Você tentou fazer isso:
strtotime($row['DT_FATURAMENTO'] ?? '')

Mas:

*

*Utilizou o operador de coalescência nula, ??, que verificará se o primeiro parâmetro é nulo, não vazio (algo vazio é não nulo);

*Se for nulo, passa como parâmetro a string '', que é JUSTAMENTE a que você não quer passar;

Parece que escreveu esse trecho de código e nem parou para analisar o que, de fato, tinha feito.
Você deve mudar a condição, considerando $data o valor em questão:
<?= empty($data) ? 'Indefinida' : date('d/m/Y', strtotime($data)) ?>

A: Isso é data default para Unix, com ajuste do fuso horário (00:00:00 UTC on 1 January 1970 +/- Horas do fuso horário).
Para solucionar o problema basta condicionalmente não converter para data caso o varchar seja nulo.


text:
Q: Realtime updates from Firestore via Node.js I was wondering if it's possible to update my app anytime the document is changed? I have a restaurant user that has a store of potential rewards. On the view, the user can add and delete rewards to their rewards store. Right now I have the functionality built that will allow the user to delete their reward. However, I need to refresh the page in order for the changes to show. I was wondering if there is a way to update the data in real-time via Firestore. I've watched some videos that explain how to do this on the client-side. However, my Firestore database calls happen on the server, and I'm not sure how I can update the rewards store in real-time from that.
Here is my code on the client side that adds delete functionality on the client side. It makes a call to my Node.js server which will delete the item in the restaurant's reward store.
NOTE The list of rewards is being obtained from the server and is passed down to the client from the server into a particular view via HTML handlebars. My concern is whether I should make these database calls from the front-end rather than the back-end.
for(var i = 0; i < rewardDeleteButtons.length; i++) {
    var deleteButton = rewardDeleteButtons[i]
    deleteButton.addEventListener('click', function(e) {
        console.log(document.cookie)
        console.log(this.value)
        fetch("/deleteReward/" + this.value, {
            method: "DELETE",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              "CSRF-Token": Cookies.get("XSRF-TOKEN"),
            },
          });
    })
}

Here is the code in my server that deletes the item from the Restaurant's reward store. Once I refresh my page, the changes show, but I don't know how to get that change to show in real time. The
app.delete('/deleteReward/:id', (req, res) => {
  console.log('\n\n\n\nInside delete\n\n\n\n')
  console.log(req.params.id)

  var rewardId = req.params.id

  const sessionCookie = req.cookies.session || "";

  var idToken = ""
  var type = ""
  if (sessionCookie) {
    idToken = sessionCookie['idToken']
    type = sessionCookie['type']
  }

  console.log("Printing session cookie")
  console.log(sessionCookie)
  admin
    .auth()
    .verifySessionCookie(idToken, true /** checkRevoked */)
    .then((decodedClaims) => {
      console.log(decodedClaims.user_id)
      deleteReward(decodedClaims.user_id, rewardId)
    })
    .catch((error) => {
      console.log(error)
    });
})

function deleteReward(restaurantId, rewardId) {
  getRestaurant('KOBmyfQEu4urNGgBTuiJ').then(data => {
    console.log(data.rewards)
    db.collection(restaurantCollection).doc('KOBmyfQEu4urNGgBTuiJ').update({
      'rewards': FieldValue.arrayRemove({ item_points: 20, item_id: 1, item_name: 'Free Meal' })
    })
  })
}

A: You can use set a Firestore listener on you client app:
db.collection(restaurantCollection)
    .onSnapshot((snapshot) => {
        snapshot.docChanges().forEach((change) => {
            if (change.type === "modified") {
                console.log("Modified Restaurant: ", change.doc.data());
            }
            if (change.type === "removed") {
                console.log("Removed Restaurant: ", change.doc.data());
            }
        });
    });

This will trigger whenever a document is added/modified/removed. Then you can check change.type and if it's "removed", just delete that restaurant div from the DOM.

The deleteReward is updating the document and not deleting it. So you should check for change.type === "modified" on client.


text:
Q: Populate datalist options by iterating through JSON file I'm trying to create a search box that will essentially autocomplete based on user input from a key-value pair in a json file. It looked like using datalist might be the best option for this, but when I execute the code below, no option tags appear in the html.
I am still pretty new to jquery and json, so I'm WAY open to suggestions.
Here's the json. The list contains 1450 items if that's relevant:
{ "osCars": [
{   "id": 1,
    "name": "Cadillac",
    "type": "Sedan",
    "desc": "A fine American automobile"
},
{   "id": 2,
    "name": "BWM",
    "type": "Sedan",
    "desc": "A fine German automobile"
},
{   "id": 3,
    "name": "Lexus",
    "type": "Sedan",
    "desc": "A fine Japanese automobile"
}
]}

Here's the html:
<input type="text" maxlength="30" list="carList" id="carSearchBox" name="carSearchBox" pattern="[A-Za-z '-]*$" placeholder="search cars" autofocus autocomplete="on">
<datalist id="carList"></datalist>
<script src="js/main.js"></script>
<script>window.onload=getCars;</script>

And here's the javascript/jquery:
function getCars() {
    var url, carOption;
    url = 'js/cars.json';

    $.getJSON(url, function(data) {
    //populate the cars datalist
        $(data.osCars).each(function() {
            carsOption = "<option value=\"" + this.id + "\">" + this.name + "</option>";
            $('#carList').append(carsOption);
        });
    });
}

A: It turns out the problem was not with my javascript as I suspected, but rather with my JSON file. I used the URL of a different JSON file I have (that I know is valid) and everything worked fine. The file I'd like to use is too long to validate with jsonLint, and has some lengthy text values. There's probably an errant double-quote mark in there somewhere that I didn't see, and that is throwing it off.

A: I believe the problem is your use of this.id as the value, rather than this.name. It appears that the datalist and autocomplete functionality in HTML5 is not implemented consistently across browsers, just yet. Ex: Chrome seems to have a problem when in a datalist, an option's inner html (display value) differs from the value.
Changing your code to use "this.name" for both id and value works fine (in Chrome at least):
function getCars() {
    $(data.osCars).each(function (idx, o) {
        carsOption = "<option value='" + this.name + "'>" + this.name + "</option>";
        $('#carList').append(carsOption);
    });
}

See this fiddler example:
http://jsfiddle.net/6HGuU/
And this related question:
HTML5 datalist value vs. inner-text
If you need to retrieve the selected ID and not the name, then you can look this up as a separate step (the related question contains an answer with a proposed approach for doing exactly this).


text:
Q: Date lookup issue: Unable to get VLookup property of WorksheetFunction class I've tried almost everything in most of the other similar type questions but I can't seem to solve the runtime error. Help please!
What I want to achieve:
1) My macro is supposed to get date from report summary files that are created every day hence, it requires the user to input which date of report he wants the data from
2) I use the vlookup method to get the data from the relevant row and input it into the central workbook with the macro
3) Every part of the code works except using the date to Vlookup and it will give me this error message
4) I have tested the code using other text based lookup values and the whole macro works (i.e. i looked up the row which has the "Total" value so it looks up "Total" but i require the macro to look up the rows with the date as the look up value)
Addtional Info:
1) In the lookup file, the dates are in the format of "m/d/yyyy" but presented in the format of "dd-mmm-yy" (but i've tried both and they dont work)
Sub GetData()

Dim strDate As Date
  strDate = InputBox("Input date of report to retrieve        (Format: DD-MM-YYYY)", "Input Date", Format(Now(), "DD-MM-YYYY"))
  If IsDate(strDate) Then

'there is some code here not relevant but basically i need to keep manipulating the date throughout the code

With ActiveSheet
    Dim XstrDate
    Dim Xfile As String

    XstrDate = Format(strDate, "mmm DD, YYYY")
    Xfile = "C:\...\...\...\Report " & XstrDate & ".xls"

Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim returnValue as Variant

Set wb = Application.Workbooks.Open(Xfile)
Set ws = wb.Worksheets("Summary")
Set rng = ws.Range("A:K")

Dim Xdate As String
    Xdate = Format(XstrDate, "m/d/yyyy")

returnValue = Application.WorksheetFunction.VLookup(Xdate, rng, 2, 0)

'... more code

remember, i've tried looking up using the text in the same column and it returned me a value. So i suspect the problem lies with the date format or something
Any smart and kind soul want to offer some suggestions here:)

A: Excel internally stores dates as a Serial Number (e.g. 1/1/2014 = 41640), which you can observe yourself if you enter a date into a cell and then change the format to Number.
With this in mind it's unlikely that a VBA date and an Excel date can be matched using the VLookup function so in my experience the best solution is to convert your date into its serial number and then perform the VLookup on that value instead.
Dim Ndate As Long
Dim returnValue As Date

Ndate = DateSerial(<Year>, <Month>, <Day>)
returnValue = Application.WorksheetFunction.VLookup(Ndate, <rng>, <col>, False)

If you need to construct your DateSerial(...) function from a Date variable in VBA you can use the Year(<date>), Month(<date>), and Day(<date>) functions to break it down into the required components.
Note: I've tried this example in the format .VLookup(DateSerial(2014,1,1),...) and it still causes the same error, hence storing the return value of DateSerial in a numeric variable first.
Happy Coding!

A: I've taken a different approach and found another solution to this problem.
Rather than use Vlookup, this is the other method that bypass the problem of VLookup date format problem, (having defined vdate in previous statements)
Dim rnge As Range, i As Long
Sheets("Summary").Select
Columns("A:A").Select
Set rnge = Intersect(Selection, ActiveSheet.UsedRange)
If rnge Is Nothing Then
     MsgBox "Date Not Found"
     GoTo done
End If

For i = rnge.Count To 1 Step -1
If rnge.Cells(i).Value = vdate Then rnge.Cells(i).EntireRow.Copy _
Destination:=ThisWorkbook.Sheets("AnotherSheet").Range("A1")
Next

done:
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True


text:
Q: Is this weird that : using testng to test in struts2, the request field doesn't exist? I am a newer to struts2.
I am doing testing in struts2 using struts2-testng-plugin, and I am following the struts documentation, it says request of MockHttpServletRequest will be available by extending StrutsTestCase. Well, I do it, let my test class extends the StrutsTestCase. What a surprise I can not get the request field. Then I look at the StrutsTestCase in the struts2-testng-plugin-2.3.15.1.jar, again let me surprise, there aren't any field like request, response.So, I just want check are there something like request and response field in struts2-junit-plugin-2.3.15.1.jar.Actually it has all of them.
So, could you tell how can I test the struts using testng-plugin?


text:
Q: Prove that $p$ is a limit point of A. Let $p$ be a limit point of $\bar{A}$ where $\bar{A}$ is the set of all limit points of $A$. Show that $p$ is also a limit point of $A$.
According to the definition of a limit point I know that I have to show that $B(p; \delta ) \cap A \neq \emptyset$ for all $\delta > 0$.
I know that $B(p; \delta ) \cap \bar{A} \neq \emptyset$. Because this set is not empty, I know I can find a point $q$ for every $\delta$ in this set, so also for $\frac{\delta}{2}$. I know I have to look at the set
$B(q; \frac{\delta}{2}) \cap A$, but I am not sure how I can use this to prove that $p$ is a limit point of $A$.

A: Let $\varepsilon>0$; you want to prove that there is a $a\in A\setminus\{p\}$ such that $d(a,p)<\varepsilon$. Since $p\in\overline A$, there is a $a'\in\overline A\setminus\{p\}$ such that $d(a',p)<\frac\varepsilon2$. And, since $a'\in\overline A$, there is a $a\in A$ such that $d(a',a)<\frac\varepsilon2$. Clearly, you can take $a\neq p$. But then$$d(a,p)\leqslant d(a,a')+d(a',p)<\frac\varepsilon2+\frac\varepsilon2=\varepsilon.$$

A: Let $x\in B(p,\delta)\cap\bar A$, write $r=d(x,p)$there exists $y\in B(x,{{\delta-r}\over 2})\cap A$, we have $d(p,y)\leq d(p,x)+d(x,y)\leq r+{{\delta-r}\over 2}$
$\delta-(r+{{\delta -r}\over 2})={{\delta-r}\over 2}$, implies that $y\in B(p,\delta)$.


text:
Q: Datetime filter for AG-Grid - Clear input text on button click Based on this proposed solution in the AG-Grid Github issues, I am trying to implement a jQuery DateTime Picker as a filter in my React/AG_Grid project.
I currently have my table set up so that I can clear the filters that have been applied to my table with a button click. The desired behavior is that once the Reset Filters button is clicked, the filters AND the text inside of the filter input should be cleared. As it is set up now, the filters are being cleared from the table as desired but when I reopen the filter input, the text from the previous filter is still there.

I have a Code Sandbox set up here with a simplified version of my current setup.
Steps to recreate:

*

*Open filter for Event Timestamp column

*Apply filter to Event Timestamp column (2020/01/31 00:00 - 2020/06/31 00:00)

*Click 'Reset Filters' at the top of the table

*Open filter for Event Timestamp column

*Notice that text from the previous filter still populates the input

const App = () => {
  const [gridApi, setGridApi] = useState([]);
  const [gridColumnApi, setGridColumnApi] = useState([]);
  const [rowData, setRowData] = useState([]);

  useEffect(() => {
    const formattedDates = dataSet.map((data) => {
      return {
        id: data.id,
        eventTimestamp: new Date(data.eventTimestamp)
      };
    });
    setRowData(formattedDates);
  }, []);

  // ***************************************************
  // The Handle Click logic for the reset filters button:
  // ***************************************************
  const resetAppliedFilters = () => {
    gridApi.setFilterModel(null);
    CustomDateComponent.prototype.setDate(null);
  };

  const cols = [
    {
      field: "id",
      headerName: "ID",
      minWidth: 100,
      maxWidth: 150
    },
    {
      field: "eventTimestamp",
      headerName: "Event Timestamp",
      minWidth: 225,
      filter: "agDateColumnFilter",
      filterParams: {
        defaultOption: "inRange",
        // ***************************************************
        // Comparator function for datetime picker:
        // ***************************************************
        comparator: function (filterLocalDate, cellValue) {
          filterLocalDate.setMilliseconds(0);
          cellValue.setMilliseconds(0);
          let filterBy = filterLocalDate.getTime();
          let filterMe = cellValue.getTime();
          if (filterBy === filterMe) {
            return 0;
          }

          if (filterMe < filterBy) {
            return -1;
          }

          if (filterMe > filterBy) {
            return 1;
          }
        }
      }
    }
  ];

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
    // ***************************************************
    // Table event listener:
    // ***************************************************
    params.api.addGlobalListener((type, event) => {
      switch (type) {
        case "filterChanged":
          console.log(event);
          return;
        default:
          return null;
      }
    });
  };

  return (

      <Button onClick={resetAppliedFilters} variant="outlined">
        Reset Filters
      </Button>

        <AgGridReact
          onGridReady={onGridReady}
          rowData={rowData}
          rowSelection="multiple"
          defaultColDef={{
            flex: 1,
            minWidth: 100,
            resizable: true,
            sortable: true,
            filter: true
          }}
          pagination
          columnDefs={cols}
          components={{
            agDateInput: CustomDateComponent
          }}
        />

  );
};

// ***************************************************
// Custom datetime picker component:
// ***************************************************
function CustomDateComponent() {}

CustomDateComponent.prototype.init = function (params) {
  this.params = params;
  this.eGui = document.createElement("div");
  this.eInput = document.createElement("input");
  this.eGui.appendChild(this.eInput);
  jQuery(this.eInput).datetimepicker({
    mask: true, // '9999/19/39 29:59' - digit is the maximum possible for a cell
    onChangeDateTime: this.onDateChanged.bind(this)
  });
};

CustomDateComponent.prototype.onDateChanged = function (currentDateTime) {
  this.date = currentDateTime;
  this.params.onDateChanged();
};

CustomDateComponent.prototype.getGui = function () {
  return this.eGui;
};

CustomDateComponent.prototype.getDate = function () {
  return this.date;
};

CustomDateComponent.prototype.setDate = function (date) {
  this.date = date;
};

CustomDateComponent.prototype.destroy = function () {
  jQuery(this.eInput).datetimepicker("destroy");
};

export default App;

If anyone can help out or point me in the right direction, it would be greatly appreciated. TIA!

A: While I was trying to figure this out on my own, I came across this Stack Overflow article that explains why you should NOT use React and jQuery together. This is great advice since you can see in the above example, the state wasn't being managed properly among other issues.
After further reading of the AG-Grid docs' custom date component section and this post on AG-Grid's blog, I was able to implement a solution that uses react-datetime-picker as the custom filter component. You then have to pass it to the table's frameworkComponents prop.
LIVE DEMO ON STACK BLITZ
DTPicker.jsx
import DateTimePicker from "react-datetime-picker";

export default forwardRef((props, ref) => {
  const [selectedDate, setSelectedDate] = useState(null);

  function handleDateChange(d) {
    if (d) {
      d = new Date(d);
      setSelectedDate(d);
    } else {
      setSelectedDate(null);
    }
  }

  // props.onDateChanged must be called after updating our component's internal state:
  useEffect(props.onDateChanged, [selectedDate]);

  // getDate and setDate are required by AG-Grid to sync ag-Grid's date
  // filter value with that of our components:
  useImperativeHandle(ref, () => {
    return {
      getDate: () => {
        return selectedDate;
      },
      setDate: d => {
        handleDateChange(d);
      }
    };
  });

  return (
    <>
      <DateTimePicker
        onChange={handleDateChange}
        value={selectedDate}
        maxDetail="second"
        disableCalendar={true}
        disableClock={true}
      />
    </>
  );
});

App.jsx
import DTPicker from './DTPicker'

// Add your custom filter logic in your column:
const cols = [
    ...,
    {
      field: "eventTimestamp",
      headerName: "Event Timestamp",
      filter: "agDateColumnFilter",
      filterParams: {
        defaultOption: "inRange",
        comparator: function(filterLocalDate, cellValue) {
          let filterBy = filterLocalDate.getTime();
          let filterMe = cellValue.getTime();
          if (filterBy === filterMe) {
            return 0;
          }

          if (filterMe < filterBy) {
            return -1;
          }

          if (filterMe > filterBy) {
            return 1;
          }
        }
      }
    },
    ...
  ];

<AgGridReact
    ...
    frameworkComponents={{
        agDateInput: DTPicker
    }}
    ...
/>


text:
Q: does there exist a function $f\in C_0^P(\mathbb{R})$ such that $\text{supp}(f) \subseteq I, f(x_0)=1$ and $\sup_{x\in\mathbb{R}}|f(x)|\leq 1?$ Fix a natural number $p\geq 1.$
Let $C_0^p(\mathbb{R})$ be a collection of all continous functions $f:\mathbb{R}\to\mathbb{R}$ such that its $i$th derivatives are continuous for all $0\leq i \leq p$ and $f$ vanishes at infinity, that is, for every $\varepsilon>0,$ the set $\{ x\in\mathbb{R}: |f(x)| \geq \varepsilon \}$ is compact.
Let $\text{supp}(f) = \overline{\{x\in\mathbb{R}: f(x)\neq 0 \}}.$

Question: Given any $x_0\in \mathbb{R}$ and any open set $I$ containing $x_0,$ does there exist a function $f\in C_0^P(\mathbb{R})$ such that $\text{supp}(f) \subseteq I, f(x_0)=1$ and $\sup_{x\in\mathbb{R}}|f(x)|\leq 1?$

My attempt:
By applying Urysohn's lemma on complement of $I$ and an open neighbourhood $U \subseteq I$ of $x,$ there exists a continous function $f:\mathbb{R}\to [0,1]$ such that $f$ is $0$ outside of $I$ and $1$ on $U.$
It remains to check whether $f$ has continuous $i$th derivatives for all $0\leq i \leq p.$
I think that $f$ may not be an element of $C_0^p(\mathbb{R}).$
I believe that something need to be done on $f$ but I do not know what should be done.
Any hint would be appreciated.

A: Summarizing the problem: make a bump function that is sufficiently smooth.  By "bump function", we mean a function that is zero off of $I$, increases up to $1$ and then back down to $0$ on the two connected components of $I \smallsetminus U,$ and is $1$ on $U$.
How can I turn a $C_0^k$ function into a $C_0^{k+1}$ function?

  Integrate it.

But if I integrate a "bump", I get a "step", so we don't get back down to $0$ as we leave $I$.  How does this give me a smoother bump?

 Make two steps -- one going up, one going down -- and multiply them (since products are at least as continuous as the multiplicands).  Suppose $f$ is a "bump" that is $0$ outside $I$.  We find $u(x) = \int_{-\infty}^x f(t) \,\mathrm{d}t$ is a step up and $d(x) = \int_{x}^\infty f(t) \,\mathrm{d}t$ is a step down.  Then $u(x) d(x)$ is a bump and is at least as continuous as $d$ and $u$.  It's also zero where either $u$ or $d$ is, so we haven't increased the support when we made this new bump.

 If you scale $u$ or $d$ so that the product is $1$ at $x_0$, you get your supremum condition.

So the strategy is ...?

 Start with the result from Urysohn's lemma, a $C_0^0(\mathbb{R})$ bump function.  For each $n \in [1,p] \subset \mathbb{Z}$, construct the $C_0^n(\mathbb{R})$ bump function via the two steps described above coming from the $C^0_0$ bump.  This gives family of bumps of increasing smoothness.  Each has support in $I$.  At each step, verify that the bump comes up to $1$.

A: Construct a function $f_0 \in C^p$ with support on $[-1,1]$ such that $0 \le f_0(x) \le 1 = f_0(0)$ for all $x$. For example, if $X_1, X_2, \dots, X_n$ are independent uniformly distributed random variables on $[-\frac{1}{n},\frac{1}{n}]$ and $n > p$, then the density function of $X_1 + X_2 + \dots + X_n$ will work. Then set $f(x) = f_0((x-x_0)/\delta)$ where $\delta$ is sufficiently small.


text:
Q: How to pass a variable to pyswarm's functions in Python I wonder how can I pass a specific variable to a function using Pyswarm in Python.
Check the example bellow
from pyswarm import pso

def model_obj(x):
    return x[0]

def cons(x):
    return x[0] - MY_VAR

lb = [0]
ub = [100]
x0 = [0]
MY_VAR = 10

xopt, fopt = pso(model_obj,lb,ub,x0,f_ieqcons=cons)

My question is how do I pass MY_VAR to the function cons.
Thank you!

A: I found the solution using *args
https://pythonhosted.org/pyswarm/


text:
Q: How to detect that Android Camera Geo tagging setting is on/off (GPS Info in the EXIF data) I'm trying to find out if there's a way to detect the "geotag" or "store-location" setting of the camera on an Android device. I don't mean the general location access setting which I'm very familiar with, but the more "hidden" setting when you use the camera.
Most users are not even aware it exists, and it's turned off by default, I would like to be able to tell the users that this setting is off so that they can turn it on if they want to, this way pictures will have all the EXIF data concerning their location.
I hope this has not been answered before on so, if its the case, I'm sorry about it and would you please link me to the right thread.

A: Each Android device usually ships with its own custom camera app, made by the manufacturer of that device. Each has their own UI and probably own way/place to store this setting, if it even exists for that device. So any answer to this question would be heavily device-dependent.
But even if you just restrict yourself to the AOSP camera app, which is the app used on the Nexus devices, there's no API for this. The app asks if you want to enable GPS tagging the first time the app is run, and after that the option to enable/disable geotagging can be found in the settings.
There's no way to confirm if that setting is on, since it's not part of any public or standard Android API. You might be able to do something with the accessibility API to read these settings, but it requires substantial permissions to do so (Accessibility service documentation here).

A: To extract the EXIF information from the files, you could consider an example similar to the updateExif example shown in this code snippet. This would enable you to get all the information including make, flash, focal length etc which is stored in the EXIF file.

A: Speaking to the Android 4.3 camera app that comes with Nexus devices, you can view and change the setting like this:

*

*Open the camera app.

*The white circle (rightmost of three icons at bottom of app screen) is used to bring up the main menu. If "store location" is turned off, that circular icon will be displayed with a small location icon with a line through it. If "store location" is turned on, there is no positive indication thereof. Tap it to continue if you want to change the setting.

*Tap the settings icon (middle icon of five) to bring up "More Options" menu.

*The "store location" icon is the leftmost of five. Tapping that icon toggles the setting (and dismisses the menu). If "store location" is off, that icon is displayed with a line through it, else without.


text:
Q: highchart drilldown dynamic point name  events: {
    drilldown: function (e) {
     if (!e.seriesOptions) {
   var Fruitsname= e.point.name;
  //var Fruitsname='Fruits';
   drilldowns = {
 Fruitname:{
      //  'Fruits': {
          name: 'Fruits',
          data: [
          ['Apples', 5],
          ['Oranges', 7],
          ['Bananas', 2]
            ]
          },
       }
    }
  }

}
I got click event on drill down using e.point.name, but string name under drill down is taking as in double quotation but it required string in single quote .
I tried using alert and console.log but it is showing without quotes,In breakpoints it showing in double quotes.I have commented line 'Fruits' it works as static value.
can any one knows how to bind point name to drill down.
Any suggestion or help will be appreciated
thanks in advance..

A: Try this way:
drilldowns = {};
drilldowns[Fruitname] = {
      name: 'Fruits',
      data: [
      ['Apples', 5],
      ['Oranges', 7],
      ['Bananas', 2]
        ]
 }


text:
Q: Interrupt vector table: why do some architectures employ a "jump table" VS an "array of pointers"? On some architectures (e.g. x86) the Interrupt Vector Table (IVT) is indeed what it says on the tin: a table of vectors, aka pointers. Each vector holds the address of an Interrupt Service Routine (ISR). When an Interrupt Request (IRQ) occurs, the CPU saves some context and loads the vector into the PC register, thus jumping to the ISR. so far so good.
But on some other architectures (e.g. ARM) the IVT contains executable code, not pointers. When an IRQ occurs, the CPU saves some context and executes the vector. But there is no space in between these "vectors", so there is no room for storing the ISR there. Thus each "vector instruction" typically just jumps to the proper ISR somewhere else in memory.
My question is: what are the advantages of the latter approach ?
I would kinda understand if the ISRs themselves had fixed well-known addresses, and were spaced out so that reasonnable IRSs would fit in-place. Then we would save one indirection level, though at the expense of some fragmentation. But this "compact jump table" approach seems to have no advantage at all. What did I miss ?

A: Some of the reasons, but probably not all of them (I'm pretty much self educated in these matters):

*

*You can have fall through (one exception does nothing, and just goes to the next in the table)

*The FIQ interrupt (Fast Interrupt Requests) is the last in the table, and as the name suggest, it's used for devices that need immediate and low latency processing.
It means you can just put that ISR in there (no jumping), and process it as fast as possible. Also, the way FIQ was thought with it's dedicated registers, it allows for optimal implementation of FIQ handlers. See https://en.wikipedia.org/wiki/Fast_interrupt_request

A: I think it has do with simplifying the processor's hardware.
If you have machine instructions (jump instructions) in the vector interrupt table, the only extra thing the processor has to do when it has to jump to an interrupt handler is to load the address of the corresponding interrupt vector in the PC.
Whereas, if you have addresses in the interrupt vector table, the processor must be able to read the interruption handler start address from memory, and then jump to it.
The extra hardware required to read from memory and writing to a register is more complex than the required to just writing to a register.


text:
Q: Update xml node value from secondary table using join based current node value Table dbo.table_a contains a XML column foo. Every row has a XML-tree in the a XML-column.
Secondary table dbo.table_b contains old value old_val and new value new_val
The XML-tree looks like this
<root>
  <Customer>
    <Name>ACME</Name>
  </Customer>
  <Def>
    <Enabled>true</Enabled>
    <CIds>
      <Id>ABC</Id>
      <Id>DEF</Id>
    </CIds>
  </Def>
</root>

Please Note that /root/Def/CIds can contain zero or several child nodes called Id.
dbo.table_b looks like this
+---------+---------+
| old_val | new_val |
+---------+---------+
| ABC     |     123 |
| DEF     |     456 |
+---------+---------+

I need to replace the value for every Id by joining the current xml node value with dbo.table_b on old_val and replacing the xml node value with new_val.
ABC should be replace with 123 and DEF with 456

A: There is no easy way to achieve this, due to the fact that even now, in 2018, the replace value of XML method still does not support modification of multiple nodes.
The simplest approach is the insert+delete tactic, as in the following example:
declare @TableA table (
    Id int identity(1,1) primary key,
    XData xml not null
);

declare @TableB table (
    OldValue varchar(50),
    NewValue int
);

insert into @TableA (XData)
select N'<root>
  <Customer>
    <Name>ACME</Name>
  </Customer>
  <Def>
    <Enabled>true</Enabled>
    <CIds>
      <Id>ABC</Id>
      <Id>DEF</Id>
    </CIds>
  </Def>
</root>';

insert into @TableB (OldValue, NewValue)
values
    ('ABC', 123),
    ('DEF', 456);

-- Before
select * from @TableA;

update a set XData.modify('insert sql:column("sq.NewData") after /root[1]/Def[1]/CIds[1]')
from @TableA a
    cross apply (
        select b.NewValue as [Id]
        from @TableB b
        where a.XData.exist('/root/Def/CIds/Id[text() = sql:column("b.OldValue")]') = 1
        for xml path(''), type, root('CIds')
    ) sq(NewData);

update a set XData.modify('delete /root[1]/Def[1]/CIds[1]')
from @TableA a;

-- After
select * from @TableA;

Its weakness is that it reconstructs the entire /CIds node, so if you have any additional data in it, like attributes, it might be too cumbersome to recreate. In this case you might have better success with a FLWOR update, but they tend to be quite slow, compared to other options.
Alternatively, you might run a series of atomic updates in a loop. As unpleasant as it may sound, it will actually work, especially if your actual XML is much more complex than the provided example.

A: I ended up with looping and updating. Although @Roger Wolf's code snippet worked I couldn't make it work in my environment.
declare @I int
declare @old varchar(50)
declare @new varchar(50)

select @I = max([foo].value('count(/root/Def/CustomerIds/CIds)', 'int'))
FROM dbo.table_a where [foo].exist('(count(/root/Def/CustomerIds/CIds/Id)') = 1

while @I > 0
begin

select @old = [foo].value('(/count(/root/Def/CustomerIds/CIds/Id)[sql:variable("@I")][1]', 'varchar(50)')
from dbo.table_a
where [foo].exist('(/count(/root/Def/CustomerIds/CIds/Id)[sql:variable("@I")]') = 1

set @new = dbo.ConvertOldNew(@old)

  update dbo.table_a
  set [foo].modify
    ('replace value of ((/count(/root/Def/CustomerIds/CIds/Id)[sql:variable("@I")]/text())[1]
      with (sql:variable("@new"))')
  where [foo].exist('(/count(/root/Def/CustomerIds/CIds/Id)[sql:variable("@I")]') = 1
  set @I = @I - 1
end

Please note that dbo.ConvertOldNew is a function returning the new value based on the old value.


text:
Q: How to run Apache Solr service from within Python I have successfully ran the example here: https://github.com/toastdriven/pysolr/ This requires that Solr is running locally by typing the following command into terminal (java -jar start.jar). My question is, can I start the service without using the terminal at all?

A: Solr works using http. You would need a container that acts a web server. Solr comes with Jetty by default, so when you do a java -jar start.jar, Jetty kicks in internally.
The only way of embedding solr, AFAIK, is to use EmbeddedSolrServer as mentioned here. This works with Solrj, which is a Solr client for Java. I'm afraid there isn't anything similar for PySolr, to my knowledge.


text:
Q: Checking dictionary value list for matches Hello new to programming and python here. I'm trying to make a program that will take a list of keys and values; then add those items to a dictionary. The program should check each value against current values in a dictionary before appending it to the key. Here is my code so far.
finalList= {'turtle':['turtle10']}

keyList = ['turtle','cat','mouse','dog']
valueList =['turtle1','turtle2','turtle1','cat1','cat2','dog','dog1']
for i in keyList:
    finalList[i]= []

 for items in finalList.keys():
    #print('***Keys***'+items)
     for elements in valueList:
         #print('***Values***'+elements)
         res = not any(finalList.values())
         if items in elements:

             if elements not in finalList.values():
                finalList[items].append(elements)

print(finalList)

Output = {'turtle': ['turtle1', 'turtle2', 'turtle1'], 'cat': ['cat1', 'cat2'], 'mouse': [], 'dog': ['dog', 'dog1']}

Why did my final if statement not check the values already in the dictionary? And if there is a better way to do them please let me know. I know this community is filled will seasoned developers; but I am clearly not, so please take it easy on me. THANK YOU!

A: In your last if there should be:
if elements not in finalList[items]: rather than
if elements not in finalList.values():

A: You can make this more concise with dictionary and set comprehension:
finalList = {i : list({j for j in valueList if i in j}) for i in keyList} #Actually a dictionary but whatever

Output:
{'turtle': ['turtle1', 'turtle2'],
 'cat': ['cat2', 'cat1'],
 'mouse': [],
 'dog': ['dog', 'dog1']}


text:
Q: Is it mandatory to import a bean to JasperSoftStudio's classpath if I want to access its attributes? I have a bean like this:
class PersonBean {
    String name;
    String lastName;
}

I want to pass it to jasper as a parameter, and access the properties name and lastName. Is it mandatory to import PersonBean to jasper's classpath to achieve it?
This is how I intend access the properties: $P{P_PERSON}.getName().
I've tried to use java.lang.Object as the parameter type, but then jasper tries to cast it, that causes an exception.

A: Try putting the attributes( name and lastName) of PersonBean class in a map of String as a key and Object as value. Pass this map to the jasper report.
Like :
Map<String, Object> map = new HashMap<>();
PersonBean person = new PersonBean();
map.put("NAME", person.getName());
map.put("LASTNAME", person.getLastName());

Pass this map to your jasper report at the time of compiling it.
Also create the parameters as NAME and LASTNAME in the jasper report. You can set the parameter type as String

A: My question was missing an important part, I corrected it and here is the answer:
Depends!
If you compile the report inside JasperSoftStudio, yes, you'll need to import the bean.
If not, then it's not necessary, and that is my case, I compile the reports at runtime.
In short: You will need the class in the classpath for compiling and running (obviously), in my case, since I just design the reports in JasperSoftStudio, it's not necessary.


text:
Q: laravel 8 (errno: 150 "Foreign key constraint is incorrectly formed") i try to create forum in last php and laravel 8. I have buy course in udemy in laravel 8 i follow video from him but in my computer have error and in video doesn't have
2021_11_13_000535_create_posts_table

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->integer('is_deleted');
            $table->integer('is_approved');
            $table->string('image');
            $table->unsignedBigInteger('discussion_id');
            $table->foreign('discussion_id')->references('id')->on('discussions')->onDelete('cascade');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

2021_11_19_165302_create_discussions_table
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDiscussionsTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::create('discussions', function (Blueprint $table) {
           $table->id();
           $table->string('title');
           $table->string('desc');
           $table->unsignedBigInteger('forum_id');
           $table->foreign('forum_id')->references('id')->on('forums')->onDelete('cascade');
           $table->integer('is_deleted')->default(0);
           $table->string('image')->nullable();
           $table->integer('notify')->default(0);
           $table->unsignedBigInteger('user_id');
           $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

           $table->timestamps();
       });
   }

   /**
    * Reverse the migrations.
    *
    * @return void
    */
   public function down()
   {
       Schema::dropIfExists('discussions');
   }
}

when i try to do migrate table i have this error :
Migrated:  2014_10_12_000000_create_users_table (1,399.45ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (2,117.91ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (1,592.76ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated:  2019_12_14_000001_create_personal_access_tokens_table (2,125.96ms)
Migrating: 2021_11_12_234608_create_categories_table
Migrated:  2021_11_12_234608_create_categories_table (2,452.77ms)
Migrating: 2021_11_12_235039_create_forums_table
Migrated:  2021_11_12_235039_create_forums_table (2,849.71ms)
Migrating: 2021_11_13_000340_create_tags_table
Migrated:  2021_11_13_000340_create_tags_table (526.62ms)
Migrating: 2021_11_13_000535_create_posts_table

   Illuminate\Database\QueryException

  SQLSTATE[HY000]: General error: 1005 Can't create table `stsdb`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_discussion_id_foreign` foreign key (`discussion_id`) references `discussions` (`id`) on delete cascade)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:703
    699▕         // If an exception occurs when attempting to run a query, we'll format the error
    700▕         // message to include the bindings with SQL, which will make this exception a
    701▕         // lot more helpful to the developer instead of just the database's errors.
    702▕         catch (Exception $e) {
  ➜ 703▕             throw new QueryException(
    704▕                 $query, $this->prepareBindings($bindings), $e
    705▕             );
    706▕         }
    707▕     }

      +9 vendor frames
  10  database/migrations/2021_11_13_000535_create_posts_table.php:28
      Illuminate\Support\Facades\Facade::__callStatic()

      +21 vendor frames
  32  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

someone can explain why have this error and how resolve this? because i dont understand i follow like in video in my pc have error and in video doesn't have. Someone can help resolve this? I have checked in google but i have dont find how resolve this, i follow tuts build forum laravel 8 with telegram notification

A: The problem is that your migration for the posts table is run prior to your discussions migration.
This happens because Laravel runs the migrations ordered by the timestamp in the migrations file name:
2021_11_13_000535_create_posts_table -> 13. November
2021_11_19_165302_create_discussions_table -> 19. November

Therefore the dicsussions table is not created yet as my comment suggested!
The solution is easy, change the file name to:
2021_11_20_000535_create_posts_table -> 20. November
Next time please take a look into your DB as I suggested earlier.
From their documentation:

Generating Migrations
You may use the make:migration Artisan command to generate a database
migration. The new migration will be placed in your
database/migrations directory. Each migration filename contains a
timestamp that allows Laravel to determine the order of the
migrations:

https://laravel.com/docs/8.x/migrations#generating-migrations


text:
Q: multiple wait_for_messages wanted discord.py Basically I am making a quiz and I want to be able to search through the answers and determine which message only has the artist in, which message only has the song name in, and which message says them both. I've made 3 check functions to show this however I want all 3 wait_for_message statements to run side by side. Any ideas on how this could be remedied?
await client.say("What is the song name and artist?")
def check1(msg):
    return name in msg.content.upper() and artist not in msg.content.upper()
def check2(msg):
    return artist in msg.content.upper() and name not in msg.content.upper()
def check3(msg):
    return name in msg.content.upper() and artist in msg.content.upper()
msg1 = await client.wait_for_message(timeout=10, check=check1)
msg2 = await client.wait_for_message(timeout=10, check=check2)
msg3 = await client.wait_for_message(timeout=20, check=check3)
if msg3 is not None:
   await client.say("@{} got both of them right! It was indeed {} by {}".format(msg3.author, toString(name),
                                                                                toString(artist)))
elif msg1 is not None and msg2 is not None:
        await client.say("@{} got the song name and @{} got the artist name! It was indeed {} by {}".format(msg1.author,
                                                                           msg2.author, toString(name), toString(artist)))
elif msg1 is not None and msg2 is None:
        await client.say("@{} got the song name but no one got the artist! It was {} by {}".format(msg1.author,
                                                                                toString(name), toString(artist)))
elif msg1 is None and msg2 is not None:
        await client.say("@{} got the artist name but no one got the song name! It was {} by {}".format(msg2.author,
                                                                                toString(name), toString(artist)))
elif msg1 is None and msg2 is None and msg3 is None:
        await client.say("No one got it! It was {} by {}! Better luck next time".format(toString(name), toString(artist)))

A: The code you are looking for is asyncio.gather. This lets you run multiple coroutines at the same time and wait until all methods are returned.
The return list from gather is in the order of the inputs, not in the order of task completion.
ret = await asyncio.gather(
    client.wait_for_message(timeout=10, check=check1),
    client.wait_for_message(timeout=10, check=check2),
    client.wait_for_message(timeout=10, check=check3)
)

msg1, msg2, msg3 = *ret
# msg1 has the name
# msg2 has the artist
# msg3 has both

Since the rewrite version of discord.py has client.wait_for throw an error instead of returning None, you can instead do this.
ret = await asyncio.gather(
    client.wait_for("message", timeout=10, check=check1),
    client.wait_for("message", timeout=10, check=check2),
    client.wait_for("message", timeout=10, check=check3),
    return_exceptions = True
)

# Test for errors
ret = [r if not isinstance(r, Exception) else None for r in ret]
msg1, msg2, msg3 = *ret


text:
Q: gcc error: Can't create precompiled header I have some useful typedefs on a header file called utypes.h. I have decided to use make and haven't found a way to compile it since then.
When I execute gcc -Wall -c utypes.h to generate the .o object of utypes I get the following error:
"utypes.h:1 fatal error: can't create precomiled header types.h.gch: Permission Denied (EACESS)
Compilation terminated.

What am I doing wrong here? Thanks.

A: You don't have write access to the directory where you are trying to put types.h.gch, or you have a pre-existing read-only copy. On Linux you can use strace to get the details.

A: just compile your stdc++.h in cmd with administrator rights. Run CMD as Administrator and then go to path of stdc++.h and then compile