text:
Q: Dynamic queue creation with RabbitMQ I've been learning RabbitMQ various topologies, however, I couldn't find any reference to dynamic queue creation (aka Declare Queue) emitted from a producer.
The idea would be to create queues dynamically depending on a particular event (e.g a HTTP request). The queue would be temporary with a TTL set and named after the event ID.
A consumer could then, subscribe to the topic "event.*" and merge all the messages related to it.
Example:

*

*HTTP POST "Create user" received

*producer creates a queue user.ID

*push all the subsequent messages concerning the user in his queue (e.g "Add username", "Add email" ...)

*worker gets assigned to a random queue "user.*" and merges everything into a user account

*queue is automatically deleted after the TTL expired

Now, is this scenario feasible with RabbitMQ ?

A: Essentially, what you want to do is use RabbitMQ to buffer messages waiting in a set of queues (which is what a message queuing system does by definition). :)
Assuming you know what your queues are from the consuming side, you won't have any issues.  There is no constraint that a producer can't create a queue. As a caveat, when queues expire, all messages in the queue are discarded (or optionally, they can be set to go to a dead-letter queue).
What code have you tried?
Edit
Upon further clarification (from your comment) - you are looking for "wildcard consuming" vs wildcard publishing. RabbitMQ does not support such a topology at the present time (this post asks for a similar feature).
What you would need to do is periodically enumerate the queues (using the RabbitMQ API); following that, your app could decide which ones to consume from. When a queue is deleted, the consumer is automatically closed.
Special Note
It should be understood that what is being asked here is an anti-pattern. The typical behavior of a system using queues is to route messages to queues based upon content. Thus, a properly-orchestrated system would have a set of workers operating on one or more statically-defined queues. Different workers may take different queues, depending upon specialization. When a series of interactions results in messages being published to the queue, the workers assigned to the queues will handle the messages in a first-come-first-served fashion (but, as this post discusses, order cannot be guaranteed with multiple consumers). The desired system behavior then emerges as a composition of workers performing various functions operating on queues.


text:
Q: SQL Server stops sending records We have a very complex analysis process with multiple variables and thousands of records that would normally generate trillions of permutation records in tempdb.  Through preprocessing and dynamic SQL we've been able to complete an analysis in a few seconds and with only a few thousand records in tempdb (instead of trillions).
The code has been in use for several years.  Today one of the variable inputs grew to double its traditional size and SQL Server was uanble to finish running the code.  It will just stop sending data for one of the preprocessing steps.  The full code is much to lengthy and complex to include here, but to illustrate what is happening:
/* Lots of SQL code */

print 'debug 1'

select distinct field
from   #table

print 'debug 2'

select   several..fields
from     many..tables..joined..with..temp..tables
where    multiple..conditions
group by several..fields

print 'debug 3'

If we execute the code in SSMS (running on the DB server), we can simply run the code down to the print 'debug 2' line and the are 330 records returned from the select distinct field statement instantly.
If we run all the code, only 290-325 (or so) records are returned from the select distinct field statement, and then the database server's CPU starts to thrash.  It will never return the rest of the 330 records and debug 2 is never printed to the Messages tab/window.  Even when we abort the query after running for hours, there are fewer than 330 records in the Result tab/window and debug 2 is not printed.
It's like the second select statement makes SQL Server unable to finish returning all of the rows for the first select statement.
I compared the query plan of both (with and without the last statement) and they are identical up to the print 'debug 2' line.  I tried adding indexes to the #temp tables, updating statistics in the db, and moving the last select statement to a stored procedure to help isolate the code.  Nothing helps.
Has anyone seen Microsoft SQL Server 2008 R2 (SP1) just stop sending records during the middle of executing a SQL statement?  What did you do to fix it?

A: Sounds like the data is stuck in a buffer somewhere to me.
Replace the PRINTs with RaisError('Debug n', 0, 0) WITH NOWAIT and see if that changes things.
PS: Your intro made me really, really, really curious for the actual code =P

redpajama_set_name: RedPajamaStackExchange


text:
Q: Feature scaling/normalization on data which has the same unit of measurement(ex. cm) In my understanding of feature scaling/normalization you need to do this, because of different measurement units inside the features and bring them to a uniform scale. And in my opinion this only belongs to data of different measurement units (ex. ft, quantity, kg, ...).
But I am unsecure if I can use data of the same unit of measurement (centimeters) without scaling, especially if I want to use distance measures.
The datasat which I use is the iris dataset (https://www.kaggle.com/datasets/uciml/iris) which consists of 4 features, but all of them are measured in centimeters. So do I need to scale or not?
The algorithm I want to use is the k nearest neighbor, a distance based algorithm.


text:
Q: Filter emails by attachment type "Email Attachment" How to filter emails in outlook 2010 for emails that has another email attached to it?
The question Search for email containg attachment of specific file type describes how to filter for excel attachments as xlsx hasattachment:true or ext:xlsx, so how is an email type defined?

A: There is no out-of-the-box way to do that. But you can go another way. What you need to do is to create a VBA macro that will iterate through your emails and set some custom property to flag that a message has email(s) attached. After that you'll be able to search your emails using this custom property.


text:
Q: IPA file size Flash Builder export i'm going to build an IOS app for the IPad, and i made a quick test.api. My issue is that the size of the file is already 13 MB big. i added a video and a sound for testing (together like 9 MB) so i was wondering is there a minimum file size when making a ipa in Flash Builder?
Maybe around 4 MB?
13MB - 9MB = 4 MB?
and then 4MB is the standard ipa size.

A: Flex/AS3 mobile apps must include the SDK in  the output in order to run.  It is referred to as "Captive Runtime" and is an option on Android, but mandatory on iOS. Essentially, they are native apps that run as virtual machines that allow you to display your AS3/Flex apps on the device without a hint of Objective-C or Java. Those SDKs are far from small. If you look in %FlashBuilder Install Directory%/sdks/, you'll see that those SDKs can be close to 1GB in size. Obviously, that doesn't all get included, but from my experience, the smallest IPA I have ever created was around 8MB.
I don't have a solid answer for what the absolute minimum size of those SDKs are, and Google turned up nothing, but my guess would be somewhere between 4-8MB, depending on if you used Flex or not.


text:
Q: Bash Password Special Character Checker So basically im trying to make my password validator check my password to see that it contains exactly one and only one of the special character (@$#!*&)
So far I got it so that it can identify if there is no special character in the parameters which is below, but i cannot seem to figure out how to make a statement that would make it so that it can identify that their is only one special character in the password.
if [ `echo $password | grep -c -E "[@#$%&*+-=]+"` -eq 0 ]; then
echo "Error"
fi

A: To verify that there is one and only one character from the group @#$%&*+-=, run:
p=${password//[^@#$%&*+=-]/}; [ "${#p}" -eq 1 ] || echo "Error"

Note that in the regex [^@#$%&*+=-], the place in which the - appears is important.  It must be either the first character (after the ^) or the last character.  If it is in the middle, it would be interpreted as indicating a range of characters.
Alternatively, to verify that there is one or more of those characters:
[ "${password//[^@#$%&*+=-]/}" ] || echo "Error"

As for the other tests that you mentioned in the comments:

*

*To verify that there is at least one lower case letter:
[ "${password}" = "${password^^}" ] && echo "Error"

${password^^} converts all the characters to upper case.  If this leaves password unchanged, then there were no lower-case letters and Error is displayed.

*To verify that there is at least one upper case letter:
[ "${password}" = "${password,,}" ] && echo "Error"

${password,,} converts all characters to lower case.  If this leaves password unchanged, then there were no upper case characters and Error is displayed.

*To verify that there is at least one number:
[ "${password//[^0-9]/}" ] || echo "Error"

${password//[^0-9]/} removes all non-numbers from password.  If there are no characters left after this, then Error is displayed.
All these tests are based on bash parameter expansions.


text:
Q: Environment variable in Azure function is not retrieved I have an Azure function. It should retrieve some environment variables values like this:
   string username = Environment.GetEnvironmentVariable("BASIC_AUTH_USERNAME", EnvironmentVariableTarget.Process) ?? _config["BASIC_AUTH_USERNAME"] ?? _config["Values:BASIC_AUTH_USERNAME"];

For local testing, the variables are set in local.settings.json:
{
  "IsEncrypted": false,
  "Values": {
     "BASIC_AUTH_USERNAME": "Set in Azure. For development, set in User Secrets (secrets.json)",
  ...
  }
}

In Azure, I set corresponding variables in the release pipeline:
- stage: Production
dependsOn: QA
variables:
- group: Production

Everything seems to be in place, and yet when I run the Azure function via Postman, the username is null. What can I be missing?

A: The variables from ADO are available as env vars inside your build agent. But you need to configure your Azure Function deployment task to pass whatever config vars you want to have there.
Assuming you use the Function Deploy task, look for appSettings: https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-function-app?view=azure-devops


text:
Q: How to mix down 2 audio file into one programmatically on Mac I have 2 audio file, and want to mix down them into one file programmatically on my Mac.
I would like to write a script using a command line tool, or write a application using an audio lib. But I cannot find a command line tool or an audio lib to do that. Does anyone have some ideas?

A: You can use ffmpeg. I installed mine with homebrew which makes life easier on a Mac. Then you can do the actual mix like this:
ffmpeg -i track1.mp3 -i track2.m4a -filter_complex amerge output.mp3

another option is:
ffmpeg -i track1.mp3 -i track2.m4a -filter_complex amix=inputs=2:duration=longest output.mp3

Or you can use sox, like this:
sox -m a.mp3 b.mp3 output.mp3

Note: Mixing down AC/DC with ABBA to test what I am suggesting does not produce a goood sound!!!


text:
Q: Realm Java prepackaged database I am trying to put a preloaded Realm database in my app.
What I am doing:

*

*I created a simple app that loads data from JSON to the Realm database (default1.realm).

*I have my actual app, where I am trying to put the default.realm file created by the loader in the res/raw folder and using the Migration Examples copyBundledRealmFile() function to copy default.realm to getFilesDir().

*After doing all this, when I try to do Realm.getInstance() then an empty Realm is returned.
What am I doing wrong?
String path3 = copyBundledRealmFile(this.getResources().openRawResource(R.raw.default1), "default.realm");

Realm r1 = Realm.getInstance(this);

r1 should point to the file I copied, right?
UPDATE: I found why I could not access the database:
03-27 10:27:50.965  17750-17750/? A/art﹕ art/runtime/check_jni.cc:65] JNI DETECTED ERROR IN APPLICATION:
input is not valid Modified UTF-8: illegal continuation byte 0x2e
03-27 10:27:50.965  17750-17750/? A/art﹕ art/runtime/check_jni.cc:65]     string: 'Unspecified exception.
Failure when converting long string to UTF-16 error_code = 2; retcode = 0; StringData.size = 40487; StringData.data = etc..

03-27 10:27:50.965  17750-17750/? A/art﹕ art/runtime/check_jni.cc:65] JNI DETECTED ERROR IN APPLICATION:
input is not valid Modified UTF-8: illegal continuation byte 0x2e
03-27 10:27:50.965  17750-17750/? A/art﹕ art/runtime/check_jni.cc:65]     string: 'Unspecified exception.
Failure when converting long string to UTF-16 error_code = 2; retcode = 0; StringData.size = 40487; StringData.data =

My question would be now why is this error happening?

A: You say that your file is named default.realm and yet you refer to it as default1 in the snippet above. Does it work if you try with default?


text:
Q: Solutions for confounding by indication In clinical trials, treatment and non-treatment groups go through random allocation, in the hope that characteristics of both groups are similar at baseline. If there are any baseline differences they can be added as covariates to adjust for them, eg in ANCOVA.
When comparing treatment effect in observational studies, where two groups differ at baseline, I understand this approach is not suitable. Propensity score matching is a popular approach. My questions are:

*

*Why can't observational studies adjust for baseline differences by adding them as covariates?

*What are other alternatives to propensity score matching and their benefits?

*Imagine a flipped example: In an observational study of N number of people on treatment X, I want to compare response to treatment X between alcohol drinkers and non-drinkers. I hypothesise that drinkers will respond less well. I know that drinkers have worse disease at baseline, so this difference needs to be adjusted. I can pretend that drinking is the "treatment" and use propensity score to match drinkers and non-drinkers for baseline disease severity. However this analogy seems to me not completely correct, as drinkers will have been drinking long before they started treatment (c.f. in an observational study comparing treatment effect, the individual will have worse disease before they start treatment). Therefore is PSM unsuitable, and if so what are the alternatives?

A: 1) They can! The problem is that if the functional form of the relationship between the covariates and the outcome is not exactly as you specify in the regression/ANCOVA, then you arrive at a biased and inconsistent estimate of the treatment effect. This matter is discussed in many articles, but the key articles for this are Schafer & Kang (2008) and Ho, Imai, King, & Stuart (2007). Another issue (mentioned in Schafer & Kang) is that if there is effect modification (the effect of treatment differs across levels of a covariate), but you only care about a marginal treatment effect (i.e., over an entire population receiving a policy change), then the effect cannot be estimated with regression  (i.e., because if you include an interaction term with treatment, then the base treatment coefficient will not equal the causal effect).
2) Other approaches include inverse probability weighting, stratification, and other non-propensity-score-based matching techniques. Inverse probability weighting uses propensity scores to compute weights which are applied to your data set to create a pseudosample in which the covariates are balanced; the weights are then used in WLS regression to get a treatment effect. Stratification by the propensity score involves estimating a propensity score and creating strata based on quantiles of the propensity score. Under ideal conditions, there will be covariate balance within each stratum, and you can compute and then average stratum-specific causal effects to arrive at an average effect estimate. There are also other matching methods that don't involve propensity scores: Mahalanobis distance matching, genetic matching, and coarsened exact matching come to mind.
3) There is a technique called marginal structure models (MSM) with time-varying treatments that might be of use. Essentially, you have three timepoints: at t1, people are "assigned" to being a drinker or not; at t2, people are "assigned" to being in treatment or not, and this assignment depends on treatment assignment at t1. Finally there is the outcome. Using MSM, you can estimate counterfactual means for the outcome for a given treatment "history". You are probably interested in all four combinations resulting from a complete cross of drinking and treatment. Then you can compare those means however you like to arrive at the effect of interest. For example, for the effect of treatment in those who are drinkers, you could calculate the difference in the means between the those who received treatment history (drinker, treatment) and those who received treatment history (drink, control).


text:
Q: Reusing a parameter in hibernate Restrictions.sqlRestriction? Let's say I would like to do
SELECT * from T where X < 12345 AND Y < 12345

using Restrictions.sqlRestriction. The constant that X and Y are being compared to is the same in my case. Ideally, I would want to pass it along to the sqlRestriction only once, and reference it by its index in the argument list. Is this possible?
I could pass it along twice, like this:
Restrictions.sqlRestriction("X < ? AND Y < ?", {12345, 12345}), but I'm asking if there is a more elegant syntax, Similar to how C#'s WriteLine allows stuff like
Console.WriteLine("This {0} appears here also {0}", 12345)

A: Try to use the hibernate functions instad writing the query "by hand".
For example:
Query query = session.createQuery("SELECT t FROM T t WHERE t.X < :maxValue AND t.Y < :maxValue");
query.setInteger("maxValue", 12345);
query.list()


text:
Q: Is there a verb for "Pass through a hoop?" I am looking for a verb that means "To pass through a hoop", either figuratively or literally. Similar to what dolphins do in those water parks, or to someone having to do something he does not want to because of the situation he is in.
Is there something similar to what I'm looking for?

A: The phrase jump through hoops is a figurative expression that means what you are asking about

Perform a difficult and grueling series of tests at someone else's request or command:
  we had to jump through all sorts of hoops to win accreditation

A: How about "traverse?"

traverse: to move or pass along or through.
"Those who wish to pursue citizenship should be able to bid their time and traverse the hoops that they would need to."
"We want the hiring process to happen easily, almost magically,
  without having to do research or traverse hoops."

Also, consider "buck through," "put on a bold/brave face
," and "make the best of a bad situation."

"He felt very strange, and decidedly shy; but put on a bold face, and let nobody guess that, though nearly thirteen, he had never been to school."
"I think we'll try to buck through without any
  borrowings for a while."
"Paul has made the best of the situation and blossomed in a variety of ways."

A: Literally, we can jump or leap through hoops.
Figuratively, we can endure or grind through unwanted situations. Endure particularly matches your request, because it means to persist in spite of ourselves or some other undesirable effect, like dolphins at a water park. One can also persevere (more positive) or grind (more negative) through hardship.


text:
Q: Delete whole Array in C I'm new to C and I'm wondering if it is possible to delete a whole array, not just an element, in C?
In C++ there is the delete[], is there something similar in C?

A: You can just use free to delete a dynamically allocated array.
int* array = malloc(10*sizeof(int));
...
free(array);

If you allocated memory for each array element, you'll also need to free each element first.
char** array = malloc(10*sizeof(char*));
for (int i=0; i<10; i++) {
    array[i] = malloc(i);
}
....
for (int i=0; i<10; i++) {
    free(array[i]);
}
free(array);

A: When you allocate memory in C using malloc, some extra information is stored after (or before) the allocated chunk. free uses this information to know how much memory you allocated in the first place and will free the entire chunk.
So if you allocated only a single element, for example a struct, it will only free one element. If you allocated an entire array of struct, it will free the entire thing.
In C++, you use new and new [] instead of malloc, which initializes values using constructor. Which is why there are two distinct delete: one for single value (delete), and one for arrays (delete []).

A: 1) If the declartion of your array was done in this way:
int A[20];

Your array could not be deleted because it's allocated statically
2) If the declartion of your array was done in this way:
int *A=malloc(20 * sizeof(int));
//or
int *A=calloc(20, sizeof(int));

Your array could be deleted with free(A) because it's allocated dynamically

A: If you've allocated the array dynamically (with malloc()), you just use free() to de-allocate it. Then you can no longer access the pointer, since you no longer "own" the memory.

A: In C++, you don't call delete unless you've used new. If you didn't use dynamic allocation, you don't free the memory.
In C, have a look at malloc and free if you want to control the lifetime of your arrays.
#include <stdlib.h>

int *array = malloc (size_in_bytes);

/* Some stuff. */

free (array); /* When I don't need it anymore. */

Otherwise, automatic variables are automatically released.

A: If you used malloc()/calloc simply use free():
type * ptr = malloc(n * sizeof(type));
if(ptr == NULL)
    couldnt_allocate_memory();
/* ... */
free(ptr);

A: Creation of the tab : malloc or calloc functions. And then free function to deallocate it

A: In C, if you are declaring your array as static
ex: int a[10], no need to delete. It will be freed when your function ends or program terminates. If you have allocated memory using any of memory allocation techniques[malloc,calloc], since it is allocated by you, should be freed by yourself and you use free(ptr) for freeing allocated memory block.


text:
Q: font size not changing in media query in css I have this html code:

filler

 Who's cuter? Click to Choose.

and this is my css media query:
@media screen and (min-width: 700px) {
  .guide {
    font-size: 25px;
    color: blue;
  }
}

The color changes to blue but the font size doesn't. Any help is appreciated.

A: You have inline styles on children of the .guide div. Try adding rules to those elements in your media query:
@media screen and (min-width: 700px) {
  .guide,
  .guide h1 b,
  .guide h2 b {
    font-size: 25px !important;
    color: blue;
  }
}

A: Your CSS in media-query is overwritten by your inline-CSS applied in your html.
You can use !important in your external CSS.
@media screen and (min-width: 700px) {
  .guide {
    font-size: 25px !important;
    color: blue;
  }
}

However, the !important rule is most times considered a bad practice. A better solution could be to use no inline-CSS at all and include it all in your external CSS.
Check here: Does embedded css always override external css?

A: It's not working because you have added inline css in HTML code, which has the highest priority.
Remove inline CSS from your html code. and it will work.

 Who's cuter? Click to Choose.

A: Please try with this code.

.title {
  font-size: 3vw;
}
.text {
  font-size: 3.2vw;
}
@media screen and (min-width: 700px) {
  .title,
  .text {
    font-size: 25px;
    color: blue;
  }
}

    filler

    Who's cuter? Click to Choose.

It will work.
Best regards.

A: Remove inline styles and use class selectors for the same and that way your css rules will take effect.

A: your code not work beacuse you use inline-Css
try this code :
html :

    filler

    Who's cuter? Click to Choose.

and Css :
 .title {
        font-size: 3vw;
      }
      .text {
        font-size: 3.2vw;
      }
      @media screen and (min-width: 700px) {
        .title,
        .text {
          font-size: 25px;
          color: blue;
        }
      }


text:
Q: How do you print within a for loop without starting a new line? I have written some code for a program which will find Pascal's triangle. However, the formatting is not coming out as I would have hoped. My code is as follows:
    def factorial(n):
        """Calculate a factorial"""
        p = 1
        for i in range(1, n+1):
            p = p * i
        return p
def binomial(n, k):
    """Calculate n choose k"""
    y = int(factorial(n)/(factorial(k)*factorial(n-k)))
    return y

a = int(input("How many rows of Pascal's triangle do you want?: "))
for j in range(a):
    for i in range(j + 1):
        n = (a-1)-j
        print(" "*n, binomial(j, i), end=" ")
    print("")

Thanks to the for loop doing the " "*nbit before every i in range(j+1), instead of getting a nice pascal's triangle:
     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1

I get:
     1
    1     1
   1    2    1
  1   3   3   1
 1  4  6  4  1

Is there anything I can do to help with this formatting error? I tried putting the n = (a-1)-j and print(" "*n) bit outside the for i in range(j+1) and inside just the for j in range(a), to see if this would only indent the text once, but this created a new line. What should I do?

A: Yet again I post after struggling for hours only to find the answer within minutes...
Here I fixed the problem of the recurring spacing by adding an if command into the code like this:
def factorial(n):
    """Calculate a factorial"""
    p = 1
    for i in range(1, n+1):
        p = p * i
    return p

def binomial(n, k):
    """Calculate n choose k"""
    y = int(factorial(n)/(factorial(k)*factorial(n-k)))
return y

a = int(input("How many rows of Pascal's triangle do you want?: "))
for j in range(a):
    for i in range(j + 1):
        if i == 0:
            n = (a-1)-j
            print(" "*n, binomial(j, i), end=" ")
        else:
            print(binomial(j, i), end=" ")
    print("")

This ensured that the initial indentation by (a-1)-j only happened for the first incidence of the for loop.


text:
Q: programmatically show the logcat -b radio on app I need to read and filter "logcat -b radio" log within my application
So I tried to write my code, but the result is empty. My cellphone has Android 6.0, please your help!


text:
Q: pip installed scripts in ~/.local/bin with outdated shebangs A while ago I installed several packages using pip with the --user option, with the result that I have several scripts in ~/.local/bin which have the hardcoded shebang
#!/usr/bin/python3.3

However, in the meanwhile, my Python distribution has been upgraded to Python 3.4, with the result that these scripts don't work anymore.
How do I upgrade these scripts to point to the new Python version?
I tried uninstalling and reinstalling the package in question, but this script never seems to get removed. Likewise, pip install --upgrade does not touch the scripts.


text:
Q: How to make an array in database? I create an a array of wordsParasits in firebase:
   set(ref(db, 'users/' + res.data.localId), {
            ArrOfParasites: [],
}

How can i update it?
If i try like this, it doesn't work:
  update(ref(db, 'users/' + user.localId), {
    ArrOfParasites: filteredArr.push()
// if i try this, outpi looks like: ArrOfParasites : 4
}

Filtered array looks like:
[["блин", 1], ["допустим", 1], ["фактически", 1], ["получается", 1]]

I need to update all array in firebase db


text:
Q: JSON Object broken using json_encode when apostrophies are present Here's the situation:
My program accepts input entered by users into a form and saves it in a MYSQL database using PHP's PDO with Prepared Statements.
The data is retrieved via an AJAX call and encoded to JSON using json_encode, like so:
echo "<script> var jsonData = '". json_encode($profileData) . "';</script>";

Then parsed using JQuery:
var Profile = jQuery.parseJSON(jsonData);

This works fine, until a user enters a ' char.
i.e. If a user enters the word

I'm

It would be escaped and stored in the DB like this: I\'m
Once retrieved from the DB, a JSON encoded string would look like this:
<script> var jsonData = '{"fname":"Daniel","about":"i\\'m a nerd"}';</script>

Although the ' is escaped, it seems to break the JSON.
I have seen people posting find/replace style work-arounds, but I would prefer to avoid this approach.
Surely there is some method that handles this, or am I initializing the JSON Object incorrectly somehow?
Any help much appreciated, any more info required just ask :)

A: The simplest way to solve the problem would be to omit the quotes in JS:
echo "<script> var jsonData = " . json_encode($profileData) . ";</script>";

which will result in
<script> var jsonData = {"fname":"Daniel","about":"i\\'m a nerd"};</script>

Then jsonData will already be an object and doesn't have to be parsed. Though the escaping might be a bit off then.

A:
Once retrieved from the DB, a JSON encoded string would look like this:
<script> var jsonData = '{"fname":"Daniel","about":"i\\'m a nerd"}';</script>

Although the ' is escaped, it seems to break the JSON.

Note that JSON is here concerned about escaping the backslash. Thus, the quote is not escaped - you still have to do it so as not to mess up the quotes you put around it.
echo "<script> var jsonData = '". json_encode($profileData).replace(/'/g, "\\'" . "';</script>";

A: Use the JSON_HEX_APOS parameter when you are encoding the JSON
json_encode($profileData, JSON_HEX_APOS);

This will turn the single quote into a special escape value that only JSON understands


text:
Q: Equality holds in triangle inequality iff both numbers are positive, both are negative or one is zero How do we show that equality holds in the triangle inequality $|a+b|=|a|+|b|$ iff both numbers are positive, both are negative or one is zero? I already showed that equality holds when one of the three conditions happens.

A: If $a$ and $b$ are positive, then $|a+b|=a+b=|a|+|b|$. If they are negative, then $|a+b|=-a-b=|a|+|b|$. Suppose one of them is $0$. Without loss of generality suppose $a=0$. Then $|a+b|=|b|=|a|+|b|$.
If none of the three situations occurs, then between $a$ and $b$ one is positive and one negative. Without loss of generality, suppose $a$ is positive. Suppose $|a+b|=|a|+|b|$. If $a+b\geq 0$, then $a+b=a-b$ so that $b=0$, a contradiction. If $a+b<0$, then $-a-b=a-b$ so that $a=0$, a contradiction.

A: Because $|a+b|$ and $|a|+|b|$ are nonnegative, the inequality $|a+b| \leq |a|+|b|$ is equivalent to
$$(|a+b|)^2 \leq (|a|+|b|)^2,$$
which becomes after simplification
$$ab \leq |ab|.$$
The equality clearly then holds iff $ab$ is nonnegative.

A: If we have
$$|a + b| = |a| + |b|$$
Then we have two cases. First
$$a + b = |a| + |b| \implies a-|a| =|b|-b$$
Both sides in the above are either simultaneously zero (in which $a = |a|$ and $b = |b|$) or simultaneously not zero, in which ($a \neq |a|$ and $b \neq |b|$). The first case is simultaneously positive and the second implies $|a| = |b| = 0$.
Similarly for the other case
$$ -a - b = |a| + |b| \implies -|a|-a = b+|b|$$
in which the same analysis applies.

A: If we have $|a+b | = | a | + | b|$, squaring both sides we obtain
$$|a+b|^2 = (|a| + |b|)^2$$
$$\iff a^2+2ab+b^2 = |a|^2 + 2|a||b| +|b|^2 = a^2 + 2|a||b| + b^2.$$
Finally, $$ab = |a||b| \ge 0 .$$
So that, $|a+b| = |a| + |b|$ iff $ab \ge 0$.


text:
Q: Ubuntu 20.04 not shutting down When I try to shut down my pc, it first sends me to the login page where it hangs for a few seconds, and then I get the following logs:
Stopping permit user sessions...
[Ok] Stopped permit user sessions.

Edit:
I got some logs using journalctl
jun 24 21:24:33 Q systemd[1]: user-runtime-dir@125.service: Succeeded.
jun 24 21:24:33 Q systemd[1]: Stopped User Runtime Directory /run/user/125.
jun 24 21:24:33 Q systemd[1]: Removed slice User Slice of UID 125.
jun 24 21:24:33 Q systemd[1]: Stopping Permit User Sessions...
jun 24 21:24:33 Q systemd[1]: systemd-user-sessions.service: Succeeded.
jun 24 21:24:33 Q systemd[1]: Stopped Permit User Sessions.
jun 24 21:25:42 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitiga>
jun 24 21:29:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitiga>
jun 24 21:34:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitiga>
jun 24 21:39:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitiga>
jun 24 21:44:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitiga>
jun 24 21:49:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitiga>
jun 24 21:54:31 Q systemd[1]: poweroff.target: Job poweroff.target/start timed >
jun 24 21:54:31 Q systemd[1]: Timed out starting Power-Off.
jun 24 21:54:31 Q systemd[1]: poweroff.target: Job poweroff.target/start failed>
jun 24 21:54:31 Q systemd[1]: Forcibly powering off: job timed out
jun 24 21:54:31 Q systemd-logind[1062]: Operation 'shutdown' finished.
jun 24 21:54:31 Q systemd[1]: Shutting down.
jun 24 21:54:31 Q systemd-shutdown[1]: Syncing filesystems and block devices.
jun 24 21:54:31 Q systemd-shutdown[1]: Sending SIGTERM to remaining processes...
jun 24 21:54:31 Q dnsmasq[1412]: exiting on receipt of SIGTERM
jun 24 21:54:31 Q NetworkManager[1027]: <info>  [1593028471.8127] caught SIGTER>
jun 24 21:54:31 Q systemd-journald[456]: Journal stopped
lines 994-1016/1016 (END)
jun 24 21:24:33 Q systemd[1]: user-runtime-dir@125.service: Succeeded.
jun 24 21:24:33 Q systemd[1]: Stopped User Runtime Directory /run/user/125.
jun 24 21:24:33 Q systemd[1]: Removed slice User Slice of UID 125.
jun 24 21:24:33 Q systemd[1]: Stopping Permit User Sessions...
jun 24 21:24:33 Q systemd[1]: systemd-user-sessions.service: Succeeded.
jun 24 21:24:33 Q systemd[1]: Stopped Permit User Sessions.
jun 24 21:25:42 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
jun 24 21:29:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
jun 24 21:34:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
jun 24 21:39:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
jun 24 21:44:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
jun 24 21:49:58 Q systemd-resolved[981]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
jun 24 21:54:31 Q systemd[1]: poweroff.target: Job poweroff.target/start timed out.
jun 24 21:54:31 Q systemd[1]: Timed out starting Power-Off.
jun 24 21:54:31 Q systemd[1]: poweroff.target: Job poweroff.target/start failed with result 'timeout'.
jun 24 21:54:31 Q systemd[1]: Forcibly powering off: job timed out
jun 24 21:54:31 Q systemd-logind[1062]: Operation 'shutdown' finished.
jun 24 21:54:31 Q systemd[1]: Shutting down.
jun 24 21:54:31 Q systemd-shutdown[1]: Syncing filesystems and block devices.
jun 24 21:54:31 Q systemd-shutdown[1]: Sending SIGTERM to remaining processes...
jun 24 21:54:31 Q dnsmasq[1412]: exiting on receipt of SIGTERM
jun 24 21:54:31 Q NetworkManager[1027]: <info>  [1593028471.8127] caught SIGTERM, shutting down normally.
jun 24 21:54:31 Q systemd-journald[456]: Journal stopped

running
dmidecode -s bios-version

returns F42a
I have an aorus x470 ultra gaming cf
amd ryzen 3700x
rtx 2070

A: I fixed the problem, I just reinstalled the NVIDIA drivers which solved the issue.

A: BIOS
Aorus x470 Ultra Gaming
You have BIOS version F42a.
There's a newer BIOS available, version F50, dated 11/27/2019, and can be downloaded here.
Note: Verify that I have the correct web page for your model #.
Note: Have good backups before updating the BIOS.


text:
Q: SSDT Equivalent for Oracle Database In SSDT there is a mechanism for managing DDL changes, for instance a new column or a change to a data type. Instead of putting an 'Alter Table' statement into the database project, instead we edit that original 'Create Table' statement which focuses on the final state that includes the new column. It detects the difference between older and new script and creates necessary 'Alter Table' script to use for deployment.
Is there any equivalent strategy to achieve the same in Oracle Database as I am using J2EE technologies and Eclipse IDE.

A: No it is not I am afraid, SSDT is a free tool developed by Microsoft to help SQL Server deployments. I would think it extremely unlikely that Microsoft would ever allow let alone help deployments to Oracle - it is a new Microsoft sure but some things will never change!
The best alternative is to use JetBrains datagrip  as an IDE and flyway as a deployment tool:
https://flywaydb.org/documentation/database/oracle
https://www.jetbrains.com/datagrip/
In my opinion Microsoft has created the best development environment of ANY RDBMS and throw in the redgate suite of tools and it makes the tooling a real differentiator.
Ed

A: It's not built into the IDE like SSDT is, but Redgate has comparison tools for Oracle that use the same methodology as SSDT Database Projects.
This can be used in conjunction with Redgate Source Control for Oracle, which maintains a schema model in your chosen VCS.

A: Well, there is "Oracle Developer Tools for Visual Studio" .
I haven't looked at this for 5+ years but it used to do some of the same things that the old Visual Studio Database Tools (datadude/dbproj/other names) did back then.


text:
Q: Limit on two variables approaching infinity I have a question on the limit of $$\lim_{x,y\to\infty}\frac{(x-1)(y-1)}{xy}$$
I had a look on answers and theory like the following question:
 Limit question as $x$ and $y$ approach infinity?
So if I'm getting it right, the limit must exist by approaching by any path, that is, if we make $y=x$
$$\lim_{x\to\infty}\frac{(x-1)^2}{x^2}=1$$
which also holds for $y=x^2$, but not for things like $y=x^{-2}$:
$$\lim_{x,y\to\infty}{x(x-1)(x^{-2}-1)}=-\infty$$
and thus the limit doesn't exist. Am I getting it right?
Thanks for your help!

A: HINT:
$$\lim_{x,y\to\infty}\frac{(x-1)(y-1)}{xy} = \lim_{x,y\to\infty}{(1-\frac1x)(1-\frac1y)}{}$$

A: se that $$\frac{(x-1)(y-1)}{xy}=\frac{xy-y-x+1}{xy}=1-\frac{1}{x}-\frac{1}{y}+\frac{1}{xy}$$

A: It is unclear exactly what $\lim\limits_{x,y\to\infty}f(x,y)$ means.
Your comments are correct for
$$
\lim_{x^2+y^2\to\infty}f(x,y)
$$
However, one might also consider the limit
$$
\lim_{\min(x,y)\to\infty}f(x,y)
$$
for which your argument does not work.


text:
Q: Firefox redirects https to http for some urls I'm developing an ASP.NET MVC application, and I'm getting very strange behavior in firefox 15. I'm browsing to url: https://www.mydomain.com/test, but it gets redirected to http://www.mydomain.com/test (so from https to http). In IE 9 this is not happening. I did some logging on the server side, and Request.IsSecureConnection is false in the Controller action. Does anybody have any suggestion for how to debug this type of problem?
Note that I don't necessarily need to force https, it can be either http or https, but when the user is authenticated, it should remain in https to safely transport the session ID cookie.
EDIT: I strongly suspect Firefox is caching whatever I visit first. On one machine I started (I think) with http, and there it won't let me do https on that url. On another machine (VM), I start with https, works ok, and it won't let me do http on the same url. So it looks like Firefox has some strange caching behavior.


text:
Q: I need to validate free flow textbox value matches value from database table I need to validate a given Name field in the asp.net form.
User Name: Alex Brandon
In the database, we have a users table with user_name column.
I need to validate on lost focus of User Name form field, that it exists in the users table and is valid else show an alert.
Does somebody has a ready solution to this?

A: Do you want to do it in javascript, or are you planning on a trip to the server?  If it's a trip to the server (via asp.net ajax or a postback) you'd just have to.
select * from users where user_name=@name

and set the name parameter to your textbox value...
Note that unless you care about case, you may want to uppercase the two names for comparison.


text:
Q: JAVA Eclipselink query I'm trying to write a JPA query that has 3 conditional where statements. But I don't seem to get the syntax correct.
try {
    Query findCustomerQuery = entityManager.createQuery("SELECT c FROM Customer c WHERE " +
            "CASE " +
            "WHEN :customerNumber is not null THEN (c.customerNumber = :customerNumber)" +
            "WHEN :customerName is not null THEN (c.name = :customerName) " +
            "WHEN :customerFirstname is not NULL THEN (c.firstName = :customerFirstname) ELSE (c.customerNumber = 0) END");

    findCustomerQuery.setParameter("customerNumber",customerNumber);
    findCustomerQuery.setParameter("customerName", customerName);
    findCustomerQuery.setParameter("customerFirstname", customerFirstname);
    return (Customer) findCustomerQuery.getSingleResult();

}finally {
    entityManager.close();
}

A: It is convenient to use the JPA Criteria API for these cases.
Here is an example for your case:
// get a query builder
CriteriaBuilder builder = em.getCriteriaBuilder();
// build query for entity
CriteriaQuery<Customer> criteriaQuery = builder.createQuery( Customer.class );
// set FROM entity
Root<Customer> tags = criteriaQuery.from( Customer.class );
// get a basic predicate
Predicate p = builder.and();
// add WHERE conditions properly
if (customerNumber != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerNumber"), customerNumber )
    );
    p = builder.and(p, conditionPredicate);
}
// do the same for customerName and customerFirstName
if (customerName != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerName"), customerName )
    );
    p = builder.and(p, conditionPredicate);
}
if (customerFirstName != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerFirstName"), customerFirstName )
    );
    p = builder.and(p, conditionPredicate);
}

// set predicate to query
criteriaQuery.where( p );

// call query and get results
TypedQuery<Customer> q = em.createQuery(criteriaQuery);
List<Customer> o = q.getResultList();

Here are more examples if you need


text:
Q: Python multiprocessing.Pool workers remain idle I am a beginner with Python. I am trying to run a simple function using multiprocessing.Pool, but when I run the program, it does not get processed. I can see that distinct processes are spawned, but that they remain idle. For example, the code below does does generate two worker processes but no output and nothing else:
import multiprocessing

def f(x):
    print("Process "+str(x))
    return True

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=2)
    result = pool.map(f, range(1000))

I am running Python 3.9 using Microsoft Visual Studio 2019. OS is Windows 10. I encountered the same problem using Python 3.7 on this computer. I have tried the same code on another computer (Also Windows 10, VS2019) and it works fine. The difference is that this one has an i9 Processor, while the other has an i7.
I have searched online, but I have not encountered any similar issue or any fix for my problem. Does anyone have any idea why does this happen and/or possible fixes? May the type of processor have something to do with it? Thanks!

A: This is a just a guess:
I know that this will not run under Jupyter Notebook or the interactive interpreter. See the multiprocessing docs, in particular the section:

The solution for those environments is to take your worker function, f, and place it in a separate module, for example worker.py, and to import the worker function:
import multiprocessing
from worker import f

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=2)
    result = pool.map(f, range(1000))

Give this a shot and let us know for others who also have Visual Studio whether this worked or not. Thanks.


text:
Q: How to Implement Search Functionality?

                    <?php
                    $search_term = get_search_query();
                    $term = get_term_by('slug', $search_term, 'blog_taxonomy');
                    $term_name = $term->name;
                    $args = array(
                        'post_type' => 'blog',
                        // 'title' => $search_term,
                        'tax_query' => array(
                            array(
                                'taxonomy' => 'blog_taxonomy',
                                'field'    => 'slug',
                                'terms'    => $search_term,
                                'orderby'   => array(
                                    'date' => 'DESC',
                                ),
                            ),
                        ),
                    );
                    $loop = new WP_Query($args);

                    if ($loop->have_posts()) {
                        while ($loop->have_posts()) {
                            $loop->the_post();
                    ?>

<?php the_time('j') ?>

<?php the_time('M') ?>

                                        <?php if (has_post_thumbnail($post->ID)) : ?>
                                            <?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail'); ?>
                                            <img src="<?= $image[0] ?>" alt="">
                                        <?php endif; ?>
                                        <img src="<?php echo get_template_directory_uri(); ?>/assets/images/blog/blog-logo.svg" class="blog-logo" alt="">

<?php the_title(); ?>

<?= $term_name ?>

                                            <?php $content = get_the_excerpt();
                                            $trimmed_content = wp_trim_words($content, 25); ?>
                                            <?php echo $trimmed_content; ?>

                                            <a href="<?= the_permalink(); ?>" class="cmn-btn">Explore more

                    <?php wp_reset_postdata();
                        }
                    }
                    ?>

Above is the code for my search Functionality, where I am using custom post type "blog" and custom taxonomy that is "blog_taxonomy". I am able to get results only from tax_query or title.
I want them both searchable, as user either enters taxonomy name or post title in search bar.
How to implement both ? tax_queries as well as commented 'title'.


text:
Q: upgrading to windows 10 on sony vaio with nvidia geforce GT 330m card error with incompitability Does anyone have a way to work around windows 10 upgrade error message with nvidia geforce gt330m display compatibility on a sony vaio vpcz13ahx model?

A: I found nvidia geforce gt 330m driver for windows 10 on following website.
geforce gt 330m driver for windows 10
Website claims that driver is developed by NVIDIA itself and available to public download on nvidia website.

A: Start by following this guide:
How to: A list of things to do if Windows 10 Setup fails
Just because nVidia driver is the reported cause of failure, there could be other issues contributing as well.
Other things to try:

*

*Anything in the Event Log to help diagnose?

*Any issue with drives/space/crosslinked files (chkdsk)?

*Start with a clean Windows 10 installation - we know this is not always possible

*Clean up any and all old installations

*Uninstall as much as you can from applications and applications no longer used

*Be 100% sure you are clean of Malware/Spyware/Virii

*Clean up Temp/Temporary Internet/etc.  Use a tool like CCLeaner (stay away from the Registry cleaner part of it)

*Get the driver for nVidia from the OEM, first.  Then Microsoft.  Lastly from nVidia.

After you have surety you have cleaned up the system, restart it.  Then try the installation.
If it still has an error, what happens when you try "Safe Mode with Networking"?

A: There's a good video on this by Robot on YouTube. You need to do a regedit.
HKeyLocal Machine
Software
Microsoft
Windows
WindowsUpdate
OS upgrade folder
Right-click on black space
Dword 32bit Value
Allow OSUpgrade
Value = 1
Hexidecimal (y)
Close regedit
Go to Windows Update.
Watch the video. I can't find it now, but those were the steps.


text:
Q: I have a div with a onClick handler and also buttons inside with onClick events. How do I prevent the buttons from firing the div onclick? Basically I have a list with members of your team. For every member there is an individual div, to select a member you click on the div. I have added an on click event handler on the div so that on click it selects that specific member and highlights it. I also have an edit button and a remove button inside the div for each member. However what is happening right now is that when you want to edit or remove a team member it also triggers the div onClick. I understand that this is expectd behaviour however I'm not sure how I can prevent the div onClick from firing when the buttons are clicked or how I can achieve the same 'look and feel' without putting the buttons in the div.
I want to keep the same look (a section for every teammember which can be clicked to select a team member)  but I don't mind changing the structure of the div. I'm working in React if that matters.

A: Here's a simple example of how you stop the clicks bubbling up to the parent:
const Button = () => (
  <div
    onClick={() => {
      console.log("I won't trigger if you click the inside div");
    }}
  >
    <div
      onClick={event => {
        event.stopPropagation(); // <-- this stops the click going through to the parent div
        console.log('Thank you for clicking the inside div');
      }}
    >
      I'm Inside
    </div>
  </div>
);

A: Change the onClick to:
    onClick = (event) => {
        //event.target includes the specific element which was clicked.
        if(event.target.id == '<YOUR-DIV-ID>'){
        //handler
        }
    }


text:
Q: Vuetify Lists: Creating Submenus from Array of objects I'm using Vue @2.5.17 and Vuetify @2.33 in a project. I want to create submenu only within the object which contains subLinks array. I tried using docs & many tutorials but was unable to achieve this. How could i achieve this?
Template
<v-navigation-drawer app dark class="primary" v-model="drawer">
    <v-list-item>
        <v-list-item-content>
            <v-list-item-title class="title">
                Al-Mehmood
            </v-list-item-title>
            <v-list-item-subtitle>Transport Company</v-list-item-subtitle>
        </v-list-item-content>
    </v-list-item>

    <v-divider></v-divider>

    <v-list dense>
        <v-list-item link v-for="navLink in navLinks" :key="navLink.text" :to="navLink.route">
            <v-list-item-icon>
                <v-icon>{{ navLink.icon }}</v-icon>
            </v-list-item-icon>

            <v-list-item-content>
                <v-list-item-title>
                    {{
                    navLink.text
                    }}
                </v-list-item-title>
            </v-list-item-content>
        </v-list-item>
    </v-list>
</v-navigation-drawer>

Script
data() {
    return {
        drawer: true,

        navLinks: [
            { icon: "dashboard", text: "Dashboard", route: "/" },
            { icon: "star", text: "Ratings", route: "/ratings" },
            {
                icon: "people",
                text: "Drivers",
                route: "/drivers",
                subLinks: [
                    { text: "Add Driver", route: "/drivers/add" },
                    { text: "Add Driver", route: "/drivers/add" }
                ]
            },

            {
                icon: "person_outline",
                text: "Manager",
                route: "/managers",
                subLinks: [
                    { text: "Add Manager", route: "/managers/add" },
                    { text: "Managers", route: "/managers" }
                ]
            },
            { icon: "person", text: "Manage Users", route: "/users" }
        ]
    };
}

Any help would highly be appreciated.

A: Use the list-group...
    <v-navigation-drawer app dark class="primary" v-model="drawer">
        <v-list>
            <v-list-item>
                <v-list-item-content>
                    <v-list-item-title class="title">
                        Al-Mehmood
                    </v-list-item-title>
                    <v-list-item-subtitle>Transport Company</v-list-item-subtitle>
                </v-list-item-content>
            </v-list-item>
            <v-divider></v-divider>
            <v-list-group no-action v-for='navLink in navLinks' :key="navLink.text">
                <v-list-item slot='activator' :to="navLink.route">
                    <v-list-item-icon>
                        <v-icon>{{ navLink.icon }}</v-icon>
                    </v-list-item-icon>
                    <v-list-item-title>{{ navLink.text }}</v-list-item-title>
                </v-list-item>
                <v-list-item v-for='sub in navLink.subLinks' :key="sub.text">
                    <v-list-item-title :to="sub.route">{{ sub.text }}</v-list-item-title>
                </v-list-item>
            </v-list-group>
        </v-list>
    </v-navigation-drawer>

Demo: https://codeply.com/p/hZE2TMlslF

A: this is the solution, a computed property!
computed: {
  filteredNavLinks() {
    return this.navLinks.filter(
      navLink => navLink.subLinks && navLink.subLinks.length
    );
  }
}

Now you v-for must be updated to use filteredNavLinks
<v-list dense>
    <v-list-item link v-for="navLink in filteredNavLinks" :key="navLink.text" :to="navLink.route">
        <v-list-item-icon>
            <v-icon>{{ navLink.icon }}</v-icon>
        </v-list-item-icon>

        <v-list-item-content>
            <v-list-item-title>
                {{
                navLink.text
                }}
            </v-list-item-title>
        </v-list-item-content>
    </v-list-item>
</v-list>

Try and let me know if it works fine.


text:
Q: Excel Smart Find and Replace only specific characters I want to change INT to INTERNATIONAL and NA to NATIONAL ASSEMBLY in whole excel workbook through an excel Macro or Find and Replace dialogue box. But when I run the macro or change it through Find and Replace dialogue box it also replace NA from CHINA last 2 characters and it became CHINATIONAL ASSEMBLY and INTERIOR to INTERNATIONALERIOR.
Now, I want that Excel should only smartly find the character NA in the workbook which is not included with any other character likewise character INT which is not attach to any other character.

A: If the values you are looking to replace are by themselves in the cells (no other text), definitely follow CharlieRB's solution.  If the values are located in the cells, along with additional text, a slightly modified version would work.
Open the Find and Replace window.  Click the "Replace" tab.

Enter the "Find what" and the "Replace with" values.  Click the "Find All" button.
Review the list at the bottom that details what records were found.  Highlight the record you want to update, and click the "Replace" button.

A: In the Find and Replace window, you need to check the box Match entire cell contents then run it.

A: *

*Save your file as a CSV file.  If you want to manipulate a subset of your worksheet (e.g., selected columns and/or rows), copy that region into a scratch file (or sheet) and save that as CSV.  If you need to modify multiple sheets, repeat this process for each sheet.

*Edit the CSV file with some sort of smart text editor (i.e., smarter than Notepad).  vi is good for this; use a command such as %s/\<INT\>/INTERNATIONAL/g.  Microsoft Word will probably suffice; use the "Find whole words only" option under More>> in "Find and Replace".

*Read the edited CSV file back into Excel.

*Copy the modified values into your original workbook, to preserve formatting.

A: If you go the VBA route, try using Regular Expressions
Here's a start
Sub ReplaceWithRE()
    Dim re As Object 'RegExp
    Dim rng As Range, cl As Range
    Dim sh As Worksheet
    Dim wb As Workbook
    Dim sReplace As String
    Dim aReplace(0 To 1, 0 To 1) As String
    Dim i As Long

    Set wb = ActiveWorkbook
    Set re = CreateObject("vbscript.regexp") ' New RegExp
    re.Global = True
    re.IgnoreCase = False
    re.MultiLine = True

    ' Load array of patterns and replacements
    aReplace(0, 0) = "\bINT\b"
    aReplace(0, 1) = "INTERNATIONAL"
    aReplace(1, 0) = "\bNA\b"
    aReplace(1, 1) = "NATIONAL ASSEMBLY"

    For Each sh In wb.Worksheets
        On Error Resume Next
        Set rng = sh.UsedRange.SpecialCells(xlCellTypeConstants)
        If Err.Number <> 0 Then
            Err.Clear
        Else
            On Error GoTo 0
            For Each cl In rng
                sReplace = cl.Value
                ' Test each cell for each pattern, replace when found
                For i = 0 To UBound(aReplace, 1)
                    re.Pattern = aReplace(i, 0)
                    If re.Test(sReplace) Then
                        sReplace = re.Replace(sReplace, aReplace(i, 1))
                    End If
                Next
                cl.Value = sReplace
            Next
        End If
    Next

End Sub


text:
Q: How do I enable the title bar to be shown in my iTerm2 window? I was playing around with preferences, and now my new windows don't have a title bar.  How can I show the title bar again?

A:
Window > Settings for New Windows > Style > Normal

Instead of Normal style, I had selected Full-Height Right of Screen, which caused the window take up the full height of the screen, and not have a title bar.
[ [Profiles


text: Q: Fix syntax checking in SQL Server when using synonyms Whether in a script window or in a stored procedure, is there any way to get SQL Server Management Studio to follow the current target a synonym points to so that syntax checking works? I'm writing SQL statements that reference a synonym that may, at different times, point to a table in one or another instance (dev, test, etc.) of the same database. It would be really nice if I didn't have red squiggles under all of the column names belonging to the underlying table when I know they're correct! Is there any way to get SSMS to figure out that they're correct?


text:
Q: Jooq code generator warns 'ignroing foreign key' I used this script to generate a schema
DROP SCHEMA IF EXISTS test_schema CASCADE;
CREATE SCHEMA test_schema;
SET search_path TO test_schema;

CREATE TABLE accounts
(
  user_id              SERIAL PRIMARY KEY,
  user_name            TEXT      NOT NULL,
  user_email           TEXT      NOT NULL,
  UNIQUE (user_name),
  UNIQUE (user_email)
);

CREATE TABLE sessions
(
  session_id          TEXT PRIMARY KEY,
  user_id             INT4      NOT NULL REFERENCES accounts (user_id),
  session_created_at  TIMESTAMP NOT NULL DEFAULT current_timestamp,
  session_deleted_at  TIMESTAMP NOT NULL DEFAULT 'infinity'
);

Then I configured the code generator with this schema.xml file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
    <!-- Configure the database connection here -->
    <jdbc>
        <driver>org.postgresql.Driver</driver>
        <url>jdbc:postgresql://localhost:7777/mydb</url>
        <user>username</user>
        <password>password</password>
    </jdbc>

    <generator>
        <database>
            <name>org.jooq.util.postgres.PostgresDatabase</name>
            <inputSchema>test_schema</inputSchema>
        </database>

        <generate>
        </generate>

        <target>
            <packageName>com.jooq.gen</packageName>
            <directory>../gen</directory>
        </target>
    </generator>
</configuration>

After running the code generator from the command line, I noticed this warning message
Apr 01, 2016 11:48:47 AM org.jooq.tools.JooqLogger info
INFO: Adding foreign key       : sessions__sessions_user_id_fkey (test_schema.sessions.user_id) referencing accounts_pkey
Apr 01, 2016 11:48:47 AM org.jooq.tools.JooqLogger warn
WARNING: Ignoring foreign key     : sessions__sessions_user_id_fkey (test_schema.sessions.user_id) referencing accounts_pkey references a schema out of scope for jooq-meta: null
Apr 01, 2016 11:48:47 AM org.jooq.tools.JooqLogger warn
WARNING: Ignoring foreign key     : sessions__sessions_user_id_fkey (test_schema.sessions.user_id) referencing accounts_pkey references a schema out of scope for jooq-meta: null

While I DON'T have any problem so far using the generated java classes, I would like to know why jooq generator sent out this warning and what is the consequence due to the ignoring of foreign key.

A: The idea is that with database designs that extend over multiple schemas, setting up the code generator not to generate all such schemas might be a mistake, and users should be made aware of this. Without the other schema being in scope for the code generator, foreign key navigational methods (such as SessionsRecord.fetchParent(SESSIONS_USER_ID_FKEY)) will not be possible.
That's it. So, you can safely ignore that message. The log level might be a bit excessive.


text:
Q: Preventing iTunes from keeping old versions on "Mobile Applications" folder I just manually deleted about 1gb of useless old version files from that folder. But I've got 966 items there and no way to going through them all, plus some of them are not even that simple to identify as being an older version of the same app since they change names.
Is there any way to automate the process? Why are they kept there in the first place?

A: I don't know an easy solution to change iTunes, but I do have a cleaner library by letting go. It's not exactly what you ask, but here goes anyhow.
I did one good backup of my user folder and then deleted all apps from within iTunes. Then I cleared out the folders to remove any left over / orphan app files.
Then I connected my devices one by one and just transferred the purchases. Less updates of un-needed apps and less space used.
I suppose they could pull an app from sale and I might miss out on some updates, but I'm willing to take that risk. I've still got the last version I wasn't using stored on my backup.

A: Here's how I did it:

*

*Backup your iTunes library in case this goes wrong. ;)

*Move all app files from "Mobile Applications" to the Desktop.

*Remove all apps from the iTunes library, but pick "Keep Files".

*(Temporarily) enable "Copy files to iTunes Media Folder when adding to library." in the iTunes preferences.

*Drag the app files from your Desktop into iTunes.

*Unfortunately, iTunes will prompt you when it finds duplicates. But  "Don't Replace" or "Replace" is preselected correctly based on which version is newer. So you can just hold the Return key down through the process.

The downside is: all apps are considered new now. So maybe disable "Automatically sync new apps" in the device sync screen before syncing.


text:
Q: Migrate Ember 1.7 to Ember 2.9 We have a quite large app building on top of Ember 1.7. There are quite a significant portion of the code is legacy and we want to refactor/re-architecture to get rid of. The goal is to be on the latest version of Ember (2.9 at this moment), leverage ember engine so later we can port portion of the app to other apps if required. This time is we don't have a lot of request for new features and we have 6-8 weeks to invest in technology updates. Also during this time, we may be required to add some features to the existing app. Our developer(s) may get pulled to work on some other small projects for couple of weeks. We consider being on Ember 2.x is crucial. In 2017, we may not have the time to do the migration. We have 2 options at this moment:

*

*Dive with our head down rebuild the app with the latest ember which mean do the refactoring at the same time with migrating. If there are new features, we will add to the old app and migrate later.

*Refactor first, re-architecture on the 1.7 version of Ember, get rid of the legacy code we don't want and migrate when we're done with refactoring. If we need to add more features to the app, we can add during the refactoring process. When done with refactoring, we will freeze the app from new features.

The first approach is more risky, thing can go out of control because of refactoring and migration at the same time. But if things go well, it could be done in shorter time.
The later approach is much safer. If we run out of time at the end, we still have a better code base. And whenever we have time we can come back to do the migration. But it would takes longer since we will need to do another short of refactor when migrate to ember 2.x. And we may never have time for migration and forever get stuck with Ember 1.7.
We are trying to look for a third approach which is refactoring and migrating a smaller chunks of the app to ember engines or smaller ember apps. And inject these small engines/apps to the existing large legacy app. However, I could not find anywhere which mention we can use Ember 2.x inside an Ember 1.x app.
Any idea, suggestion, tips hint on that we can reach to our goals will be really appreciated. One more thing, the existing app using RequireJS.

A: Actually I think you should think about two migrations:

*

*migrating to ember 2.9,

*and migrating to ember-cli

The most important question I think is, if it might be possible to jump to ember 1.13 in a single short step. This highly depends on your usage of private API. If you can jump to ember 1.13 in a few hours that should be your first step.
If you have a 1.13 app without deprecations, you actually could just jump to 2.x. So here the number of deprecations will help you to evaluate the required effort.

Now lets talk about the jump to ember-cli. This will probably be much harder then the jump to ember 2.9, because you have to touch every single file! It could be a good idea to do this ASAP, on 1.7 or 1.13. However if this is a good idea depends on the knowledge of you and your teammates. If you have a decent knowledge of ember-cli during the 1.x phase you could try it. If you don't have that it could be hard to get this knowledge, because this internet is not freezed. And a lot of things have changed since then.

If you can get your app on 1.13 with ember-cli it's a good point for refactoring and get rid of all the deprecations. Don't over-refactor you code tho. If you can jump to 2.9 do it, and do the refactoring later.

If these multi step upgrade is not possible for you, I would recommend your options 1. There are things like ember-islands, however I doubt that you will save much time with that.
Probably I would try to rebuild the app on 2.9 with as few refactoring as possible and as much reuse of code as possible. Later start the refactoring to engines.


text:
Q: Restructuring a nested collection of arrays I have an array of arrays, where each inner array contains three items: A postcode, a street name and an array of dates [for garbage collection].
The user will provide their postcode and house number, and the appropriate information needs to be displayed to them. There's also a need to be able to add dates to each 'collection array' after carrying out checks.
This is the code I have, but the data seems badly structured. How could it be improved?
var postcodes = [
        ["BT161JR18", "Londonderry Park", [collectionArrayBT161JR18]],
        ["BT161JR19",  "Ballyregan Cresent",  [collectionArrayBT161JR19]],
        ["BT161JR11", "Ballyregan Road",  [collectionArrayBT161JR11]],
    ]   ;

var collectionArrayBT161JR18 = ["16/05/14", "18/06/14", "19/07/14"];
var collectionArrayBT161JR19 = ["17/05/14", "11/06/14"];
var collectionArrayBT161JR11 = ["14/05/14", "20/06/14"];

A: What you should do is to use arrays of objects instead arrays of arrays of arrays...
For example same code could be designed like this:
var collectionArrayBT161JR18 = ["16/05/14", "18/06/14", "19/07/14"];
var collectionArrayBT161JR19 = ["17/05/14", "11/06/14"];
var collectionArrayBT161JR11 = ["14/05/14", "20/06/14"];

var postcodes = [
        {postcode: "BT161JR18", place: "Londonderry Park", dates: collectionArrayBT161JR18},
        {postcode: "BT161JR19", place: "Ballyregan Cresent", dates: collectionArrayBT161JR19},
        {postcode: "BT161JR11", place: "Ballyregan Road", dates: collectionArrayBT161JR11}
    ]   ;

On this way you don't need to remember indexes (which you will forget over time), instead you use logical names.
Also notice that you need first to define dates and then to include them further in your postcodes structure.

Update to a comment: Searching for dates for given postcode is pretty straight forward.
//for your code
function findDates(pc /*postcode to search*/)
    for (var i=0; i<postcodes.length; i++) {
        if (postcodes[i][0] === pc)
            return postcodes[i][2][0]
    return false
}
//for suggested code
function findDates(pc /*postcode to search*/)
    for (var i=0; i<postcodes.length; i++) {
        if (postcodes[i].postcode === pc)
            return postcodes[i].dates
    return false
}

A: You should use the postcodes as properties in an object to create the main container, instead of using an array. That way, you do not need to iterate over the array to find the postcode.
var collectionArrayBT161JR18 = ["16/05/14", "18/06/14", "19/07/14"];
var collectionArrayBT161JR19 = ["17/05/14", "11/06/14"];
var collectionArrayBT161JR11 = ["14/05/14", "20/06/14"];

var postcodes = {
    BT161JR18: {place: "Londonderry Park",   dates: collectionArrayBT161JR18},
    BT161JR19: {place: "Ballyregan Cresent", dates: collectionArrayBT161JR19},
    BT161JR11: {place: "Ballyregan Road",    dates: collectionArrayBT161JR11}
}

A: setup an array in javascript
    var postcodes = new Array();
    var collectionArrayBT161JR18 = new Array();
    var collectionArrayBT161JR19 = new Array();
    var collectionArrayBT161JR11 = new Array();


text:
Q: Add php array in variable How will I add the PHP array to variable so i can add it to the database as one variable, e.g.
$personnel = ['name1', 'name2', 'name3'];

I tried to use foreach then add it to the database but the last value only send to the database
foreach ($personnel as $person) {
  $p = $person.", ";
}
$sql = mysqli_query($con, "INSERT INTO travel_print (personnel, name, office, division, unit_head, position, date, purpose, venue, reference, date_to, date_from, activity, check_type) VALUES ('$p','$name','$office','$division','$unit_head','$position','$date','$purpose','$venue','$reference','$date_to','$date_from','$activity','$business')");

result:

the result that i need.

A: You can use implode function:
$p = implode(',', $personnel);

You can get more info in https://www.php.net/manual/en/function.implode.php

A: You can use serialize:
$args = ['person', 'person', 'person'];
$string = serialize($args);

Now you can put $string in database.
Using unserialize() for return array from string.
Or, if you want to save array like this: person, person, person,
You can simple use implode
$people = ['fred', 'wilma', 'barney'];
$string = implode(', ', $people);


text:
Q: Get feed from Age Gated Instagram account We are working on a project for our client which is an Alcoholic Brand. We are trying to get image feed via https://api.instagram.com/v1/users/{user_id}/media/recent/?client_id={client_id} but we get an APIAgeGatedError. We think this is related to Alcoholic advertising in the account. Is there any way to get a feed from this account?
Thanks in advance.


text:
Q: How to convert a BeautifulSoup list array into a String? I want to extract 4 numbers from a webpage with BeautifulSoup to later save those values in one line as a String in CSV format.
Extracting and saving the values to variables is working fine with BeautifulSoups findAll() function. The 4 values I need are within <p> tags with the css-style attribute "font-size: 13pt". Those values are saved in the list array linkData[].
I just don't know how I can save those variables in one line as a String. Right now, I am always getting line breaks, which is a problem, because I need the CSV output to be: var0,var1,var2,var3
Instead of:
var0
var1
var2
var3

I have already tried several things which I added to my code below. I almost got it working with my third approach but unfortunately, the encoding seems to be wrong if I use this option.
I need 987, 1002, 278, 19, but the output of print() is (u'\n987\n', u'\n1002\n', u'\n278\n', u'\n19\n'). Is there an option to change the encoding?
I am fairly new to BeautifulSoup so any help is highly appreciated!
Here's my code:
from bs4 import BeautifulSoup
import urllib2

opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.example.com')

html = response.read()
soup = BeautifulSoup(html, 'html.parser')

linkData = soup.findAll("p", {"style": "font-size: 13pt;"})

var0 = linkData[0].text
var1 = linkData[1].text
var2 = linkData[2].text
var3 = linkData[3].text

# Approach 1: Just print variables comma-separated
print var0, var1

# Approach 2: Using join to concatenate the variables
linkDataList = [var0, var1, var2, var3]
str1 = ''.join(linkDataList)
print str1

# Approach 3: Use print() function
print(var0, var1, var2, var3)

Best regards!

A: Just strip all the blank spaces using str.strip()  when you define the variables.
var0 = linkData[0].text.strip()
var1 = linkData[1].text.strip()
var2 = linkData[2].text.strip()
var3 = linkData[3].text.strip()


text:
Q: rails 5 redirect_back not working i have a admin edit page and form in here. when i submit the form, it is going to the update action and updates the admin, there is no problem. After the update, i want redirect to the index page in the same controller. But it gets redirected to the edit form again. I tried a couple of things but in vain and gets redirected to edit page. i tried too much things but it is always going to edit page.
Controller (admins_controller.rb)
class Admin::AdminsController < ApplicationController
  def index
    @admins = Admin.all
  end

  def edit
    @admin = Admin.find(params[:id])
  end

  def update
    @admin = Admin.find(params[:id])
    if @admin.update(admin_params)
      redirect_back fallback_location: admin_admins_path
    else
      render 'edit'
    end
  end

  private

  def admin_params
      params.require(:admin).permit(:id, :username, :password)
  end
end

I'm trying admin_admins_path it does not work.

A: redirect_back like its name, it redirects to the route which it submitted the request, in this case is the edit page.
you should use redirect_to
redirect_to admin_index_path


text:
Q: Python Nested For Loops With Match/Update Criteria I am writing a script in python which loops two tables against each other. If a condition is met then the script will make an update on the dependent table.
My python code so far:
def updatedata():
    for y in range(updatetable.shape[0]):
        for x in range(mastertable.shape[0]):
            if updatetable[y].s_date <= mastertable[x].index <= updatetable[y].e_date:
                mastertable[x].field2 = updatetable[y]. field2
                mastertable[y].field3 = updatetable[y]. field3

I also have this iteration technique:
for index, row in mastertable.iterrows():
    print (row['Value'], index)

for index, row in updatetable.iterrows():
    print (row['field1'], row['field2'])

I am following how I would write this in VBA:
For x = 1 to lastrow_update
    for y = 1 to lastrow_master
        if update(x,1) <= master(y,1) and master(y,1) <= update(x,2) then
        master (y,2) = update(x,3)

I am getting errors with the python code.
1) how do I create two control variables for the "for loops"
2) how do I exit the inner loop after a match to cut down on run time
error for def updatedata()
Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2525, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/user1/Desktop/project4.py", line 41, in <module>
    updatedata()
  File "/Users/user1/Desktop/project4.py", line 20, in updatedata
    if presidents_data[y].tookoffice <= sp500[x].index <= presidents_data[y].leftoffice:
  File "/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 2139, in __getitem__
    return self._getitem_column(key)
  File "/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 2146, in _getitem_column
    return self._get_item_cache(key)
  File "/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 1842, in _get_item_cache
    values = self._data.get(item)
  File "/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py", line 3843, in get
    loc = self.items.get_loc(item)
  File "/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2527, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0

sample of data:
               president tookoffice leftoffice       party
0      Lyndon B. Johnson 1963-11-22 1969-01-20  Democratic
1  Franklin D. Roosevelt 1933-03-04 1945-04-12  Democratic
2         Herbert Hoover 1929-03-04 1933-03-04  Republican
3      Warren G. Harding 1921-03-04 1923-08-02  Republican
4           Barack Obama 2009-01-20 2017-01-20  Democratic
            Value  president  party_of_president
Date
1871-01-01   4.44  president  party_of_president
1871-02-01   4.50  president  party_of_president
1871-03-01   4.61  president  party_of_president
1871-04-01   4.74  president  party_of_president
1871-05-01   4.86  president  party_of_president

A: When indexing by rows using an integer index, you need .iloc:
if updatetable.iloc[y].s_date <= mastertable.iloc[x].index <= updatetable.iloc[y].e_date:

The syntax updatetable.iloc[y] means "get the column called y", in which case y should be "president" or another string for which you have a column.

A: Consider pandas's merge_asof (i.e., "interval merge") using the backward direction for tookoffice or equivalently forward direction with leftoffice:
merge_df = pd.merge_asof(value_df, pres_df, left_on='Date', right_on='tookoffice',
                         suffixes=['','_'], direction='backward')

merge_df = pd.merge_asof(value_df, pres_df, left_on='Date', right_on='leftoffice',
                         suffixes=['','_'], direction='forward')

Below is demonstration using random data, mirroring posted data. For below solution, two things must done:

*

*president dataframes's tookoffice and leftoffice must be sorted;

*value dataframe's index should be reset to have Date as a column in dataframe (set back at end).

Data
from io import StringIO
import numpy as np
import pandas as pd

txt = '''
               president tookoffice leftoffice       party
0      "Lyndon B. Johnson" "1963-11-22" "1969-01-20"  Democratic
1  "Franklin D. Roosevelt" "1933-03-04" "1945-04-12"  Democratic
2         "Herbert Hoover" "1929-03-04" "1933-03-04"  Republican
3      "Warren G. Harding" "1921-03-04" "1923-08-02"  Republican
4           "Barack Obama" "2009-01-20" "2017-01-20"  Democratic'''

pres_df = pd.read_table(StringIO(txt), sep="\s+", index_col=[0],
                        parse_dates=['tookoffice', 'leftoffice'])

pres_df = pres_df.sort_values(['tookoffice', 'leftoffice'])

np.random.seed(7012018)   # SEEDED FOR REPRODUCIBILITY
value_df = pd.DataFrame({'Value': 4 + abs(np.random.randn(1765)),
                         'president': 'president',
                         'party_of_president': 'party_of_president'},
                        columns=['Value', 'president', 'party_of_president'],
                        index=pd.date_range('1871-01-01', '2018-01-01', freq='MS'))\
                       .rename_axis('Date')

value_df = value_df.reset_index()

Merge
merge_df = pd.merge_asof(value_df, pres_df, left_on='Date', right_on='tookoffice',
                         suffixes=['','_'], direction='backward')

# UPDATE NEEDED COLUMNS TO ADJACENT COLUMNS
merge_df['president'] = merge_df['president_']
merge_df['party_of_president'] = merge_df['party']

merge_df['president'] = merge_df['president_']
merge_df['party_of_president'] = merge_df['party']

# CLEAN UP (IN CASE PRESIDENT DF IS NOT EXHAUSTIVE BETWEEN 1871-2018)
mask = ~merge_df['Date'].between(merge_df['tookoffice'], merge_df['leftoffice'])

merge_df.loc[mask, 'president'] = np.nan
merge_df.loc[mask, 'party_of_president'] = np.nan

# SUBSET FIRST 4 COLUMNS AND SET INDEX
merge_df = merge_df[merge_df.columns[:4]].set_index('Date')

Output
print(merge_df.shape)    # SAME SHAPE AS ORIGINAL value_df
# (1765, 3)

# FIRST 20 RECORDS
print(merge_df.head(20))
#                Value president party_of_president
# Date
# 1871-01-01  4.859688       NaN                NaN
# 1871-02-01  4.309355       NaN                NaN
# 1871-03-01  5.003074       NaN                NaN
# 1871-04-01  4.769772       NaN                NaN
# 1871-05-01  5.765133       NaN                NaN
# 1871-06-01  5.408663       NaN                NaN
# 1871-07-01  4.177684       NaN                NaN
# 1871-08-01  5.980318       NaN                NaN
# 1871-09-01  5.029296       NaN                NaN
# 1871-10-01  4.604133       NaN                NaN
# 1871-11-01  4.691276       NaN                NaN
# 1871-12-01  5.387712       NaN                NaN
# 1872-01-01  4.387162       NaN                NaN
# 1872-02-01  4.002513       NaN                NaN
# 1872-03-01  6.105690       NaN                NaN
# 1872-04-01  5.604589       NaN                NaN
# 1872-05-01  4.860393       NaN                NaN
# 1872-06-01  4.776127       NaN                NaN
# 1872-07-01  4.280952       NaN                NaN
# 1872-08-01  4.886334       NaN                NaN

# FIRST NON-NULL VALUES
print(merge_df[~pd.isnull(merge_df['president'])].head(20))
#                Value          president party_of_president
# Date
# 1921-04-01  5.713479  Warren G. Harding         Republican
# 1921-05-01  4.542561  Warren G. Harding         Republican
# 1921-06-01  5.148667  Warren G. Harding         Republican
# 1921-07-01  4.949704  Warren G. Harding         Republican
# 1921-08-01  5.138469  Warren G. Harding         Republican
# 1921-09-01  5.797446  Warren G. Harding         Republican
# 1921-10-01  4.498131  Warren G. Harding         Republican
# 1921-11-01  4.216718  Warren G. Harding         Republican
# 1921-12-01  6.110533  Warren G. Harding         Republican
# 1922-01-01  5.179318  Warren G. Harding         Republican
# 1922-02-01  4.808477  Warren G. Harding         Republican
# 1922-03-01  4.466641  Warren G. Harding         Republican
# 1922-04-01  4.307025  Warren G. Harding         Republican
# 1922-05-01  4.337476  Warren G. Harding         Republican
# 1922-06-01  4.396854  Warren G. Harding         Republican
# 1922-07-01  4.391316  Warren G. Harding         Republican
# 1922-08-01  4.748302  Warren G. Harding         Republican
# 1922-09-01  5.468115  Warren G. Harding         Republican
# 1922-10-01  4.295268  Warren G. Harding         Republican
# 1922-11-01  5.432448  Warren G. Harding         Republican


text:
Q: Make cursor corresponding array with multiple rows followed by same row id's I have a DB in which id's are change after few rows, then same I'd in some rows then change I'd.  What I want that, the same I'd values will be populated listview's in one line, then when the Ids are same,  they are all in  one row. And thus the next rows populate with same rows which have same ID's.
My DB columns and rows  are as follows:

   Verse_id -------words_id----------words_ar------ translate_bn--
1-----------------------1---------------Mamun-----------Assistant---
1-----------------------2--------------- Salam------------Operator------
1-----------------------3---------------John--------------Assistant------
2 ----------------------1--------------- Smith-------------Manager------
2-----------------------2---------------Roger--------------Director--------
3-----------------------1---------------Qoel---------------Helper----------
3-----------------------2---------------Saki---------------Mechanics-----
3-----------------------3----------------Ali-----------------Getman----------

I want this DB in three lines, as follows :   (listview):
1.     Mamun.           Salam             John
       Assistant.       Operator.        Assistant
------------------------------------------------------------------
2.     Smith.            Roger.
       Manager.         Director
------------------------------------------------------------------
3.      Qoel.            Saki.              Ali.
        Helper.        Mechanics.          Getman

I have Tried in Two way :
First :
private static final String PRIMARY_ID = "_id";
    private static final String TABLE_NAME = "bywords";
    private static final String FRIEND_ID = "verse_id";
    private static final String WORDS_ID = "words_id";
    private static final String WORDS_bN = "translate_bn";
    private static final String WORDS_AR = "words_ar";

private SQLiteDatabase database;
    private ArrayList<String> friends;

    private ArrayList<String> trans1;

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

        mContext = this;

        ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
        database = dbOpenHelper.openDataBase();

        Cursor cursor = database.rawQuery("SELECT * FROM  bywords", null);

        ListView list4=(ListView)findViewById(R.id.list4)   ;

        String[] from = {WORDS_AR }; // _id mandatory
        int[] to = new int[]{R.id.alquran_text};

        CursorAdapter adapter = new SimpleCursorAdapter(
                mContext,
                R.layout.list_item,
                cursor,
                from,
                to,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        list4.setAdapter(adapter);

And Then Second :
    trans1 = new ArrayList<String>();

        String[] allColumns2 = new String[] { FRIEND_ID,
                BN_TRANS };

        Cursor friendCursor2 = database.query(TABLE_NAME, allColumns2, null,
                null, null, null, null);

        if (friendCursor2 != null) {
            friendCursor2.moveToFirst();
        }
        //return friendCursor;

        if(!friendCursor2.isAfterLast()) {
            do {
                String name = friendCursor2.getString(1);
                trans1.add(name);
            } while (friendCursor2.moveToNext());
        }

        friendCursor2.close();

    String [] bntrans1= new String[trans1.size()];
                bntrans1 = trans1.toArray(bntrans1);

ListAdapter adapter = new ArrayAdapter<String>(
                        getApplicationContext(), R.layout.alert_row, seleted_route) {

                    ViewHolder holder;
                    Drawable icon;

                    class ViewHolder {
                        ImageView icon;
                        TextView title;
                        TextView title2;
                    }

                    public View getView(int position, View convertView,
                                        ViewGroup parent) {
                        final LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                                .getSystemService(
                                        Context.LAYOUT_INFLATER_SERVICE);

                        if (convertView == null) {
                            convertView = inflater.inflate(
                                    R.layout.alert_row, null);

                            holder = new ViewHolder();
                            //holder.icon = (ImageView) convertView
                            //      .findViewById(R.id.icon4);
                            holder.title = (TextView) convertView
                                    .findViewById(R.id.title4);
                            holder.title2 = (TextView) convertView
                                    .findViewById(R.id.title2);

                            convertView.setTag(holder);
                        } else {
                            // view already defined, retrieve view holder
                            holder = (ViewHolder) convertView.getTag();
                        }

                        Drawable drawable = getResources().getDrawable(R.drawable.iqra1); //this is an image from the drawables folder

                        holder.title.setText(seleted_route[position]);
                        holder.title2.setText(seleted_route[position]);
                        //holder.icon.setImageDrawable(drawable);

                        return convertView;
                    }
                };

By the second way I can populate two column in two text view in one rows. But what I want that the corresponding rows with same id of rows must  populate in one line of listview with verse I'd. The id's whataver are same in rows  may be 5, 10 or twenty rows same id. Whenever the same Id They are one line, When the Id change the newline begins.


text:
Q: How come my array doesnt print out my index? C# .NET I just started out with arrays and it is AMAZING!
One small thing though, how come my for loop isnt printing out the whole index or rather the value of the index one by one, but instead only prints out the last one?

Here is my code if you are having some issues with viewing the image!
namespace Arrays
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int[] numbers = new int[5];

        private void Form1_Load(object sender, EventArgs e)
        {
            numbers[0] = 12;
            numbers[1] = 10;
            numbers[2] = 25;
            numbers[3] = 10;
            numbers[4] = 15;
        }

        private void button1_Click(object sender, EventArgs e)

        {
            for (int i = 0; i < numbers.Length; i++)

            displayArrays.Text = numbers[i].ToString();
        }

    }
}

A: Because you are just assigning value each time. Change
displayArrays.Text = numbers[i].ToString();

To
displayArrays.Text += numbers[i].ToString();

Or if separator is needed:
displayArrays.Text += numbers[i].ToString() + ", "; // But need to worry about trailling separator.

If you want the index, then i represents your current index. numbers[i] represents array value at index i.

A: Mostly other answers answered what you need, you could simplify a bit with this one liner.
Remove for loop completely and place this logic.
displayArrays.Text = string.Join(",", numbers);

A: Try this code
for (int i = 0; i < numbers.Length; i++)
        displayArrays.Text += ", " + numbers[i].ToString();


text:
Q: Can we have an isometric embedding of this metric space into an Hilbert space? A metric space (from this Q&A), is defined below. I'd like to know if its possible to have an isometric embedding of this metric space into an hilbert space? As per Schoenberg theorem $-d^2(x,y)$ need to be conditionally positive definite. So I want to verify if $d(x,y)$ of this metric space satisfy this condition.
Consider $L^2(\mathbb{R}) \setminus \{0\}$ and impose the following equivalence class on this.
Equivalence class $\sim$
Let $f$ be a function and we define its equivalence class as $f\sim g$ iff $g(x) = kf_{\theta}(x+\tau)$, for some $\theta \in [-\pi,\pi], k \in \mathbb{R}\setminus \{0\}$,$\tau \in \mathbb{R}$ and $$f_{\theta}(x) = f(x) \cos(\theta) + f_h(x) \sin(\theta)$$ where $f_h(x)$ is the hilbert transform of $f(x)$.
Lets us denote this set together with this equivalence class as $R = (L^2(\mathbb{R}) \setminus \{0\})/ \sim $.
Now we define metric..
Given $f,g \in R$, let $$h(x) = \frac{\int \limits_{-\infty}^{\infty}f(t)g(t+x)\mathrm dt}{\sqrt{\int \limits_{-\infty}^{\infty}f(t)^2\mathrm dt \int \limits_{-\infty}^{\infty}g(t)^2\mathrm dt}}.$$
Now define $$H(x) = \sqrt{h(x)^2 + h_h(x)^2}$$ where $h_h(x)$ is the hilbert transform of $h(x)$.
and our similarity measure is given as $$ s(f,g) = \sup_x H(x). $$
Define metric as $$d(f,g) = \arccos(s(f,g)).$$

(proof that $(R,d)$ is a metric space)...
Note we can move from this space to a projective Hilbert space with translations identified by making the below transition
Replace $f$ by $F(x)=f(x)+if_h(x)$. Thats it!
If we denote Willie's cosine metric on $M$ as $w$, then given any $f,g \in R$, we create  objects $F,G \in M$ given as $F(x) = f(x) + if_h(x), G(x) = g(x) + ig_h(x)$.
Now it can be seen that
$$d(f,g) = w(F,G)$$ Hence $(R,d)$ is a metric space.


text:
Q: Load multiple JS files in Firefox Extension I am creating an extension for Firefox using JPM. In the package.json file, we have this line for the entry point...
"main": "index.js"

How do I change it, or what else can I do, to include more JS files in my extension? I am basically porting a Chrome extension where I have 2-3 JS files.
I tried the following, but it didn't work.
"main": ["index.js", "file2.js"]

"main": [{"index.js", "file2.js"}]

"main": "index.js,file2.js"

To clarify a bit more, both of these files are meant to run in the background and are not content scripts.

A: As far as I know, through the package.json file you can specify only one main.jsscript .
As the developers' documentation says:

Minimally you'll have a single module implemented by a script called "main.js", but you can include additional modules in lib, and import them using the require() function. To learn how to implement and import your own modules, see the tutorial on Implementing Reusable Modules.

So, you can create your own library in the lib directory, let's say test.js following the documentation and included to your main.js. Take a look at an example of this:
test.js:
vat test = function() {console.log("I'm a module");};
exports.test = test;

and in your main.js:
var test = require('./test');
test.test();

A: I had the same problem. If you put your 'file2.js' in the 'data' directory you can add the line
    var x = require('./data/file2.js');
in the 'main.js' file. Then call your function like:
    x.yourFunc();
Be sure to export your functions in file2.js with an assignment to the exports variable for each function:
    exports.func1 = function() { return yourFunc(); }


text:
Q: How can I use Cucumber to test Devise's Rememberable functionality? I'd like to have a Cucumber feature testing the rememberable functionality of devise (a remember me cookie).
It is easy to check the remember me check box using capybara but how should I simulate a user returning to the site after closing their window?

A: I came up with the following rack-test hack, and slightly cleaner selenium api use, to test Devise remember-me functionality in cucumber/capybara. It just tells the driver to manually erase the session cookie. Not all drivers are supported, I only implemented the two I've used:
http://gist.github.com/484787
This assumes cookie storage of the session. Remove @announce tag from the scenario to get rid of the verbosity.
Another option, suggested by Matt Wynne in the mailing list discussion, may be looking at other cookie stores, and deleting them by query or file deletion:
lifted from agile rails book:
config.action_controller.session_store = CGI::Session::PStore (or just :p_store)
config.action_controller.session_options[:tmpdir] = "/Users/dave/tmp"
config.action_controller.session_options[:prefix] = "myapp_session_"

or
rake db:sessions:create
config.action_controller.session_store = :active_record_store

Rails also has a reset session method, but I believe we don't have access to this because we can't hook into the rails session when testing with capybara.
Hope this helps,
Nick

A: nruth's gist was really helpful but I felt like deleting the cookie by name was cheating. I created a step that deletes the cookies a browser would delete when it was closed and restarted (any cookie without an expiry date set and set in the future).
You can see it in this commit (though I've only done it for the RackTest driver as I don't have Selenium setup). You can also see my login/remember_me feature in this commit. And I refactored the classes to separate files in this commit.
I hope that's helpful.

A: I used email-spec to accomplish this.  My Scenario looks like the following:
@allow-rescue
Scenario: Create New Account (Everything cool)
Given I am not authenticated
When I go to register
And I fill in "Name" with "bill"
And I fill in "Email" with "bill@example.com"
And I fill in "Password" with "please"
And I fill in "Password Confirmation" with "please"
And I press "Sign up"
Then "bill@example.com" should receive an email
And I open the email
And I should see "Confirm my account" in the email body
When I follow "Confirm my account" in the email
Then I should see "Your account was successfully confirmed. You are now signed in."

Note the @allow-rescue decoration above the scenario that is necessary when using Devise.
Hope this helps.

A: I guess you could log out with capybara, and then log back in something like
Given I am on the login screen
And I select 'Remember Me'
And I click 'login'
Then I should be 'logged in'
When I click 'log out'
Then I should be 'logged out' #=> potentially destroy a session here?
When I click log in
Then I should be logged in
And I should not be directed to the login form.

This should use cabybara's current cookie state to model this flow.

A: You can use show_me_the_cookies for this as shown below:
And(/^I leave the site$/) do
  expire_cookies
end