text:
Q: How to build a loop to import many dataframes and modify them in the same way? I have one dataframe of news for each month from january 1996 to december 2018, which means 264 dataframes. They all have the same structure and I need to modify them in the same way. For example, my code for one dataframe is more or less the following:
#import data (only one column $V1)
News.9601 <- read.delim("D:/Reuters/1996/News.RTRS.199601.0210.txt.gz", header=FALSE,quote = "")

#split the first columns in more variables
News.9601 = News.9601 %>%
  mutate(v2=lapply(strsplit(as.character(V1), "\"mimeType\""), "[", 2))

#select only those news that include "R:"
news.9601=news.9601[grepl('R:',news.9601$v2),]

#select only those news that include certain "tags" in $v2

for(i in 1:30){
  tags_split1=paste(tags_split[[i]],collapse = "|")
  tags_split1=gsub("[[:space:]]", "", tags_split1)
  nam=paste("A", i, sep = "")

  assign(nam,news.9601[grepl(tags_split1,news.9601$v2,perl = T),]
         )
}
news.9601=rbind(A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15,A16,A17,
                 A18,A19,A20,A21,A22,A23,A24,A25,A26,A27,A28,A29,A30)

news.9601=news.9601[!duplicated(news.9601),]

#Some text analysis, rx.app is a matching rule
news.9601 = news.9601 %>%
  mutate(approach <- regmatches(title_body, gregexpr(rx.app, v2, perl=TRUE)),
         approach=lengths(approach))

write.csv(news.9601, file = "news.9601.csv")
rm(news.9601)

This is what I have to do for every month-data, except for the dataframe name "D:/Reuters/1996/News.RTRS.199601.0210.txt.gz" in which both the year "/1996/" and the file name change according to the month and year.
Is there some way to import and run the code above for all my months-data in a loop, rather than re-writing the same code for 264 times?
Thanks a lot!

A: something like this should work
files <- list.files(path="folderpath/", full.names=TRUE, recursive=FALSE)

files store all the file names in that folder, than loop that files one by one
for (file in files){

 }

A: Here the code you may use, using a liste of file.
Format_Funtion <- function(mypath, mylist) {
    mydata <- read.delim(paste0(mypath, mylist),header=FALSE,quote = "")

    #split the first columns in more variables
    mydata <- mydata %>%
        mutate(v2=lapply(strsplit(as.character(V1), "\"mimeType\""), "[", 2))

    #select only those news that include "R:"
    mydata=mydata[grepl('R:',mydata$v2),]

    #select only those news that include certain "tags" in $v2
    for(i in 1:30){
        tags_split1=paste(tags_split[[i]],collapse = "|")
        tags_split1=gsub("[[:space:]]", "", tags_split1)
        nam=paste("A", i, sep = "")

        assign(nam,mydata[grepl(tags_split1,mydata$v2,perl = T),])
    }

    mydata=rbind(A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15,A16,A17,
             A18,A19,A20,A21,A22,A23,A24,A25,A26,A27,A28,A29,A30)

    mydata=mydata[!duplicated(mydata),]

    #Some text analysis, rx.app is a matching rule
mydata = mydata %>%
        mutate(approach <- regmatches(title_body, gregexpr(rx.app, v2, perl=TRUE)),
           approach=lengths(approach))

    write.csv(mydata, file = paste0(sub(".txt.gz", "", mylist), ".csv"))
}

You can add the path for a output directory in the last line of code if needed.
mypath <- "D:/Reuters/1996/"
mylist <- list.files(path=mypath, pattern="txt.gz$")
lapply(Format_Function, mypath, mylist)


text:
Q: Handling abrupt PayPal payment cancellations I have an ASP.net application.
The User can purchase 1 of my products via PayPal.
When the User is redirected to the PayPal site for confirmation and processing of the payment what happens if the User does not make the payment but also closes the web page rather than the cancel button?
How long should I wait to see if an order has gone though (or not)? Thanks

A: There are two ways that paypal informs you for a payment, or a cancellation, or an issue in general. These are the:

*

*Payment Data Transfer (PDT)

*Instant Payment Notification (IPN)
The PDT is data that paypal send you when the user is return back to your page, and IPN are data that send you dynamically even if user did not return back to you.
The suggestions is to implement both of this on your site. There are sdk and asp.net samples direct from PayPal on how to do it, and all the details about.
On the links above there all you need to know to develop it.
Especial to your question, this IPN page, have examples on how to capture infomations about payments even if the user did not come back.

If a payment is not done with in 30 minutes, the you can consider it canceled, because the session of the payment on paypal side is less than 30 minutes.
More details on session: The paypal session is 15 minutes if user did not do anything. Consider now that if user go for the payment, and fails, eventually will stop interactive with pp after some minutes. So we have 15 minutes paypal session + some minutes for user tries to pay, you have at least 30 minutes that you can wait the user to pay.
If the user, cancel, or close and come back to use, and ask again for to pay, then you - and paypal creates a new order id, and the payment will be be done on the second order id (not on the first)
And here are some samples code : http://paypal.github.io/sdk/sample-apps/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add collision to HTML5 Canvas Hi I have the following HTML5 Canvas app: http://dev.driz.co.uk/app/
When you move the mouse around it will cause the balls to move around, the problem however is that the balls do not react to each other. Instead they just pass over or behind each other.
Looking for some collision detection info for HTML5 Canvas.
Thanks.

A: Hey everyone. Not sure if you have found this already but I am in the process of creating a snooker game in canvas. My collision detection / handling of the balls is as follows. It's using trig at the moment but could be optimised using some vector math instead. Anyway, you can see the progress with it in action -> here
This loop runs in my animate function:
// checks if the any of the balls have collided with each other
for(i=0;i<ballArray.length;i++)
{
    for(j=i;j<ballArray.length;j++)
    {
        if(j != i)
        {

            if( Math.pow((ballArray[j].x - ballArray[i].x),2) + Math.pow((ballArray[j].y - ballArray[i].y),2) <= (ballArray[i].radius + ballArray[j].radius) * (ballArray[i].radius + ballArray[j].radius))
            {
                dx = ballArray[i].x - ballArray[j].x;
                dy = ballArray[i].y - ballArray[j].y;
                // collision angle is often refered to as the greek character 'phi'
                phi = Math.atan2(dy, dx);

                magnitude_1 = Math.sqrt(ballArray[i].vx * ballArray[i].vx + ballArray[i].vy * ballArray[i].vy);
                magnitude_2 = Math.sqrt(ballArray[j].vx * ballArray[j].vx + ballArray[j].vy * ballArray[j].vy);

                direction_1 = Math.atan2(ballArray[i].vy, ballArray[i].vx);
                direction_2 = Math.atan2(ballArray[j].vy, ballArray[j].vx);

                new_xspeed_1 = magnitude_1 * Math.cos(direction_1 - phi);
                new_yspeed_1 = magnitude_1 * Math.sin(direction_1 - phi);

                new_xspeed_2 = magnitude_2 * Math.cos(direction_2 - phi);
                new_yspeed_2 = magnitude_2 * Math.sin(direction_2 - phi);

                final_xspeed_1 = ((ballArray[i].mass - ballArray[j].mass) * new_xspeed_1 + (ballArray[j].mass + ballArray[j].mass) * new_xspeed_2) / (ballArray[i].mass + ballArray[j].mass);
                final_xspeed_2 = ((ballArray[i].mass + ballArray[i].mass) * new_xspeed_1 + (ballArray[j].mass - ballArray[i].mass) * new_xspeed_2) / (ballArray[i].mass + ballArray[j].mass);

                final_yspeed_1 = new_yspeed_1;
                final_yspeed_2 = new_yspeed_2;

                ballArray[i].vx = Math.cos(phi) * final_xspeed_1 + Math.cos(phi + Math.PI / 2) * final_yspeed_1;
                ballArray[i].vy = Math.sin(phi) * final_xspeed_1 + Math.sin(phi + Math.PI / 2) * final_yspeed_1;
                ballArray[j].vx = Math.cos(phi) * final_xspeed_2 + Math.cos(phi + Math.PI / 2) * final_yspeed_2;
                ballArray[j].vy = Math.sin(phi) * final_xspeed_2 + Math.sin(phi + Math.PI / 2) * final_yspeed_2;
            }
        }
    }
}


text:
Q: What is the use of --driver-class-path in the spark command? As per spark docs,

To get started you will need to include the JDBC driver for you particular database on the spark classpath. For example, to connect to postgres from the Spark Shell you would run the following command:

bin/spark-shell --driver-class-path postgresql-9.4.1207.jar --jars postgresql-9.4.1207.jar

Job is working fine without --driver-class-path. Then, what is the use of --driver-class-path in the spark command?

A: --driver-class-path or spark.driver.extraClassPath can be used for to modify class path only for the Spark driver. This is useful for libraries which are not required by the executors (for example any code that is used only locally).
Compared to that, --jars or spark.jars will not only add jars to both driver and executor classpath, but also distribute archives over the cluster. If particular jar is used only by the driver this is unnecessary overhead.

A: Let's say we run the following command with Spark 3.3.0:
spark-submit --driver-class-path DCP.jar --jars JARS.jar MAIN.jar

What the scripts will actually execute is:
java
  -cp DCP.jar:spark/conf:spark/jars/*
  org.apache.spark.deploy.SparkSubmit
  --conf spark.driver.extraClassPath=DCP.jar
  --jars JARS.jar
  MAIN.jar

(I've removed the irrelevant bits.)
The surprise (for me) is that only DCP.jar is on the classpath. Neither JARS.jar nor MAIN.jar are on the JVM classpath. This means any JDBC driver registration from those jars will not be activated. You need to put the JDBC jar on --driver-class-path.
But you also want the workers to be able to do JDBC. So you need to put the JDBC jar on --jars too. Both are required, like the documentation says.


text:
Q: View sent message on Firebase console This is my first time using firebase. I am integrating Firebase Cloud Message with a node.js server and an Android client. When I push the messages to the server, the response is that the message went to the firebase server successfully.
But when I go to the firebase console, I don't see my message there and also my android device does not receive the message. I am sending the messages as topics and the android device has also subscribed to the topics.
I will be glad if someone can share a link to view the messages on the server or suggest what I am missing out.
Below is a sample response:
Message sent to Firebase for delivery, response:
{
  "name": "projects/my-project-id/messages/7660010658785245660"
}
Below is the code that I am using to push to the server
let admin       =   require('firebase-admin'),
    serviceAccount = require('the link to my service account is here'),
    fcmObj = {};

    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
      });

    fcmObj.sendMsg = function(){

      let options = {
        priority: "high",
        timeToLive: 60 * 60 *24
      },

      message = {
        data: {
          content: 'Hello.. we are testing our api and fcm.',
          sender: 'From Server'
        },
        topic: "News"
      };

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message, options)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', JSON.stringify(response));
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });
}

module.exports = fcmObj;

A:
Below is a sample response: Message sent to Firebase for delivery, response: { "name": "projects/my-project-id/messages/7660010658785245660" }

Means that your Firebase SDK is is sending the message successfully. (i.e. credentials are configured properly and SDK is initialised successfully.)
In your code, you've defined data( payload is optional, see documentation here: https://firebase.google.com/docs/cloud-messaging/concept-options#notification-messages-with-optional-data-payload), to display the notification message you need to add a notification object.
Just add following object in your message object and it should work then:
"notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },


text:
Q: How the maximum value of Bytes is calculated? Can any one tell me how the range of the data types are calculated? For example, in MySQL or PostgreSQL where we have smallint, integer and bigint, the range of smallint is from -32768 or +32767. How are these ranges calculated?

A: Your data type is int which is represented as 2-bytes type. 2 bytes means 2 x 8 = 16 bits in it's binary representation. Also, your sample data type is signed - and that means highest bit will be used as sign (0 for positives, 1 for negatives).
From math it's known that with binary values you can hold 2^n unique values, i.e. for your 16-1 bits that will be 15 free bits. So that will be -(2^n) .. 2^n-1 range, where n=15. When you'll calculate -(2^15) and 2^15 - 1 you'll get your -32768 and 32767. That's it.

A: Look to this pages in documentation
http://www.postgresql.org/docs/9.2/static/datatype-numeric.html
Numbers are based from data binary width 0111111111111111 ~ 32767, 1000000000000000 ~ -32768
you can find lot of documentation: search "complement format arithmetic numbers"


text:
Q: How to access AKENEO REST API WITH OAuth 2.0 ACCESS TOKEN with power Query I am trying to access AKENEO REST API WITH OAuth 2.0 ACCESS TOKEN with power Query and after a long day of looking for the solution myself reading a lot of articles about the subject I have to say I'm dry on this one
Here is the documentation I am using from https://api.akeneo.com/documentation, my PIM version is V5 :

Here is my M code :

Here is my response:

As far as I understood:

*

*I encoded the "client_id:secret" in B64 to fill the Authorisation header

*I try to do a POST so I use Content in the url

*I specify the header "Content-Type" as "application.json" and I send Json format value in the postData

*I use anonymous authentication with Power BI considering that the authentication informations are imbembed into the url

I suppose that there is something wrong here but I can't figure it out …
If you can help me on this one I would be grateful, also I am very interested in understanding what's wrong here so don't hesitate to explain !
Regards
Sylvain CHARLETY


text:
Q: Can a GCM client (device) send message to another GCM client directly without going to server According to the documentation at
http://developer.android.com/google/gcm/client.html
http://developer.android.com/google/gcm/server.html
A 3rd-party application server that you must implement. This application server sends data to a GCM-enabled Android application via the chosen GCM connection server.
From above,  it implies that you CANNOT send message from a client to another client directly.
Someone please confirm.

A: It is possible to send GCM-Messages directly from your Device to the Google-Server without any 3rd-party-server.
Just run an AsyncTask like this example:
  HttpPost httppost;
            try
            {
                httppost = new HttpPost("https://android.googleapis.com/gcm/send");
            }
            catch (IllegalArgumentException e)
            {
                return false;
            }
            httppost.setHeader("Authorization","key=xxxxxxxxxxxxxx");
            httppost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            postParams.add(new BasicNameValuePair("registration_id", "xxxxxxxxxxxxx"));
            postParams.add(new BasicNameValuePair("data.mode", "exampleContentOfYourMessage"));
            HttpResponse response;
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity entity;
            try {
                httppost.setEntity(new UrlEncodedFormEntity(postParams, "utf-8"));
            }
            catch (UnsupportedEncodingException e)
            {
                return false;
            }
            try {
                response = httpClient.execute(httppost);
            } catch (ClientProtocolException e) {
                return false;
            } catch (IOException e) {
                return false;
            }
            entity = response.getEntity();
            if (entity != null && response.getStatusLine().getStatusCode() == 200)
            {
                return true;
            }
            else
            {
                Log.e("Tag","No Connection");
                return false;
            }

But I have no Idea how I may send a GCM-Message to multiple registration-Ids :(
Greetings, Malte


text:
Q: ssh session as python subprocess takes input but does not print it to stdout I'm trying use python's cmd library to create a shell with limited commands.  One requirement I have is to be able to run a command that executes an existing shell script which opens an ssh session on a remote machine and from there allows the user to interact with the remote shell as if it was a regular ssh session.
Simply using subprocess.Popen('[/path/to/connect.sh]') works well at least as a starting point except for one issue.  You can interact with the remote shell but the input that you type is not shown on stdout...so for example you see the prompt on your stdout but when you type 'ls' you don't see it being typed but when you hit return it works as expected.
I'm trying to wrap my head around how to print the input to stdout and still send it along to the remote ssh session.
EDIT:
Actual code without using cmd was just the one line:
ssh_session = subprocess.Popen(['connect.sh'])
it was fired from a do_* method in a class which extended cmd.Cmd.  I think I may end up using paramiko but would still be interested in anyone's input on this.

A: Assuming you are using a Unix like system, SSH detects if you are on a terminal or not. When it detects that you are not on a terminal, like when using subprocess, it will not echo the characters typed. Instead you might want to use a pseudo-terminal, see pexpect, or pty. This way you can get the output from SSH as if it was running on a true terminal.


text:
Q: click_action attribute for web push notification through FCM My questions is some what similar to (question) but with some differences.
I am using FCM Admin SDK, but still do not see an option to send the click_action attribute for Web Push notifications.
I checked out admin.messaging.NotificationMessagePayload as well, but looks like this is only applicable to Android and iOS.
As per the comments in the above questions, this click_action is not available for web push using http v1 API (and I think FCM admin SDK as well)
Please help me on how to send the click_action attribute for a web push notification using FCM Admin SDK.
If there are any other workarounds, that would be helpful as well.
Thanks in advance.

A: There is some confusion on how to open a page once you click on the notification popup. The documentation asks to use FCMOptions link attribute however it does not correctly open the page but just brings the browser to the foreground with the last tab to focus(). The solution to this is to change the payload to  use click_action.
"notification":{
   "body":"this is the notification text",
   "title":"New Notification",
   "click_action":"https://theURLyouwanttoopen.com/"
}

Check more

A: I've got the same issue here.
After some trial, as Adrien said, it works but just not documented yet.
And also not included in admin SDK as well. (at least in Python, which I'm using)
Refer to another answer to the same question https://stackoverflow.com/a/52764782/1318878
You can use custom data to do it.
Here's how I create a notification with click action in Python:
notification=messaging.WebpushNotification(
    title=<your_title>,
    body=<your_body>,
    custom_data={"click_action": <your_url>}
)


text:
Q: Why specify index range in order to write a while loop list in Python? mean_temp.txt =
city,country,month ave: highest high,month ave: lowest low
    Beijing,China,30.9,-8.4
    Cairo,Egypt,34.7,1.2
    London,UK,23.5,2.1
    Nairobi,Kenya,26.3,10.5
    New York City,USA,28.9,-2.8
    Sydney,Australia,26.5,8.7
    Tokyo,Japan,30.8,0.9

mean_temp = open('mean_temp.txt', 'r')
city_temp = mean_temp.readline().split(",")

while city_temp[0]:
    print(city_temp[0], city_temp[2])
    city_temp = mean_temp.readline().split(",")

mean_temp.close()

The assignment is to just print the highest temperature for each city (ex: Beijing, 30.9).
My first attempt at solving this problem was to simply write the while loop as "while city_temp: ". I still don't quite understand why I need to specify the index for the while loop to not make the "out of index" error. Why do I need to write "while city_temp[0]:"? I thought the while loop will naturally end once it reaches the end of the list... :( Would love and appreciate help on this thank you!

A: This is so that the while loop will end when it reaches the end of file, with which readline() would return '' and gets split into [''] with split(','), at which point the index 0 is '' and evaluates to False, so the while loop would end.
If you want a loop that ends more "naturally" at the end of file, it's recommended to use the file object as an iterator so you can use a for loop to iterate over it instead:
with open('mean_temp.txt', 'r') as mean_temp:
    for line in mean_temp:
        city, _, temp = line.split(',')
        print(city, temp)

A: The [0] you're using isn't the index of the line in the file, it's the index of the first element of the tuple you get by splitting one line on its commas. The reason you're checking that element is to recognize when there are no more lines.
A simpler and more idiomatic approach would be like this:
with open('file.csv') as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        # do something with row

A: Because it will always have an element of '' at the end of the loop, so then split, it won't have an third (second element) in the list (this is what makes the error), only one element in there, which is [''].
So you have to do [0] to also check for the first (zeroth) element for conditioning if it's empty, basically if it's empty, bool(city_temp) will be False then it exits the loop
Note that [''] is still True because it contains an element
Better code, only works on python 3:
with open('mean_temp.txt', 'r') as f:
   for i in f:
      print(' '.join(i.split(',')[::3]),end='')
print()

Unless in the top of the code you write from __future__ import print_function, then it will work

A: Because when you reach the end of your file, mean_temp.readline() will return the empty string, ''. When you call split on the empty string:
>>> ''.split(',')
['']

It returns a list with the empty string in it, which is truthy
>>> bool(''.split(','))
True

However, you shouldn't be using a while-loop at all. Instead, use a for-loop:
for line in mean_temp:
    # do stuff with line...


text:
Q: NIO. Multiple client channels listening on same port Using NIO, how do I register multiple client connections on the same machine to listen on the same port.
I have something like this for the first channel...
channel1 = DatagramChannel.open();
channel1.configureBlocking(false);
channel1.socket().bind(new InetSocketAddress(localPort));
channel1.connect(socketAddress);
SelectionKey key1 = channel1.register(readSelector, SelectionKey.OP_READ);
key1.attach(driverHandler1);

Now how do I configure channel2 to also listen on the same port since I cant bind() again.

A: Before you bind each channel you must call channelN.socket().setReuseAddress(true), for each N. Then you can bind them all.


text:
Q: How to extract into hash Hey, I am not sure why my code does not work. I am trying to extract some information from html file which contains.
    Junk id="i_0100_1" alt="text1, text2 | text3"
Junk Junk id="i_0100_2" alt="text1, text2 | text3"

I am using this to do it.
my $file = "page.html";

open (LOGFILE, $file);
my %hash;
while (my $line = <LOGFILE>)
{
    %hash = $line =~ /^\s*id="([^"]*)"\s*alt="([^"]*)"/mg;
    print $hash{'id'};
}
close LOGFILE;

What am I missing?

A: *

*Per other suggestion: You might not be opening the file. Check the return or use autodie.

*The scanned HTML may not be in lower case. Use the i regex flag.

*Per the rules of HTML, not all attribute values need to be quoted.

*Also per the rules of HTML, the '=' does not have to come right after the attribute name or right before the value.

*They might not always occur in the same order or adjacent to each other.

*You're using regexes to parse HTML!
#6 is a summary of the problems with 3-5. The solution I suggest is use HTML::Parser or HTML::TreeBuilder

A: You should always check the return value from opening a file:
open LOGFILE, $file or die $!;

Also, the ^ anchor is probably unnecessary in the regex.

A: In addition to Axeman's suggestions (the most important of which is to not parse HTML yourself):

*

*The ^ anchor will prevent your regex from matching since "id" isn't at the
beginning of the line.

*You're resetting the data in %hash with each assignment, which probably
isn't what you want.

*You're printing the value for key "id" but you don't store that in the hash.
What you store (or would, if the pattern ever matched) is the value of the
id attribute.

A: You need not require ^\s* in the beginning
try this   id\=\"(.*)\"\salt=\"(.*)\"
Demo http://rubular.com/r/ySG0XO5jbJ
EDIT
Try removing these modifiers /mg

A: This did the trick:
my $file = "page.htm";

open (LOGFILE, $file);
my %hash;
while (my $line = <LOGFILE>)
{
    %hash = $line =~ /\s*id="([^"]*)"\s*alt="([^"]*)"/;
    for my $key ( keys %hash ) {
        my $value = $hash{$key};
        print "$key\n$value\n";
    }
}
close LOGFILE;

The problem was with the hash output and the regex definition. Thanks to eugene, michael and ish. :)


text:
Q: Перевод изображения в матрицу чисел С помощью каких библиотек можно представить изображение в виде матрицы чисел RGB

A: Так как Вы не указали, ни платформу, ни типы изображений, то ответ такой

*

*Qt (хотя это не совсем библиотека) - класс QImage, функция pixel(x,y)

*ImageMagick/GraphicMagick

A: wxWidgets позволяет через wxImage получить массив RGB непосредственно, он их в таком виде хранит. Ну, или через соответствующие функции-члены wxImage.
Кстати, wxWidgets кроссплатформенный :)


text:
Q: java code that reads all the .xml files in a folder and the value between specific tags I have a folder that contains only .xml files. My program needs to read each file and then return the names of the files that have 'false' between tags. I was thinking:
        final Pattern pattern = Pattern.compile("<isTest>(.+?)</isTest>");
        final Matcher matcher = pattern.matcher("<isTest>false</isTest>");
        matcher.find();
        System.out.println(matcher.group(1));

I am new to java so any help will be much appreciated.
Can u tell me where I am going wrong?
public class FileIO
{
    public static void main(String[] args)
    {
        File dir = new File("d:\temp");

        List<String> list = new ArrayList<String>();

        //storing the names of the files in an array.
        if (dir.isDirectory())
        {
          String[] fileList = dir.list();
          Pattern p = Pattern.compile("^(.*?)\\.xml$");

          for (String file : fileList)
          {
            Matcher m = p.matcher(file);
            if (m.matches())
            {
              list.add(m.group(1));
            }
          }
        }

        try
        {

            XPathFactory xPathFactory = XPathFactory.newInstance( );
            XPath xpath = xPathFactory.newXPath(  );
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(  );
            DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(  );

            //Loop over files

            for (int i = 0; i < fileList.length; i++)
            {
                Document doc =  builder.parse(fileList[i]);
                boolean matches = "false".equals(xpath.evaluate("//isTest/text()", doc));
            }
        }

        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

A: If the files have an XSD that you can utilize, JAXB is the solution of choice.  You do not want to use a regular expression on XML because CDATA will ruin your day as will nested tags.
Using SAX like so is a probable solution:
public static void main(String[] args)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

    boolean isTest= false;

    public void startElement(String uri, String localName,String qName,
                Attributes attributes) throws SAXException {

        System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("isTest")) {
            isTest= true;
        }

    }

    public void endElement(String uri, String localName,
        String qName) throws SAXException {

        System.out.println("End Element :" + qName);

    }

    public void characters(char ch[], int start, int length) throws SAXException {

        if (isTest) {
            System.out.println("is test : " + new String(ch, start, length));
            isTest= false;
        }
    }

     };

       saxParser.parse("c:\\file.xml", handler);
}

Code adapted from here

A: Sax is probably more efficient (memory wise) but here is a snippet of an xPath version, likely shorter, line wise
XPathFactory xPathFactory = XPathFactory.newInstance( );
XPath xpath = xPathFactory.newXPath(  );
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(  );
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(  );

/* Loop over files */

Document doc =  builder.parse(file);
boolean matches = "false".equals(xpath.evaluate("//isTest/text()", doc));


text:
Q: Razorpay .net integration automatic payment capture I am trying to integrate razorpay payment gateway into my application and while doing the same , I came across the concept of automatic payment capture. In the razorpay documentation for setting automatic and manual expiry period they are using payment.capture_options. But I am not sure how they got the payment object. Please help
reference URL
https://razorpay.com/docs/payments/payments/capture-settings/api/

code from documentation.
How do I get this payment object while creating an order. ?


text:
Q: Using offset for multiple criteria I have 5 lines of code that I need to reproduce about 180 times. With each line (or group of lines) I need do adjust just a few numbers. It is super tedious to do with replace. Is there a way to do this with offset or something like that? Here is the code:
If Target.Address = "$E$7" Then
    MsgBox Worksheets("Budget Hours").Range("F3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("F6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("F7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("F8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("F9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("F10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$8" Then
    MsgBox Worksheets("Budget Hours").Range("G3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("G6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("G7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("G8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("G9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("G10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$9" Then
    MsgBox Worksheets("Budget Hours").Range("H3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("H6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("H7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("H8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("H9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("H10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$10" Then
    MsgBox Worksheets("Budget Hours").Range("I3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("I6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("I7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("I8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("I9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("I10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$11" Then
    MsgBox Worksheets("Budget Hours").Range("J3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("J6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("J7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("J8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("J9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("J10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$12" Then
    MsgBox Worksheets("Budget Hours").Range("K3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("K6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("K7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("K8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("K9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("K10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$13" Then
    MsgBox Worksheets("Budget Hours").Range("L3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("L6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("L7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("L8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("L9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("L10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$14" Then
    MsgBox Worksheets("Budget Hours").Range("M3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("M6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("M7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("M8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("M9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("M10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$15" Then
    MsgBox Worksheets("Budget Hours").Range("N3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("N6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("N7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("N8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("N9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("N10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$16" Then
    MsgBox Worksheets("Budget Hours").Range("O3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("O6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("O7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("O8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("O9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("O10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$17" Then
    MsgBox Worksheets("Budget Hours").Range("P3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("P6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("P7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("P8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("P9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("P10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$18" Then
    MsgBox Worksheets("Budget Hours").Range("Q3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("Q6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("Q7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("Q8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("Q9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("Q10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$19" Then
    MsgBox Worksheets("Budget Hours").Range("R3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("R6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("R7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("R8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("R9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("R10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$20" Then
    MsgBox Worksheets("Budget Hours").Range("S3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("S6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("S7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("S8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("S9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("S10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$21" Then
    MsgBox Worksheets("Budget Hours").Range("T3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("T6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("T7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("T8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("T9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("T10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$22" Then
    MsgBox Worksheets("Budget Hours").Range("U3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("U6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("U7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("U8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("U9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("U10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$23" Then
    MsgBox Worksheets("Budget Hours").Range("V3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("V6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("V7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("V8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("V9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("V10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$24" Then
    MsgBox Worksheets("Budget Hours").Range("W3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("W6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("W7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("W8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("W9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("W10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$25" Then
    MsgBox Worksheets("Budget Hours").Range("X3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("X6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("X7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("X8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("X9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("X10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$26" Then
    MsgBox Worksheets("Budget Hours").Range("Y3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("Y6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("Y7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("Y8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("Y9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("Y10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value
    ElseIf Target.Address = "$E$27" Then
    MsgBox Worksheets("Budget Hours").Range("Z3").Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Range("Z6").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Range("Z7").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Range("Z8").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Range("Z9").Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Range("Z10").Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value

So the 6, 7, 8, 9, and 10 are replaced with 15, 16, 17, 18, and 19 in the next grouping. Then there is another 6 sets of the above code. Is there a way to implement some sort of offset so I can only adjust that and the rest will balance? It will always be five consecutive numbers so a single offset to would work to get to the correct starting point. An aside - the offset will not always be equal to 9 (ie. 6 becoming 15). One of the offsets will be a different number so I'd like to be able to adjust accordingly.

A: I'm unsure what triggers the next "grouping" but here's a different appraoch.
Untested:
Dim ws As Worksheet, rng1 As Range, rng2 As Range, msg, i As Long

Set ws = Worksheets("Budget Hours")

Set rng1 = ws.Range("E6:E10")
Set rng2 = rng1.Offset(0, target.Row - 6)

msg = rng2.EntireColumn.Cells(3).Value & vbNewLine
For i = 1 To rng1.Cells.count
    msg = msg & vbNewLine & rng1.Cells(i).Value & " - " & rng2.Cells(i).Value & " Hours"
Next i

MsgBox msg, , ws.Range("E5").Value

A: Assuming they will continue to all follow the same pattern, where target.row correlates to the ending column this should work.
Take the .row from target and subtract one to get your new column.
    MsgBox Worksheets("Budget Hours").Cells(3, target.Row - 1).Value & vbNewLine _
        & vbNewLine & Worksheets("Budget Hours").Range("E6").Value & " - " & Worksheets("Budget Hours").Cells(6, target.Row - 1).Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E7").Value & " - " & Worksheets("Budget Hours").Cells(7, target.Row - 1).Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E8").Value & " - " & Worksheets("Budget Hours").Cells(8, target.Row - 1).Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E9").Value & " - " & Worksheets("Budget Hours").Cells(9, target.Row - 1).Value & " Hours" _
        & vbNewLine & Worksheets("Budget Hours").Range("E10").Value & " - " & Worksheets("Budget Hours").Cells(10, target.Row - 1).Value & " Hours" _
            , , Worksheets("Budget Hours").Range("E5").Value

Now you shouldn't need any if statements.

A: I have adjusted for what @TimWilliams said above. I now tried to make it work for my second grouping but it doesn't quite work. Here's the code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.Calculate

Dim ws1 As Worksheet, ws2 As Worksheet, list As Range, msg, i As Long

Set ws1 = Worksheets("Budget Hours")
Set ws2 = Worksheets("Schedule")

'Phase 01
Dim rngPH1 As Range, rng1 As Range, rng2 As Range
Set rngPH1 = ws2.Range("E7:E27")
Set rng1 = ws1.Range("E6:E10")
Set rng2 = rng1.Offset(0, Target.Row - 6)

For Each list In rngPH1
    msg = rng2.EntireColumn.Cells(3).Value & vbNewLine
    For i = 1 To rng1.Cells.Count
        msg = msg & vbNewLine & rng1.Cells(i).Value & " - " & rng2.Cells(i).Value & " Hours"
    Next i
Next list

MsgBox msg, , ws1.Range("E5").Value

'Phase 02
Dim rngPH2 As Range, rng3 As Range, rng4 As Range
Set rngPH2 = ws2.Range("E43:E63")
Set rng3 = ws1.Range("E15:E19")
Set rng4 = rng3.Offset(0, Target.Row - 36)

For Each list In rngPH2
    msg = rng4.EntireColumn.Cells(3).Value & vbNewLine
    For i = 1 To rng1.Cells.Count
        msg = msg & vbNewLine & rng3.Cells(i).Value & " - " & rng4.Cells(i).Value & " Hours"
    Next i
Next list

MsgBox msg, , ws1.Range("E14").Value

End Sub

So my problem is that I want the Phase 01 stuff to only work on the range Schedule("E7:E27"). The Phase 02 stuff I want only to work on the range Schedule("E43:E63"). I thought by using rngPH1 and rngPH2 I could accomplish this but it didn't work. If I click in say Schedule("E8"), it brings up the correct stuff from ws1 perfectly, but then carries on to the Phase 02 stuff which I don't want. How do I get it to do the Phase 01 stuff only on the range rngPH1 and the Phase 02 stuff only on the range rngPH2?


text:
Q: Form entry gets inserted into the HTML code? I am using following code to display HTML Form on my web page. This code also uses a third-party .js file that is linked to it. Everything is working fine except that when the first record is inserted and after saving the record the control comes back to this form, the company name entered in the first entry is seen in the code itself. I mean to say that the entry company name is somehow gets inserted into the HTML code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

        <title>Job Listing Entry</title>

        <Form id="frmNewEntry" method="post" action="insert_listing.php">

Date:	<input id="LDate" name="LDate" type="text" size="50">[yyyy/mm/dd]

Places:	<input id="Places" name="Places" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">

Company:	<input id="Company" name="Company" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">

Designation:	<input id="Designation" name="Designation" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">

Project Details:	<textarea class="widgEditor" id="ProjectDetails" name="ProjectDetails" cols="100" rows="10""></textarea>

Desired Candidate:	<textarea class="widgEditor" id="DesiredCandidate" name="DesiredCandidate" rows="5" cols="100" onblur="this.value=MakeInitialCapital(this.value);"></textarea>

HR Name:	<input id="HRName" name="HRName" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">

HR Contact:	<input id="HRContact" name="HRContact" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">

Email:	<input id="Email" name="Email" type="text" size="50">

<input id="Submit" name="Submit" value="Submit" type="submit">

        </Form>

For example, if I had typed the company name, say, Example Solutions, then the first line of the above code gets modified as:
Example Solutions <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

A: Are you using some kind of server side processing language such as PHP?  If so then make sure you don't have an 'echo' statement lurking around dumping the company name.  Given the location in the HTML where the company name is being printed my guess is it is happening on the server side and not with JavaScript.

A: I got a new tool: openWYSIWYG


text:
Q: Global associative array only visible when the script is sourced a second time I have the following script called .bash_functions.test which is already sourced by my .bash_functions script:
# vim: set syn=sh noet:

mp4Options_BIS="-movflags +frag_keyframe"
declare -A audioExtension=( [libspeex]=spx [speex]=spx [opus]=opus [vorbis]=ogg [aac]=m4a [mp3]=mp3 [mp2]=mp2 [ac3]=ac3 [wmav2]=wma [pcm_dvd]=wav [pcm_s16le]=wav )

function test1 {
    echo "=> mp4Options_BIS = $mp4Options_BIS"
    echo "=> audioExtension = ${audioExtension[*]}"
}

And when I run the test1 function I see this:
=> mp4Options_BIS = -movflags +frag_keyframe
=> audioExtension =

Finally, when I source the script once more and re-run the test1 function I see this:
=> mp4Options_BIS = -movflags +frag_keyframe
=> audioExtension = ac3 wma opus mp3 wav mp2 wav spx m4a spx ogg

In fact, I use my Source function in the first source call and the source builtin and the second source call:
$ grep -r .bash_functions.test
.bash_functions:source $initDir/.bash_functions.test
$ type Source
Source is a function
Source ()
{
    test "$debug" -gt 0 && time source "$@" && echo || source "$@"
}

And here is what happens:
$ Source .initBash/.bash_functions.test
$ test1
=> mp4Options_BIS = -movflags +frag_keyframe
=> audioExtension =
$ source .initBash/.bash_functions.test
$ test1
=> mp4Options_BIS = -movflags +frag_keyframe
=> audioExtension = ac3 wma opus mp3 wav mp2 wav spx m4a spx ogg

Why is it working like this?

A: declare/typeset without -g declares variables in the current scope in addition to setting the type.
Here, because declare -A audioExtension=(...) ends up being run within the Source function, that causes the audioExtension variable to be declared local to that function, and as a consequence its definition to be lost once Source returns.
You could change it to typeset -Ag audioExtension=(...) which always declares the variable in the global scope (it's different from zsh/mksh/yash where typeset -g only prevents the variable from being made local (only updates the type/attributes and value); it makes a difference when your Source function is called from another function itself; see bash vs zsh: scoping and `typeset -g` for details).
If you used ksh93 instead of bash (that's the shell bash borrowed that associative array syntax from), you could define your Source function as:
Source() {
  ...
}

as opposed to:
function Source {
  ...
}

In ksh93, functions defined with the Bourne-style func() cmd syntax don't have a local scope while function func { ones have static local scope (there, there's only one global scope and one local per-function scope, not a stack of local scopes).
In bash (and other shells with local scoping), there's no similar way to have a function that doesn't introduce a new scope. You could use an alias instead like:
shopt -s expand_aliases
if [ "$debug" -gt 0 ]; then
  alias Source='time source'
else
  alias Source=source
fi

(note that the aliases are expanded at the time code is read, not at the time it's executed).
It would make a functional difference compared to your function approach in that in:
Source ./myfile | other-cmd

We would be timing both source myfile and other-cmd as it's expanded to time source ./myfile | other-cmd while in the function approach we would only by timing source ./myfile.
Using source=(time source); "${source[@]}" /some/file wouldn't  work (it would invoke the time standalone utility instead of the bash time keyword).


text:
Q: how can i pass data from parent controller in codeigniter I am trying to prevent myself from repeating the same code over and over in every controller. So i place function that fetch the data in the parent controller, and i am trying to pass that data in the child controller.
class Frontend_Controller extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('configOptionsModel');
    $this->db->where('configid = "2"');
        $specialdata['bgimage'] = $this->configOptionsModel->get();
    }
}

Here is the code for the child controller
 class Home extends Frontend_Controller {

public function __construct() {
        parent::__construct();
        print_r($this->specialdta); // line where error occurs
        die();
    }

    public function index()
{
    $data['main_content'] = 'home';
    $this->load->view('frontEnd/template',$data);
}
 }

I get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Home::$specialdta
Filename: controllers/home.php
Line Number: 9

Sure enough, line 9 is: print_r($this->specialdta);
I know that if you extends a controller (class), you have access to the methods and properties from the parent controller (classs), since they are declared public.
Can anyone explain me what i am doing wrong?
Regards,Zoran

A: CodeIgniter is not magic and follows PHP class specifications and rules. Like any inheritance model, to access variables from a parent class, you must assign them to $this in the parent.
$this->specialdata = $this->configOptionsModel->get(); in the parent constructor will work for you, but beware of assigning data attributes wildly like this. Under the hood, and many classes down the inheritance chain, CodeIgniter's core may have some common properties reserved and you don't want to overwrite them.


text:
Q: PowerBI Embedded - Hide specific filters My report of PowerBI have three types of filters

*

*hidden filters

*visible filters

*filters coming from drill-through

From embedded I have the option to hide the filter panel if all the filters present are not visible and show the panel if at least one filter is visible
i look at the following property for this
filter.displaySettings.isHiddenInViewMode

https://learn.microsoft.com/en-us/javascript/api/overview/powerbi/control-report-filters
But i can't manage if the filter is coming from a drillthrough or not
Is there any way to do it?
Thanks in advance

A: Currently it is not possible to know if the filter is applied from a hidden or visible filter or from drill through
Though you can use getFilter method (in Report, Page or Visual) to fetch details like filter type, table, column etc.
The output look something like:

Reference:
Use filters when embedding a report in Power BI embedded analytics | Microsoft Docs


text:
Q: Is it safe to store only the Firebase Storage download URL token (not the full path)? I have an Angular app using Firebase Storage to store user uploaded photo files. After the user uploads a file, I call getDownloadURL() (returns Observable) to get the full public URL path. I want to store the URL string in a Firestore database so it can be bound to an img html element src property for display on a web page. That will save me from having to call the Storage API to get every image URL one-by-one asynchronously.
This URL includes a token value in the query string which I assume is un-guessable and used for security as a sort of password. To save space, should I only store the token in the database? I can assemble the rest of the cloud folder path using variables - the token is the unique part. The full URL path is quite long as you can see. Do you think the rest of the URL path will ever change?
Example Firebase Storage download URL (not real)
https: -- //firebasestorage.googleapis.com/ -- v0/b/my-bucket-name-goes-here/o/T4uk5DnzXlO1C7hs9HrSdb7yxsM2%2Fthumb%2FcX2kCobDqdRgN3snefYh.jpg?alt=media&token=238b33ad-f823-4876-a5e2-626ca157ed10

A: The only guarantee that you receive from the API is that the entire URL will fetch the file in storage.  You should treat it opaquely and not try to break down or interpret its components.


text:
Q: Test if NSObject is observing string I have a NSObject that listens for ~30 string signals.  I want to post any number of strings to this object.  But I first want to test to see if it's observing the current string.
The documentation for [NSNotificationCenter][1] doesn't suggest this is possible.  There are only add/remove remove observer, and post notification methods.
The documentation for KVO makes me think this may be possible using the [[NSNotificationCenter defaultCenter] observationInfo] method.  I don't have a clue how I would use the returned void*.  The documentation states the return value:

A pointer that identifies information about all of the observers that
  are registered with the receiver, the options that were used at
  registration-time, and so on.

I especially appreciate the "and so on".  That was the most helpful part...sigh.
Considering the number of signals the object is handling, I don't want to manually check each string.  Is there a graceful way to check whether the object is observing a string (try/catch doesn't qualify) at the NSObject level or KVO level that doesn't use private API?
Thanks.

A: The pointer used by -observationInfo is opaque (i.e. meaningless) to you; it's just a token. From the header (emphasis mine):

Take or return a pointer that identifies information about all of the
  observers that are registered with the receiver, the options that were
  used at registration-time, etc. The default implementation of these
  methods store observation info in a global dictionary keyed by the
  receivers' pointers. For improved performance, you can override these
  methods to store the opaque data pointer in an instance variable.
  Overrides of these methods must not attempt to send Objective-C
  messages to the passed-in observation info, including -retain and
  -release.

Also, KVO observations and NSNotificationCenter observations are two completely separate mechanisms with no relation between them. Neither offers any public API for figuring out who is observing what. The only way I can conceive to track observations would be to override the add/remove methods (either with method overrides for KVO or by swizzling the methods on NSNotificationCenter) and then keeping track of the observation information yourself.
I don't mean to be "that guy" but wanting to know about who's observing what is generally a red flag that something isn't well architected. If you're worried about performance, I wouldn't be. KVO and NSNotificationCenter are fairly fast/low overhead mechanisms. ~30 observations aint nothin' to either. I wouldn't worry about it.


text:
Q: How to reduce the size of an APK file in Unity? Is the minimum APK size of an Android app made by Unity 8MB? I am building an empty project, but still getting 8MB. Is there a way to reduce the APK size?

A: In Player settings, Device Filter, Select ARMv7 only
(In latest unity (2018.1), this can be found as Other Settings, Target Architecture)
Also scroll down, set Stripping level to Use Micro mscorlib
These should reduce the size a bit further

A: For reducing APK size:
In Unity 5.6.0f3 I have created a simple "Hello world" program and build an APK file, it consumes 21.2 MB at first but to reduce the size you have to follow these steps:

*

*
Unity 5.6.0f3:  Player settings > other settings > optimization > API compatibility
  level
Unity 2018.3.6f1: Player Settings > Other Settings > Configuration > API Compatibility Level

.NET 2.0 Subset.
To avoid memory wastage, Unity also supports the .NET 2.0 Subset API profile. This is very similar to the Mono "MonoTouch" profile, so many limitations of the "MonoTouch" profile also apply to Unity's .NET 2.0 Subset profile.Unity's .NET 2.0 Subset profile.

*
Unity 5.6.0f3:  Player settings > other settings > device filter > ARMv7
Unity 2018.3.6f1: Player Settings > Other Settings > Configuration > Target Architectures

ARM and x86 are both processor architectures. x86 belongs to Intel while ARM is used by different companies and widely used, so no need to select both architectures.

*
Unity 5.6.0f3: Player settings > other settings > rendering path > Legacy Vertex

*
Unity 5.6.0f3: Player settings > other settings > Optimization > Stripping level > Use micro mscorlib

The Lightweight mscorlib version will be used at expense of limited compatibility.
Most games do not use all the functionality of the provided DLLs. With this option, you can strip out unused parts to reduce the size of the built player on Android devices.

After applying all these changes it becomes 10.4 MB.
For reducing IPA size:
In Xcode, there are few flags you need to set,

*

*Build Settings-> Enable Objective-C Exception-Yes

*Build Settings-> Enable BitCode-No

*Build Settings-> Compress PNG files -No

A: Even though your project doesn't contain any of your code yet, it still contains the Unity libraries and they are a fixed size. 8MB is very small for any Android app, let alone a game. I wouldn't worry about that until later.

A: Unity 2020.3.38f1
A empty project in unity take 6 mb size in ARMv7  and take 12mb size in both ARMv7and ARM 64 during building the apk


text:
Q: Digital signatures in a smart card: Why have two certificates, one for authentication and the other for non-repudiation (signing)? Update: reading itext whitepaper on using smart cards to sign and have the following question:
Digital signatures in a smart card:  Why have two certificates, one for authentication and the other for non-repudiation?  Why can't one certificate be used for both since both authentication and non-repudiation certificates uses private keys to encrypt and public key to decrypt.  Is it because the "authentication certificate" contains sensitive info?
It's said that the authentication signatures allows the card to prove his identity and also the certificate contains privacy-sensitive information such as gender, date of birth, and national number.  The non-repudiation signature is used for to generate electronic signatures.

A: It is common practice to have multiple keys for multiple purposes.
There may be a lot of technical differences and procedural differences:

*

*Authentication could have the PIN cached while the private key of the non-repudiation (non-rep) certificate could require a PIN to be supplied by the holder for each signature operation.

*One private key could be revoked (e.g. the more sensitive non-rep key) while the authentication key could still be be used.

*Authentication maybe used for longer than the non-rep key.

*The key usage of the non-rep key could be more strict.

*The CA keys of the non-rep key could also have a higher grade of protection.

*It used to be the case that e.g. SSL authentication required different signature (MD5 + SHA-1) or encryption operations. The higher the access to keys, the less secure they will be. Nowadays TLS can be used to have a more regular signature in combination with ephemeral Diffie-Hellman.

*As Eugene has commented, there may be legislature in place that requires separate keys and/or certificate chains for authentication and non-rep.

Even if all the above are not true yet, they may apply in the future. Hence the specific keys for a specific purpose. And note that the above is just out of the top of my head.


text:
Q: Bind rvalue reference to (auto generated) lvalue My search found many posts on rvalue binding to lvalue but not anything similar. Sorry if it is a duplicate.
struct StrHolder {
    StrHolder(std::string&& s) : name(s) {}
    void Print() const { std::cout << "My name is " << name << std::endl; }
    std::string name;
};

int main()
{
    StrHolder s{"Tom"};  // (1) - OK, as expected
    s.Print();

    std::string n1 {"Angi"};
    StrHolder p{std::move(n1)};  // (2) - OK, also as expected
    p.Print();

    //StrHolder q{n1}; // (3) - NOT OK. Also expected. Cannot bind rvalue reference to lvalue
    //q.Print();

    auto name1 {"Bon"}; // name1 is an lvalue
    StrHolder z{name1}; // (4) - Why is this OK ?
    z.Print();

    return 0;
}

The variable 'name1' declared as auto, above is an lvalue. Therefore, initialization of 'z' should fail but it does not.
Am I missing anything here ?

A: name1 is an lvalue... but it's not a std::string, it's a char const*. Constructing a StrHolder from it involves making a temporary std::string using its implicit constructor from char const*, then invoking StrHolder::StrHolder() with an rvalue reference to that temporary. name1 gets left alone, and is never moved from.


text:
Q: Canvas default settings to enable user input I am building a IMG crop/re-size/zoom tool and I want to be able to pass some default parameters into the drawImage() function in case some are not defined yet.
For example:
I get a re-size request and can therefor input width and height:
drawImage(this.loadedImg,0, 0, 0, 0, 0,0,this.imageWidth, this.imageHeight);

I cant find the defaults anywhere. I tried false and 0, but neighter worked.
Does anyone have an idea?

A: I'm not sure I got clearly what you are after, So I'll assume you want the default values for the arguments of drawImage(source, sx, sy, sw, sh, dx, dy, dw, dh) when you use the short version drawImage(source, dx, dy) or the less short drawImage(source, dx, dy, dw, dh).
In case of an <img> element as source, it is drawImage(img, 0,0, img.naturalWidth, img.naturalHeight, 0, 0, img.naturalWidth, img.naturalHeight).
In case of a <video> element as source, it is drawImage(vid, 0,0, vid.videoWidth, vid.videoHeight, dx, dy, vid.videoWidth, vid.videoHeight).
For any other source type it is drawImage(source, 0, 0, source.width, source.height, 0, 0, dx, dy).
So we can make this table :
drawImage(
   source: always inputed,
   sx: input || 0,
   sy: input || 0,
   sw: input || source.[natural | video]width,
   sh: input || source.[natural | video]height,
   dx: always inputed,
   dy: always inputed,
   dw: input || sw,
   dh: input || sh
)


text:
Q: Properties of space-time intervals derived by symmetry principles In many books about special relativity I found the following arguments:
1) because the transformations between two inertial reference frames $K$ and $K'$ are linear and because if $\Delta s^2 = 0 $ we find also $ \Delta s'^2=0 $ then it has to be $\Delta s^2 = \lambda \Delta s'^2$
2) because space-time is uniform and space is isotropic the constant $\lambda$ can depend at most on $|\vec v|$, where $\vec v$ is the velocity of $K'$ with respect to $K$
I know that the consequences of those reasoning are right but I can't see how they can be demonstrated and if, stated in that way, they are undoubtly right.

A: I think you can build an acceptable argument by developing this skeleton:
Linear means of the form y=mx+c
If zero is preserved c=0
If there is no intrinsic property to change the ratio of proportionality it must depend on the only extrinsic variable.


text:
Q: WAS 6.0 startup failing: NoClassDefFound for ibmorb.jar When I am trying to start my WAS server using eclipse, I am getting the following exception
java.lang.NoClassDefFoundError: Files/IBM/WebSphere/AppServer/java/jre/lib/ext/ibmorb/jar;C:/Program
Caused by: java.lang.ClassNotFoundException: Files.IBM.WebSphere.AppServer.java.jre.lib.ext.ibmorb.jar;C:.Program

I think the problem will be resolved when we place the jar in the path. If yes, please let me know from where can I get the jar file.
Thanks in advance,
Karthik.

A: How are you starting it? I would start the app server from it's command line /bin/startServer server1
Once i know that things are working well, i will look at troubleshooting stuff. ibmorb.jar is a pretty important file and i don't see how they could go missing.
They should typically be in the jre/lib directory.
From the logs that you have i suspect there are some issues. Notice
Files/IBM/WebSphere... in your error message.
"C:/Program Files" is not present in that structure. I suspect the space in Program Files is giving you trouble.  Try using the 8 char notation c:/Progra~1 in your eclipse config of WebSphere and see if that helps over come this issue.
Try these only after you get the server starting on its own (outside eclipse) to ensure that your WAS set up is good and running.
HTH
Manglu


text:
Q: Fast square roots I need to compute the square roots of lots of numbers. The numbers increase monotonically by fixed step. For example, 1, 2, 3, ..., 1 000 000.
What is the fastest way to do so? Is it possible somehow to take the advantage of the growth and calculate the square roots incrementally?
I thought I would calculate the derivative and add it at each step. But the derivative contains again a square root so it doesn't help. Also, I don't mind to trade some precision for speed.

A: I'd suggest to calculate the square root $s_k\stackrel!=\sqrt{a_k}$ by using $s_{k-1}+(s_{k-1}-s_{k-2})$ as an initial value for the iteration $x_{n+1}=(x_n+a_k/x_n)/2$.

A: Here's a neat way to compute the next square root once the numbers are large.  Let $s_n=\sqrt{n}$ be the previous value you computed and then use the Taylor expansion
$$ s_{n+1}=\sqrt{n}\sqrt{1+1/n}=s_n\sqrt{1+1/n}=s_n\left(1+\frac{1}{2n}-\frac{1}{8n^2}+\frac{1}{16n^3}-\frac{5}{128n^4}+\cdots\right)
$$
For example for $n=100$ the first three terms give you six correct digits.  For binary arithmetic note the convenient powers of two in the denominators.  The error will accumulate from one term to the next, but if we correct the answer in the cases $s_{m^2}=m$, then the error can't get too out of hand.  Also note that anytime $n$ is not a prime, say $n=kl$ you can of course use $s_n=s_ks_l$ to compute the square root.  I would at least do this for all even numbers, and then perhaps the odd numbered ones could be computed using the formula above.
I have another idea for how to make it faster using a rational approximation instead of a Taylor approximation, but I will need some time to work out the details.

A: Another approach: approximate the square root function by a polynomial, or maybe a rational function. The degree will depend on what accuracy you need and over how wide an interval. Calculating a good approximation is not easy, but you only have to do it once. If any of your numbers are close to zero, a polynomial won't work very well, so you'll have to use a rational approximation.
If your input numbers are in an arithmetic sequence (some constant step between each consecutive pair), then you can calculate values of the polynomial very quickly by forward differencing.
I'm not sure that this approach is any better than the other one suggested. Depends on what sort of hardware you have, what accuracy you require, etc.

A: As promised, here is another way to compute the square root using rational approximations.  The method converges as fast as Newton's method, but is not as well known.  I read about this in AMS monthly, but unfortunately I don't remember the issue or authors.  If anyone has a pointer to the article that would be great.  Let's use the formula
$$
\sqrt{n+1}=\frac{n}{\sqrt{n-1}} \sqrt{1-1/n^2}
$$
as a starting point.  If $\sqrt{n-1}$ is known, we only need to compute $\sqrt{1-1/n^2}$.  Let's take $x=-1/n^2$ and let's try to find a fraction $(a+bx)^2/(c+dx)^2$ that is close to $1+x$.  It can be checked that
$$
\frac{(4+3x)^2}{(4+x)^2}=1+x-\frac{x^3}{16}+\frac{x^4}{32}+\cdots=1+x+\mathcal{O}(x^3)
$$
does the trick.
Therefore we have
$$
\sqrt{1+x}=\frac{4+3x}{4+x}\sqrt{(1+x)\frac{(4+x)^2}{(4+3x)^2}}=\frac{4+3x}{4+x}\sqrt{1+\frac{x^3}{(4+3x)^2}}
$$
We can now repeat the whole procedure again by using $\frac{x^3}{(4+3x)^2}$ in place of $x$.
Thus we take $x_1=-1/n^2$, $x_2=x_1^3/(4+3x_1)^2$ and we get
$$ \sqrt{1-\frac{1}{n^2}}\approx \frac{(4+3x_1)(4+3x_2)}{(4+x_1)(4+3x_2)}
$$
and the error is already of order $\mathcal{O}(n^{-18})$, which for $n=10$ should be enough to reconstruct the square-root to double precision.  Even the first term $\frac{4+3x_1}{4+x_1}$ is probably pretty good for practical purposes.


text:
Q: Multiple lineplots with a dependency variable One dataframe contains the percentage change of several nerve amplitudes at the corresponding measurement points and a second their respective diameters.
>>> amp.head()
   Timepoint 1  Timepoint 2  Timepoint 3  Timepoint 4  Timepoint 5  Timepoint 6
0     1.277778     0.944444     0.444444          0.0          0.0          0.0
1     0.941176     0.705882     0.352941          0.0          0.0          0.0
2     0.818182     0.490909     0.309091          0.0          0.0          0.0
3     1.000000     0.658537     0.414634          0.0          0.0          0.0
4     0.588235     0.455882     0.323529          0.0          0.0          0.0

>>> dia.head()
0    1.3
1    1.1
2    1.2
3    1.5
4    1.6

I would like to plot the amplitudes in relation to their diameter, as hue='insert column here' does in many Seaborn plots.
def plot_rows(df, color="xkcd:red"):
    # Reference: https://stackoverflow.com/questions/32105817/plot-entire-row-on-pandas

    number = df.shape[0]
    rows = range(number)
    fig, ax = plt.subplots(figsize=(8, 8))
    plt.show()

Although this function does plot the amplitudes row by row, it doesn't show their diameter. Is it possible to do so any other way?
I thought about combining both datasets, sort them according to the diameter, divide the diameter in let's say 3 groups and then plot them all on the same graph with different colors, but I just can't figure out how.
Something like this was my first take
new_df = pd.concat([amp, dia], axis=1)
# sort the values into categories and exclude "Diameter [mm]" from the plot
small = new_df[(new_df["Diameter [mm]"] < max(new_df["Diameter [mm]"]) / 2)][:-1]
plot_rows(small[[small.columns.values]])

A: Great question. I had to do some learning to come up with this answer. Perhaps somebody else can add to this post, maybe there is an easier or better solution!
I put your subset data into a CSV and placed it to a dataframe (amp) and series (dia). Your data are much easier to plot if you simply take the transpose of amp.
>>> amp.T
>>>
                   0           1           2           3           4
Timepoint 1 1.277778    0.941176    0.818182    1.000000    0.588235
Timepoint 2 0.944444    0.705882    0.490909    0.658537    0.455882
Timepoint 3 0.444444    0.352941    0.309091    0.414634    0.323529
Timepoint 4 0.000000    0.000000    0.000000    0.000000    0.000000
Timepoint 5 0.000000    0.000000    0.000000    0.000000    0.000000
Timepoint 6 0.000000    0.000000    0.000000    0.000000    0.000000

I was able to get an answer together and apply it to your dataset using the following posts/resources.
Line collection tutorial
Excellent post by @ahwillia
Basically you use the LineCollection class to apply a colormap to the lines with mpl.cm.ScalarMappable.set_array and then plot them at the same time by adding the collection to the axis. This also facilitates use of a colorbar. Reviewing these documentation may help you understand the implementation better and apply it more broadly to datasets. Here is an implementation for your data.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.collections import LineCollection
from matplotlib import ticker

#read CSV and define diameter
amp = pd.read_csv('stack_overflow.csv')
dia = pd.Series([1.3, 1.1, 1.2, 1.5, 1.6])

fig, ax = plt.subplots(figsize=(12,8))

#xs are a len(timepoints) X len(timepoints) matrix one row of xs for each line
#ys are a len(timepoints) X len(timepoints) matrix one row of ys for each line
xs = [np.arange(len(amp.columns))] * len(amp.columns)
ys = amp.values

#segments is an array of x/y pairs, such as multiple of the following
# [[0.  1.277778]
 # [1.  0.944444]
 # [2.  0.444444]
 # [3.  0.      ]
 # [4.  0.      ]
 # [5.  0.      ]]
segments = [np.column_stack([x, y]) for x,y in zip(xs, ys)]
#create LineCollection object and pass **kwargs
lines = LineCollection(segments, cmap = 'viridis', linewidth=3.5)

#set_array is a cmap function that takes the dia values and normalizes them
#then maps to the colormap provided to lines
lines.set_array(dia)

#plot lines and scale axis
ax.add_collection(lines)
ax.autoscale()

#add colorbar
ax_cb = fig.colorbar(lines)

#styling
hide_spines = [ax.spines[s].set_visible(False) for s in ['top','right']]
tic_params  = ax.tick_params(axis='both', labelsize=14, bottom=True, left=False)
x_ticks     = ax.set_xticks(np.arange(len(amp.columns)))
tick_labels = ax.set_xticklabels(amp.columns)
y_label     =  ax.set_ylabel('Amplitude')

Alternatively, if you just want to plot the lines and color them, it's quite simple to do with pandas plotting on amp.T with a seaborn colormap. Though I couldn't find a way to show the colorbar with this implementation

amp.T.plot(color=sns.color_palette("Set2", 8), figsize=(12,8), linewidth=3.5)
ax = plt.gca()
ax.legend(edgecolor='w', fontsize=14)
hide_spines = [ax.spines[s].set_visible(False) for s in ['top','right']]
tic_params  = ax.tick_params(axis='both', labelsize=14, bottom=True, left=False)
x_ticks     = ax.set_xticks(np.arange(len(amp.columns)))
tick_labels = ax.set_xticklabels(amp.columns)
y_label     =  ax.set_ylabel('Amplitude', fontsize=14)


text:
Q: How do I redraw my bar plot without keeping the previous one? I've made an animation in which the blue bars get updated from frame to frame. The problem is that the bars from the previous iteration stay on the canvas without being removed. How do I make the iterative plotting non-additive (non-overlapping frames like in a gif that updates everything from frame to frame)?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.ticker import AutoMinorLocator, MaxNLocator

def count_elements(iterable):

    val_dict = {}

    val_list = list(iterable)

    for i in set(val_list):
        val_dict.update({i:val_list.count(i)})

    return np.array(list(val_dict.keys())),np.array(list(val_dict.values()))

# Generate n rolls for a probability distribution of two spins of a wheel of fortune that has 4 equally large wedges. The wedges have numbers from one to 4 on them.
p = 0.25
prob_dist = np.array([[2,3,4,5,6,7,8],[p*p,2*p*p,3*p*p,4*p*p,3*p*p,2*p*p,p*p]])
mu = sum([prob_dist[0,i]*prob_dist[1,i] for i in range(prob_dist.shape[1])])
sig = sum([prob_dist[1,i]*(prob_dist[0,i]-mu)*(prob_dist[0,i]-mu) for i in range(prob_dist.shape[1])])

# true distribution
fig, ax = plt.subplots(figsize=(7,4))
ax.bar(prob_dist[0], prob_dist[1], width=0.5, align="center", ec=None, color='red', alpha=0.5)

# Experimental data
n = 10
rolls = np.random.randint(1,5,n) + np.random.randint(1,5,n)
exp_vals, exp_count = count_elements(rolls)
ax.bar(exp_vals,exp_count/n, width=0.3, align="center", ec=None, color='blue', alpha=0.5)

def update(frame):

    n = int(10 *1**frame)
    rolls = np.random.randint(1,5,n) + np.random.randint(1,5,n)
    exp_vals, exp_count = count_elements(rolls)

    ax.bar(exp_vals,exp_count/n, width=0.3, align="center", ec=None, color='blue', alpha=0.5)

ani = FuncAnimation(fig, update, frames=range(1,10),repeat=False,blit=False,interval=1000)
plt.show()

A: It seems you only update the height of the bars, so you should do exactly that - update the heights of the bars:
...
# true distribution
fig, ax = plt.subplots(figsize=(7,4))
ax.bar(prob_dist[0], prob_dist[1], width=0.5, align="center", ec=None, color='red', alpha=0.5)
#store the x-values
all_x_vals = prob_dist[0]

#catch the bar container for the update in the animation loop
bc = ax.bar(all_x_vals, 0, width=0.3, align="center", ec=None, color='blue', alpha=0.5)

def update(frame):
    #not sure what this is as it will always be 10
    n = int(10 *1**frame)
    rolls = np.random.randint(1,5,n) + np.random.randint(1,5,n)
    exp_vals, exp_count = count_elements(rolls)

    heights = np.zeros_like(all_x_vals)
    heights[np.in1d(all_x_vals, exp_vals).nonzero()[0]] = exp_count/n

    for b, h in zip(bc, heights):
        b.set_height(h)

    #sanity check, should be 1
    #print(sum(b.get_height() for b in bc))

ani = FuncAnimation(fig, update, frames=range(0,10),repeat=False,blit=False,interval=1000)
plt.show()


text:
Q: Objective-C function argument and static variable same name I am having some issue about naming overridings of static variables in objective-c.
My .h file is:
    #import <Foundation/Foundation.h>

@interface FetchClass : NSObject

+ (void)initWithNSManagedObjectContext:(NSManagedObjectContext *) managedObjectContext;
@end

And my .m file is:
static NSManagedObjectContext * managedObjectContext;

    @implementation FetchClass

    + (void)initWithNSManagedObjectContext: (NSManagedObjectContext *) managedObjectContext{
        FetchClass.managedObjectContext = managedObjectContext;
    }

However, I get the error
"Property managedObjectContext not found on object of type FetchTasks"
So, the problem is, function argument managedObjectContext is of course overriding the static variable of the same name. That is why I have to get the static variable through Class.staticVariableName. But this time I get error as I mentioned above.
However If I change the static variable name to some other name , like:
static NSManagedObjectContext * managedObjectContextOtherName;

@implementation FetchClass

+ (void)initWithNSManagedObjectContext: (NSManagedObjectContext *) managedObjectContext{
    managedObjectContextOtherName = managedObjectContext;
}

It works perfectly.  My question is that, how to use these variables (static variable and function argument variable) if they have same name?

A: A static variable, like your managedObjectContext, is the closest thing to a class variable that Objective-C provides but it is not the same thing and this is why you get errors doing what you are trying - you cannot resolve your reference by qualifying it with the class name.
In (Objective-)C a static variable declared outside of any function/method has global lifetime and file scope - i.e. the variable always exists but is only visible from within the same source file as its declaration. There is no "file scope" qualifier you can use to resolve ambiguity/hiding when reference a static, any variable with the same name in an inner scope will hide the static.
In your case you can just use:
+ (void)initWithNSManagedObjectContext:(NSManagedObjectContext *)_managedObjectContext
{
   managedObjectContext = _managedObjectContext;
}

(And there is no need to change your declaration of initWithNSManagedObjectContext: in the interface - parameter names are not required to match - so your "public" declaration doesn't require _'s in the names if you don't wish it to.)

A: Method arguments and instance variable should have different names. When they are the same, the compiler should warn you that it using the method variable.


text:
Q: Connect or Express middleware to modify the response.body I would like to have a middleware function which modifies the response body.
This is for an express server.
Something like:
function modify(req, res, next){
  res.on('send', function(){
    res.body = res.body + "modified"
  });

  next();
}

express.use(modify);

I don't understand what event to listen for.  Any help or documentation would be appreciate.

A: Overwriting the response's write method seemed to work for me with Express 4. This allows modifying the response's body even when it's a stream.
app.use(function (req, res, next) {
  var write = res.write;
  res.write = function (chunk) {
    if (~res.getHeader('Content-Type').indexOf('text/html')) {
      chunk instanceof Buffer && (chunk = chunk.toString());
      chunk = chunk.replace(/(<\/body>)/, "<script>alert('hi')</script>\n\n$1");
      res.setHeader('Content-Length', chunk.length);
    }
    write.apply(this, arguments);
  };
  next();
});

Just make sure to register this middleware before any other middleware that may be modifying the response.

A: You don't need to listen to any events. Just make it
function modify(req, res, next){
  res.body = res.body + "modified";

  next();
}

And use it after you use the router. This way after all your routes have executed you can modify the body

A: I believe the OP actually wants to modify the response stream once a middleware has handled the request. Look at the bundled Compress middleware implementation for an example of how this is done. Connect monkey patches the ServerResponse prototype to emit the header event when writeHead is called, but before it is completed.

A: There seems to be a module for doing just this called connect-static-transform, check it out:
https://github.com/KenPowers/connect-static-transform

A connect middleware which allows transformation of static files before serving them.

And it comes with examples, like this one.

A: express-mung is designed for this.  Instead of events its just more middleware.  Your example would look something like
const mung = require('express-mung')

module.exports = mung.json(body => body.modifiedBy = 'me');


text:
Q: $2D$ random walk stopping time A $2D$ random walk starts at $(X_0, Y_0) = (k, k)$ where $k>0$ is an integer.
At each step $(X_{n+1}, Y_{n+1}) = (X_{n}-1, Y_{n})$ or $(X_{n+1}, Y_{n+1}) = (X_{n}, Y_{n}-1)$ with the same probability. The process stops when $X_n = 0$ or $Y_n=0$. Let $t$ be the number of moves before stopping. I want to calculate $\Bbb E(t)$. A straight forward calculation gives $$\Bbb E(t) = 2k(1-\frac{C(2k, k)}{2^{2k}}).$$
Apparently there is an elegant solution using martingales.
So far, I've shown that $X_n + \frac{n}{2}$, $Y_n+\frac{n}{2}$ (and their combinations such as $X_n - Y_n$), $(X_n-Y_n)^2 - \frac{n}{2} $, $\frac{C(X_n+Y_n, X_n)}{2^{X_n+Y_n}}$ and $\alpha^{-X_n}\beta^{-Y_n}$ (where $\alpha+ \beta = 2$) are martingales.


text:
Q: Apache POI word table giving OOM exception on large set of data I am using apache poi to generate Word from jdbc query . It works fine for 4000 records but once we inserted 17000 records in the table, I started getting Java Out of Memory space . I am getting all the data in one shot as shown below , is there a way to insert rows in word table in batches or any other optimized way which I am missing.
This is my driver code which gets in table name and HttpServlet and passes it to class which implements ResultSetExtractor.
public void generateWord(String tableName, HttpServletResponse response, String[] filter) throws DataAccessException, IOException {
        //Table validation logic
        String sql = "select * from table";
        mainJdbcTemplate.query(sql, paramMap,
                new StreamingWordResultSetExtractor(response.getOutputStream(), tableName));
    }

Custom class which implements Result Set extractor . I get in all the result set data and use poi to generate Word.
public class StreamingWordResultSetExtractor implements ResultSetExtractor<Void> {

    private final OutputStream os;
    private String tableName;

    /**
     * @param os the OutputStream to stream the Excel to
     */
    public StreamingWordResultSetExtractor(final OutputStream os, final String tableName) {
        this.os = os;
        this.tableName = tableName;
    }

    // Set Custom Font Size
    static void setFontSize(XWPFTableCell cell, int size) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontSize(size);
            }
        }
    }

    // Set table cell as link
    static void setLink(XWPFTableCell cell, String text, String link) {
        XWPFParagraph paragraph = cell.addParagraph();
        XWPFRun run = paragraph.createHyperlinkRun(link);
        run.setText(text);
        run.setUnderline(UnderlinePatterns.SINGLE);
        run.setColor("0000FF");

    }

    // Set table style
    static XWPFStyle createTableStyle(XWPFStyles styles, String styleId) {
        //omitting code
        return style;
    }

    @Override
    public Void extractData(ResultSet rs) throws SQLException, DataAccessException {

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnsNumber = rsmd.getColumnCount();

        log.info("Generating Word");
        XWPFDocument document = new XWPFDocument();

        // Set page orientation
        CTDocument1 ctDocument = document.getDocument();
        CTBody ctBody = ctDocument.getBody();
        CTSectPr ctSectPr = (ctBody.isSetSectPr()) ? ctBody.getSectPr() : ctBody.addNewSectPr();
        CTPageSz ctPageSz = (ctSectPr.isSetPgSz()) ? ctSectPr.getPgSz() : ctSectPr.addNewPgSz();
        ctPageSz.setOrient(STPageOrientation.LANDSCAPE);

        // set paper size A3
        ctPageSz.setW(java.math.BigInteger.valueOf(Math.round(23.4 * 1440))); // 16.5 inches
        ctPageSz.setH(java.math.BigInteger.valueOf(Math.round(16.5 * 1440))); // 11.7 inches

        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(tableName);

        // Creating Table with 1 row and as many columns as in the result set
        XWPFTable table = document.createTable(1, columnsNumber);

        // Get header Row
        XWPFTableRow header = table.getRow(0);
        // Set header columns
        for (int col = 0; col < columnsNumber; col++) {
            header.getCell(col).setText(rsmd.getColumnLabel(col + 1));
            // header.getCell(col).getCTTc().addNewTcPr().addNewShd().setFill("0394fc");
            setFontSize(header.getCell(col), 8);

        }
        // Repeat header on every page
        header.setRepeatHeader(true);
        // Set data rows
        while (rs.next()) {
            XWPFTableRow desRow = table.createRow();
            for (int col = 0; col < columnsNumber; col++) {
                final var value = rs.getObject(col + 1);
                String v = value == null ? "" : value.toString();

                if (v.startsWith("<a")) {
                    Document doc = Jsoup.parse(v);
                    Elements rows = doc.getElementsByTag("a");
                    String text = "";
                    for (Element element : rows) {
                        text = element.text();
                        String href = element.attr("href").trim();
                        String encURL = "";
                        encURL = UriUtils.encodePath(href, StandardCharsets.UTF_8);
                        setLink(desRow.getCell(col), text, encURL);
                        setFontSize(desRow.getCell(col), 7);
                    }

                } else {
                    desRow.getCell(col).setText(v);
                    setFontSize(desRow.getCell(col), 7);
                }
            }
        }

        table.removeBorders();
        XWPFStyles styles = document.createStyles();
        XWPFStyle style;
        style = createTableStyle(styles, "ListTableStyle");
        table.setStyleID(style.getStyleId());
        try {
            document.write(os);
            document.close();
            log.info("Word generation complete");
        } catch (IOException e) {
            log.error("Error occurred: {0}", e);
        }
        return null;
    }

}

A: First make sure that ResultSet rs fetches the data lazily (depending on your configuration the whole query will be in memory and/or will not be freed when doing rs.next). Read more about this jdbc behavior.
With this, you can be sure that your jdbc query consumes very little memory.
On the other hand, the XWPFDocument class store all intermediate data in memory:
public class XWPFDocument extends POIXMLDocument implements Document, IBody {
    private static final Logger LOG = LogManager.getLogger(XWPFDocument.class);

    protected List<XWPFFooter> footers = new ArrayList<>();
    protected List<XWPFHeader> headers = new ArrayList<>();
    protected List<XWPFHyperlink> hyperlinks = new ArrayList<>();
    ...

then, you cannot use that class to generate your file in a streaming fashion way.
Now your processing limit is the memory used by this class.
If it consumes a lot of memory (which is likely), a dirty way is generate multiple output files and join these using some other utility or (since they are xml) join ciertain xml elements directly.
If you can generate an spreadsheet instead doc, you can use the streaming version SXSSFSheet.