text:
Q: Function call order with the same function as arguments. Javascript I have following code:
function f() {

    //...do stuff with arguments
    //and return something...

}

f(root,
    f(child1),
    f(child2,
        f(subchild1),
        ....
    ),
);

I want to know when the root level of 'f' is called, so I introduce a flag as an argument:
f(root, '-r',
  f(child1),
  f(child2),
  //...
)

My question is: Is there a way to know when 'f' is called on the top level "f(root,...)" without adding additional arguments?

A: No, you have no way of telling, in code within f, that its return value isn't being used to build an arguments list for a subsequent call to f. (Or indeed, that its return value is or isn't being used for any particular thing, or nothing, at all.) It's not an unreasonable question, but that information just isn't available to f.

A: You could actually use f.caller and check if it's null; but it's forbidden in "strict mode" due to tail call optimization: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
Also, it would be unreliable for your type of code: ideally, you shouldn't need such type of branching between the root and the children (see for example any tree structure implementation like the DOM or hyper-script`).
Generally, if you have a f function than returns a tree node, it shouldn't matter at what level is called. For example:
let subchild = f(subchild1)

f(root,
    f(child1),
    f(child2, subchild),
        ....
    ),
);

That should returns the same structure of your code, but if you will check the caller it won't, since f(subchild1) will be the same as f(root).


text:
Q: Creating accessors in Java I'm trying to write a class and create accessors in Eclipse that I will have to use later on, however I'm having trouble doing so. I have the directions listed below but keep getting stuck on the last two.
Directions:

Write a class StringSet.  A StringSet object is given a series of String objects.  It stores these Strings (or a reference to them, to be precise) and can perform limited calculations on the entire series.  A StringSet class has the following specification:

*

*a single instance variable of type ArrayList<String>

*a single default constructor

*mutator that adds a String newStr to the StringSet object
void add(String newStr)

*accessor that returns the number of String objects that have   been added to this StringSet object
int size()

*accessor that returns the total number of characters in all    of the Strings that have been added to this StringSet object
int numChars()

*accessor that returns the number of Strings in the StringSet   object that have exactly len characters
int countStrings(int len)

My code so far:
import java.util.ArrayList;

public class StringSet {

    ArrayList<String> StringSet = new ArrayList<String>();

    public StringSet() {
    }

    public void add(String newStr) {
        StringSet.add(newStr);
    }

    public int getsize() {
        return StringSet.size();
    }

    public int getnumChars() {
        return StringSet.length();
    }

    public int countStrings(int len) {
        if (StringSet.equals(len)) {
            return StringSet.size();
        }
    }
}

A: Your string set is an array of string objects. Think of it as though you've added each of the following to stringSet (indexes are to the left of the value).
0[Hello]
1[My]
2[name]
3[is]
5[Keith]

For simplicity I'm going to use a primitive String[] rather than an ArrayList
Question 5
Create a variable that will increment its value by the size of each String. Then use a for loop to evaluate each individual String's length and add it to that variable:
int totalCharsInStringSet = 0;
for (int i = 0; i < stringSet.size(); i++) { // loop through each index
    // add the length of the string at this index to your running tally
    totalCharsInStringSet += stringSet[i].length;
}
// you've read through all of the array; return the result
return totalCharsInStringSet;

Question 6
Calling stringSet.size() is just going to count how many elements are in the array; i.e., 5. So you need to create a tally of how many individual strings match the target length. Craete a variable to keep that tally. And again, use a for loop to iterate through the array, and compare each string's length to the target value. If it matches, increment your tally:
int numberOfMatches = 0;
for (int i = 0; i < stringSet.size(); i++) {
   if (string[i].length == len) {  // "len" is your input target length
        numberOfMatches ++;
   }
}
return numMatches;

A: Number 5: You iterate through your ArrayList and add up the length of the strings stored there.
Number 6: You iterate through you ArrayList and check if the length of the String matches the desired length, and keep track of the number of matching strings.

A: Well ArrayLists don't have a length() method, so what you need to do to count total number of chars in the string set is iterate through the StringSet list and find the length of each string and add it to a running total.
int sum = 0;
for(int i = 0; i < StringSet.size(); i++){
   sum = sum + StringSet.get(i).length();
}
return sum;

For the countStrings you need to place this if statement in a for loop and increment a sum each time the if statement is triggered and return the sum
int sum = 0;
for(int i = 0; i < StringSet.size(); i++){
    if(StringSet.get(i).length() == len){
        sum = sum + 1;
    }
}
return sum;

A: For Question 5:
public int getnumChars()
{
    int countChar = 0;
    for(String strSet: StringSet){
        countChar += strSet.length();
    }
    return countChar;
}

For Question 6:
public int countStrings(int len)
{
    int count = 0;
    for(String strSet: StringSet){
        if(strSet.length() == len){
            count++;
        };
    }

    return count;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I know the IP address of Tor route? I am a college student who is conducting Tor research at a Japanese university.
How can I display the IP address of the route as shown in the picture?

I suspect I need to do some operations from the control port.

A: The way that works is a bit tricky.  Tor will create different circuits when it starts up and SOCKS requests will use a circuit it finds suitable.
The Tor browser (powered by TorButton) has special domain isolation functionality where it proxies requests for a specific domain:port combination through an isolated circuit by using credentials with Tor's SOCKS proxy.  This is how you can have two tabs open in the Tor Browser, and visit two different domains and have different IP addresses for each site (because each tab is using a completely different circuit).
To accomplish what you're trying to do, you'll need to mimic this behavior.
Here is a proof of concept to get you started.

*

*Start Tor

*Connect to Tor's control port

*Start listening for STREAM events SETEVENTS STREAM

*Issue a SOCKS request through Tor using proxy credentials (it will work best if the username is the domain:port combo for the site you are connecting to, and a random password you will use for each subsequent request to this domain)

*Monitor the stream events for the SENTCONNECT event matching your domain target and extract the circuit ID from the event.

*Send a GETINFO circuit-status command to the controller for the list of circuits, and the circuit path will be present with the circuit ID from the previous step.

This will get you the nodes you are relaying through, which you can then fetch info for to get the relay names and addresses for.
Expanding on the PoC above, here is example output you could expect to see.
Connect to controller and listen for events
AUTHENTICATE "password"
250 OK
SETEVENTS STREAM
250 OK

Issue a request with proxy credentials
curl --socks5-hostname localhost:9050 \
-U "torproject.org%3A:randomPasswordHere" \
https://torproject.org/donate`

The proxy username is torproject.org:443 which is the domain and port we are requesting.  randomPasswordHere is the password.
Monitoring the STREAM events
When the above request goes through, some events will be sent by the controller.
Example:
650 STREAM 153 NEW 0 torproject.org:443 SOURCE_ADDR=127.0.0.1:45508 PURPOSE=USER
650 STREAM 153 SENTCONNECT 38 torproject.org:443
650 STREAM 153 REMAP 38 154.35.132.71:443 SOURCE=EXIT
650 STREAM 153 SUCCEEDED 38 154.35.132.71:443
650 STREAM 153 CLOSED 38 154.35.132.71:443 REASON=DONE

The event we are interested in is the SENTCONNECT event where the target is the domain port combination we requested.
The format for these events is:
"650" SP "STREAM" SP StreamID SP StreamStatus SP CircuitID SP Target
          [SP "REASON=" Reason [ SP "REMOTE_REASON=" Reason ]]
          [SP "SOURCE=" Source] [ SP "SOURCE_ADDR=" Address ":" Port ]
          [SP "PURPOSE=" Purpose]
          CRLF

Applying that knowledge to the above data, 153 is the stream ID, 38 is the circuit ID we are interested in, torproject.org:443 is the target we requested.
Get circuit-status data
Now knowing the circuit ID our request used, we can pull circuit information to find the path the request took from the network.
GETINFO circuit-status
250+circuit-status=
38 BUILT $9E1E4F5B5F94812D02C4D18CB4086CE71CA5C614~torpidsDEhetzner1,$F0D264435B31F70FEFB322794E93211A8419F890~ANGRYRONIN,$79E169B25E4C7CE99584F6ED06F379478F23E2B8~MilesPrower BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL TIME_CREATED=2018-06-14T17:26:38.216992 SOCKS_USERNAME="torproject.org:443" SOCKS_PASSWORD="randomPasswordHere"
.
250 OK

You will see other circuits here, but I omitted them for simplicity.
38 is the circuit ID we are interested in, so you can parse the circuit information to find that the relay torpidsDEhetzner1 is the guard, ANGRYRONIN is the middle, and MilesPrower is the exit.  Double check that the SOCKS_USERNAME and SOCKS_PASSWORD fields are present and match those from the request to ensure you have the right circuit.
Getting relay info
You can then issue various commands to the controller to get info about the relays.
GETINFO ns/id/79E169B25E4C7CE99584F6ED06F379478F23E2B8
250+ns/id/79E169B25E4C7CE99584F6ED06F379478F23E2B8=
r MilesPrower eeFpsl5MfOmVhPbtBvN5R48j4rg axOufc4UeKsDqI/SrNiH31jyB1Y 2018-06-14 05:38:34 62.210.129.246 443 80
s Exit Fast Guard Running Stable V2Dir Valid
w Bandwidth=8170
.
250 OK

From there you can extract the IP address and information about the relays in the circuit.
Further reading:

*

*Tor control-spec.txt: Protocol implementation details for working with the Tor control port

*Tor Browser Design: Look for Tor circuit and HTTP connection linkability in section 4.5 (Cross-Origin Identifier Unlinkability)

*torbutton source: and it's domain-isolator and tor-circuit-display.js
Libraries like stem (Python) or TorUtils (PHP) (disclosure: I am the author of PHP TorUtils) can help with communicating with the Tor control protocol.
I hope this help!


text:
Q: WAR File too big I have deployed my WAR file to Tomcat, but it's almost 160 MB and server is running really slow. Can any one suggest to me how to speed up things up?

A: Why is that necessarily a problem?  If you have a lot of 3rd party JARs your WAR file might be that large.  What can you remove and still have the app run?
If we assume that size is not necessarily the reason why your app server is slow, what could be the root cause?
I'd recommend monitoring your app server under some moderate load using Visual VM with all the plugins installed.  It'll show you what's happening with heap, CPU, threads, object creation, and lots of other interesting things.
I'd also turn on Chrome tools and see what's happening when pages are loaded and rendered.
Have you run YSlow! to see how your pages perform?
You don't have root cause for slow.  I'd find it before I guessed.
Update - Just a point of reference: I have a web app that uses Spring 3, all its dependencies, and several other 3rd party JARs.  The WAR file is 31MB.  You might have a problem.


text:
Q: How do you delete a Signing Certificate in Xcode? When I go to Xcode > Preferences > Accounts and then click on Manage Certificates for my selected Apple ID, I see my list of Signing Certificates.  I tried to delete the certificate from the UI but the delete option is grayed out.  I then found another Stack Overflow page that said to remove certificates from Keychain Access.  I found it and removed it.  However, when I go back to Xcode to the same place as before the Signing Certificate is still there and the option to delete it is still grayed out (see image below).  I don't get it.  Why is it so hard to just let me delete my certificate?

A: I finally deleted the Certificates in XCode.

*

*Delete every item you think is related to certificates in Keychain Access > Keys. It will look like 'blank keys'

*Back to XCode Preferences > Accounts > Manage Certificates you should see those unwanted certificates showing (x) marks.

*Restart computer

A: It's not enough to delete it from your keychain, the certificate is still present in Apple Developer Center at this point.
To remove it completely do the following:

*

*Log in to Apple Developer Center

*Find the certificate in question and click it

*Now click the "Revoke" button (see attached screenshot). Certificate should disappear.

*Go back to Xcode and refresh the dialog. Now it should be gone.

If it's not gone after you have done this, it just means it's still present in your keychain locally, so just remove it from here as well and you should be good.

A: To remove a certificate that appear as "Not in Keychain" in XCode, I have found the following works.

*

*Revoke the certificate in the Apple Developer Portal (as per previous answer).

*Remove any provisioning profiles that reference the (removed) certificate.

A: You can't really delete a certificate, apparently. You can browse them in "Certificates, Identifiers & Profiles" inside of your developer account portal, but as far as I can tell, they'll remain there until they expire, and then they'll disappear automatically.

A: In case it helps anyone:
I revoked also (deleted) a certificate in App Developer account.
Then I thought I had deleted the certificate too in Keychain access but kept getting error messages, when trying to upload an app update to the AppStore.
I then found out that there are two separate places in keychain access, where in one the certificate is kept (funny enough under keys, once login is selected in keychains) and in the other one the private key (of course under the item certificates in keychains). I made sure that both are deleted and now all is good.


text:
Q: stop bubbling up Async await Task to caller without getting deadlock I have a problem where I have a library that uses an async function, GetParametersByPathAsync (which is defined here: https://github.com/aws/aws-sdk-net/blob/master/sdk/src/Services/SimpleSystemsManagement/Generated/_mobile/AmazonSimpleSystemsManagementClient.cs#L2718)
I have a library function defined as
Task<Dictionary<string,string>> GetAllParameters(string region)
{
    var pars = DoParameterGatheringWork(reigion);
    ...(do some more work)
    return dict;
}

which calls another method
async Task<Dictionary<string,string>> DoParameterGatheringWork(string region)
{
    ...
    var response = await GetParametersByPathAsync(requestObj);
    ... (process the response)
    return parameterDict;
}

that awaits on the GetParametersByPathAsync and gathers things.
This is a problem because GetAllParameters has to be called by my service from a static constructor and initialize a parameter Dictionary<string,string> MyParameters { get; }
I would like to stop this bubbling up of Tasks at some point in the library, so it can just expose Dictionary<string,string> GetAllParameters(string region), not the Task version. (I am completely fine with it becoming synchronous..)
I don't think I should be just doing Task.Wait() or Task.Result either because that will cause deadlocks.
Maybe this isn't the best way to go about it, but I am unsure how to continue on from here.
Any thoughts would be appreciated!
Edit:
Here is the constructor code I would like to have:
public class MyConfiguration
{
    static MyConfiguration()
    {
        ...
        Parameters = ServiceConfiguration.GetAllParameters(); // (library call)
    }
    public static Dictionary<string, string> Parameters { get; }
}

and the client will be able to use this anywhere just by MyConfiguration.Parameters["IAMAPARAMETER"]

A: After comment: at the end of this answer: How to call the async method from a non-async method
Apparently DoParameterGatheringWork is a function that normally would have to do some busy waiting for another process, like a database, or a file, or some information from the internet.
The designer of that function thought it would be a waste of time if your thread would be waiting idly for the result of this remove action. Therefore he decided to make it async, so the callers could do other things while the other process would process the request.
You saw correct that this means that all callers should also be async, and that a constructor can't be async.
If you want to benefit from the advantages of async-await (meaning that your callers can continue processing instead of idly waiting, make your constructor ligthweight and let some Create function do the async job you normally would do in the constructor. Force everyone who wants an object of your class to use this async Create function.
public class MyConfiguration
{
    // Static async Create function, does everything you'd normally do in the constructor:
    public static async Task<MyConfiguration> CreateAsync()
    {
        Dictionary<string,string> allParameters = await ServiceConfiguration.GetAllParameters(...);
        MyConfiguration createdConfiguration = new MyConfiguration(allParameters);
        return createdConfiguration;
     }

     // make sure that no one except CreateAsync can call the constructor:
     private MyConfiguration(Dictionary<string,string> allParameters)
     {
          parameters = allParameters;
     }
}

What you do is that you make the constructor as lightweight as possible and do all the difficult stuff, including await in the CreateAsync function.
Usage:
The following will lead to compiler error, so you know the problem before you start running:
MyConfiguration config = new MyConfiguration(...);

Proper usage:
async Task<...> DoSomethingAsync(...)
{
     ...
     // I need a configuration:
     MyConfiguration config = await MyConfiguration.Create();
     // from here you can use the fully initialized MyConfiguration object:
     config.DoSomethingElse();
     ...
}

Simple comme bonjour
Addition: how to call async method from a non-async function
To call an async function from a non-async method, use Task.Run to start the async function, Task.Wait to wait for the async function to complete and Task.Result to get the return value of the async function.
static void Main(string[] args)
{
    // call an async function:
    var asyncTask = Task.Run( () => MyAsyncFunction(...));

    // if desired: do other things
    DoSomethingElse();

    // now you need the result of the async function
    asyncTask.Wait();
    var returnValue = asyncTask.Result;
    Process(returnvalue);
}


text:
Q: How to load paths into ListBox and afterwards start the file per selected Index public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    private void cmdAdd_Click(object sender, EventArgs e)
    {

        OpenFileDialog OP = new OpenFileDialog();
        OP.Title = "Please select the wanted .exe";
        string FileName = String.Empty;
        string PathName = String.Empty;
        OP.InitialDirectory = @"C:\Users\" + Environment.UserName.ToString() + @"\Desktop";
        OP.DefaultExt = ".exe";
        OP.Filter = "Game executable (*.exe) |*.exe";
        DialogResult Ergebnis = OP.ShowDialog();

        if (Ergebnis == DialogResult.OK)
        {
            FileInfo File = new FileInfo(OP.FileName);

            if (File.Exists)
            {
                PathName = File.FullName;
            }
        }

        if (PathName != String.Empty)
        {

            textBox1.Text = PathName;
            listBox1.Items.Add(PathName);
        }
    }

    private void cmdStart_Click(object sender, EventArgs e)
    {
        string SelectedItem = "";
        if (listBox1.SelectedItem != null)
        {
            SelectedItem = listBox1.SelectedItem.ToString();
            /*MessageBox.Show(SelectedItem);*/
        }

        Process Pro = new Process();
        Pro.StartInfo.FileName = SelectedItem;
        DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (Ergebnis2.Equals(true))
        {
            try
            {
                Pro.Start();
            }
            catch (Exception)
            {
                MessageBox.Show("The Start of the Program was aborted!\r\nOr you didn't specify the right Path!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

    }

    private void cmdSave_Click(object sender, EventArgs e)
    {
        StreamWriter SaveFile = new StreamWriter(@"C:\Users\" + Environment.UserName.ToString() + @"\Desktop\savedgames.txt");
        foreach (var item in listBox1.Items)
        {
            SaveFile.WriteLine(item.ToString());
        }

        SaveFile.Close();
        MessageBox.Show("EZPZ");
    }

    private void cmdLoad_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(@"C:\Users\" + Environment.UserName.ToString() + @"\Desktop\savedgames.txt");
        string line = string.Empty;
        try
        {

            line = sr.ReadLine();

            while (line != null)
            {
                this.listBox1.Items.Add(line);

                line = sr.ReadLine();
            }

            sr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
        finally
        {
            sr.Close();
        }
    }
}

Hello Stackoverflow-Community,
So i've tried to be able to start the selected File(from the Listbox) by clicking the Start button.The items in the Listbox are loaded in from a .txt-File, But it seems that the path that i get (from the .txt-File) is not actually the same that was written inside.
For example: H:\Exe\556689600.exe is written inside the .txt-File but when i check while pausing the application the value of the SelectedItem is "H:(two backslashes)Exe(two backslashes)556689600.exe" so i'd like it to be H:\Exe\556689600.exe so it can be properly started.
EDIT: The main problem is that i can't start the .exe that i selected (via cmdStart) and i don't know why.
Please keep in mind that i'm (as you can see from the code) not very experienced in programming and that i'm not an native english speaker, so pardon me for any grammatical mistakes/logic mistakes made.
Thanks in advance,
Stephen

A: The problem is with:
        DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (Ergebnis2.Equals(true))

DialogResult holds the Enum data 'DialogResult.Yes', so you need to compare it to that value, and not (true).
Edit:
I suggest practicing working with debug:
In this case, I plated a breakpoint on the 'cmdstart_Click' method and followed it step by step (Used F10)
I saw that we jump over the 'if' condition, and checked why.


text:
Q: Robot crosses boundary on collision rather than bounce back while implementing particle filter I have written the following code, where I am trying to create a particle filter. The problem I am facing is that even after using intersects method and other conditions, the robot sometimes overlaps the obstacles. Moreover, it goes out of boundary through upper left corner after wobbling again and again with the corner.
I check for the collisions and then if it seems there is a collision I move the robot by amount x in the reverse direction.
I calculate amount x by the following method, where x means current position.
public void setXPosition_robot(int x)
    {
        double distance=0;
        distance = unit_moved + randomDouble(0, forwardNoise);
        robot_x= (int) (x + Math.sin(Math.toRadians(robot_orientation))*distance);
        //System.out.println("Robot_X:"+robot_x);
    }

I am using the following code to check the collisions:
private void adjustRobotOrientation(Graphics2D g)
{
    int x=robot_x;
    int y=robot_y;

    if((x<0)&&(y<0))
    {
        robot_orientation=robot_orientation+randomDouble(160, 180);
    }

    if((x>620)||((y>395))||((x<1))||((y<1)))
    {
        robot_orientation=robot_orientation+randomDouble(160, 220);
    }
 }

private void collisionAvoidanceRobot(int x, int y, int r)
    {
        boolean collide1=false;
        boolean collide2=false;
        boolean collide3=false;
        boolean collide4=false;
        boolean collide5=false;
        boolean collide6=false;
        x+=unit_moved;
        y+=unit_moved;

        Shape collisionrobot=new Ellipse2D.Double(x,y,r,r);
        collide1=collisionrobot.intersects(obst1);
        if(collide1)
        {
            robot_orientation=robot_orientation+randomDouble(160, 220);
        }
        collide2=collisionrobot.intersects(obst2);
        if(collide2)
        {
            robot_orientation=robot_orientation+randomDouble(160, 220);
        }
        collide3=collisionrobot.intersects(obst3);
        if(collide3)
        {
            robot_orientation=robot_orientation+randomDouble(160, 220);
        }
        collide4=collisionrobot.intersects(obst4);
        if(collide4)
        {
            robot_orientation=robot_orientation+randomDouble(160, 220);
        }
        collide5=collisionrobot.intersects(obst5);
        if(collide5)
        {
            robot_orientation=robot_orientation+randomDouble(160, 220);
        }
        collide6=collisionrobot.intersects(obst6);
        if(collide6)
        {
            robot_orientation=robot_orientation+randomDouble(160, 220);
        }

    }

If you want to see, the complete code is in two files:
1. http://pastebin.com/ZYfSzptc (main class)
2. http://pastebin.com/hqTTyq5n

A: If a robot's velocity causes it to move past an obstacle between clock ticks, no collision will be detected. You can

*

*Use finer ticks and larger objects to preclude the effect, as shown in the KineticModel cited here.

*Anticipate the effect and compensate for it, as shown here.
Both examples use the vector approach cited here.


text:
Q: Chrome Admin Login fails Magento 2 Trying to login to Admin panel(Magento 2) with Chrome failed with no error message, with Firefox its working fine.

*

*Tried different domain name instead of local host

*Tried disabling system config -> web -> default cookie settings ->
use HTTP only
But no luck...

A: This was reported to us in GitHub: http://alankent.me/2015/04/25/use-of-localhost-when-installing-magento-2-quick-note/
We could not reproduce the issue in-house but we discovered that Chrome requires at least one period in the host name to set a cookie: http://alankent.me/2015/04/25/use-of-localhost-when-installing-magento-2-quick-note/
Try that and let us know.

A: You may try changing base_url, in DB, I guess with your ip/127.0.0.1


text:
Q: localhost doesnot work with xampp Maybe it is asked several times before but I couldn't get any solution. I have installed xampp in my computer. I have changed httpd.conf and httpd-ssl.conf for "port 80" and "443" troubles. Now the control panel shows that, Apache and MySql is running fine. But http://localhost is not working. Shows Not Found in my browser.

A: Try this first:

*

*Turn off skype, and all other applications that are running and then turn on the server

*make sure that the server works as default installation (with all apps closed in first step)

A: Oh...I wrote http://localhost on my address bar. It did not work. Then I wrote http://localhost:8081(the port number which I changed) and it worked nicely.


text:
Q: Finding size of largest subtree of a bst contained in a range This was a recent interview question. The question asked to find the size of the largest subtree of a BST contained within a range [x, y] were x < y. The BST is defined recursively where each node has an integer value, a left child node, and a right child node. I was only able to the total number of nodes in the tree that lie within the range but was not able to find the largest subtree. Here's the code I used, in python:
def solution(x, y, T):
    if T is None:
        return 0
    size = 0
    if x < T.val:
        size += solution(x, y, T.left)
    if x <= T.val and y >= T.val:
        size += 1
    # The following if statement was my attempt at resetting the count
    # whenever we find a node outside the range, but it doesn't work
    if x > T.val or y < T.val:
        size = 0
    if B > T.x:
        size += solution(A, B, T.right)
    return size

The solution should be O(N) where N is the number of nodes in the tree.

A: We can solve the problem recursively. We need to know the left and the right border of each subtree (that is, the smallest and the largest element). If it lies in range [x, y], we can just update the answer with the total size of the current subtree. Here is some code (the solution function returns a tuple with some extra information on top of the answer. If just want it to return the size of the largest subtree in range, you can wrap it around and use it as a helper function).
def min_with_none(a, b):
    """
    Returns the minimum of two elements.
    If one them is None, the other is returned.
    """
    if a is None:
        return b
    if b is None
        return a
    return min(a, b)

def max_with_none(a, b):
    """
    Returns the maximum of two elements.
    If one them is None, the other is returned.
    """
    if a is None:
        return b
    if b is None:
        return a
    return max(a, b)

def solution(x, y, T):
    """
    This function returns a tuple
    (max size of subtree in [x, y] range, total size of the subtree, min of subtree, max of subtree)
    """
    if T is None:
        return (0, 0, None, None)

    # Solves the problem for the children recursively
    left_ans, left_size, left_min, _ = solution(x, y, T.left)
    right_ans, right_size, _, right_max = solution(x, y, T.right)

    # The size of this subtree
    cur_size = 1 + left_size + right_size

    # The left border of the subtree is T.val or the smallest element in the
    # left subtree (if it's not empty)
    cur_min = min_with_none(T.val, left_min)

    # The right border of the subtree is T.val or the largest element in the
    # right subtree (if it's not empty)
    cur_max = max_with_none(T.val, right_max)

    # The answer is the maximum of answer for the left and for the right
    # subtree
    cur_ans = max(left_ans, right_ans)
    # If the current subtree is within the [x, y] range, it becomes the new answer,
    # as any subtree of this subtree is smaller than itself
    if x <= cur_min and cur_max <= y:
        cur_ans = cur_size

    return (cur_size, cur_ans, cur_min, cur_max)

This solution clearly runs in linear time as it visits every node only once and performs a constant number of operations per node.

A: With each node in BST, you can associate a valid range for it say [Li,Ri], which implies that all elements in subtree of that node lie in the valid range.
You can easily define these ranges recursively:
For a node i let's say the range is [Li, Ri] and the value stored in this node is val.
For left child of i, the range is [Li, val − 1]. And similarly for right child the range is [val + 1, Ri].
For root node the valid range is [−inf, inf].

A: Let's say our size function returned -1 for an invalid subtree. A (sub)tree is valid if both the node's value and all the values in its subtrees are in range.
# returns a tuple: (size of T, best valid size among itself and its subtrees)
def f(x,y,T):
  if T is None:
    return (0,0)

  l_size, l_best = f(x,y,T.left)
  r_size, r_best = f(x,y,T.right)

  if x <= T.value <= y and l_size >= 0 and r_size >= 0:
    return (1 + l_size + r_size,1 + l_size + r_size)
  else:
    return (-1,max(l_best,r_best))


text:
Q: indexing all combinations without making list What is the most efficient way to to find the i'th combination of all combinations without repetition and without first creating all combinations until i. K is fixed (number of elements in each combination) and N is fixed (number of elements to be combined). The order does not matter although extra kudos for finding i in the following order...

1
2
3
4
5
6
7
8

1,2,3,4
1,2,3,5
1,2,3,6
1,2,4,5
1,2,4,6
1,2,5,6
1,3,4,5
1,3,4,6

9
10
11
12
13
14
15

1,3,5,6
1,4,5,6
2,3,4,5
2,3,4,6
2,3,5,6
2,4,5,6
3,4,5,6

A: Much later update
After reading Zodman's comment below and his blog post, it turns out that this can be simplified! As it turns out, it is beneficial to change the setup as follows:

*

*Start indexing from zero

*Build combinations with zero as the smallest value, i.e. from $0,1,...,n-1$
Then we can answer the following question:

What is the lowest index a combination containing the number $m$?

Since there are $m$ values smaller than $m$, namely $0,1,...,m-1$, there will be:
$$
x=\binom mk
$$
combinations before $m$ appears for the first time. These will have indexes $0,1,...,x-1$ and so the first combination containing $m$ will have index $x$. This leads to both a ranking and an unranking algorithm:
Ranking
This is the name used in the blog post for finding the index given a combination. Consider this worked example:
$$
rank([7,4,0])=\binom 73+\binom 42+\binom 01=35+6+0=41
$$
so the index of the combination $[7,4,0]$ is $41$, since:

*

*You can make $35$ combinations of three less than $7$, so $[7,1,0]$ has index $35$

*You can make $6$ combinations of two less than $4$, so $[4,0]$ has index $6$ in this set of subcases which is then added, since we are starting from $35$
Formula
$$
rank([c_0,...,c_{k-1}])=\sum_{i=0}^k\binom{c_i}{k-i}
$$
where $c_i$'s are sorted in descending order.
Unranking
This is done similarly, by finding what the blog article calls the combinadic for the index, given $(n,k)$. So if $(n,k)=(10,3)$ and we want to find the $101$-st combination, then we must solve:
$$
101=\sum_{i=0}^k\binom{c_i}{k-i}=\binom 93+\binom62+\binom21=84+15+2
$$
This is solved by being greedy with the larger terms, and we have found $[9,6,2]$ as the answer.
Original answer
Note that the first number only changes after the rest have performed a full set of combinations within the subset they should be in, ie. we have
$$
|\{1xyz\mid 2\leq x<y<z\leq 6\}
$$
making a total of $\binom53=10$ combinations starting with $1$ since the three numbers $x,y$ and $z$ are chosen from the five possible values $2,3,4,5$ and $6$. Similarly we have
$$
|\{2xyz\mid 3\leq x<y<z\leq 6\}
$$
giving us $\binom43=4$ combinations starting with $2$. Based on this principle, we can make a list of values for which the first digit changes:
$$
\begin{array}{|c|c|}
\hline
\text{form}&\text{last }i&\text{formula for last }i\\
\hline
1xyz&10&\binom53=10\\
2xyz&14&10+\binom43=10+4\\
3xyz&15&14+\binom33=14+1\\
\hline
\end{array}
$$

This principle can be repeated down to the next level: Suppose we were to find the $58$-th combination $C=[x,y,z]$ of $k=3$ numbers chosen from $1,2,...,10=n$. Then we see that
$$
\begin{array}{|c|c|}
\hline
x&y&z&\text{last }i&\text{formula for last }i\\
\hline
1&y&z&36&\binom92=36\\
2&y&z&64&36+\binom82=36+28\\
\hline
&3&z&43&36+\binom71=36+7\\
&4&z&49&43+\binom61=43+6\\
&5&z&54&49+\binom51=49+5\\
&6&z&58&54+\binom41=54+4\\
\hline
&&7&55&54+\binom30=54+1\\
&&8&56&55+\binom20=55+1\\
&&9&57&56+\binom10=56+1\\
&&10&58&57+\binom00=57+1\\
\hline
\end{array}
$$
Following the logic of the table above we have $C=[2,6,10]$, and in fact:
$$
58=1+\underbrace{\binom 92}_{\text{1st digit}}+\underbrace{\binom71+\binom61+\binom51}_{\text{2nd digit}}+\underbrace{\binom30+\binom20+\binom10}_{\text{3rd digit}}
$$
where each digit can now be derived from the number of terms $1,3,3$ above as follows:
$$
\begin{align}
x&=1+1&=2\\
y&=x+1+3&=6\\
z&=y+1+3&=10
\end{align}
$$

Here is a Python-code where this is implemented:
def C(n,k): #computes nCk, the number of combinations n choose k
    result = 1
    for i in range(n):
        result*=(i+1)
    for i in range(k):
        result/=(i+1)
    for i in range(n-k):
        result/=(i+1)
    return result

def cgen(i,n,k):
    """
    returns the i-th combination of k numbers chosen from 1,2,...,n
    """
    c = []
    r = i+0
    j = 0
    for s in range(1,k+1):
        cs = j+1
        while r-C(n-cs,k-s)>0:
            r -= C(n-cs,k-s)
            cs += 1
        c.append(cs)
        j = cs
    return c

Note that this method does never compute previous combinations, but it still has to compute and sum relevant figures for the amount of previous combinations. But it is really fast! For instance, I asked it to compute cgen(173103094564,100,10) which is the $173103094564$-th combination of $k=10$ numbers chosen from $1,2,...,100=n$, and it immediately responded:
[1, 3, 5, 11, 19, 25, 38, 66, 80, 82]

which I would never have guessed, nor have constructed through $173103094564$ iterations!

Just to show the strength of it, I just did
cgen(68814103099439929837637702193841,1000,15)->
[7, 198, 280, 324, 448, 456, 517, 607, 668, 695, 697, 875, 879, 924, 954]

which actually took roughly 3 seconds to compute. We should not complain when we compare this to first having to construct the $68814103099439929837637702193840$ previous combinations - that would be infeasible!

A: Just a quick summary of what is described under Combinatorial number system on Wikipedia (and elsewhere). The order is lexicographically increasing with individual combinations written in decreasing order (so in your example this makes all combinations with a $6$ come after those without a $6$, unlike the order you listed).
For the easiest description, two things should be $0$-based: the combinations should be from the set $\{0,1,\ldots,n-1\}$ (so subtract $1$ from every element to get to this form), and the list of combinations starts at index$~0$. The elements of a combination however will themselves by indexed $c_1,\ldots,c_k$ in increasing order. Then the $k$-combination $\{c_1,\ldots,c_k\}$ comes at position $\binom{c_1}1+\binom{c_2}2+\cdots+\binom{c_k}k$, which of course is easy to compute. The essential point is that these numbers are different for different $k$-combinations, see under the link for details.


text:
Q: Intercept EventEmitters with Jasmine I'm building a node.js module and I wish also to test it with Jasmine.
Let say my module look similar to this:
var myModule = function (foo, bar) {

  // Begin a workflow
  var workflow = new (require('events').EventEmitter)();

  workflow.on('test', function () {
    var greet = greet();
    return greet;
  });

  workflow.emit('test');

};

function greet () {
  return "Hi!";
}

module.exports = {
  myModule: myModule
};

How can I test my module with Jasmine targeting all my Events I emit?
Something like this:
var myModule = require('../myModule.js');

describe('My Module test', function () {

  it('should get greet value', function () {
    myModule.on('test', function () { // "test" as I wrote in myModule
      expect(myModule.greet).toHaveBeenCalled();
    });
  });
});

A: I accomplish this using proxyquire: https://github.com/thlorenz/proxyquire
In your test file:
var proxyquire =  require('proxyquire');
var mockEvents = {};
var myModule = proxyquire('../myModule.js', {
  events: mockEvents
});

describe('My Module test', function () {
  beforeEach(function() {
    mockEvents.EventEmitter = function () {};

    mockEvents.EventEmitter.prototype = {
      on: function () { },
      emit: function () { }
    };

    spyOn(mockEvents.EventEmitter.prototype, 'on');
    spyOn(mockEvents.EventEmitter.prototype, 'emit');
  });

  it('should get greet value', function () {
    myModule()
    expect(mockEvents.EventEmitter.prototype.on).toHaveBeenCalledWith('test');
    expect(mockEvents.EventEmitter.prototype.emit).toHaveBeenCalledWith('test');
  });
});

You can also use a spy as your mock EventEmitter, etc.

A: The main problem is that greet is not really exposed and is therefore not accessible in the tests. Here are some ways to handle this:

*

*Add it to the prototype chain to make it accessible (this is what I have done below).

*Expose the function in the module.exports. This could be wrapped in a process.env.NODE_ENV !== production to exclude it from production.

*Not expose it but test the event emitter functionality and impact of the function (this is probably not ideal).
To achieve what you want, you could monkey patch the functions and test that they have been called and test the result of greet individually:
MyModule.js
var EventEmitter = require('events').EventEmitter;
var MyModule = function (foo, bar) {
  // Begin a workflow
  var workflow = new EventEmitter();

  workflow.on('test', function () {
    return this.greet();
  }.bind(this));

  workflow.emit('test');
};

MyModule.prototype.greet = function () {
  return "Hi!";
};

module.exports = MyModule;

MyModule-tests.js
var EventEmitter = require('events').EventEmitter;

describe('MyModule', function () {
  it('emits an event upon construction', function () {
    // Monkey patch
    var originalEventEmitterOn = EventEmitter.prototype.on;
    EventEmitter.prototype.on = jasmine.createSpy('on');

    // Create module
    var MyModule = require('./MyModule');
    new MyModule();
    expect(EventEmitter.prototype.on).toHaveBeenCalled();

    // Reset
    EventEmitter.prototype.on = originalEventEmitterOn;
  });

  it('calls greet upon construction', function () {
    var MyModule = require('./MyModule');

    // Monkey patch
    var originalGreet = MyModule.prototype.greet
    MyModule.prototype.greet = jasmine.createSpy('greet');

    var myModule = new MyModule();
    expect(myModule.greet).toHaveBeenCalled();

    // Reset
    MyModule.prototype.greet = originalGreet;
  });

  it('returns "Hi!"', function () {
    var MyModule = require('./MyModule');
    var myModule = new MyModule();
    expect(myModule.greet()).toBe("Hi!");
  });
});


text:
Q: XSLT variable containing XML I have found this site which says that I can pick a specific node of this code
<xsl:variable name="in-xml" as="item()*"> <in-xml>
     1
     <c>2</c>
     3
     4
     5    </in-xml> </xsl:variable>

It says that if you wrote this:
$in-xml/*[position() > 2]

you would get this:
3
4
5

but it seems not to be working for me.
Here is the site: http://www.xsltfunctions.com/xsl/fn_position.html
Can anyone give the code to get that???

A: In XSLT 1.0, XPath expressions can only be performed on input data, not on data created in the course of evaluating the stylesheet.  So one way to make your example work would be to move the in-xml data to an external document and load it using the document() function.  There are also some tricky / clever techniques that involve writing the in-xml element as a child of xsl:stylesheet and using document('')/xsl:stylesheet/in-xml to declare the variable; these techniques work with good XSLT 1.0 implementations but fail in some browser implementations.
In XSLT 2.0, the constraint on the use of XPath was relaxed and something along the lines you sketch should work.

A: EXSLT defines node-set() which can be used here. Here is a MsXsl implementation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
        <xsl:variable name="in-xml" >
            <in-xml>
                1
                <c>2</c>
                3
                4
                5
            </in-xml>
        </xsl:variable>

        <xsl:value-of select="msxsl:node-set($in-xml)/in-xml/a[position() > 2][1]"/>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Youtube API V3 GET banner image with PHP (Undefined Index) Thank you for your help, I'm trying to get the banner image from an specific channel on YouTube using the Api V3.
I'm using the following format:

https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&id={CHANNEL-ID}&key={YOUR_API_KEY}

Getting the following info:
{
 "kind": "youtube#channelListResponse",
 "etag": "\"F9iA7pnxqNgrkOutjQAa9F2k8HY/s93ZotjagYf2fFr0mqM9MxU-SaU\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#channel",
   "etag": "\"F9iA7pnxqNgrkOutjQAa9F2k8HY/Tz1L-MnftzBIXiDdwzUINRNgkUY\"",
   "id": "UCD6YMmVyF50oiwXisgbF-2w",
   "brandingSettings": {
    "channel": {
     "title": "ArrolladoraLimonVEVO",
     "keywords": "Arrolladora Limon VEVO Music",
     "showRelatedChannels": true,
     "showBrowseView": true,
     "featuredChannelsTitle": "Featured Channels",
     "featuredChannelsUrls": [
      "UC2pmfLm7iq6Ov1UwYrWYkZA",
      "UCnrJTmHzaiAjuA_pTpfd9Uw"
     ],
     "unsubscribedTrailer": "5ZZ6I4pmGIE",
     "profileColor": "#000000"
    },
    "image": {
     "bannerImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1060-fcrop64=1,00005a57ffffa5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerMobileImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w640-fcrop64=1,32b75a57cd48a5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTabletLowImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1138-fcrop64=1,00005a57ffffa5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTabletImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1707-fcrop64=1,00005a57ffffa5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTabletHdImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w2276-fcrop64=1,00005a57ffffa5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTabletExtraHdImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w2560-fcrop64=1,00005a57ffffa5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerMobileLowImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w320-fcrop64=1,32b75a57cd48a5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerMobileMediumHdImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w960-fcrop64=1,32b75a57cd48a5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerMobileHdImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1280-fcrop64=1,32b75a57cd48a5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerMobileExtraHdImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1440-fcrop64=1,32b75a57cd48a5a8-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTvImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w2120-fcrop64=1,00000000ffffffff-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTvLowImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w854-fcrop64=1,00000000ffffffff-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTvMediumImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1280-fcrop64=1,00000000ffffffff-nd/la_arrolladora_youtube_pre_order.png",
     "bannerTvHighImageUrl": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w1920-fcrop64=1,00000000ffffffff-nd/la_arrolladora_youtube_pre_order.png"
    },
    "hints": [
     {
      "property": "channel.banner.mobile.medium.image.url",
      "value": "https://yt3.ggpht.com/-Cv2TDQuv-kw/VJC0D9dimxI/AAAAAAAAADU/vaNVkDmXyz4/w640-fcrop64=1,32b75a57cd48a5a8-nd/la_arrolladora_youtube_pre_order.png"
     },
     {
      "property": "channel.featured_tab.template.string",
      "value": "Everything"
     },
     {
      "property": "channel.modules.show_comments.bool",
      "value": "True"
     },
     {
      "property": "channel.banner.image_height.int",
      "value": "0"
     }
    ]
   }
  }
 ]
}

The problem is on my PHP code, I'm receiving the following error:

Notice: Undefined index: image

Code:
<?php
 $feedURL2 = "https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&id=UCD6YMmVyF50oiwXisgbF-2w&key=*****";

function GetytBanner() {
    global $feedURL2;
    $json = file_get_contents ($feedURL2);
    $obj = json_decode($json,true);
    return $obj['items']['image']['bannerImageUrl'];
}

 ?>

<?php echo GetytBanner(); ?>

A: I have been using a wrong format:
return $obj['items']['image']['bannerImageUrl'];

Correct way:
return $obj['items'][0]['brandingSettings']['image']['bannerTvHighImageUrl'];


text:
Q: wordpress set post_status as "draft" in 'save_post' action I have a custom function that works with my custom post type. While porocessing save_post action:
add_action( 'save_post', 'my_custom_function' );

I would like to set post status as draft (in case of a problem with getting custom data from outside api).
In my my_custom_function function I have this little block:
if ($error == true) {
    $override_post = array();
    $override_post['ID'] = $post_id;
    $override_post['post_status'] = 'draft';
    wp_update_post( $override_post );
}

but it seems, that after save_post is being processed, then post_status is being set again.
Anybody have an idea, where should I hook into, so while saving post data I can modify its post_status, post_date and some other post data informations so they are not being overriten?

A: You should hook it to wp_insert_post_data. Then you could use a function like this to set your post status to draft:
add_filter( 'wp_insert_post_data', 'set_post_to_draft', 99, 2 );

function set_post_to_draft( $data, $postarr ) {

  if ( your_condition ) {
    $data['post_status'] = 'draft';
  }

  return $data;
}

A: I had to make a post type with only one post_status option, and it seem to fit your needs too, as it is works exactly with the save_post hook.
add_action( 'save_post', 'my_function' );
function my_function( $post_id ){
    if ( ! wp_is_post_revision( $post_id ) ){
        // avoid endless circle
        remove_action('save_post', 'my_function');

        // update the data before saving
        wp_update_post( wp_slash([
            'ID' => $_POST['ID'],
            'post_status' => 'draft'
        ]));

        // restore the saving hook
        add_action('save_post', 'my_function');
    }
}

The original solution found here:
https://wp-kama.ru/function/wp_update_post


text:
Q: Is yarn global add broken on Windows? When I install react-native-cli with yarn add global react-native-cli on Windows 7 or 10, it won't run. The PATH is set properly, and npm install -g react-native-cli works fine. I tested with other packages, they act the same. I tested on MacOS and Ubuntu Bash inside Windows 10, and those both work fine.
I'm using yarn 0.27.5, and have tried both node 6.10 and 7.8.
My current workaround is to use npm for global installs, but I'd prefer to use yarn for consistency (and npm 5 has its own Windows-specific issues).

A: I have fixed the same issue by ensuring the result of yarn global bin is added to both the user environment variables' %PATH% and to the system environment variables' %PATH%. I only had it in the user ones and that didn't work.


text:
Q: For what values of $c$ is $\sin (x+y) = c$ a smooth curve? Asked Calculating the derivative, it's onto as long as $c$ isn't 1 or -1.
But when c = 1 or -1, is it still a smooth curve?
EDIT: I wrote c = 0 for some stupid reason

A: It is a bunch of parallel lines, all of slope $-1$.  When $c$ reaches $\pm1$, the lines collide in pairs; as $c$ passes $-1$ or $1$, they disappear.
So they are always smooth, if they exist.


text:
Q: javascript issue in chrome I have the following code in javascript
I am storing a php array in a javascript array below
<script type="text/javascript">

    var name=new Array();
    <?php
        for($i=0;$i<count($ids); $i++)
            {
                echo "name[$i]='".$name[$i]."';";
            }
    ?>

</script>

When i alert name[1], in firefox I am able to see the value of name[1], but when i run the code in chrome i get undefined in the alert box.
How can i solve this.
Do I have to change the way I am storing the array or do I have to do something else.

A: Because you're committing a great sin in declaring your variable:

*

*It's a global, which is bad practice.

*it's name is name, which is a reserved keyword in chrome, just open console and type for (n in window){if (n === 'name'){console.log(true)}}, it'll log true

*don't use new Array();, use []
on php front: either use the double quotes consistently, or use single quotes (but that's just my personal preference):
echo "name[$i]='{$name[$i]}';";
echo 'name['.$i.']="'.$name[$i].'";';

Like the way you place the curly's, though... :-P


text:
Q: pipenv locking for NumPy fails on Python3.9 and pip21.0.1 When I try to install pandas via pipenv I get a bunch of numpy errors after the locking process. When I try to install bs4 via pipenv it works fine, but for some reason, it fails with pandas. I have tried deleting and reinstalling pipenv and removing the environment, but nothing has worked.
I am using Python 3.9.1 and pip 21.0.1.
I am on macOS Big Sur.
Here is the code snippet of the errors I get. The errors occur during the locking process (writing to pipenv.lock):
  Copying numpy.egg-info to build/bdist.macosx-11-x86_64/wheel/numpy-1.20.0-py3.9.egg-info
  running install_scripts
  Traceback (most recent call last):
    File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_vendor/pep517/_in_process.py", line 257, in <module>
      main()
    File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_vendor/pep517/_in_process.py", line 240, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_vendor/pep517/_in_process.py", line 181, in build_wheel
      return _build_backend().build_wheel(wheel_directory, config_settings,
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 211, in build_wheel
      return self._build_with_temp_dir(['bdist_wheel'], '.whl',
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 197, in _build_with_temp_dir
      self.run_setup()
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 248, in run_setup
      super(_BuildMetaLegacyBackend,
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 142, in run_setup
      exec(compile(code, __file__, 'exec'), locals())
    File "setup.py", line 513, in <module>
      setup_package()
    File "setup.py", line 505, in setup_package
      setup(**metadata)
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-install-o5k4mrv9/numpy/numpy/distutils/core.py", line 169, in setup
      return old_setup(**new_attr)
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/setuptools/__init__.py", line 165, in setup
      return distutils.core.setup(**attrs)
    File "/usr/local/Cellar/python@3.9/3.9.1_6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/distutils/core.py", line 148, in setup
      dist.run_commands()
    File "/usr/local/Cellar/python@3.9/3.9.1_6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/distutils/dist.py", line 966, in run_commands
      self.run_command(cmd)
    File "/usr/local/Cellar/python@3.9/3.9.1_6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/wheel/bdist_wheel.py", line 328, in run
      impl_tag, abi_tag, plat_tag = self.get_tag()
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/wheel/bdist_wheel.py", line 252, in get_tag
      plat_name = get_platform(self.bdist_dir)
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/wheel/bdist_wheel.py", line 48, in get_platform
      result = calculate_macosx_platform_tag(archive_root, result)
    File "/private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-9iqn62cr/overlay/lib/python3.9/site-packages/wheel/macosx_libfile.py", line 356, in calculate_macosx_platform_tag
      assert len(base_version) == 2
  AssertionError

  ########### EXT COMPILER OPTIMIZATION ###########
  Platform      :
    Architecture: x64
    Compiler    : clang

  CPU baseline  :
    Requested   : 'min'
    Enabled     : SSE SSE2 SSE3
    Flags       : -msse -msse2 -msse3
    Extra checks: none

  CPU dispatch  :
    Requested   : 'max -xop -fma4'
    Enabled     : SSSE3 SSE41 POPCNT SSE42 AVX F16C FMA3 AVX2 AVX512F AVX512CD AVX512_KNL AVX512_SKX AVX512_CLX AVX512_CNL AVX512_ICL
    Generated   :
                :
    SSE41       : SSE SSE2 SSE3 SSSE3
    Flags       : -msse -msse2 -msse3 -mssse3 -msse4.1
    Extra checks: none
    Detect      : SSE SSE2 SSE3 SSSE3 SSE41
                : numpy/core/src/umath/_umath_tests.dispatch.c
                :
    SSE42       : SSE SSE2 SSE3 SSSE3 SSE41 POPCNT
    Flags       : -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2
    Extra checks: none
    Detect      : SSE SSE2 SSE3 SSSE3 SSE41 POPCNT SSE42
                : build/src.macosx-11-x86_64-3.9/numpy/core/src/_simd/_simd.dispatch.c
                :
    AVX2        : SSE SSE2 SSE3 SSSE3 SSE41 POPCNT SSE42 AVX F16C
    Flags       : -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mavx2
    Extra checks: none
    Detect      : AVX F16C AVX2
                : numpy/core/src/umath/_umath_tests.dispatch.c
                :
    (FMA3 AVX2) : SSE SSE2 SSE3 SSSE3 SSE41 POPCNT SSE42 AVX F16C
    Flags       : -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2
    Extra checks: none
    Detect      : AVX F16C FMA3 AVX2
                : build/src.macosx-11-x86_64-3.9/numpy/core/src/_simd/_simd.dispatch.c
                :
    AVX512F     : SSE SSE2 SSE3 SSSE3 SSE41 POPCNT SSE42 AVX F16C FMA3 AVX2
    Flags       : -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f
    Extra checks: AVX512F_REDUCE
    Detect      : AVX512F
                : build/src.macosx-11-x86_64-3.9/numpy/core/src/_simd/_simd.dispatch.c
                :
    AVX512_SKX  : SSE SSE2 SSE3 SSSE3 SSE41 POPCNT SSE42 AVX F16C FMA3 AVX2 AVX512F AVX512CD
    Flags       : -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq
    Extra checks: AVX512BW_MASK AVX512DQ_MASK
    Detect      : AVX512_SKX
                : build/src.macosx-11-x86_64-3.9/numpy/core/src/_simd/_simd.dispatch.c
  CCompilerOpt._cache_write[796] : write cache to path -> /private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-install-o5k4mrv9/numpy/build/temp.macosx-11-x86_64-3.9/ccompiler_opt_cache_ext.py

  ########### CLIB COMPILER OPTIMIZATION ###########
  Platform      :
    Architecture: x64
    Compiler    : clang

  CPU baseline  :
    Requested   : 'min'
    Enabled     : SSE SSE2 SSE3
    Flags       : -msse -msse2 -msse3
    Extra checks: none

  CPU dispatch  :
    Requested   : 'max -xop -fma4'
    Enabled     : SSSE3 SSE41 POPCNT SSE42 AVX F16C FMA3 AVX2 AVX512F AVX512CD AVX512_KNL AVX512_SKX AVX512_CLX AVX512_CNL AVX512_ICL
    Generated   : none
  CCompilerOpt._cache_write[796] : write cache to path -> /private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-install-o5k4mrv9/numpy/build/temp.macosx-11-x86_64-3.9/ccompiler_opt_cache_clib.py
  ----------------------------------------
  ERROR: Failed building wheel for numpy
Failed to build numpy
ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly
----------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 764, in <module>
    main()
  File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 758, in main
    _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write,
  File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 741, in _main
    resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev)
  File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 702, in resolve_packages
    results, resolver = resolve(
  File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 684, in resolve
    return resolve_deps(
  File "/usr/local/lib/python3.9/site-packages/pipenv/utils.py", line 1395, in resolve_deps
    results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
  File "/usr/local/lib/python3.9/site-packages/pipenv/utils.py", line 1108, in actually_resolve_deps
    resolver.resolve()
  File "/usr/local/lib/python3.9/site-packages/pipenv/utils.py", line 823, in resolve
    results = self.resolver.resolve(max_rounds=environments.PIPENV_MAX_ROUNDS)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/resolver.py", line 180, in resolve
    has_changed, best_matches = self._resolve_one_round()
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/resolver.py", line 268, in _resolve_one_round
    their_constraints.extend(self._iter_dependencies(best_match))
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/resolver.py", line 383, in _iter_dependencies
    dependencies = self.repository.get_dependencies(ireq)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/repositories/pypi.py", line 229, in get_dependencies
    legacy_results = self.get_legacy_dependencies(ireq)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/repositories/pypi.py", line 350, in get_legacy_dependencies
    results, ireq = self.resolve_reqs(
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/repositories/pypi.py", line 306, in resolve_reqs
    results = resolver._resolve_one(reqset, ireq)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/legacy_resolve.py", line 339, in _resolve_one
    abstract_dist = self._get_abstract_dist_for(req_to_install)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/legacy_resolve.py", line 287, in _get_abstract_dist_for
    abstract_dist = self.preparer.prepare_linked_requirement(req)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/operations/prepare.py", line 508, in prepare_linked_requirement
    abstract_dist = _get_prepared_distribution(
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/operations/prepare.py", line 95, in _get_prepared_distribution
    abstract_dist.prepare_distribution_metadata(finder, build_isolation)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/distributions/sdist.py", line 38, in prepare_distribution_metadata
    self._setup_isolation(finder)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/distributions/sdist.py", line 66, in _setup_isolation
    self.req.build_env.install_requirements(
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/build_env.py", line 202, in install_requirements
    call_subprocess(args, spinner=spinner)
  File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/utils/subprocess.py", line 242, in call_subprocess
    raise InstallationError(exc_msg)
pipenv.patched.notpip._internal.exceptions.InstallationError: Command errored out with exit status 1: /Users/kaiznanji/.local/share/virtualenvs/Kalgo-wH0XXFPH/bin/python /usr/local/lib/python3.9/site-packages/pipenv/patched/notpip install --ignore-installed --no-user --prefix /private/var/folders/d9/737381n90cv4_jc2pnx1vc5w0000gn/T/pip-build-env-4nfnxp9e/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.29.21,<3' 'numpy==1.16.5; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.5; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy; python_version>='"'"'3.9'"'"'' Check the logs for full command output.

Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
bs4 = "*"
requests = "*"
pandas = "*"
joblib = "*"

[dev-packages]

[requires]
python_version = "3.9"

A: I face this problem constantly. Sometimes this solution works, but not all the time. Run this in your terminal:
export SYSTEM_VERSION_COMPAT=1

If someone else understands why this works sometimes, please feel free to comment or edit my answer.

A: The stacktrace from the original poster as well as mine included an error in bdist_wheel.py.  Opening that exact file, it was importing 'distutils' to call 'distutils.util.get_platform()'.  But when I started a python shell to see what that call returned on my machine, the active version of distutils didn't have 'util' subpackage.  That's a clue that the python version I'm using is not the version being used by pipenv to build libraries.
That led me to figure out what version of python I really wanted to use and make sure pipenv was using that as well as currently installed packages:
> which python
/usr/local/Caskroom/miniforge/base/bin/python

>pipenv install --python=/usr/local/Caskroom/miniforge/base/bin/python  --site-packages

This works so far and may help some folks, however specifying the python version does not work for pipenv lock so it's probably not a complete solution.
Ultimately I probably need to go back to basics and use pyenv to properly manage the python version and keep things consistent.

A: Running this first solved it for me:
export SYSTEM_VERSION_COMPAT=1


text:
Q: Sort my contacts alphabetic using cURL I'm receiving all of my contacts on Google Contacts using this method:
session_start();

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ClientLogin');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = array(
    'accountType' => 'GOOGLE',
    'Email' => 'email',
    'Passwd' => 'password',
    'source' => 'sourcetest',
    'service' => 'cp'
);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$responses = explode("\n", curl_exec($ch));
$_SESSION['auth'] = str_replace('Auth=', '', $responses[2]);
$_SESSION['email'] = 'email';

$url = 'https://www.google.com/m8/feeds/contacts/default/full';
$url .= '?group=http://www.google.com/m8/feeds/groups/'.$_SESSION['email'].'/base/6';
$url .= '&max-results=500&alt=json';

$ch = curl_init($url);

$header[] = 'Authorization: GoogleLogin auth='.$_SESSION['auth'];
$header[] = 'GData-Version: 3.0';

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);

$response = curl_exec($ch);
curl_close($ch);

/** **** **** **** **** **** **** **** **** **** **** **/

# CONTROL
if(isset($response_as_array['feed']) AND isset($response_as_array['feed']['entry'])) {

    # TABLE
    echo '
';
    echo '
';
        echo '';
            echo 'Namn';
        echo '	';

        echo '';
            echo 'Telefon-nummer';
        echo '	';
    echo '
';

    # LOOP
    foreach($response_as_array['feed']['entry'] AS $i => $entry) {

        # CONTROL: Hide my name
        if(utf8_decode($entry['gd$name']['gd$fullName']['$t']) != 'Erik Edgren') {

            echo '
';
                echo '';
                    echo utf8_decode($entry['gd$name']['gd$fullName']['$t']);
                echo '	';

                echo '';
                    echo isset($entry['gd$phoneNumber'][0]) ? $entry['gd$phoneNumber'][0]['$t'] : '';
                echo '	';
            echo '
';

        }

    }

    echo '
';

}

It works fine but it's not sorting the contacts alphabetically. How can I do this?
Thanks in advance.

A: I assume that you have an array in $response_as_array['feed']['entry'] which have all your contacts, then you can use:
usort($response_as_array['feed']['entry'], function($a, $b) {
    return strcmp($a['gd$name']['gd$fullName']['$t'], $b['gd$name']['gd$fullName']['$t']);
});

A: You could try asort(): http://php.net/manual/en/function.asort.php
You may have to re-arrange the data from Google to do this temporarily.
To be honest I would have imagined Google to provide some additional conditions you could use to get them to sort it for you. Which would be appended to the request URL.


text:
Q: Why does reprepro complain about the "all" architecture? I started setting up a deb repository today for some of our applications. Given that they are interpreted scripts, I went with "all" architecture (from conf/distributions):
Codename: lucid
Architectures: all

But reprepro will print a warning when I try to add a .deb to the repository:
WARNING: Distribution lucid contains an architecture called 'all'.

Now I wonder why it warns about that? What's the problem?

A: Ah ha! I finally just figured it out. This has been frustrating me for ages now.
If you specify your .deb (control file) as Architecture: all, then don't put anything into the reprepro distributions file other than the arch's that you want it to get put into.
Architectures: amd64 i386 ...


text:
Q: Universal audio player with controls in multiple view controllers Audioboo iOS app has a universal audio player with controls (i.e. play/pause button.) view always visible on loaded view controllers when playing content. Also sometimes the view controllers themselves have controls as well (play/pause button and a countdown timer)
My question is what's the best way to know when loading a view that the player is playing its  corresponding content and update this view's control state and timer?
Check these screenshot links
http://cl.ly/image/2k213Q0L2U2w
http://cl.ly/image/3o0F0a150d1T
//The bottom player view is always visible when navigating between view controllers.
NOTE :
  This is my first question ever here, so please let me know if you have any questions or want me to clear something up :]

A: In your class that manages audio player you should add public property, that would point on currently playing entity. For instance:
@interface MyAudioPlayer : AVPlayer
...
@property (nonatomic, strong) Song *currentSong
...
@end

and don't forget to assign corresponding song to this property whenever the new song starts playing.
Then you would be able to access this current song from any view controller.
UPD:
After some clarification, I post update for future reference.
In order to manage correspondence between player data and UI part for multiple UIViewControllers there are 3 main approaches:
1) You might want to use NSNotification, sent by player manager class when some event appears (like changing the song, etc.) and intercepted by your view controllers.
2)  You might want to use KVO and subscribe your view controllers to changes in player class.
3) You might want to take a look at ReactiveCocoa which is replacement to KVO paradigm.

A: Make a custom tab-bar that plays the song and has a bar to track progress and such. Then when you change views, the 'current song' view will not change and will remain the same. You could also just add a custom view on the top of the screen using the AppDelegate. Hope that helps!


text:
Q: Why can't magnetic flux be no longer defined for non-zero diameter wire? This is a continuation of my previous question:
This is the concerned quote form Purcell's Electricity and Magnetism's Electromagnetic Induction:

You may think that one of the rings we considered earlier would have made a simpler example to illustrate the calculation of self-inductance. However, if we try to calculate the inductance of a simple circular loop of wire , we encounter a puzzling difficulty . It seems a good idea to simplify the problem by assuming that the wire has zero diameter. But we soon discover that, if finite current flows in a filament of zero diameter, the flux threading a loop made of such a filament is infinite! The reason is that the field $B,$ in the neighbourhood of a filamentary current, varies as $1/r,$ where $r$ is the distance from the filament, and the integral of $B\times \mathcal{area}$ diverges as $\int (dr/r)$ when we extend it down to $r= 0\;.$ To avoid this, we may let the radius of the wire be finite, and not zero, which is more realistic anyway. This may make the calculation a bit more complicated, but that won't worry us. The real difficulty is that different parts of the wire now appear as different circuits, linked by different amounts of flux. We are no longer sure what we mean by the flux through the circuit. In fact, because the electromotive force is different from the different filamentary loops into which the circuit can be divided, some redistribution  of current density must occur when rapidly changing currents flow in the ring. Hence the inductance of the circuit may depend somewhat on the rapidity of $I,$ ...
We avoided this embarrassment in the toroidal coil example by ignoring the field in the immediate vicinity of the individual turns of the winding. Most of the flux does not pass through the wire themselves, and whenever that is the case the effect we have just been worrying about will be unimportant.

I didn't understand the difficulty faced as stated by Purcell when a non-zero diameter wire is taken into account. Why did he say " different parts of the wire now appear as different circuits, linked by different amounts of flux"? "We are no longer sure what we mean by the flux through the circuit"- Why is it so? why can't we define flux for the non-zero diameter wire?
Really I'm not getting why different parts of a non-zero diameter wire become different circuits:/
Can anyone please explain this to me why flux can no longer be defined and how different parts of the non-zero diameter become different circuits?

A: In science you need to make predictions. To make a prediction you have to predict something will happen before you see it happens. Which means you need to use your mind to figure out what you think will happen.
A common way to do this is to use your mind to make a mathematical model and then manipulate the mathematical model with your mind to come up with your prediction.
So you need to be able to do some mathematics and to know what real world things your mathematics corresponds to.
The kind of mathematics you can learn includes (but is not limited to) scalar fields, vector fields, gradients, divergences, curls, line integrals, area integrals, volume integrals, fluxes through surfaces and so on.
Sometimes a mathematical result will tell you that the line integral around a mathematical closed curve (a loop) is equal to the mathematical flux through a mathematical surface enclosed by the mathematical loop.
So, for instance the line integral of a vector field $\vec E$ around a mathematical loop might be equal to the flux of $\vec \nabla \times \vec E$ through a mathematical surface bounded by that loop. That's all mathematics.
If you tried to relate this mathematical result about 1d mathematical curves to the real world you'd essentially have two options. The first option would be to model your wire as a 1d loop, in which case you have to deal with a diverging magnetic field as you get close to the wire. The second option is to have a thick wire and realize there are many possible 1d curves through that wire, each having a different line integral of the electric field (modelled by a vector field) along one of the many 1d curves through the wire.
Experimentally you might try to relate the line integral of the electric field to an EMF or even a current through a wire. But if different parts of the wire have different electric fields, and there are many curves that loop through the wire. No single one of them has a direct and obvious correspondence to an EMF. And the current might not be as simple as a cross section all having a $\vec J$ piercing through it orthogonally.
If you had an annulus shaped wire instead of a  1d curve, and all the current was going in a circular direction. Then you could compute the EMF around the inner loop or around the outer loop. And you'd get different results. Neither directly applies to the loop as a whole. You could also compute an EMF around a loop with intermediate radius. Or one that wiggles between the inner and outer radius. When the wire was modelled by a 1d mathematical curve, your line integral could be "around the loop" and by staying in the loop, you had exactly one curve. Now, there are lots of curves that stay in the loop.
If your current stays in your loop, a natural direction to do a line integral is the direction the current is going, but there is no guarantee that such a curve is closed. But for the example we looked at, such a curve is closed.
And each circular loop has its own line integral. And for each loop you might also look at the flux of $-\partial \vec B /\partial t$ through any of the mathematical surfaces bounded by each one of the mathematical loops.
So for instance you could make a mathematical model where there is some $\vec J$ going around the wire. And find the magnetic field. And find the flux through every loop (the inner one, the outer one, and the ones in between). And find for each loop the rate the magnetic flux is changing in time, and relate that to the $\vec J$ along that curve.
From Maxwell you might expect that $\vec \nabla \times \vec E=-\partial \vec B /\partial t.$ And mathematically you might expect that the line integral of the electric field around a closed loop equal the flux of the curl through the surface bounded by the loop. So if $\vec J=k\vec E$ (a small scale version of Ohm's law) then we have \begin{align}\oint_{\partial S} \vec J\cdot d\ell &=k\oint_{\partial S} \vec E\cdot d\ell\\&=k\iint_{S} \left(\vec \nabla \times \vec E\right)\cdot \hat n dA\\&=k\iint_{S} \left(-\frac{\partial \vec B}{\partial t}
\right)\cdot \hat n dA,\end{align} where $S$ is a surface bounded by $\partial S$ which is one of the loops within the wire.
So lots of loops, lots of different surfaces. But if you make a model with a certain $k$ and a certain magnetic field and $\vec J$ you can confirm that your model matches above.
And the fact that you restricted your models to ones where \begin{align}\iint_{S} \left(\vec \nabla \times \vec E\right)\cdot \hat n dA &=\iint_{S} \left(-\frac{\partial \vec B}{\partial t}
\right)\cdot \hat n dA,\end{align} is where you tested the laws of physics. The first line was part of your model. The others were just math. And the part where \begin{align}\iint_{S} \left(\vec \nabla \times \vec E\right)\cdot \hat n dA &=\iint_{S} \left(-\frac{\partial \vec B}{\partial t}
\right)\cdot \hat n dA,\end{align} was the law of physics.
You use the laws of physics to make models and you compare what happens in the model to what happens in reality. And in this case there isn't a simple thing called an EMF that directly corresponds to some unique curve.
In this model you have electric and magnetic fields everywhere. And in some places there is a wire where the electric field and current density are proportional and everywhere else there is no current density. Then you can make that model conform to Maxwell by making sure the magnetic field and the electric field are connected the way Maxwell demands.
One way to satisfy Maxwell would be to have both the electric and magnetic field to be the electric and magnetic parts of the electromagnetic field given by Jefimenko's equations:
$$\vec E(\vec r,t)=\frac{1}{4\pi\epsilon_0}\int\left[\frac{\rho(\vec r',t_r)}{|\vec r -\vec r'|}+\frac{\partial \rho(\vec r',t_r)}{c\partial t}\right]\frac{\vec r -\vec r'}{|\vec r -\vec r'|^2}\; \mathrm{d}^3\vec{r}'
-\frac{1}{4\pi\epsilon_0c^2}\int\frac{1}{|\vec r-\vec r'|}\frac{\partial  \vec J(\vec r',t_r)}{\partial t}\mathbb{d}^3\vec r'$$ and
$$\vec B(\vec r,t)=\frac{\mu_0}{4\pi}\int\left[\frac{\vec J(\vec r',t_r)}{|\vec r -\vec r'|^3}+\frac{1}{|\vec r -\vec r'|^2}\frac{\partial \vec J(\vec r',t_r)}{c\partial t}\right]\times(\vec r -\vec r')\mathbb{d}^3\vec r'$$
where $t_r$ is actually a function of $\vec r'$, specifically $t_r=t-\frac{|\vec r-\vec r'|}{c}.$
These reduce to Coulomb and Biot-Savart only when those time derivatives are exactly zero, which is statics. So Jefimenko is an example of proper time dependent laws for the electromagnetic field. Note that both the electric and the magnetic part of the electromagnetic field have parts that depend on the time variation of current.
So if you use these equations, the change in current directly causes both electric and magnetic fields. But when the current changes at place-time $(\vec r_1,t_1)$, there is an electric and a magnetic field. But the field exists only at place-times $(\vec r_2,t_2)$ where $t_2=t_1+\frac{|\vec r_2-\vec r_1|}{c}$.

Right from the beginning of studying electromagnetism, I always came before these: straight wire, circular loop, circular ring etcetera. These all referring to 1d current-carrying conductors. See this statement: we need to find the magnetic field at the center due to current in a circular ring- obviously, this is not talking of an annalus - it is talking about a zero-diameter wire, isn't it? That means at all the places, where they are saying current is flowing, $\vec J= \infty$ as the wire diameter is zero. So, does that mean all these books are saying are total wrong?

If you had current flowing through an annulus with inner radius $a$ and outer radius $b$ then when you find the magnetic field in the center, some of the current is a distance $a$ away. Some of it is a distance $b$ away. And some of it is an in between distance away.
But if $(b-a)/b<<1$ then none of the computations are off by very much percentage wise when you are at the center if you just computed as if it was all at $a.$ Divide by $a,$ divide by $b,$ divide by something in between and percentage wise you aren't off by much. The whole idea of a continuous current rather than a velocity times a delta function where each discrete charge is located is a fiction. And trying to have a delta function where each charge is located would be a false accuracy if Quantum Mechanically you don't think discrete charges have a location and a velocity.
So the point is someone could ask you to compute the magnetic field in the center of a circular loop of radius $a$ and if in reality it is super tiny thickness then when you do it properly as an annulus with outer radius $b$ and inner radius $a$ you will get a tiny bit smaller magnetic field. But in the limit as $b$ approaches $a$ you get closer to the result you computed with the 1d circle of current with radius $a.$
But the field near the current itself gets much more accurate when you give it some thickness.
Basically, from far away a thick wire starts to look thin. And if you compute with the thin one you might get real accurate results.
And you might be hung up wrong versus right. Your job is to make predictions. The predictions have to relate to real measurements and the real measurements will always have some uncertainty. Every ruler has a smallest spacing, every clock a shortest tick. Every detector has a rate of misfires that falsely react to nothing, and a rate that it falsely false to react to a true signal. They exist, and so any calculation that starts to get more precise than those errors stops being detectable. And so you never need to be perfect with your theory. You must need to be better than the experimentalist.
And the experimentalist could get arbitrarily good (but still has nonzero error) so you might need to be arbitrarily good too, but you never need to be perfect.
Finally, when percentage wise a much smaller magnetic flux goes through the wires parts than not through the wire, then you aren't very wrong when you just stop at the inner most part of the wire.


text:
Q: Why are there no (augmented assignment) operators like +=, -= or ++ in Ada? I'm wondering why there are no operators like +=, -=, ++, -=, <<= or x ? y : z (not an augmented assignment ...) in Ada? Many other languages (C, C++, C#, Java, Perl) have them.
-- Example (C/C++/...):
int a = 3;

a += 4; /* A */
// long: a = a + 4

a++; /* B */
// long: a = a + 1

a = ( a > 3 ? 10 : 5 ); /* C */
// long: ' if a > 3 then a = 10 else a = 5'

-- Example (Ada):
a : integer := 3;

a := a + 4;   -- A --
a := a + 1;   -- B --

if a > 3 then -- C --
    a := 10;
else
    a := 5;
end if;

( Example doesn't make sense - only for demonstration )
Is it because ...

*

*Operator-overloading (but C++ has such a mechanism too)?

*Readability?

*Technical reasons / limitations?

*It's only a trick for making those expressions shorter and not really required for programming?

*The assignment operator in Ada is := and not = (so += -> +=:)?

A: Because the design of Ada was taken much more closely from mathematics than some other languages... And so...
Assignment is not an operator
Operators have specific properties - they operate on quantities returning a result - while leaving the quantities themselves unchanged.
This is important - stick rigorously to this understanding of an "operator" and you make a lot of optimisations possible because the semantics are much more predictable. Essentially, operators don't have side effects. You can repeat them or factor out repeated ones, and you have a lot more freedom to reorder expressions without changing their results.
If you mistake assignment for an operator, ... well, basically you're screwed.
Just ONE "operator" with side effects means you lose valuable properties for ALL operators ... for what? some notational convenience, a hugely fertile breeding ground for bugs, and no extra performance or efficiency.
Incidentally when I had to poke around inside GCC recently I found a function in its expression analyser that explicitly broke (intermediate representation for) a++ and transformed it internally into (intermediate representation for) a = a + 1; So the shorter form really doesn't appear to be any more efficient!
The same rationale applies (less strictly in Ada than VHDL) to functions - they are just operators in another guise, and pure functions (in VHDL that's every function without the word "impure" in its declaration!) don't have side effects.
Which is also why Ada has both functions and procedures : functions, operators and expressions are essentially similar (and ideally, stateless and side-effect free); procedures, assignments and statements are a separate category (procedure calls and assignments are forms of statement).
Separating the concepts and using the appropriate one for each task goes a long way to making clear programs that you can understand and probably do what you intended...
Oh and Ada-2012 has finally caught up with VHDL-2008 and Algol-W (1963) with if- and case-expressions...
a := (if a > 3 then 10 else 5);
-- to my eyes MUCH more readable than ?: especially in multiple if-exprs!

b := (case a is
      when 3 => 5;
      when 6|7 => 10;
      when others => 0);

It is obvious that the assignments here are still statements...
Just to make sure:
Assignment is not an operator
Ada's designers had an impressive and usually VERY clear grasp of what was possible without compromising integrity and what would just lead to a mess. While newer language features have been added, as compiler techniques developed enough to make them reliable, it has always been a cautious process and the Ada-83 subset is still there virtually intact.


text:
Q: How to connect to Message Hub from Data Science Experience / Spark as a Service using confluent-kafka-python? The Bluemix MessageHub docs point python users to the confluent kafka library:

So I tried to install:
!pip install --user confluent-kafka

However, I've hit this error:
Collecting confluent-kafka
  Using cached confluent-kafka-0.9.1.2.tar.gz
Installing collected packages: confluent-kafka
  Running setup.py install for confluent-kafka ... - \ error
    Complete output from command /usr/local/src/bluemix_jupyter_bundle.v22/notebook/bin/python -u -c "import setuptools, tokenize;__file__='/gpfs/global_fs01/sym_shared/YPProdSpark/user/xxxx/notebook/tmp/pip-build-N3zDUh/confluent-kafka/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /gpfs/fs01/user/xxxx/notebook/tmp/pip-PyAwq2-record/install-record.txt --single-version-externally-managed --compile --user --prefix=:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/confluent_kafka
    copying confluent_kafka/__init__.py -> build/lib.linux-x86_64-2.7/confluent_kafka
    creating build/lib.linux-x86_64-2.7/confluent_kafka/kafkatest
    copying confluent_kafka/kafkatest/__init__.py -> build/lib.linux-x86_64-2.7/confluent_kafka/kafkatest
    copying confluent_kafka/kafkatest/verifiable_consumer.py -> build/lib.linux-x86_64-2.7/confluent_kafka/kafkatest
    copying confluent_kafka/kafkatest/verifiable_producer.py -> build/lib.linux-x86_64-2.7/confluent_kafka/kafkatest
    copying confluent_kafka/kafkatest/verifiable_client.py -> build/lib.linux-x86_64-2.7/confluent_kafka/kafkatest
    running build_ext
    building 'confluent_kafka.cimpl' extension
    creating build/temp.linux-x86_64-2.7
    creating build/temp.linux-x86_64-2.7/confluent_kafka
    creating build/temp.linux-x86_64-2.7/confluent_kafka/src
    gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/src/bluemix_jupyter_bundle.v22/notebook/include/python2.7 -c confluent_kafka/src/confluent_kafka.c -o build/temp.linux-x86_64-2.7/confluent_kafka/src/confluent_kafka.o
    In file included from confluent_kafka/src/confluent_kafka.c:17:0:
    confluent_kafka/src/confluent_kafka.h:20:32: fatal error: librdkafka/rdkafka.h: No such file or directory
     #include <librdkafka/rdkafka.h>
                                    ^
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/local/src/bluemix_jupyter_bundle.v22/notebook/bin/python -u -c "import setuptools, tokenize;__file__='/gpfs/global_fs01/sym_shared/YPProdSpark/user/xxxx/notebook/tmp/pip-build-N3zDUh/confluent-kafka/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /gpfs/fs01/user/xxxx/notebook/tmp/pip-PyAwq2-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /gpfs/global_fs01/sym_shared/YPProdSpark/user/xxxx/notebook/tmp/pip-build-N3zDUh/confluent-kafka/

A: As per the confluent readme, you need the librdkafka native library installed before you can use their Python client.
As you found in your other comment their is the alternative pure Python library kafka-python which you might find easier to work with for a Bluemix application


text:
Q: Not to display SQLPLUS prompt I am trying to connect with sqlplus using a bash script. When I execute the script below SQLPLUS banner displayed.
Below the script:
$ORACLE_HOME/bin/sqlplus "/ as sysdba" <<EOF
  set echo off
  set heading off
  spool bind.txt
  select * from DBMS_LOCK_ALLOCATED where name = '$uservar';
  spool off
  exit
EOF

Output of the script
oracle@DMOTA01:~/script> ./before_bind.sh

SQL*Plus: Release 11.2.0.3.0 Production on Wed Nov 27 11:54:01 2019

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> SQL>   2    3    4  Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
oracle@DMOTA01:~/script>

I don't want to display "SQL*Plus: Release 11............. Real Application Testing options" lines. How i can do it?

A: You need to add -S to sqlplus to switch it in silence mode:
$ORACLE_HOME/bin/sqlplus -S "/ as sysdba" <<EOF
  set echo off
  set heading off
  spool bind.txt
  select * from DBMS_LOCK_ALLOCATED where name = '$uservar';
  spool off
  exit
EOF


text:
Q: Show directory tree instead of index.html how can I define apache virtual host to show a directory tree even if index.html/php exists?

A: You have to enabled the Indexes option and remove the DirectoryIndex option.
If you have AllowOverride enabled you can add the following to your .htaccess file.
Options Indexes FollowSymLinks
DirectoryIndex disabled

If you get a welcome page, you may need to remove/edit /etc/httpd/conf.d/welcome.conf.  ON Red Hat derived OS's and others this can interfere with some directory listing.


text:
Q: Adding/Removing field by using Sequelize I'm using Sequelize-cli and have some trouble with using it.
Note that it's my first time using Sequelize, might be I lost some concepts, will be very appreciate it told me what am I missing.
I made a simple model like this:
$ sequelize model:generate --name Notes --attributes text:content

And I get this migration file:
'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Notes', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      content: {
        type: Sequelize.TEXT
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Notes');
  }
};

However now I need to add new field "title" the string type, but I can't find any related information about this process.
Should I just run db:migrate:undo to remove all tables and update migration & model file and redo the migration? I think this isn't proper way to using sequelize.
I'm also keep confusing the concept of "migration", why should I use this?
And it seems like all data is gone after run "migrate:undo" command, is there a way to save them so that I can restore the data after updating the table schema?
Any advice will very appreciate it!

A: Solved this by create new migration and use queryInterface.addColumn to create new fields!
module.exports = {
  up: (queryInterface, Sequelize) => {
     return queryInterface.addColumn(
      'Notes',
      'title',
      Sequelize.STRING
    );
  },
   down: (queryInterface, Sequelize) => {
   return queryInterface.removeColumn(
     'Notes',
     'title'
   );
  }
};


text:
Q: angular2 webapi call async not working I have an angular 2app with a class and a method, the method executes a web api call and then sets some items on local storage, the problem is that because its ASYNC then on the next line I dont have the local storage values yet because the web api hasnt returned any info at that point.
How can I make sure that the web api has been succesfully returned before the localstorage.getitem line.
Code reduced for brevity.
Service
 login(email) {
        let params: URLSearchParams = new URLSearchParams();
        params.set('email', email);

        //Header
        let headers = new Headers({
            'Content-Type': AppSettings.ContentType,
            'Authorization': AppSettings.Authorization + localStorage.getItem("AccessToken"),
            'X-Developer-Id': AppSettings.XDeveloperId,
            'X-Api-Key': AppSettings.XApiKey
        });

        var RequestOptions: RequestOptionsArgs = {
            url: AppSettings.UrlLoginPatient,
            method: 'GET',
            search: params,
            headers: headers,
            body: null
        };

        this.http.get(AppSettings.UrlLoginPatient, RequestOptions)
            .map(res => res.json())
            .subscribe(
            data => { this.saveData(data, email); },
            err => this.Error(err)
            );
    }

    saveData(data, email) {
        localStorage.setItem('patientId', data.data.patientId);
        localStorage.setItem('emailLogin', email);
    }

    Error(err) {
        console.log('error: ' + err);
    }

Component
LoginApp() {

    this.login.login('a@com.com');

    if (localStorage.getItem("patientId") != null) {
      this.navCtrl.push(AttentionTypePage);
    } else {
      let alert = this.alertCtrl.create({
        subTitle: 'El correo electrónico no ha sido encontrado.',
        buttons: ['Intentar nuevamente']
      });
      alert.present();
    }
  }

A: To ensure that you have the right informations, you shouldn't subscribe in your service but in your component :
Service
login(email) {
  //do stuff with headers, and request options
  return this.http.get(AppSettings.UrlLoginPatient, RequestOptions)
    .map(res => res.json())
    .do(data => this.saveData(data, email));
}

Component
LoginApp() {
  this.login.login('a@com.com').do(data => {
    if (localStorage.getItem("patientId") != null) {
      this.navCtrl.push(AttentionTypePage);
    } else {
      let alert = this.alertCtrl.create({
        subTitle: 'El correo electrónico no ha sido encontrado.',
        buttons: ['Intentar nuevamente']
      });
      alert.present();
    }
  }).subscribe();
}