text:
Q: How to generate GameObjects, then respawn them when they are stopped I'm writing a system that instantiates clouds (prefabs that I created) in random locations. When they are spawned, they move to a spot via Vector2.MoveTowards. What I am trying to do, is check whether they stopped. And if they stopped, to create new ones.
My system:
Script 1 (Procedural Clouds (I know they are not procedurally created, but I started off naming the script this because that is what I want to achieve in the long run) ):

*

*A public GameObject array where I store prefabs that I created, and these prefabs get instantiated in script.

*One Vector3 (had to use Vector3 instead of 2 because I use Random.Range) which is one of the start positions (I have 6 start positions in total.)

*At first I used InvokedRepeating in Start function to instantiate at random times, but I ditched that and decided to call my spawn-methods based on if the cloud has already been spawned or not. (I could try a coroutine with an IEnumerator, but I don't know if that will serve it's purpose here)

Script 2 (MoveClouds):

*

*In start function I define three end positions which are Vector3.

This is where I start to struggle. I first tried to use .transform.position = Vector3.MoveTowards(). But my problem here was to check if the clouds had stopped. I tried hasChanged, but that did not work. So after a lot of Googling and trying to make it work, I decided to attach Rigidbody2D to the clouds, because I thought I could check if velocity.magnitude == 0, then they are stopped. I also applied both rb.velocity and rb.addforce, to that there is actual force to check if that force has stopped and a new one should be spawned. I do not want to use RB since they are not going to be related to any physics, they are simply just going to move from one random point to another specific point, then evaporate and when they are evaporated, then a new one spawns.
I know it's a long post, but I appreciate any help! I have been working in Unity for a little over 3 months, so I'm still pretty new to this.
My code:
Script 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProceduralClouds : MonoBehaviour
{
    public GameObject[] clouds;
    Vector3 startPos1, startPos2, startPos3, startPos4, startPos5, startPos6;
    [HideInInspector] public GameObject cloud1, cloud2, cloud3, cloud4, cloud5, cloud6;
    public bool cloud1Spawned, cloud2Spawned, cloud3Spawned, cloud4Spawned, cloud5Spawned, cloud6Spawned;

    private void Start()
    {

        /*InvokeRepeating(nameof(SpawnCloud1), 0, 20);
        InvokeRepeating(nameof(SpawnCloud2), 1, 22);
        InvokeRepeating(nameof(SpawnCloud3), 3, 25);
        InvokeRepeating(nameof(SpawnCloud4), 0, 18);
        InvokeRepeating(nameof(SpawnCloud5), 2, 20);
        InvokeRepeating(nameof(SpawnCloud6), 5, 21); */
    }

    private void Update()
    {
        startPos1 = new Vector3(Random.Range(15, 25), Random.Range(0, 10), 0);
        startPos2 = new Vector3(Random.Range(15, 25), Random.Range(0, 10), 0);
        startPos3 = new Vector3(Random.Range(15, 25), Random.Range(0, 10), 0);
        startPos4 = new Vector3(Random.Range(15, 25), Random.Range(0, 10), 0);
        startPos5 = new Vector3(Random.Range(15, 25), Random.Range(0, 10), 0);
        startPos6 = new Vector3(Random.Range(15, 25), Random.Range(0, 10), 0);

        // test prints:

        print("Cloud 1 spawned: " + cloud1Spawned);

        SpawnCloud1();
        SpawnCloud2();
        SpawnCloud3();
        SpawnCloud4();
        SpawnCloud5();
        SpawnCloud6();

    }

    private void SpawnCloud1()
    {

        if (!cloud1Spawned)
        {
            cloud1 = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos1, Quaternion.identity);
            cloud1Spawned = true;
        }
    }

    private void SpawnCloud2()
    {

        if (!cloud2Spawned)
        {
            cloud2Spawned = true;
            cloud2 = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos2, Quaternion.identity);
        }
    }

    private void SpawnCloud3()
    {

        if (!cloud3Spawned)
        {
            cloud3 = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos3, Quaternion.identity);
            cloud3Spawned = true;
        }
    }

    private void SpawnCloud4()
    {

        if (!cloud4Spawned)
        {
            cloud4 = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos4, Quaternion.identity);
            cloud4Spawned = true;
        }
    }

    private void SpawnCloud5()
    {

        if (!cloud5Spawned)
        {
            cloud5 = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos5, Quaternion.identity);
            cloud5Spawned = true;
        }
    }

    private void SpawnCloud6()
    {

        if (!cloud6Spawned)
        {
            cloud6 = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos6, Quaternion.identity);
            cloud6Spawned = true;
        }
    }
}

Script 2:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveClouds : MonoBehaviour
{
    public float step;
    private ProceduralClouds proCloudsScript;
    private GameObject cloud1, cloud2, cloud3, cloud4, cloud5, cloud6;
    private Vector3 endPosBottom, endPosMiddle, endPosTop;
    private void Start()
    {
        proCloudsScript = GameObject.Find("ScriptHandler").GetComponent<ProceduralClouds>();
        endPosBottom = new Vector3(-26, 8, 0);
        endPosMiddle = new Vector3(-26, 10, 0);
        endPosTop = new Vector3(-26, 12, 0);
    }

    private void Update()
    {
        cloud1 = proCloudsScript.cloud1;
        cloud2 = proCloudsScript.cloud2;
        cloud3 = proCloudsScript.cloud3;
        cloud4 = proCloudsScript.cloud4;
        cloud5 = proCloudsScript.cloud5;
        cloud6 = proCloudsScript.cloud6;

        float step = this.step * Time.deltaTime;
       /* cloud1.transform.position = Vector3.MoveTowards(cloud1.transform.position, endPosBottom, step);
        cloud2.transform.position = Vector3.MoveTowards(cloud2.transform.position, endPosTop, step);
        cloud3.transform.position = Vector3.MoveTowards(cloud3.transform.position, endPosMiddle, step);
        cloud4.transform.position = Vector3.MoveTowards(cloud4.transform.position, endPosTop, step);
        cloud5.transform.position = Vector3.MoveTowards(cloud5.transform.position, endPosBottom, step);
        cloud6.transform.position = Vector3.MoveTowards(cloud6.transform.position, endPosMiddle, step);*/

        cloud1.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(cloud1.transform.position,
        endPosBottom, step);
        cloud2.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(cloud2.transform.position,
        endPosMiddle, step);
        cloud3.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(cloud3.transform.position,
        endPosTop, step);
        cloud4.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(cloud4.transform.position,
        endPosTop, step);
        cloud5.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(cloud5.transform.position,
        endPosBottom, step);
        cloud6.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(cloud6.transform.position,
        endPosMiddle, step);

        if (cloud1.GetComponent<Rigidbody2D>().velocity.magnitude == 0 )
        {
            print("Cloud 1 is still");
            proCloudsScript.cloud1Spawned = false;
            print(cloud1.GetComponent<Rigidbody2D>().velocity.magnitude);
        }

        if (cloud2.GetComponent<Rigidbody2D>().velocity.magnitude == 0)
        {
            print("Cloud 2 is still");
            proCloudsScript.cloud2Spawned = false;
            print(cloud2.GetComponent<Rigidbody2D>().velocity.magnitude);
        }

        if (cloud3.GetComponent<Rigidbody2D>().velocity.magnitude == 0)
        {
            print("Cloud 3 is still");
            proCloudsScript.cloud3Spawned = false;
            print(cloud3.GetComponent<Rigidbody2D>().velocity.magnitude);
        }

        if (cloud4.GetComponent<Rigidbody2D>().velocity.magnitude == 0)
        {
            print("Cloud 4 is still");
            proCloudsScript.cloud4Spawned = false;
            print(cloud4.GetComponent<Rigidbody2D>().velocity.magnitude);
        }

        if (cloud5.GetComponent<Rigidbody2D>().velocity.magnitude == 0)
        {
            print("Cloud 5 is still");
            proCloudsScript.cloud5Spawned = false;
            print(cloud5.GetComponent<Rigidbody2D>().velocity.magnitude);
        }

        if (cloud6.GetComponent<Rigidbody2D>().velocity.magnitude == 0)
        {
            print("Cloud 6 is still");
            proCloudsScript.cloud6Spawned = false;
            print(cloud6.GetComponent<Rigidbody2D>().velocity.magnitude);
        }

    }
}

A: I see a lot of small issues in your code!

*

*I would start with the usage of Vector3 .. if you actually want Vector2 then rather use that ;)

*Implementing the same functionality over and over again just to have different numbers is really not good! Try to merger all this together into a single method. This is a) better for maintenance and b) for scalability!

*You are passing a position generated by using
Vector2.MoveTowards(cloud1.transform.position, endPosBottom, step);

to a velocity -> makes no sense.

*even though it was improved a lot in newer versions, using GetComponent over ad over again multiple times and every frame is extremely inefficient.

*generating new random positions every frame and then throw them away most of the times since you don't spawn a cloud if it still moves is again very inefficient.
So I would do it like this
// Responsible for creating and initializing cloud instances
public class ProceduralClouds : MonoBehaviour
{
    // As before here assign your prefabs
    // CloudMove is a dedicated script that will go onto your cloud prefabs
    // See next code snippet
    public CloudMove[] clouds;
    // How many clouds should be spawned?
    public int amountOfClouds = 6;

    // Configure your possible target position in the Inspector
    public Vector2[] targetPositions = { new Vector3(-26, 8, 0), new Vector3(-26, 10, 0), new Vector3(-26, 12, 0) };

    // This will keep track which target position chose next
    // (could make it random as well)
    private int currentTargetIndex;

    private void Start()
    {
        // Spawn the first "wave" of clouds
        for(var i = 0; i < amountOfClouds; i++)
        {
            SpawnCloud();
        }
    }

    private void SpawnCloud()
    {
        // pick a random start position
        var startPos = new Vector2(Random.Range(15, 25), Random.Range(0, 10));
        // get the next target position
        var targetPos = targetPositions [currentTargetIndex];
        // Increase the index, wrap around if reaching end of array
        currentTargetIndex = (currentTargetIndex + 1) % targetPositions.Length;

        // instantiate the cloud
        var cloud = Instantiate(clouds[Random.Range(0, clouds.Length)], startPos, Quaternion.identity);
        // assign its target position
        // Could also pick a random speed here
        cloud.targetPosition = targetPos;
        // Assign a callback to an event we will implement
        // This is way better than poll check stuff in Update
        cloud.OnReachedTarget += SpawnCloud;
    }
}

And then another script that goes directly on your cloud prefabs:
// Responsible for moving one cloud instance
public class CloudMove : MonoBehaviour
{
    // Basically equals your step
    // But this way the clouds could even have individual speed values
    public float speed = 1;

    // Will be assigned by the spawner script
    public Vector2 targetPosition;
    // Whoever wants can be listening here
    public event Action OnReachedTarget;

    private void Update ()
    {
        // Move towards the target position with given speed
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);

        // Either use this check with a precision of 0.00001
        if((Vector2)transform.position == targetPosition)
        // Or alternatively if you need a more exact precision
        //if(Mathf.Approximately(Vector2.Distance(transform.position, targetPosition), 0))
        {
            // Invoke the event so whoever is listening is informed
            OnReachedTarget?.Invoke();

            // You might be interested in destroying this cloud once it reached its target
            //Destroy(gameObject):
        }
    }
}


text:
Q: How to jump to a particular page's some drop-down's particular value using JavaScript? Suppose we have a drop-down like for "Page2.html":
Page2.html

    <select id="first-drop" name="first-drop">
        <option value="Select a State">Select a Steate</option>
        <option value="NY">New York</option>
        <option value="NJ">New Jersey</option>
    </select>

Now, from "Page1.html", we have a link like
Page1.html
go to page 1

So the goal is:
on click of that link, it will go to "Page2.html" and it will select the second drop down value and will be selected. for example, it will select the second drop down value ie "NJ" one. Can we do it programmatically?
I am able to go to the specific page drop-down location. But i failed to select the second value form the drop-down.
window.location.href = forwardedWebsiteLink + "?" + "#first-drop";

Any idea which can do this?

A: You could combine two things: URI Anchors (adding # in your uri) and GET parameters (? followed by values) to make something like example.com#first-drop?firstDropDown=nj
In JavaScript (on page2.html) all you'd have to do would be this:

//Run the script on page load.
window.onload = function() {
  var url = window.location.href;

  //Let me cheat since we don't have page1 and page2 in this example...
  url += "#firstDropDown?firstDropDown=ny";

  // Select the text after the # and before the ? symbol.
  var dropDown = url.substring(url.indexOf('#') + 1, url.indexOf('?') - 1);

  // Select the text after the ? symbol
  var selectedOption = url.substring(url.indexOf('?') + 1);

  // Filter the dropdown's ID and its value into an object.
  selectedOption = {
    elem: selectedOption.substring(0, selectedOption.indexOf('=')),
    value: selectedOption.substring(selectedOption.indexOf('=') + 1)
  };

  // Get the dropdown DOMElement in the page so we can change the selectedIndex.
  dropDown = document.querySelector('#' + selectedOption.elem);

  var index = 0, selectedIndex = 0;

  // Loop through dropDown's children element to find the right one.
  dropDown.childNodes.forEach(function(elem, i) {
    // Make sur to look for DOMElement nodes only.
    if (elem.nodeType == 1) {

      if (elem.value === selectedOption.value) {
        elem.setAttribute("selected", "selected");
        selectedIndex = index;
        return true;
      }
      index++;
    }
  });
  // Now that we have the right index, let's make sure it's selected.
  dropDown.selectedIndex = selectedIndex;
}
<select id="firstDropDown">
  <option value="nj">New Jersey</option>
  <option value="ny">New York</option>
  <option value="la">Los Angeles</option>
</select>

Running the snippet will select New York as the city.

A: When you redirect, you can pass the value on the location.search which can be parsed using any of the numerous methods described here:

*

*How can I get query string values in JavaScript?

*The $.param( ) inverse function in JavaScript / jQuery
On the page 1, you could pass the parameter like this:
window.location.href = forwardedWebsiteLink + "?first-drop=NJ#first-drop"

On page 2, you could do something like this using jQuery BBQ $.deparam():
if (location.hash === '#first-drop') {
  var value = $.deparam.querystring()['first-drop']

  $('#first-drop [value]')
    .removeAttr('selected')
    .filter(function () { return this.value === value })
    .attr('selected', 'selected')
}

A: I'd modify the link to the second page a bit:
New York
Then on page 2, I'd add some JavaScript that runs when the page loads.
let params = (new URL(document.location)).searchParams;
let state = params.get("state");

(See searchParams for more information)
Then you get a reference to your select box:
let dropdown = document.querySelector('#first-drop');

And then set the value to the state that was passed in.
dropdown.value = state;

I can't remember off-hand if the value is case-sensitive, but just in case, modify your dropdown a bit:

    <select id="first-drop" name="first-drop">
        <option value="Select a State">Select a Steate</option>
        <option value="ny">New York</option>
        <option value="nj">New Jersey</option>
    </select>

I think something like that would work. I haven't tested it, though.
Good luck.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Complications regarding use of 'by then' Is this sentence grammatically correct?

When I was last there, he hadn't arrived by then.

Should 'by then' be used if a sentence already has 'when'? And if it can't be used, then what would be the correct structure of the sentence?

A: Regardless of grammar, it doesn't make logical sense. Then has to refer to a specific time.

I last checked at five o'clock, and he hadn't arrived by then.

...but we can say

When I was last there, he hadn't arrived yet/ he still hadn't arrived.


text:
Q: vlookup an item within range I was faced to a situation where I have to classify a list of numbers based on the size of the number.
For example, number between 2 and 8 is classified in class A. Number 16 to 25 is classified in class C. I can work on it with IF formula, but it doesnt feel good since it was like brute forcing IF within IF within IF and it is bad.
Is there any ARRAYFORMULA that can help me work on this? An arrayformula that doesnt need to be dragged down when data is added below. Maybe a formula that is related to VLOOKUP or any other formula will do.
This is the sample case:
https://docs.google.com/spreadsheets/d/1Dlrgp-aAlU2DknlG5u5XWJdXDpU5qj6EfofiCO3UTDQ/edit#gid=0

*

*Range A:A is the given data

*Range B:B is the desired outcome

*Range E:F is hte condition that has to be met

A: You can do a lookup on the lower end of each range:
=ArrayFormula(if(A:A="","",vlookup(A:A,{split(E1:E9,"-"),F1:F9},3,true)))

assuming there are no values more than 1200.


text:
Q: Variance calculation RELU function (deep learning) weight initialization is important for modern deep learning. To understand [1,2], I would like to understand the following:
$$
E[x^2] = 0.5 Var[y],
$$
where $x= max(0,y)$, $E[.]$ is the expectation, $Var[.]$ the variance, $x,y$ are random variables. We assume $y$ to have zero mean and to be symmetrical around the mean.
Thanx for an explanation/derivation
K
[1] http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
[2] http://arxiv.org/abs/1502.01852

A: In terms of integrals you have:
$$
E[x^2] = \int_{-\infty}^{+\infty} \max(0,y)^2 p(y) dy
$$
where the part $y < 0$ does not contribute to the Integral
$$
 = \int_{0}^{+\infty} y^2 p(y) dy
$$
which we can write as half the integral over the entire real domain ($y^2$ is symmetric around 0 and $p(y)$ is assumed to be symmetric around $0$):
$$
 = \frac{1}{2}\int_{-\infty}^{+\infty} y^2 p(y) dy
$$
now subtracting zero in the square we get:
$$
 = \frac{1}{2}\int_{-\infty}^{+\infty} (y - E[y])^2 p(y) dy
$$
which is
$$
 = \frac{1}{2} E[(y - E[y])^2] = \frac{1}{2} Var[y]
$$


text:
Q: Add Multiple Rows NOT Just The Last Row I'm having an issue adding multiple rows to the database via a POST form.  Here's a short snippet of the form:
<form action='/process.php' method='post'>

$result = mysqli_query($con,"SELECT * FROM b_tasks_report WHERE TASK_ID=$taskid GROUP BY WEEK_ID");

while($row = mysqli_fetch_array($result))
{
$current_weekly_id = $row['WEEK_ID'];
if ($current_weekly_id == 1){
echo "
";
echo "
<input type='hidden' name='productname' value='Week 1 Hours'>
<input type='hidden' name='code' value='232'>
<input type='checkbox' name='wid[]" . $row['WEEK_ID'] . "' value='" . $row['WEEK_ID'] . "'>Week " . $row['WEEK_ID'] . "	";
echo "
";
}

if ($current_weekly_id == 2){
echo "
";
echo "
<input type='hidden' name='productname' value='Week 2 Hours'>
<input type='hidden' name='code' value='232'>
<input type='checkbox' name='wid[]" . $row['WEEK_ID'] . "' value='" . $row['WEEK_ID'] . "'>Week " . $row['WEEK_ID'] . "	";
echo "
";
}

<input style='margin-top: 15px;' type='image' name='submit'>

I would like to ensure these two rows are added to the database.  This is the insert I have:
$sql="INSERT into b_sale_basket ()
VALUES
('".$_POST['productname']."','".$_POST['code']."','".$_POST['wid']."')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}

This does add the last row but not the first.  I am aware that I need a foreach but I can't get it to work.  I'm stuck on:
foreach($_POST['wid'] as $weekid
before the insert but not having any luck! How do I get it to add both rows as it should do?
Thanks,
Andy


text:
Q: Android: WebView Scroll Animation i am implementing an app which has some contents to show in webview.
i am so far achieved smooth animation of scrolling webview contents using the object Animator.
Now what issue i am facing is that it is working fine for first and second page and scrolls as demand. but when i want to scroll on 3rd page what issue i have is that it starts scrolling from first page then moving to second and then to third i dont want this to happen i want is that webview should maintain its scroll position and scroll from the current position.
here is my code so far to make the webview contents scroll using objectanimator.
            if (incre <= totalPages) {
                    incre++;
                    totalNumberofPages = totalNumberofPages + incre;
                    // view.loadUrl("javascript:pageScroll("
                    // + incre * view.getWidth() + ")");

                    ObjectAnimator anim = ObjectAnimator.ofInt(view,
                            "scrollX", 0, incre * view.getWidth());
                    anim.setDuration(4000);
                    anim.start();

                    // view.scrollTo(incre*view.getWidth(), 0);

                    anim.addListener(new AnimatorListener() {

                        @Override
                        public void onAnimationStart(Animator animation) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            // TODO Auto-generated method stub
                            // view.scrollTo(0, incre*view.getWidth());

                            view.scrollTo(incre * view.getWidth(), 0);
                            ReaderActivity.txt_numberofpages_left
                                    .setText("Page:  " + incre + " of "
                                            + totalPages);
                            ReaderActivity.txt_leftPage.setText(""
                                    + totalNumberofPages);
                            ReaderActivity.txt_RightPage.setText(""
                                    + (totalNumberofPages + 1));
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                            // TODO Auto-generated method stub

                        }
                    });

A: this is happening due to this line of code
  ObjectAnimator anim = ObjectAnimator.ofInt(view,
                        "scrollX", 0, incre * view.getWidth());
                anim.setDuration(4000);
                anim.start();

after scrollX u are sending hardcoded 0 which will make your contents to scroll from start to the position maintain the last position and pass that position instead of this 0.


text:
Q: How can I call another page or function in my custom Wordpress plugin? I've created a custom Wordpress plugin.  I set a menu item on the left side of the Admin panel which links to the main page for the plugin which I can access.  Works fine.
I then put a link on that main plugin page in order to be able to click a link that runs a PHP script, but it returns a blank page.  This URL syntax is confusing within the Admin section for Plugins.  I just want to call my script!
I'm doing what is suggested here, but it just serves up a blank page: http://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_%28action%29
Why is it so hard to just link to a page and call a function from a Plugin within the Admin section?  I have Debug Mode enabled, too.
Thanks.

A: Wow, this was confusing.
With a little help from http://clivern.com/adding-menus-and-submenus-for-wordpress-plugins/ I now understand that you can't just link to your own plugin functions and pages in the Wordpress Admin section.  You have to create menu items using add_menu_page() and add_submenu_page () that are then interpreted by Wordpress as blocks of code shown on a page...
Man this is frustrating and strange and it took HOURS just to figure this stupid little thing out.  Really poorly documented.  I found a few other things in the "Plugin Handbook" but nothing to do with this.  They don't get into how to write a plugin that has admin-only functionality and being able to link to those functions and how the Admin URL syntax works.


text:
Q: generate sequence of (telephone) numbers in table in mySQL This is my first post/question since I couldn't find the answer to what I was looking for no matter how I searched. So here it is:
I have a small table of a few hundred rows with four columns (plus id col) as seen on the example below:
| id | phone1 | phone2 | phone3   | phone4 |
| 1  |059374-6|        | 065371-7 |023126-8
| 2  |        |026372-3| 024353-7 |
| 3  |...
.
.
.

I need to generate the sequence for all the (telephone) numbers of the specific range they belong. In other words, for the first phone number I need to retrieve the numbers:
059374
059375
059376

and consequently for the rest of the phones in the table.
All the number ranges are given in the above mentioned form and do not exceed the total of 10 numbers (max is something like 099500-9). In addition, they are populated through 4 different columns, as shown in the above example, something I have solved so far by using UNION ALL (in order to put them all in one column and finally find all duplicates which is the ultimate goal).
So, is there any elegant way to generate the numbers needed?
I have searched many threads for similar topics but surprisingly none seem to answer my question.
Finally, if there is any better way than combining all cols into one with UNION ALL and then GROUP BY col1 for finding the duplicates would be highly appreciated.

A: Create a table that contains the numbers from 0 to 9. Extract the starting and ending digits of each number, and join with the number table to find all the numbers in the range.
WITH digits AS (
    SELECT 0 AS dig
    UNION
    SELECT 1 AS dig
    ...
    UNION
    SELECT 9 AS dig)
SELECT SUBSTR(phone1, 1, 5) + digits.dig
FROM yourTable
JOIN digits ON dig BETWEEN SUBSTR(phone1, 6, 1) AND SUBSTR(phone1, 8, 1)
WHERE phone1 != ''

This shows how to do it for the phone1 column, you can use UNION to repeat it for the other 3 columns.


text:
Q: Short story with very a old, plant-like warrior who fights a war against an enemy species This has been eating at me for a few years now. I believe I read this in one of the 'best sci-fi of the year' aggregations.
The plot centers around an old warrior living in peace in a small town. He was once part of a unit or army that had been fighting a war for hundreds or thousands of years. I don't think the town people know about the war or even that these two species exist (because they hide/camouflage maybe).
At some point, the warrior realizes that the enemy has found him and will be attacking soon. He then starts performing some sort of ritual meant to individually call his old friends from the unit, but each ritual reveals that they have died.
Eventually his enemies arrive on the planet (after numerous signs) and he has to fight alone and knows he will probably die. I believe the fighting was primarily fencing/sword fighting. Also, the warrior is some sort of plant species and he grows bark as a shield.


text:
Q: Endless recursion in gawk-script Please pardon me in advance for posting such a big part of my problem, but I just can't put my finger on the part that fails...
I got input-files like this (abas-FO if you care to know):
.fo U|xiininputfile = whatever
.type text U|xigibsgarnich
.assign U|xigibsgarnich
..
..Comment
.copy U|xigibswohl = Spaß
.ein "ow1/UWEDEFTEST.FOP"
.in "ow1/UWEINPUT2"
.continue BOTTOM
.read "SOemthing" U|xttmp
!BOTTOM
..
..

Now I want to recursivly follow each .in[put]/.ein[gabe]-statement, parse the mentioned file and if I don't know it yet, add it to an array. My code looks like this:
#!/bin/awk -f

function getFopMap(inputregex, infile, mandantdir, infiles){
    while(getline f < infile){
        #printf "*"
        #don't match if there is a '
        if(f ~ inputregex "[^']"){
            #remove .input-part
            sub(inputregex, "", f)
            #trim right
            sub(/[[:blank:]]+$/, "", f)
            #remove leading and trailing "
            gsub(/(^\"|\"$)/,"" ,f)

            if(!(f in infiles)){
                infiles[f] = "found"
            }
        }
    }
    close(infile)

    for (i in infiles){
        if(infiles[i] == "found"){
            infiles[i] = "parsed"
            cmd = "test -f \"" i "\""
            if(system(cmd) == 0){
                close(cmd)
                getFopMap(inputregex, f, mandantdir, infiles)
            }
        }
    }
}

BEGIN{
    #Matches something like [.input myfile] or [.ein    "ow1/myfile"]
    inputregex = "^\\.(in|ein)[^[:blank:]]*[[:blank:]]+"

    #Get absolute path of infile
    cmd = "python -c 'import os;print os.path.abspath(\"" ARGV[1] "\")'"
    cmd | getline rootfile
    close(cmd)

    infiles[rootfile] = "parsed"
    getFopMap(inputregex, rootfile, mandantdir, infiles)

    #output result
    for(infile in infiles) print infile
    exit
}

I call the script (in the same directory the paths are relative to) like this:

./script ow1/UWEDEFTEST.FOP

I get no output. It just hangs up. If I remove the comment before the printf "*" command, I'm seeing stars, without end.
I appreciate every help and hints how to do it better.
My awk:
gawk Version 3.1.7

A: idk it it's your only problem but you're calling getline incorrectly and consequently will go into an infinite loop in some scenarios. Make sure you fully understand all of the caveats at http://awk.info/?tip/getline and you might want to use the recursion example there as the starting point for your code.
The most important item initially for your code is that when getline fails it can return a negative value so then while(getline f < infile) will create an infinite loop since the failing getline will always be returning non-zero and will so continue to be called and continue to fail. You need to use while ( (getline f < infile) > 0) instead.


text:
Q: joining merge multiple dataframes without matching index I have a complete data set that looks like this:
pandas==1.1.5
all_data_set = [
        ('A','Area1','AA','A B D E'),
        ('B','Area1','AA','A B D E'),
        ('C','Area2','BB','C'),
        ('D','Area1','CC','A B D E'),
        ('E','Area1','CC','A B D E'),
        ('F','Area3','BB','F'),
        ('G','Area4','AA','G H'),
        ('H','Area4','CC','G H'),
        ('I','Area5','BB','I'),
        ('J','Area6','AA','J L'),
        ('L','Area6','CC','J L'),
        ('M','Area5','BB','M')
        ]
all_df = pd.DataFrame(data = all_data_set, columns = ['Name','Area','Type','Group'])

 Name   Area Type    Group
0     A  Area1   AA  A B D E
1     B  Area1   AA  A B D E
2     C  Area2   BB        C
3     D  Area1   CC  A B D E
4     E  Area1   CC  A B D E
5     F  Area3   BB        F
6     G  Area4   AA      G H
7     H  Area4   CC      G H
8     I  Area5   BB        I
9     J  Area6   AA      J L
10    L  Area6   CC      J L
11    M  Area5   BB        M

From this data set I created 3 df's grouped by Type:
aa_df = all_df.loc[all_df['Type']=='AA']
aa_df = aa_df.rename(columns={'Group':'AA group'})
bb_df = all_df.loc[all_df['Type']=='BB']
bb_df = bb_df.rename(columns={'Group':'BB group'})
cc_df = all_df.loc[all_df['Type']=='CC']
cc_df = cc_df.rename(columns={'Group':'CC group'

 Name   Area Type AA group
0    A  Area1   AA  A B D E
1    B  Area1   AA  A B D E
6    G  Area4   AA      G H
9    J  Area6   AA      J L

   Name   Area Type BB group
2     C  Area2   BB        C
5     F  Area3   BB        F
8     I  Area5   BB        I
11    M  Area5   BB        M

   Name   Area Type CC group
3     D  Area1   CC  A B D E
4     E  Area1   CC  A B D E
7     H  Area4   CC      G H
10    L  Area6   CC      J L

My Goal is to Join them following these rules:

*

*All Members are grouped by matching Area . ie Area1 has Names A B D E

*AA Members are only Type = AA . ie of A B D E only A and B are AA Type

*CC Members are only Type = CC

*BB Members are always single and are also AA and CC Members

The resulting df should look like this
       Name   Area Type All Members AA Members CC Members
0     A  Area1   AA     A B D E        A B        D E
1     B  Area1   AA     A B D E        A B        D E
2     C  Area2   BB           C          C          C
3     D  Area1   CC     A B D E        A B        D E
4     E  Area1   CC     A B D E        A B        D E
5     F  Area3   BB           F          F          F
6     G  Area4   AA         G H          G          H
7     H  Area4   CC         G H          G          H
8     I  Area5   BB           I          I          I
9     J  Area6   AA         J L          J          L
10    L  Area6   CC         J L          J          L
11    M  Area5   BB           M          M          M

Im lost on how to join the 3 types of DFs since I don't have a shared index between the 3 , I was thinking I need some type of isin to look back at the all_df and reference the group. But the group is just like you see it, its names separated by spaces so I think I need to convert that to a list maybe?
Is there a way to do this using pandas or will I need a series of loops and lookups?

A: If think you don't need your grouped dfs. You can compute your members with groupby then use the created df to lookup AA and CC members. Finally fill NA values with Name:
import pandas as pd

all_data_set = [
        ('A','Area1','AA','A B D E'),
        ('B','Area1','AA','A B D E'),
        ('C','Area2','BB','C'),
        ('D','Area1','CC','A B D E'),
        ('E','Area1','CC','A B D E'),
        ('F','Area3','BB','F'),
        ('G','Area4','AA','G H'),
        ('H','Area4','CC','G H'),
        ('I','Area5','BB','I'),
        ('J','Area6','AA','J L'),
        ('L','Area6','CC','J L'),
        ('M','Area5','BB','M')
        ]
all_df = pd.DataFrame(data = all_data_set, columns = ['Name','Area','Type','Group'])

members_df = all_df.groupby(['Area', 'Type']).agg({'Name': list})
#print(members_df)

def get_members(row, typ):
    try:
        return " ".join(members_df.loc[(row['Area'], typ), 'Name'])
    except KeyError:
        return

all_df['AA members'] = all_df.apply(lambda x: get_members(x, 'AA'), axis=1)
all_df['CC members'] = all_df.apply(lambda x: get_members(x, 'CC'), axis=1)

# filling na values
all_df.loc[all_df['AA members'].isna(), 'AA members'] = all_df['Name']
all_df.loc[all_df['CC members'].isna(), 'CC members'] = all_df['Name']

print(all_df)

Output:
   Name   Area Type    Group AA members CC members
0     A  Area1   AA  A B D E        A B        D E
1     B  Area1   AA  A B D E        A B        D E
2     C  Area2   BB        C          C          C
3     D  Area1   CC  A B D E        A B        D E
4     E  Area1   CC  A B D E        A B        D E
5     F  Area3   BB        F          F          F
6     G  Area4   AA      G H          G          H
7     H  Area4   CC      G H          G          H
8     I  Area5   BB        I          I          I
9     J  Area6   AA      J L          J          L
10    L  Area6   CC      J L          J          L
11    M  Area5   BB        M          M          M


text:
Q: I can't extend border on last child I have created an organisational tree and I am lowering certain boxes to show "importance" of job roles and just general neatness. This works all fine but for some reason I can't seem to extend the border on the last child to match up with the box.
On my full tree (not the fiddle) I have multiple branches and they all extend perfectly except for the last right smaller branch on each bigger branch.
To extend the border i'm adding a class to each <li> like so:

.finance li:after { height: 80px; border-left: 1px solid #ccc;
  z-index:-999;}

I just can't understand why it works fine on all <li>'s except for the last ones.
I have reproduced the problem in this fiddle:
EXAMPLE

UPDATE:
This is my full tree with the line problems: http://jsfiddle.net/HSwx4/
And here it is when I edit .tree li:last-child::before: http://jsfiddle.net/HSwx4/1/

A: It's inheriting a height of 20px from your .tree li::before, .tree li::after selector. Change your .tree li:last-child::before selector to include a height of its own:
.tree li:last-child::before {
    border-right: 1px solid #ccc;
    -webkit-border-radius: 0 0px 0 0;
    -moz-border-radius: 0 0px 0 0;
    border-radius: 0 0px 0 0;
    height: 100%;
}

JSFiddle demo.

A: Finally figured it out!
I added:
li .warehouse:last-child:after {top:20px;height: 290px !important; border-left: 2px solid #999 !important;}

I needed to add !important so it made sure it forced the border to appear because
.tree li:first-child:before, .tree li:last-child:after{
had
border: 0 none;


text:
Q: Track all Methods and Classes I have a project with many packages and classes. It is obvious that it will have many Methods too. Currently, i am using Netbeans7.0 IDE. Is there any program, API or way to track all the possible path/methods/options like tree structure of all the classes? I wish to see all the branches which starts from first Method.

A: So, basically, what you need is a call graph of your project? Call graphs can be generated either through static code analysis or dynamically as your code is executed. Both approaches are useful and both have their advantages and disadvantages.
Both the Eclipse and the Netbeans profiler are able to do this dynamically, as mentioned here.
For static call graph generation have a look here and here.
EDIT:
The Eclipse IDE also has the capability to generate a tree-like call structure using the Call Hierarchy tab, as mentioned here. NetBeans has something similar since version 6.5.

A: Give Understand a look.


text:
Q: Gridview rowdatabound is taking forever setting the onclick javascript for checkboxes in rows enter code hereI have a gridview in some code I inherited that is using rowdatabound to add javascript to checkboxes. This is to enable the row checkboxes to be set by a master checkbox in the header. And that all works. The problem is performance. The users do not want paging, and some of these grids can have thousands of rows. Rendering is fast if we don't use Attributes.Add() to hook up the javascript. If I do use rowdatabound for the javascript injection, performance goes from instantaneous to nearly a minute for a mere 600 rows. That's not right.
So I have two questions:
1) Is it normal for rowdatabound to take forever to handle these javascript injections?
2) If so, what would you recommend as a faster alternative to setting up the row checkboxes to work with the master checkbox in the header?
And as I am new to the forum, I want to thank everyone here for help already received. I have been lurking for weeks now and you all have been quite impressive with your knowledge and willingness to help.
UPDATE:
Thanks everyone for your help. Here's what I ended up doing:
First, I had to set some variables in my aspx to capture clientID for a Master Page environment:

Then I set the onclick for the header checkbox to the name of my header function, and also set the onclick for the child checkbox to the name of my child click function. I provided only three parameters, "this" for the clicked checkbox itself, the MasterPage friendly name of the GridView, and a number representing the column. Hard-coded, I know, but the columns are not dynmamic, so not an issue at this time:
<asp:GridView id="ChangedAddressesGridView" runat="server" AutoGenerateColumns="False" >
    <Columns>
        <asp:BoundField datafield="AddressId" headertext="ID" />
        <asp:BoundField datafield="Code" headertext="Code" />
        <asp:BoundField datafield="Facility" headertext="Facility" />
        <asp:BoundField datafield="Address" headertext="Address" />

        <asp:TemplateField headertext="Select">
            <HeaderTemplate>
                <asp:Label id="LBLOverride" runat="server" text="Override" font-size="Smaller" font-names="Arial"></asp:Label>

                <asp:CheckBox id="chkBxHeader1" runat="server" onclick="HeaderClick(this,ChangedAddressesGridViewID,'4');"></asp:CheckBox>

            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox id="chkBxSelect1" runat="server" onclick="ChildClick(this,ChangedAddressesGridViewID,'4');" ></asp:CheckBox>
            </ItemTemplate>
            <headerstyle horizontalalign="Center" />
            <itemstyle horizontalalign="Center" />
        </asp:TemplateField>

        <asp:BoundField datafield="CAddress" headertext="Corrected Address" />

        <asp:TemplateField headertext="Select">
            <HeaderTemplate>
                <asp:Label id="lblChange" runat="server" text="Change" font-size="Smaller" font-names="Arial"></asp:Label>

                <asp:CheckBox id="chkBxHeader2" runat="server" onclick="HeaderClick(this,ChangedAddressesGridViewID,'6');"></asp:CheckBox>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox id="chkBxSelect2" runat="server" onclick="ChildClick(this,ChangedAddressesGridViewID,'6');"></asp:CheckBox>
            </ItemTemplate>
            <headerstyle horizontalalign="Center" />
            <itemstyle horizontalalign="Center" />
        </asp:TemplateField>

     </Columns>
</asp:GridView>

Here's the JavaScript that makes it work:
function GetHeaderCheckBox(grid, cellnum) {
    cell = grid.rows[0].cells[cellnum];
    for (j = 0; j < cell.childNodes.length; j++) {
        if (cell.childNodes[j].type == "checkbox") {return cell.childNodes[j]; }
    }
    return false;
}

function CheckBoxIsChecked(row, cellnum) {
    cell = row.cells[cellnum];
    for (j = 0; j < cell.childNodes.length; j++) {
        if (cell.childNodes[j].type == "checkbox") {
            return cell.childNodes[j].checked;
        }
    }
}

function SetCheckBox(row, cellnum, checkedValue) {
     cell = row.cells[cellnum];
     for (j = 0; j < cell.childNodes.length; j++) {
         if (cell.childNodes[j].type == "checkbox") {
             cell.childNodes[j].checked = checkedValue;
         }
     }
}

function HeaderClick(HeaderCheckBox, GridViewID, checkboxcolumn) {

    var checkedValue;
    var grid = document.getElementById(GridViewID);
    var TotalChkBx = grid.rows.length;

    if (HeaderCheckBox.checked == true) { checkedValue = true; } else { checkedValue = false; }

    for (var n = 1; n < TotalChkBx; n++) {
        SetCheckBox(grid.rows[n], checkboxcolumn, checkedValue);
    };
}

function ChildClick(RowCheckBox, GridViewID, checkboxcolumn) {

    var grid = document.getElementById(GridViewID);
    var HeaderCheckBox = GetHeaderCheckBox(grid, checkboxcolumn);
    var TotalChkBx = grid.rows.length;
    var TotalChkBxChecked = 0;

    for (var n = 1; n < TotalChkBx; n++) {
        if (CheckBoxIsChecked(grid.rows[n], checkboxcolumn)) { TotalChkBxChecked++; }
    };

    if (TotalChkBxChecked == TotalChkBx - 1) { HeaderCheckBox.checked = true; } else { HeaderCheckBox.checked = false; }
}

There you have it. The one thing different about this than most similar examples is I wanted to go by columns rather than just spin through the "inputs" list. This is because I have two checkbox columns, and I wasn't sure how, with "inputs," I would be able to keep them separate without getting very messy. So I found an example that helped me see how to do this here:
http://technico.qnownow.com/how-to-delete-multiple-rows-from-gridview-with-checkboxes/
Also, to eliminate more unnecessary parameters, I had the child function figure out its header checkbox on its own.
Anyway, now I have a select-all header/child checkbox pattern I can drop in anywhere. The previous version had to look up a specific checkbox name, so it was limited to just that one column, which meant that you had to copy/paste the functionality wherever you needed it. Differences had crept in and I was getting inconsistent and wrong behavior. With this solution, so far, no errors, and the same exact behavior everywhere.
And no rowdatabound. Life is good.
Thanks again to everyone. You all helped me think through various parts of the problem.

A: If my understanding is correct, you add JavaScript just to interact with a  Master's checkbox to check/uncheck all checkboxes inside the GridView
This is my assumption since you didn't provide nay code nor you answered my question above....
Well if this is the case you could use JQuery on the client side to get the same effect:
Example:

<asp:CheckBox Text="Check/Uncheck all" runat="server" ID="masterCheck" />
<asp:GridView runat="server" ID="myCustomGridView">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="myCheckBox" Text='<%# Eval("job_desc") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

This is a live sample

A: you can do the same from backend without using javascript. use the CheckedChanged function of the header checkbox to do this. the code should look something like this -
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = (CheckBox)GridView1.HeaderRow.FindControl("chkAll");
    if (chk.Checked)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            chkrow.Checked = true;
        }

    }
    else
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            chkrow.Checked = false;
        }
    }

}

let me know how this performs.


text:
Q: tcpdump -i any doesn't work on FreeBSD How to listen all interfaces on FreeBSD with tcpdump
> tcpdump -i any
tcpdump: any: No such device exists
(BIOCSETIF failed: Device not configured)

(I would like to listen ICMP)

A: I'm looking at this on FreeBSD 11.3 and there doesn't appear to be any way to do an "any".  I thought multiple -is might work, despite the manpage's silence on it, but it only takes the first one.  If tcpdump gets enhanced to support multiple -is then this ought to do it (or you can prove that it doesn't on your system):
tcpdump --list-interfaces | grep Running | cut -f 1 -d ' ' | cut -f 2- -d '.' | awk '{ print "-i " $1 }' | xargs -t -Jinterfaces tcpdump interfaces host 8.8.8.8

A: From the tcpdump man page:

An  interface  argument  of  "all"  or "pktap,all" can be used to capture packets from all interfaces,
                including loopback and tunnel interfaces.

Therefore you can simply do, for example:
tcpdump -i all tcp port 80

If you don't specify the -i flag, then a set of all interfaces are again included in a pseudo interface that by default excludes loopback and tunnel interfaces. Again from the tcpdump man page:

On  Darwin  systems  version 13 or later, when the interface is unspecified, tcpdump will use a pseudo
                interface to capture packets on a set of interfaces determined by  the  kernel  (excludes  by  default
                loopback and tunnel interfaces).

A: I can't vouch for how well this method would serve any particular  use case, but the brute force way to do this in FreeBSD would be to run N instances of tcpdump, one for each of the N interfaces known to ifconfig.  You might run them as a grouped and backgrounded command, sending their combined output to a single file.  It seems inevitable that the output file will have numerous duplicated packets, such as showing a packet when it arrives on interface a and then showing it again when it departs on interface b.
But if you really have to do it that way, consider:
{
    for i in $(ifconfig -l)
    do
        ( tcpdump -i $i & )
    done
} > tcpdump.out

A: As with anything in FreeBSD:
Reading the manpage usually explains everything.
       -i interface
   --interface=interface
      Listen on interface.  If unspecified, tcpdump searches the  sys-
      tem interface list for the lowest numbered, configured up inter-
      face (excluding loopback), which may turn out to be,  for  exam-
      ple, ``eth0''.

      On  Linux  systems with 2.2 or later kernels, an interface argu-
      ment of ``any'' can be used to capture packets from  all  inter-
      faces.   Note  that  captures  on the ``any'' device will not be
      done in promiscuous mode.

      If the -D flag is supported, an interface number as  printed  by
      that flag can be used as the interface argument, if no interface
      on the system has that number as a name.

https://www.freebsd.org/cgi/man.cgi?query=tcpdump&apropos=0&sektion=0&manpath=FreeBSD+12.1-RELEASE+and+Ports&arch=default&format=html


text:
Q: Making all 16 Combination of Emulator So there are 4 types of screen sizes small,medium,large and x-large and 4 types of screen density ldpi,mdpi,hdpi and xhdpi.
Do anyone know of any tutorial about how can I make all 16 kinds of emulators using Eclipse IDE.
Thanks in advance.

A: Check Table 3 under How to Test Your Application on Multiple Screens
http://developer.android.com/guide/practices/screens_support.html


text:
Q: K&R - Recursive descent parser - strcat What would be the reason for out[0] = '\0'; on the main() function?
It does seem to be working without it.
Code
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXTOKEN 100
enum { NAME, PARENS, BRACKETS };

int tokentype;
char token[MAXTOKEN]; /*last token string */
char name[MAXTOKEN]; /*identifier name */
char datatype[MAXTOKEN]; /*data type = char, int, etc. */
char out[1000];

void dcl(void);
void dirdcl(void);
int gettoken(void);

/*
Grammar:

    dcl:            optional * direct-dcl
    direct-dcl:     name
                    (dcl)
                    direct-dcl()
                    direct-dcl[optional size]
*/

int main() /* convert declaration to words */
{
    while (gettoken() != EOF) {    /* 1st token on line */

        /* 1. gettoken() gets the datatype from the token  */
        strcpy(datatype, token);

        /* 2. Init out to end of the line? */
        /* out[0] = '\0'; */

         /* parse rest of line */
        dcl();

        if (tokentype != '\n')
            printf("syntax error\n");

        printf("%s: %s %s\n", name, out, datatype);
    }

    return 0;
}

int gettoken(void) /* return next token */
{
    int c, getch(void);
    void ungetch(int);
    char *p = token;

    /* Skip blank spaces and tabs */
    while ((c = getch()) == ' ' || c == '\t')
        ;

    if (c == '(') {

        if ((c = getch()) == ')') {

            strcpy(token, "()");
            return tokentype = PARENS;

        } else {
            ungetch(c);
            return tokentype = '(';
        }

    } else if (c == '[') {

        for (*p++ = c; (*p++ = getch()) != ']'; )
            ;

        *p = '\0';
        return tokentype = BRACKETS;

    } else if (isalpha(c)) {

        /* Reads the next character of input */
        for (*p++ = c; isalnum(c = getch()); ) {
            *p++ = c;
        }

        *p = '\0';
        ungetch(c); /* Get back the space, tab */

        return tokentype = NAME;

    } else
        return tokentype = c;
}

/* dcl: parse a declarator */
void dcl(void)
{
    int ns;

    for (ns = 0; gettoken() == '*'; ) /* count *'s */
        ns++;

    dirdcl();

    while (ns-- > 0)
        strcat(out, " pointer to");
}

/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
    int type;

    if (tokentype == '(') {

        dcl();

        if (tokentype != ')')
            printf("error: missing )\n");

    }
    else if (tokentype == NAME) /* variable name */ {
        strcpy(name, token);
        printf("token: %s\n", token);
    }
    else
        printf("error: expected name or (dcl)\n");

    while ((type = gettoken()) == PARENS || type == BRACKETS) {

        if (type == PARENS)
            strcat(out, " function returning");
        else {
            strcat(out, " array");
            strcat(out, token);
            strcat(out, " of");
        }

    }
}

A: You need out[0] to be zero in order for strcat to work.
While this line
out[0] = '\0';

was required prior to the introduction of static initialization rules, it is no longer required, because static arrays, such as out[], are initialized to all zeros.
According to initialization rules of C99,

*

*...

*if it has arithmetic type, it is initialized to (positive or unsigned) zero.

*if it is an aggregate, every member is initialized (recursively) according to these rules.

A: It is resetting the char array (aka string) to empty array. (removing junk values)
like we use:
int i = 0;

before doing something like:
i += 1;

so that junk value don't add
So just '\0' in 0 index of array tells that array is completely empty and the strcat function starts appending value from 0 index, over writing the junk values in other indexes of array.
If program is working without resetting array then it means your IDE tool is doing that for you, but it is good practice to reset it.

A: In short: In this particular case it's not strictly necessary, but in many other cases that look suspiciously similar, it is, so most people do it as "good style". So why would it be necessary?
There is no such thing as "empty" memory. There is no such thing as a "length". Unless you explicitly keep track of it, or define your own.
Memory is just bytes, which are numbers from 0 to 255. Since 0 is just as valid a number as 255, there is no way to tell whether a byte is used or not. You can "add up" several bytes if you need larger numbers, but everything is built out of bytes, in the end. Text is simply mapped to a number. A couple decades ago it was decided which number represents which character. So if you see a byte with the value 32, it could be a 32. Or it could be the 32nd letter in the computer's alphabet (which is the space character).
When you receive a string and you don't know how much text you will be dealing with, what you usually do is you reserve a large block of bytes. This is what char out[1000]; above does. But how do you tell where the text ends? How much of the 1000 bytes you've already used?
Well, in the old days, some people would just declare another variable, say, int length; and keep track of how many bytes they've used so far. The designers of C went a different route. They decided to pick a very rare character and use that as a marker. They picked the character with the value 0 for that (That is not the character '0'. The character '0' actually is the 48th letter of a computer's alphabet).
So you can just look at all the bytes in your string from the start, and if a character is > 0, you know it is used. If you reach a 0 character, you know this is the end of your string. There are various advantages to either approach. An int uses 4 bytes, an additional 0-character only 1. On the other hand, if you use an int, a string can also contain a 0-character, it's just another character, nobody cares.
Whenever you write "foo" in C, what C actually does is reserve room for 4 bytes, for 'f', 'o', 'o' and for the 0 to indicate the end. When you write "" in C, what it does is reserve room for a single byte, the 0. So that you can tell that the string is empty.
So, what is memory filled with before you put something into it at startup? Well, in most cases, it is just garbage. Whatever was in that memory the last time it was used (after all, you have limited RAM, so when you quit one application on your computer, its memory can get re-used for the next app you launch after that). These will be random numbers, often outside of the range of common characters.
So, if you want strcat to see out as an empty string, you need to give it a block of memory that starts with this 0 value character. If you just leave memory like it is, there might be some random characters in it. Your buffer might contain "jbhasugaudq7e1723876123798dbkda0skno§§^^%$#-9H0HWDZmwus0/usr/local/bin"
or whatever was in that memory before. If you now appended some text to it, it would think the stuff before the first 0 (which is just randomly in this place) was a valid string, and append it to that. It will only know that this string is supposed to be empty, if you put a 0 right at the start.
So why did I say it is "not strictly necessary"? Well, because in your case, out is a global variable, and global variables are special because they automatically get cleared to 0 when your application starts up (or assigned any value that you assign them when you declare them).
However, this is only true for global variables (both regular globals and static globals). So many programmers make it a habit to always initialize their blocks of bytes. That way, if someone later decides to change a global into a local variable, or copy-and-pastes the code to another spot to use with a local variable, they do not have to worry about forgetting to add this statement.
This is especially useful as random memory often contains 0 characters. So depending on what program you previously used, you might not notice you forgot the initial 0 because there happened to be one already in there. And only later, when one of your users runs this application, they get garbage at the start of their string.
Does that clarify things a bit?


text:
Q: 404 to 301 - Fixing old links I have currently updated a site and made many improvements to it. The old site ran off 3 different systems and had wordpress (and the other systems) in the webroot. I have moved wordpress into a subdirectory (wordpress) and I also updated my blog posts to be prefixed with blog/. Pages and the front page are not prefixed with blog/.
The issue I am having is that I want to gracefully tell Google and other search engines that these posts are now prefixed with /blog/.
I used the following code in my 404 page before I realized that wordpress throws a 404 header. Obviously, this is not the correct way to implement this fix.
// Check if old site URL and redirect if so
if (substr($s, 0, 8) != 'reviews/') {
    if (substr($s, 0, 5) != 'blog/' && substr($s, 0, 10) != 'wordpress/' ) {
        // Force our 301 redirect so we can keep the new URI: /blog/
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: /blog/{$s}");
        exit();
    }
}

What I need to do is find out when wordpress knows this is a 404 and see if it matches my checks (currently what is in the snippet above) and if a match occurs force a 301 redirect to update the crawlers.
I am not sure if this information is available on init, as this is my next step to test.
I tried playing with template_redirect and redirect_canonical but they don't seem to be the correct methods to attach to.
Any help on this is appreciated. I am still trying to find a solution and will post back when I find one.
Thanks in advance.

A: If you intend to do checks based on template tags you should hook on wp action. template_redirect will suffice too, but wp is earlier. This is when WP handles 404 itself.
To perform a 301 redirect use status_header( 301 );, wp_safe_redirect(); immediately followed by exit;
You could use a plugin handle these for you. It's bit tricky to set-up if you are not that technical. Good luck.


text:
Q: laravel MongoDB\BSON\UTCDateTime class not found I have mongo database which contain time value like this

"time" : ISODate("2019-11-28T12:51:38.827Z"),

when I get this value from database using laravel I get it like this

"time":{"$date":{"$numberLong":"1574945497100"}}

I need to convert this value to readable date , I find in the internet solution to use

MongoDB\BSON\UTCDateTime

class , but when I apply this code
 $utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
 $datetime = $utcdatetime->toDateTime();

I have this error

Class 'App\Http\Controllers\MongoDB\BSON\UTCDateTime'  not found

I installed  mongodb driver in my php
 php -i | grep -i mongoDB
/etc/php/7.2/cli/conf.d/20-mongodb.ini,
 mongodb
MongoDB support => enabled
MongoDB extension version => 1.6.0
MongoDB extension stability => stable
mongodb.debug => no value => no value

I don't know why laravel not see this class

A: put slash before MongoDB
$utcdatetime = new \MongoDB\BSON\UTCDateTime(1416445411987);
$datetime = $utcdatetime->toDateTime();


text:
Q: chart.js bar chart datalabel vanishes on hovering over chart I have a bar chart that has a label over each bar.
The problem is that when I hover on the chart, all of the labels disappear.
Before hovering:

After hovering:

and here's my code:
let barChartData = {
    labels:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
    datasets: [{
        label: 'Sessions',
        backgroundColor: 'rgba(0,163,224, 0.7)',
        borderColor: 'rgba(0,163,224, 1)',
        borderWidth: 1,
        data:[81, 69, 60, 51, 37, 35, 45, 65, 86, 58, 64, 39, 48, 29, 69, 80, 52, 61, 56, 40, 51, 31, 70, 51, 32, 51, 27, 30, 44, 59, 46]
    }]
};
let ctx = document.getElementById(id).getContext("2d");
let chart = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        "animation": {
            "duration": 1,
            "onComplete": function () {
                let chartInstance = this.chart, ctx = chartInstance.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';
                ctx.fontColor = 'black'
                this.data.datasets.forEach(function (dataset, i) {
                    let meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function (bar, index) {
                        let data = dataset.data[index];
                        ctx.fillText(data, bar._model.x, bar._model.y - 5);
                    });
                });
            }
        },
        plugins: {
            datalabels: {
                color: '#000000'
            }
        },
        legend: {
            display: false
        },
        tooltips: {
            enabled: true,
            mode: 'label'
        },
    }
});

I removed the animation field but didn't work.
the chartjs version I'm using is 2.7.3

A: You can fix the problem with an update to Chart.js 2.9.3 and passing an empty hover function:
<html>
<head>

</head>
<body>
<canvas id="container"></canvas>
<script src="https://pagecdn.io/lib/chart/2.9.3/Chart.bundle.min.js"></script>
</body>
</html>

let barChartData = {
    labels:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
    datasets: [{
        label: 'Sessions',
        backgroundColor: 'rgba(0,163,224, 0.7)',
        borderColor: 'rgba(0,163,224, 1)',
        borderWidth: 1,
        data:[81, 69, 60, 51, 37, 35, 45, 65, 86, 58, 64, 39, 48, 29, 69, 80, 52, 61, 56, 40, 51, 31, 70, 51, 32, 51, 27, 30, 44, 59, 46]
    }]
};
const id = 'container';
let ctx = document.getElementById(id).getContext("2d");
let chart = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        "animation": {
            "duration": 1,
            "onComplete": function () {
                let chartInstance = this.chart, ctx = chartInstance.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';
                ctx.fontColor = 'black'
                this.data.datasets.forEach(function (dataset, i) {
                    let meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function (bar, index) {
                        let data = dataset.data[index];
                        ctx.fillText(data, bar._model.x, bar._model.y - 5);
                    });
                });
            }
        },
        hover: () => {},
        plugins: {
            datalabels: {
                color: '#000000'
            }
        },
        legend: {
            display: false
        },
        tooltips: {
            enabled: true,
            mode: 'label'
        },
    }
});

This fix doesn't work with Chart.js 2.7.3. I don't know if it's a bug or a different behavior on purpose.
Live example


text:
Q: Find exact match of variable within multiple arrays I'm trying to write a bash code which should get a variable and search within multiple arrays.  For example:
$var = site.com

And my arrays are:
array1=(test world myword something bla my.site.com)
array=(google facebook stackoverflow site.com)
array=(music eating video site.com.dev)

The code that I'm trying to run and unfortunately not working is:
#!/bin/bash
if [[ ${array1[*]} =~ "$var" ]]; then
   echo "it's array1"
elif [[ ${array2[*]} =~ "$var" ]]; then
   echo "it's array2"
elif [[ ${array3[*]} =~ "$var" ]]; then
   echo "it's array3"
fi

The problem here is that it even it return the same array for "site.com", "my.site.com" and "site.com.dev".
What's missing here and how I should write it properly?

A: =~ is an unanchored regex -- when the right side is quoted, it becomes a substring search. ${array[*]} assembles a string by combining all the entries in your array with the first character in IFS (a space by default) between them. Thus, [[ ${array[*]} =~ "$var" ]] is flattening your array into a string, and doing a substring search on that string.
site.com is a substring of my.site.com and of site.com.dev, so it's expected for it to match.
If you want an efficient, exact-match-only search, invert your arrays to be associative rather than numerically-indexed, and do a key lookup for each.
That is:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*) echo "ERROR: Needs bash 4.0 or newer" >&2; exit 1;; esac

var=site.com

declare -A array1=( [test]=1 [world]=1 [myword]=1 [something]=1 [my.site.com]=1 )
declare -A array2=( [google]=1 [facebook]=1 [stackoverflow]=1 [site.com]=1 )
declare -A array3=( [music]=1 [eating]=1 [video]=1 [site.com.dev]=1 )

if [[ ${array1["$var"]} ]]; then echo "It's array1"
elif [[ ${array2["$var"]} ]]; then echo "It's array2"
elif [[ ${array3["$var"]} ]]; then echo "It's array3"
else echo "Not found"
fi


text:
Q: How do I use the Euler-Maclaurin Summation to find the zeros of the Riemann-Zeta function? I read this paper which describes Euler-Maclaurin Summation as a method for evaluating sums in terms of an integral. I also read from this Quora answer that Euler-Maclaurin summation is one method to find zeros on the critical strip.
However, it isn't obvious to me how to use this formula in order to find zeros. Can someone please explain it in terms a not-so-bright undergraduate can understand?


text:
Q: Per site stats related to association bonus I would like to get some statistics to help me better understand the role of association bonus at different sites.
For a given site, I would like to know:

*

*How many users were granted bonus based on this site reputation.

*How many users have been granted a bonus from other sites, how many of them have a positive on-site reputation "balance", and how does amount of users with bonus compare against ones having upvote privilege.

*Of users with bonus, which site has granted most and how many (what percent of users with bonus has got it from top-granting site)

As the SE network is huge, I would not object if the data is limited to, say, 20-30 top-traffic sites, although fuller stats would be much appreciated.


text:
Q: Obtaining frames from IP Camera with low latency I am currently using this command to get frames from my RTSP stream and reading frames from stdout:
ffmpeg -nostdin -rtsp_transport tcp -i <rtsp_stream> -pix_fmt bgr24 -an -vcodec rawvideo -f rawvideo -

However, I would like to get the same latency as when I see it via ffplay:
ffplay -fflags nobuffer -flags low_delay -tune zerolatency -framedrop -rtsp_transport tcp <rtsp_stream>

or when I play it via VLC Media > Open Network Stream with :network_caching=300ms.
I would like to know what other parameters I can use with my ffmpeg command to get an equivalent (or better) result compared to the ffplay command.
I have made references from: How to dump raw RTSP stream to file?,  Open CV RTSP camera buffer lag, How to pipe output from ffmpeg using python?, bad ffmpeg performace compared to ffplay and VLC, How to minimize the delay in a live streaming with ffmpeg
My current implmentation:
FFMPEG_CMD = "ffmpeg -nostdin -rtsp_transport tcp -i <rtsp_stream> -pix_fmt bgr24 -an -vcodec rawvideo -f rawvideo -".split(" ")
WIDTH = 2560
HEIGHT = 1440

process = subprocess.Popen(FFMPEG_CMD, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)

while True:
    raw_frame = process.stdout.read(WIDTH*HEIGHT*3)
    frame = np.frombuffer(raw_frame, np.uint8)
    frame = frame.reshape((HEIGHT, WIDTH, 3))

    <do stuff with frame/ show frame etc.>

Thanks for reading.

ffmpeg command I am now using for < 1s latency.
ffmpeg -nostdin -flags low_delay -rtsp_transport tcp -i <rtsp_stream> -pix_fmt bgr24 -an -vcodec rawvideo -f rawvideo -

Implementation with suggestion(s) from Answers:
import subprocess
import numpy as np

FFMPEG_CMD = "ffmpeg -nostdin -flags low_delay -rtsp_transport tcp -i <rtsp_stream> -pix_fmt bgr24 -an -vcodec rawvideo -f rawvideo -".split(" ")
WIDTH = 2560
HEIGHT = 1440

process = subprocess.Popen(FFMPEG_CMD, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)

raw_frame = np.empty((HEIGHT, WIDTH, 3), np.uint8)
frame_bytes = memoryview(raw_frame).cast("B")

while process.poll() is None:
    process.stdout.readinto(frame_bytes)
    frame = raw_frame.reshape((HEIGHT, WIDTH, 3))

    <do stuff with frame/ show frame etc.>

A: I did some research about reducing the video latency.
My following answer demonstrates that the relevant FFmpeg flags are -probesize 32 and -flags low_delay.
The above flags are relevant for the video decoder side (receiver side).
The video encoding parameters "transmitter / encoder side" is more significant for determining the end to end latency.
Adding the argument -tune zerolatency reduces the encoder latency to minimum, but the required bandwidth is much higher (and probably not relevant for streaming over the internet).
I am going to restrict my answer to decoding latency, because it seems more relevant to the topic of your question.
The subject regarding "know how others obtain video frames with low latency" is a subject for a separate question (and I don't know the answer).

For comparing the latency differences between FFplay and FFmpeg (decoder), I created a "self contained" test sample.
Main "principles":

*

*Execute FFmpeg sub-process for streaming two RTSP output streams in parallel.
The streamed video is synthetic pattern with frame counter as text over the video.
The two output streams applies the same encoding parameters (only the port is different).
The RTSP IP address is 127.0.0.1 (localhost).
(Note: We may use tee muxer instead of encoding twice, but I never tried it).

*Execute FFplay sub-process that to decode and display one video stream.

*Execute FFmpeg sub-process that to decode the other video stream.
OpenCV imshow is used for displaying the video.

*The displayed video with the larger counter is the one with the lower latency.

Code sample (updated):
import cv2
import numpy as np
import subprocess as sp
import shlex

rtsp_stream0 = 'rtsp://127.0.0.1:21415/live.stream'  # Use localhost for testing
rtsp_stream1 = 'rtsp://127.0.0.1:31415/live.stream'
width = 256  # Use low resolution (for testing).
height = 144
fps = 30

# https://stackoverflow.com/questions/60462840/ffmpeg-delay-in-decoding-h264
ffmpeg_cmd = shlex.split(f'ffmpeg -nostdin -probesize 32 -flags low_delay -fflags nobuffer -rtsp_flags listen -rtsp_transport tcp -stimeout 1000000 -an -i {rtsp_stream0} -pix_fmt bgr24 -an -vcodec rawvideo -f rawvideo pipe:')

# FFplay command before updating the code (latency is still too high):
# ffplay_cmd = shlex.split(f'ffplay -probesize 32 -analyzeduration 0 -sync ext -fflags nobuffer -flags low_delay -avioflags direct -rtsp_flags listen -strict experimental -framedrop -rtsp_transport tcp -listen_timeout 1000000 {rtsp_stream1}')

# Updated FFplay command - adding "-vf setpts=0" (fixing the latency issue):
# https://stackoverflow.com/questions/16658873/how-to-minimize-the-delay-in-a-live-streaming-with-ffmpeg
ffplay_cmd = shlex.split(f'ffplay -probesize 32 -analyzeduration 0 -sync ext -fflags nobuffer -flags low_delay -avioflags direct -rtsp_flags listen -strict experimental -framedrop -vf setpts=0 -rtsp_transport tcp -listen_timeout 1000000 {rtsp_stream1}')

# Execute FFplay to used as reference
ffplay_process = sp.Popen(ffplay_cmd)

# Open sub-process that gets in_stream as input and uses stdout as an output PIPE.
process = sp.Popen(ffmpeg_cmd, stdout=sp.PIPE) #,stderr=sp.DEVNULL

# The following FFmpeg sub-process stream RTSP video.
# The video is synthetic video with frame counter (that counts every frame) at 30fps.
# The arguments of the encoder are almost default arguments - not tuned for low latency.
# drawtext filter with the n or frame_num function https://stackoverflow.com/questions/15364861/frame-number-overlay-with-ffmpeg
rtsp_streaming_process = sp.Popen(shlex.split(f'ffmpeg -re -f lavfi -i testsrc=size={width}x{height}:rate={fps} '
                                               '-filter_complex "drawtext=fontfile=Arial.ttf: text=''%{frame_num}'': start_number=1: x=(w-tw)/2: y=h-(2*lh): fontcolor=black: fontsize=72: box=1: boxcolor=white: boxborderw=5",'
                                               'split[v0][v1] '  # Split the input into [v0] and [v1]
                                               '-vcodec libx264 -pix_fmt yuv420p -g 30 -rtsp_transport tcp -f rtsp -muxdelay 0.1 -bsf:v dump_extra '
                                              f'-map "[v0]" -an {rtsp_stream0} '
                                               '-vcodec libx264 -pix_fmt yuv420p -g 30 -rtsp_transport tcp -f rtsp -muxdelay 0.1 -bsf:v dump_extra '
                                              f'-map "[v1]" -an {rtsp_stream1}'))

while True:
    raw_frame = process.stdout.read(width*height*3)

    if len(raw_frame) != (width*height*3):
        print('Error reading frame!!!')  # Break the loop in case of an error (too few bytes were read).
        break

    # Transform the byte read into a numpy array, and reshape it to video frame dimensions
    frame = np.frombuffer(raw_frame, np.uint8)
    frame = frame.reshape((height, width, 3))

    # Show frame for testing
    cv2.imshow('frame', frame)
    key = cv2.waitKey(1)

    if key == 27:
        break

process.stdout.close()
process.wait()
ffplay_process.kill()
rtsp_streaming_process.kill()
cv2.destroyAllWindows()

Sample output before adding adding -vf setpts=0:
Sample output (left side is OpenCV and right side is FFplay):

It looks like FFmpeg-OpenCV latency is lower by 6 frames before adding -vf setpts=0 to FFplay command.
Note: It took me some time to find the solution, and I decided to keep the result of the original post for showing the importance of adding the setpts filter.

Update:
Adding -vf setpts=0 solved the latency issue.
The latest answer from the following post suggests to add setpts video filter that resets all the video timestamps to zero.
It may not be a good idea with the present of audio stream, but when lowest video latency is required, this is the best solution I could find.
After adding -vf setpts=0 the latency of FFplay and OpenCV is about the same:

Repeating the test with mpv media player:
(Note: It seemed more relevant before I found the FFplay solution).
When applying all the mpv "latency hacks" from this page, the latency of mpv and OpenCV is about the same:

There must be a solution with FFplay, but I can't find it...

Code sample (using mpv instead of FFplay):
import cv2
import numpy as np
import subprocess as sp
import shlex

rtsp_stream0 = 'rtsp://127.0.0.1:21415/live.stream'  # Use localhost for testing
rtsp_stream1 = 'rtsp://127.0.0.1:31415/live.stream'
width = 256  # Use low resolution (for testing).
height = 144
fps = 30

# https://stackoverflow.com/questions/60462840/ffmpeg-delay-in-decoding-h264
ffmpeg_cmd = shlex.split(f'ffmpeg -nostdin -probesize 32 -flags low_delay -fflags nobuffer -rtsp_flags listen -rtsp_transport tcp -stimeout 1000000 -an -i {rtsp_stream0} -pix_fmt bgr24 -an -vcodec rawvideo -f rawvideo pipe:')

# https://stackoverflow.com/questions/16658873/how-to-minimize-the-delay-in-a-live-streaming-with-ffmpeg
#ffplay_cmd = shlex.split(f'ffplay -probesize 32 -analyzeduration 0 -sync ext -fflags nobuffer -flags low_delay -avioflags direct -rtsp_flags listen -strict experimental -framedrop -rtsp_transport tcp -listen_timeout 1000000 {rtsp_stream1}')

# https://github.com/mpv-player/mpv/issues/4213
mpv_cmd = shlex.split(f'mpv --demuxer-lavf-o=rtsp_flags=listen --rtsp-transport=tcp --profile=low-latency --no-cache --untimed --no-demuxer-thread --vd-lavc-threads=1 {rtsp_stream1}')

# Execute FFplay to used as reference
#ffplay_process = sp.Popen(ffplay_cmd)

# Execute mpv media player (as reference)
mpv_process = sp.Popen(mpv_cmd)

# Open sub-process that gets in_stream as input and uses stdout as an output PIPE.
process = sp.Popen(ffmpeg_cmd, stdout=sp.PIPE) #,stderr=sp.DEVNULL

# The following FFmpeg sub-process stream RTSP video.
# The video is synthetic video with frame counter (that counts every frame) at 30fps.
# The arguments of the encoder are almost default arguments - not tuned for low latency.
# drawtext filter with the n or frame_num function https://stackoverflow.com/questions/15364861/frame-number-overlay-with-ffmpeg
rtsp_streaming_process = sp.Popen(shlex.split(f'ffmpeg -re -f lavfi -i testsrc=size={width}x{height}:rate={fps} '
                                               '-filter_complex "drawtext=fontfile=Arial.ttf: text=''%{frame_num}'': start_number=1: x=(w-tw)/2: y=h-(2*lh): fontcolor=black: fontsize=72: box=1: boxcolor=white: boxborderw=5",'
                                               'split[v0][v1] '  # Split the input into [v0] and [v1]
                                               '-vcodec libx264 -pix_fmt yuv420p -g 30 -rtsp_transport tcp -f rtsp -muxdelay 0.1 -bsf:v dump_extra '
                                              f'-map "[v0]" -an {rtsp_stream0} '
                                               '-vcodec libx264 -pix_fmt yuv420p -g 30 -rtsp_transport tcp -f rtsp -muxdelay 0.1 -bsf:v dump_extra '
                                              f'-map "[v1]" -an {rtsp_stream1}'))

while True:
    raw_frame = process.stdout.read(width*height*3)

    if len(raw_frame) != (width*height*3):
        print('Error reading frame!!!')  # Break the loop in case of an error (too few bytes were read).
        break

    # Transform the byte read into a numpy array, and reshape it to video frame dimensions
    frame = np.frombuffer(raw_frame, np.uint8)
    frame = frame.reshape((height, width, 3))

    # Show frame for testing
    cv2.imshow('frame', frame)
    key = cv2.waitKey(1)

    if key == 27:
        break

process.stdout.close()
process.wait()
#ffplay_process.kill()
mpv_process.kill()
rtsp_streaming_process.kill()
cv2.destroyAllWindows()

A: Assuming that the bottleneck is indeed somewhere in your example code (and not in <do stuff with frame/ show frame etc.>), you can try to update numpy array as opposed to creating one every time:
frame = np.empty((HEIGHT, WIDTH, 3), np.uint8)
frame_bytes = memoryview(frame).cast("b")
while True:
    process.stdout.readinto(frame_bytes) # fills the buffer of frame
    ...


text:
Q: Spring RequestBody map JSON string to Point2D coordinates I want to map an incoming JSON string to a custom POJO in my @PostMapping:
@PostMapping(value = "/classification", consumes = "application/json", produces = "application/json")
public ResponseEntity<String> getClassificationResults (
            @RequestBody Classification classification) {

     this.elasticSearchService.getSpatialData(classification);
  return ResponseEntity.ok(" ");
}

My classification POJO:
public class Classification {
    @JsonProperty
    private ArrayList<Point2D.Double> shapes;
    @JsonProperty
    private String [] colors;
    @JsonProperty
    private String [] pattern;
    @JsonProperty
    private Integer size;
...
}

which (of course) results in the error:

JSON parse error: Cannot construct instance of
  java.awt.geom.Point2D$Double (although at least one Creator exists):
  no String-argument constructor/factory method to deserialize from
  String value

Data example:
"[[8.880321034663876,49.121984026160106],
 [8.746452886806255,49.11327654230291],
 [8.61786489671323,49.087497674922325],...]"

My resulting object must not be an ArrayList of Point2D objects, but rather any type of Array which contains the same values as the example - just converted to number.
Do I have to specify my own Jackson deserializer (how can I do this?) for this problem, or is it sufficient to change the Classification constructor?

A: You can implement custom deserialiser or using MixIn feature define Shape.ARRAY for Point2D class:
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.json.JsonMapper;

import java.awt.geom.Point2D;
import java.util.List;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        JsonMapper jsonMapper = JsonMapper.builder()
                .addMixIn(Point2D.Double.class, Point2DDoubleMixIn.class)
                .build();

        String json = "[[8.880321034663876,49.121984026160106],[8.746452886806255,49.11327654230291],[8.61786489671323,49.087497674922325]]";

        TypeReference<List<Point2D.Double>> type = new TypeReference<List<Point2D.Double>>() {};
        List<Point2D.Double> shapes = jsonMapper.readValue(json, type);
        System.out.println(shapes);
    }
}

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
interface Point2DDoubleMixIn { }

See also:

*

*Specifying the Shape.


text:
Q: mathbb allowed only in math mode I want to type this equation,

however I am struggling with \mathcal and \mathbb,
Here is my code, can anyone tell me what's wrong to my code and how to fix it? Thanks!
\begin{equation}
\min _{W} \underset{(x, y) \sim \mathcal{D}}{\mathbb{E}} \mathcal{L}(W ;(x, y))
\end{equation}

What I am having is: The letter E, and D did not display as expected

Solved: the package of \usepackage{breqn} disrupted the compilation. When I remove this line, the problem is resolved.

A: According totally with the comments of @moewe and @DG' here I add a minimal compilable code, where you can obtain, correctly, your expected 2nd image.
\documentclass[a4paper,12pt]{article}
\usepackage{mathtools,amssymb}
\begin{document}
\begin{equation}
\min_{W} \underset{(x, y) \sim \mathcal{D}}{\mathbb{E}} \mathcal{L}(W ;(x, y))
\end{equation}
\end{document}

The snapshot is:


text:
Q: Force aspx/cs to be contained in the project dll I have a project name= extension that is getting load as an "extension" in other project name= container.
When container loads the extension the extension dll is getting copied to bin folder in container project.
extension contains an page.aspx with a cs file,
How can i "force" the cs file to be contained in the dll  so i could reach it through 'aspx' page?
My final goal - Call an page.aspx http://container/page.aspx?id=1234
and read the query-string parameter id for stream back a content of a pdf


text:
Q: How to use Middleware in Graphql with laravel? I am working on laravel application with graphql queries. in schema file some queries and mutations are there. the queries are like apis.
type Query {
    users: [User!]! @all @orderBy(column: "created_at",direction: DESC)
    user(id: ID @eq): User @find
}

here i have these two queries but i don't know how to create middleware for this query. if we create a separate query file for this and we call them means we are using laravel code in the query file but there also we are calling from schema file.
So i wanted to know any possibilities of setting middleware for the queries in graphql.
like group middleware.


text:
Q: Infinitesimal generator of Markov chain using numpy I am computing the infinitesimal generator of a continuous-time Markov chain from the transition probabilities p. I am following the methodology described here, just translated the R code to python/numpy.
p = np.array([[0.8,0.2,0],[0.1,0.7,0.2],[0.1,0.1,0.8]]) # probabilities, rows sum to 1
values, vectors = np.linalg.eig(p)
q = vectors@np.diag(np.log(values))@np.linalg.inv(vectors)
print(q)
 [[-0.238  0.273 -0.035]
 [ 0.119 -0.392  0.273]
 [ 0.119  0.119 -0.238]]

If q contains transition rates, like explained in page 17 here, I would expect that given p[0,2] is 0, the corresponding q[0,2] should also be 0, but that is not the case.
Is there something wrong with my methodology? or is it my assumption that 0 values in p should also correspond to 0 values in q?


text:
Q: How to access domain with www I am facing  problem www URL I can't access URL with www .I want to access URL with www my domain name is http://test.com but I need to access http://www.test.com

A: Check your dns records. You have to add a "www" subdomain with either a "IN A" recird to the ip were test.com is served, or a "IN CNAME" to "test.com." (note that final dot, it's important! it means that it's a fully qualified domain name, not another subdomain of the main zone).
For example, if you want www.test.com to point to the same thing that test.com do, add (in bind syntax) the folowing line to your zone :
www IN CNAME test.com.

hope that helps.


text:
Q: pg_restore: using the -L (use-list) option not working I every now and then restores a db-dump. To save time and I want to exclude some large un-needed tables.
I try to use the -L (use-list) option but when running the pg_restor command it does not work.
I get the same result even if I'm using a un-edited list.
This is the command I use:
pg_restore -v -U [user] -L "restore.pgdump.list" -d [dbname]-h localhost -p 5432 [dump-file]
This is the result:
pg_restore: [archiver] WARNING: line ignored: ÿþ
pg_restore: connecting to database for restore
Password:
pg_restore: implied data-only restore
If I go with the same command without the L-option the database is restored correctly.
Would much appreciate your help
Peter


text:
Q: How to ask a question which implies an ordinal number as an answer? How do I ask a question which implies an ordinal number as an answer? E.g. if I want to ask "which exit should I take on a motorway?" and I don't want to get an answer "left" or "right" or "the next one", but rather "first", "second" etc. What do I need to add to my question or how can I modify it in this case?

A: You would say something like;

I've just left I-95 and am now on I-476 North. How many exits up is
  the one I should take?

But you might get a number, not an ordinal, e.g. "Your exit is three exits ahead" rather than "Take the third exit".
Asking which exit might get you the name of the exit.

A: If you want to make clear that you want a number for an answer, I think you'd have to include the word "number" or something synonymous in your question.
For example, yes, in the question you used in your example, "Which exit should I take on the motorway?", someone might quite reasonably answer, "The Reading exit", or "The exit right after the big gray factory".
If you asked, "What number exit should I take?" or "Which number exit should I take?", then I'd expect someone to reply, "The fourth one" or "Exit number 4."
I don't know any simple way to say you want an ordinal number rather than a cardinal number. You could say, "What is the ordinal number of the exit that I should take?" Depending on who you're speaking to, they may well not know what an ordinal number is. You might end up having to use a very clumsy sentence, like, "What is the ordinal number of the exit that I should take? You know, like first, second, third, whatever?"
Of course if you asked, "What number exit should I take?", and someone said, "exit 3", hopefully you can figure out that that's equivalent to "the third exit". I'm not sure in what context an answer of "three" instead of "third" would be a problem.

A: In contrast to Jays answer, do not ask "What number exit should I take?", but:
What exit number should I take?
You are again specifically asking for the number (which is what you want), but it is a little less ambiguous. You are now (syntactically) asking for the number property of an exit.


text:
Q: How important is W3C XHTML/CSS validation when finalizing work? Even though I always strive for complete validation these days, I often wonder if it's a waste of time.  If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal?
What level do you hold your code to when you create it for:
a) yourself
b) your clients
P.S. Jeff and company, why doesn't stack overflow validate? :)
EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems"
I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going

A: I think this is an area in which you should strive to use the Robustness principle as far as is practical (which is good advice for any area of coding). Just because something works today doesn't mean it will work tomorrow: if you're relying on a particular HTML/CSS hack or even if you've just been a little lax in emitting strictly valid code, the next iteration of browsers could well break. Doing it once the right way minimises this problem (though does not entirely mitigate it).
There is a certain element of pragmatism to take here, though. I'd certainly do all I could for a client's site to be valid, but I would be willing to take more risks in my own space.

A: I think it's only "tech" guys that really care for "100% standard compliance". My usual page consumers (= users) don't care if there's no alt-attribute for a "menu border picture element".
I usually just make sure that I don't see any obvious errors (all tags closed, all lower case, attributes in quotes, ...), but if it looks good on IE and FF, that's all I care for. I don't really care if I use a non-standard attribute in any HTML tag, so that the page doesn't validate against an DTD - as long as I get the visual results that I intended to get.

A: For understanding why validation matters, it is needed to understand how a browser works at its different layers, and also a little bit about the history of web from the perspective of web browsers.
The HTML you give to a browser is interpreted by the browser following the DOM, an application programming interface that maps out the entire page as a hierarchy of nodes. Each part of that  tree is a type of node containing different kinds of data. DOM (Document Object Model) was necessary because of the diversity of HTML pages that early web browsers (Netscape, IE...) implemented to allow alter the appearance and content of a web page without reloading it. For preserving the cross-platform nature of the web, W3C wanted to fix the different implementation of those browsers, proposing DOM.
DOM support became a huge priority for most web browsers vendors, and efforts have been ongoing to improve support on each release. So, it worked.
DOM is the very basic step with which a web browser starts. Its main flow is:

*

*parsing HTML to construct the DOM tree

*render tree construction

*layout of the render tree

*painting the render tree

The step 1 gives the content tree, with the tags turned to DOM nodes. The step 2 gives the render tree, containing styling information.
So, why validation matters: because content tree and render tree are the basis from which the web browser start its job. The most they are well defined, the better for the web browser.
Ultimately, the DOM is also the basis for your JavaScript events. So, its validation helps to the interaction layer too.

A: a) Must look the same
b) As standards-compliant as possible, but not so anal that it blocks finishing work
In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up.

A: I know this isn't answering your whole question, but it is worth considering that by using completely valid html you can be sure that your website should work properly in future web browsers that haven't been released yet.

A: My approach tends to be to ensure I can completely validate on all pages, however I still send the page as text/html instead of application/xhtml+xml so there are no ugly XML errors in the event I have missed something.

A: For me, I feel like I've done a good job if my code validates. Seeing the green check box on the w3c pages just makes me slightly giddy. As for group b, They usually only care that it looks and works the same across browsers. They only place I've found that this is not true is the government sector. They require complete validation not only with the w3c but also passing ADA tests (basically how does it sound with a screen reader).
p.s. when I say government sector, I mean specifically the state of California and a few counties inside it. I have had no ther experience with other government groups besides them.

A: I think validation is a good litmus test of whether you've done things properly, so if there are only a few minor problems, why not fix them and ensure your site will at least be understood correctly by browsers in the future (even if they do render things differently for other reasons)?
OTOH, for most projects, validation seems like a huge headache and if you can get things working across browsers, it's not worth spending an extra day/week+ on just validation.

A: Except that the validators themselves are so positively anal,
 when they flag an error or warning whenever a -moz- or -webkit or -o- i.e. a browser specific qualification term is used.
also they want you to specify 0px rather than 0 or other units
Zero is Zero whatever units the validator wants to check it against!
just try validating the WordPress twentyeleven style.css it throws 140 odd errors which are all of the nature above or the validator is recovering from parse errors
The validators are useless if you cannot sort the wheat from the chaff!!!
We need validators that recognise browser specific qualification terms!