text:
Q: Reason for inertia of motion of Earth orbiting the Sun We all know the following universal truth since childhood.

Earth (and other planets) orbits around the Sun.

And, while I was reading this post, I found that the reason behind Earth revolution is chiefly due to one force:

* Gravitational pull
Some physicists explains the movement of Earth around the Sun on the basis of the following image:

As we can see, the initial state of rock is rest. And when we apply a force, it starts moving in a circular path.

Now my question is from where the Earth had got the inertia of motion? As the rock in the above example was initially at rest and so the Earth should also be in state of rest (without any force applied on it).

A: There is no sideways force.  Without any force at all, the planet would keep moving in a straight line with a constant speed.  You can probably find more information about this by searching for "conservation of momentum."  When the gravitational force that pulls the planet toward the Sun is included, the planet's would-be straight path is bent into a circular orbit.  This gravitational force toward the center of the circle is called the "centripetal force".
The post you cited depicts this incorrectly, which is especially disappointing because that appears to be a NASA site! In the picture labelled "This activity demonstrates...", the "centripetal force" should point toward the center, not in the direction of motion.
Here's a different NASA webpage that describes it correctly: https://imagine.gsfc.nasa.gov/features/yba/CygX1_mass/gravity/circular_motion.html.  The caption of one of the pictures on that page says, "Centripetal means center-seeking. Centripetal forces are always directed toward the center of the circular path." [emphasis added]
Note added: While I was typing this post (including looking for a NASA website that gets it right), other answers appeared, and I didn't notice that until after I posted this answer.  I didn't mean to be repetitive.

A: There is no sideways force. It is just the Sun's gravity (shown in that diagram) combined with the fact that the Earth is already moving. This is similar to when you swing a rock tied to string around you in a circle (dangerous!!); the rock's circular movement is due to one force, the force from the string.

A: You are misinterpreting the post and figure. The earth tends to move in a straight line due to inertia (Newton's first law).
However, earth senses a sideway force due to gravity from the sun. Sideway refers to the force perpendicular to the straight line.

A: The Earth has never been at rest.
The Solar system is thought to have formed from the collapse of a large cloud of gas and dust.  Individual molecules of that cloud probably had relatively small velocities to begin with, but as the cloud collapsed, they accelerated (converting gravitational potential energy into kinetic energy) and conservation of angular momentum forced them into a spinning disk (same phenomenon as an ice skater spinning faster when they pull their arms in).  Collisions built rocks out of molecules and planets out of rocks.  In the process, each planet accumulated (nearly) all the kinetic energy of everything that went into its formation.
The last major change to the Earth's kinetic energy was probably due to the giant impact that formed the Moon.


text:
Q: Any way to get the specific foreign key constraint that is failing as a result of executing a single statement? I'm using SQLite as the backend for an iOS app. I am facing a bug where a particular delete operation is not executing due to a failed foreign key constraint. Despite narrowing down the culprit to four different foreign key constraints, I'm still not sure which one it is. Is there a way for SQLite to tell me which specific foreign key constraint is causing the error?

A: You could always use a query to pre-check and determine the conflicts. Something along the lines of :-
CREATE TABLE IF NOT EXISTS parent (id INTEGER PRIMARY KEY,name TEXT);
INSERT INTO parent (name) VALUES ('parent1'),('parent2'),('parent3'),('parent4');

/* This being the pre-check query */
SELECT
    2 IN (SELECT id FROM parent) AS FK1CHECK,
    3 IN (SELECT id FROM parent) AS FK2CHECK,
    10 IN (SELECT id FROM parent) AS FK3CHECK;

*

*where 2 (exists), 3 (exists) and 10 (would be FK conflict)

*obviously you would bind the 3 parameters/values to be checked so the query would be:-
SELECT
    ? IN (SELECT id FROM parent) AS FK1CHECK,
    ? IN (SELECT id FROM parent) AS FK2CHECK,
    ? IN (SELECT id FROM parent) AS FK3CHECK;

*for simplicity just the 1 parent table but that would be adjusted to suit the situation
The result :-
1   1   0

i.e. F3CHECK, as it is 0, indicates a FK conflict would result
Additonal
Regarding the comment:-

i see why the third query would fail, but i don't see why it would be a failure of a foreign key constraint. it's just a nonexistent record, and you haven't defined any foreign key constraints here. so there really shouldn't be any foreign key constraints failures anyways. struggling to see how this relates to my issue

There aren't 3 queries it is a single query that outputs 3 columns, via 3 sub queries, each indicating whether the relationship would work. That is it is effectively doing what the FK constraint would do.
As you are struggling to understand then the following demonstrates, step by step :-
/* drop the demo tables if they already exist */
DROP TABLE IF EXISTS child1;
DROP TABLE IF EXISTS child2;
DROP TABLE IF EXISTS child3;
DROP TABLE IF EXISTS parent;
/* turn on Foreign Key Support */
PRAGMA foreign_keys = ON;
/* Show the Foreign Key Support status */
PRAGMA foreign_keys;

/* create the parent table which will be a parent to 3 child tables */
CREATE TABLE IF NOT EXISTS parent (id INTEGER PRIMARY KEY, name TEXT);
/* create the 3 child tables with a Foreign Key constraint */
CREATE TABLE IF NOT EXISTS child1 (id INTEGER PRIMARY KEY, parentid INTEGER REFERENCES parent(id));
CREATE TABLE IF NOT EXISTS child2 (id INTEGER PRIMARY KEY, parentid INTEGER REFERENCES parent(id));
CREATE TABLE IF NOT EXISTS child3 (id INTEGER PRIMARY KEY, parentid INTEGER REFERENCES parent(id));

/* Add some parent rows */
INSERT INTO parent VALUES (1,'P1'),(2,'P2'),(3,'P3');

/* Attempt to insert three rows
    child1 row with relationship to parent P1 (i.e. parentid = 1),
    child2 with relationship to P2 (i.e. parentid = 2) and
    child3 with relationship to P3 (i.e. parentid = 3)
    but first PRE CHECK
*/
/* THE PRECHECK */
SELECT (SELECT 1 /*parentid value for child1 insert*/ IN (SELECT id FROM parent)) AS check1,
    (SELECT 2 /* parentid value for child2 insert */ IN (SELECT id FROM parent)) AS check2,
    (SELECT 3 /* parentid value for child3 insert */ IN (SELECT id FROM parent)) AS check3
;
/* This results in 1,1,1 i.e. ok to insert all three*/ :-

/* The the inserts */
INSERT INTO child1 (parentid) VALUES(1 /* parentid value for child1 insert*/);
INSERT INTO child2 (parentid) VALUES(2 /* parentid value for child2 insert*/);
INSERT INTO child3 (parentid) VALUES(3 /* parentid value for child3 insert*/);

/* Show the resultant data */
SELECT * FROM parent
    LEFT JOIN child1 ON child1.parentid = parent.id
    LEFT JOIN child2 ON child2.parentid = parent.id
    LEFT JOIN child3 ON child3.parentid = parent.id
;

/* Attempt to insert three rows
    child1 row with relationship to parent P2 (i.e. parentid = 1),
    child2 with relationship to P3 (i.e. parentid = 2) and
    child3 with relationship to non-existent (i.e. parentid = 3)
    but first PRE CHECK
*/
SELECT (SELECT 2 /*parentid value for child1 insert*/ IN (SELECT id FROM parent)) AS check1,
    (SELECT 3 /* parentid value for child2 insert */ IN (SELECT id FROM parent)) AS check2,
    (SELECT 10 /* parentid value for child3 insert */ IN (SELECT id FROM parent)) AS check3
;
/* result will be 1,1,0 i.e. the 3rd insert will fail */

INSERT INTO child1 (parentid) VALUES(2 /* parentid value for child1 insert*/);
INSERT INTO child2 (parentid) VALUES(3 /* parentid value for child2 insert*/);
INSERT INTO child3 (parentid) VALUES(10 /* parentid value for child3 insert*/);

When run the first result is from the PRAGMA foreign_keys :-

*

*i.e. foreign key support is true 1, so foreign key support is turned on

The second result is the PRE-CHECK :-

*

*as check1 is 1 then the first insert will not result in a foreign key conflict/failure.

*as check2 is 1 then the second insert will not result in a foreign key conflict/failure

*as check3 is 1 then the thrid insert will not result in a foreign key conflict/failure

The third result a query after the inserts :-

i.e. the respective child1/2/3 rows have been inserted.
The fourth/last is the PRE-CHECK for the 2nd set of inserts :-

As highlighted the check3 INDICATES that a foreign key conflict/failure WILL happen if the inserts go ahead. The result could be used to determine the ensuing logic and determine which of the foreign keys would cause the conflict.
Lastly as the above was undertaken with an SQLite tool (Navicat) then the INSERTS are attempted the messages being :-
INSERT INTO child1 (parentid) VALUES(2 /* parentid value for child1 insert*/)
> Affected rows: 1
> Time: 0.083s

INSERT INTO child2 (parentid) VALUES(3 /* parentid value for child2 insert*/)
> Affected rows: 1
> Time: 0.074s

INSERT INTO child3 (parentid) VALUES(10 /* parentid value for child3 insert*/)
> FOREIGN KEY constraint failed
> Time: 0s

i.e. as was DETERMINED by the PRE-CHECK (check3 being 0) the attempt to insert into child3 failed with the predicted outcome.
Of course the above would have to be tailored to suit. A more specific answer could have been given if more specific detail were provided.

A: There is no way that I know of to get directly from SQLite the specific foreign key constraint that raised the error.
What you can do, for debugging purposes, to find that constraint, is to turn off foreign key constraint checks (they are turned off by default) by running:
PRAGMA foreign_keys = OFF;

Then run your code and insert the row(s) that violate the constraints (you won't get any errors).
After that, run:
SELECT * FROM pragma_foreign_key_check();

You will get a resultset consisting of 4 columns: table, rowid, parent and fkid for the row(s) of any table in the database that violate a foreign key constraint.
Check the documentation for pragma_foreign_key_check() and the answer I gave in a similar question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could not resolve URL for sitemap node in Area Searching the internet I found a similar problem, but mine occurs only with nodes in other areas of the project.
Error

Could not resolve URL for sitemap node Carta de Interveniência which
  represents action carta_interveniencia in controller processo. Ensure
  that the route  for this sitemap node can be resolved and that its
  default values allow resolving the URL for the current sitemap node.

Sitemap
<mvcSiteMapNode title="Cadastros" clickable="false" roles="*" >

    <mvcSiteMapNode title="Processos" controller="processos" action="index">
        <mvcSiteMapNode title="Novo" action="novo" />
        <mvcSiteMapNode title="Editar" action="editar" dynamicNodeProvider="CreditoImobiliarioBB.Web.Infra.Sitemap.ProcessosDynamicNodeProvider, CreditoImobiliarioBB.Web" />
        <mvcSiteMapNode title="Detalhes" action="detalhes" preservedRouteParameters="id" dynamicNodeProvider="CreditoImobiliarioBB.Web.Infra.Sitemap.ProcessosDynamicNodeProvider, CreditoImobiliarioBB.Web">
            <mvcSiteMapNode title="Documentos" key="ProcessoDocumentos2" clickable="false" area="Documentos" controller="processo">
                <mvcSiteMapNode title="Carta de Interveniência" preservedRouteParameters="id" action="carta_interveniencia"></mvcSiteMapNode>
            </mvcSiteMapNode>
        </mvcSiteMapNode>

    </mvcSiteMapNode>

Area registration
public class DocumentosAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Documentos";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            name: "Documentos",
            url: "{controller}/{id}/documento/{action}",
            defaults: null,
            constraints: new { id = @"^\d+$" },
            namespaces: new string[] { "CreditoImobiliarioBB.Web.Areas.Documentos" }
        );
    }
}

A: The default implementation of the resolver behaves this way. It tries to locate the route based off exactly what you have in your sitemap.  Since your sitemap does not have the id parameter and you have a constraint on that, the route is not found and the resolver throws an exception.   However, there is no real reason the resolver has to resolve every URL when it loads the sitemap.
You can create your own resolver and register that with the sitemap.  Copy and paste the default one into your own class.  Near the bottom of the default code is this:
if (string.IsNullOrEmpty(returnValue))
{
    throw new UrlResolverException(string.Format(Messages.CouldNotResolve, mvcSiteMapNode.Title, action, controller, mvcSiteMapNode.Route ?? ""));
}

 _urlkey = key;
_url = returnValue;
return returnValue;

Change that code to this:
if (string.IsNullOrEmpty(returnValue))
{
    return Guid.NewGuid().ToString();
}

 _urlkey = key;
_url = returnValue;
return returnValue;


text:
Q: Understanding merge sort code I'm trying to implement a merge sort using the following websites as resources.
http://interactivepython.org/courselib/static/pythonds/SortSearch/TheMergeSort.html
https://www.khanacademy.org/computing/computer-science/algorithms/merge-sort/p/challenge-implement-merge
To me, my code looks fine; however, given my incorrect output it is obviously wrong.  I'm not sure where or why it is wrong.  I think I understand merge sort when I look at the image explanations of it but trying to implement it has been very difficult.  I have tried to give all variables names some meaning to help reduce confusion ("i", "j", "k", "m, and "n" are a little hard to keep track of what they represent).  I have also tried to use print statements to help debug my code but recursion has never been easy for me so I'm not sure exactly what my print statements are telling me other than the output is wrong.  I've also tried to use the debugger but for whatever reason the debugger doesn't list the values that are in any of my arrays so I can't really proceed via the debugger. Any help in clarifying the implementation of merge sort would be greatly appreciated.
#include <stdio.h>

void merge_sort(int array[], int startIndex, int endIndex);
void merge(int array[], int startIndex, int midIndex, int endIndex);

int main(void)
{
    int size = 8;
    int numbers[8] = {14, 7, 3, 12, 9, 11, 6, 2};

    printf("Unsorted Array!\n");
    for(int i = 0; i < size; i++)
    {
        printf("%i ", numbers[i]);
    }
    printf("\n");

    merge_sort(numbers, 0, 7);

    printf("Sorted Array!\n");
    for(int i = 0; i < size; i++)
    {
        printf("%i ", numbers[i]);
    }
    printf("\n");
}

void merge_sort(int array[], int startIndex, int endIndex)
{
    // determine size of the array
    int size = (endIndex - startIndex) + 1; // updated

    // if the array has more than 1 element then it needs broken down into smaller arrays
    if(size > 1)
    {
        int midIndex = (startIndex + endIndex) / 2;

        merge_sort(array, startIndex, midIndex); // Sort the LEFT side
        merge_sort(array, midIndex + 1, endIndex); // Sort the RIGHT side

        merge(array, startIndex, midIndex, endIndex);
    }
}

void merge(int array[], int startIndex, int midIndex, int endIndex)
{
   int leftSize = midIndex - startIndex + 1;
   int rightSize = endIndex - midIndex;
   int originalArrayIndex = 0;
   int leftArray[leftSize];
   int rightArray[rightSize];
   int currentLeftIndex = 0;
   int currentRightIndex = 0;

   // fill the leftArray
   for(int i = 0; i < leftSize; i++)
   {
       leftArray[i] = array[i];
       printf("%i ", leftArray[i]);
   }
   printf(" === Left array\n");

   // fill the rightArray
   for(int i = 0; i < rightSize; i++)
   {
       rightArray[i] = array[leftSize + i];
       printf("%i ", rightArray[i]);
   }
   printf(" === Right array\n");

   // do the actual merge
   // leftStart < leftSize and rightStart < rightSize
   while((currentLeftIndex < leftSize) && (currentRightIndex < rightSize))
   {
       // if the left array value is smaller than the right array value then that means the left array value goes into the original array[]
       if(leftArray[currentLeftIndex] < rightArray[currentRightIndex])
       {
           array[originalArrayIndex] = leftArray[currentLeftIndex];
           originalArrayIndex++;
           currentLeftIndex++;
       }
       else
       {
           array[originalArrayIndex] = rightArray[currentRightIndex];
           originalArrayIndex++;
           currentRightIndex++;
       }
   }

   // no clue what this is
   while(currentLeftIndex < leftSize)
   {
       array[originalArrayIndex] = leftArray[currentLeftIndex];
       originalArrayIndex++;
       currentLeftIndex++;
   }

   // no clue what this is
   while(currentRightIndex < rightSize)
   {
       array[originalArrayIndex] = rightArray[currentRightIndex];
       originalArrayIndex++;
       currentRightIndex++;
   }

   for(int i = 0; i < leftSize; i++)
   {
       printf("%i ", leftArray[i]);
   }
   printf(" ==== left array after sort\n");

   for(int i = 0; i < rightSize; i++)
   {
       printf("%i ", rightArray[i]);
   }
   printf(" ==== right array after sort\n");

   for(int i = 0; i < endIndex + 1; i++)
   {
       printf("%i ", array[i]);
   }
   printf(" ===== post merge =====\n");
}

Output is listed below:

Unsorted Array!
14 7 3 12 9 11 6 2
14 7  === Left array
3 12  === Right array
14 7  ==== left array after sort
3 12  ==== right array after sort
3 12 14 7  ===== post merge =====
3 12  === Left array
14 7  === Right array
3 12  ==== left array after sort
14 7  ==== right array after sort
3 12 14 7 9 11 6 2  ===== post merge =====
3 12 14 7  === Left array
9 11 6 2  === Right array
3 12 14 7  ==== left array after sort
9 11 6 2  ==== right array after sort
3 9 11 6 2 12 14 7  ===== post merge =====
Sorted Array!
3 9 11 6 2 12 14 7

Updated Output:

Unsorted Array!
14 7 3 12 9 11 6 2
14  === Left array
7  === Right array
7 14  ===== post merge =====
7  === Left array
14  === Right array
7 14 3 12  ===== post merge =====
7 14  === Left array
3 12  === Right array
3 7 12 14  ===== post merge =====
3  === Left array
7  === Right array
3 7 12 14 9 11  ===== post merge =====
3  === Left array
7  === Right array
3 7 12 14 9 11 6 2  ===== post merge =====
3 7  === Left array
12 14  === Right array
3 7 12 14 9 11 6 2  ===== post merge =====
3 7 12 14  === Left array
9 11 6 2  === Right array
3 7 9 11 6 2 12 14  ===== post merge =====
Sorted Array!
3 7 9 11 6 2 12 14

A: Your error is here:
   // fill the rightArray
   for(int i = 0; i < rightSize; i++)
   {
       rightArray[i] = array[rightSize + i];
       printf("%i ", rightArray[i]);
   }
   printf(" === Right array\n");

you need to indent by left array size:
   rightArray[i] = array[leftSize + i];

By the way, the parts you commented on with

// no clue what this is

are there to keep inserting indices in the case where the program already finished inserting all of the indices of one of the two arrays.
Update:
There is another (bigger) problem. You also need to keep track of your current position at the original array. If you look closely you'll see that you always copying values starting from numbers[0] even when working with its right half.
But keeping another counter is a messy approach so consider changing your function definitions to:
merge_sort (int array[], int arraySize);
merge (int leftArray[], int leftSize, int rightArray[], int rightSize, int targetArray[]);

This will help keep things clean and simple.
This is what it should look like:
#include <stdio.h>

void merge_sort(int array[], int arraySize);
void merge(int leftArray[], int leftSize, int rightArray[], int rightSize, int targetArray[]);

int main(void)
{
    int numbers[8] = { 14, 7, 3, 12, 9, 11, 6, 2 };
    int size = sizeof(numbers) / sizeof(int);

    printf("Unsorted Array!\n");
    for (int i = 0; i < size; i++)
    {
        printf("%i, ", numbers[i]);
    }
    printf("\n");

    merge_sort(numbers, size);

    printf("Sorted Array!\n");
    for (int i = 0; i < size; i++)
    {
        printf("%i ", numbers[i]);
    }
    printf("\n");
}

void merge_sort(int array[], int arraySize)
{
    if (arraySize > 1)
    {
        int leftSize = arraySize / 2;
        int rightSize = arraySize - leftSize;

        merge_sort(array, leftSize); // Sort the LEFT side
        merge_sort(array + leftSize, rightSize); // Sort the RIGHT side

        int* targetArray = (int*)malloc(arraySize * sizeof(int));
        merge(array, leftSize, array + leftSize, rightSize, targetArray);
        memcpy(array, targetArray, arraySize * sizeof(int));

        free(targetArray);
    }
}

void merge(int leftArray[], int leftSize, int rightArray[], int rightSize, int targetArray[])
{
    int currentLeftIndex = 0;
    int currentRightIndex = 0;
    int targetIndex = 0;

    while ((currentLeftIndex < leftSize) && (currentRightIndex < rightSize))
    {
        if (leftArray[currentLeftIndex] < rightArray[currentRightIndex])
        {
            targetArray[targetIndex] = leftArray[currentLeftIndex];
            currentLeftIndex++;
        }
        else
        {
            targetArray[targetIndex] = rightArray[currentRightIndex];
            currentRightIndex++;
        }
        targetIndex++;
    }

    while (currentLeftIndex < leftSize)
    {
        targetArray[targetIndex] = leftArray[currentLeftIndex];
        targetIndex++;
        currentLeftIndex++;
    }

    while (currentRightIndex < rightSize)
    {
        targetArray[targetIndex] = rightArray[currentRightIndex];
        targetIndex++;
        currentRightIndex++;
    }
}

A: When initializing your temporary left and right arrays in merge, you need to fix the indices that you're accessing. For example, you currently have
// fill the leftArray
for(int i = 0; i < leftSize; i++)
{
    leftArray[i] = array[i];
    printf("%i ", leftArray[i]);
}
printf(" === Left array\n");

// fill the rightArray
for(int i = 0; i < rightSize; i++)
{
    rightArray[i] = array[rightSize + i];
    printf("%i ", rightArray[i]);
}
printf(" === Right array\n");

but this assuming that array is some chunk of the original array. Although visually the mergesort algorithm literally splits up the original array into subarrays, the code doesn't actually do that. You're still tampering with the original array through out, but the parameters int startIndex, int midIndex, int endIndex are like borders within the original array. Therefore, when initializing leftArray and rightArray you need to access the elements of array using the parameters like so,
// fill the leftArray
for(int i = 0; i < leftSize; i++)
{
    leftArray[i] = array[i];
    printf("%i ", leftArray[startIndex + i]);
}
printf(" === Left array\n");

// fill the rightArray
for(int i = 0; i < rightSize; i++)
{
    rightArray[i] = array[midIndex + i];
    printf("%i ", rightArray[i]);
}
printf(" === Right array\n");

A: This version working. It's the original code with fixes noted in comments as // fixed this line //. Other changes are due to using Microsoft compiler (old C syntax). Also cleaned up the indentation.
#include <stdio.h>

void merge_sort(int array[], int startIndex, int endIndex);
void merge(int array[], int startIndex, int midIndex, int endIndex);

int main(void)
{
int i;            // my compiler is old style c
int size = 8;
int numbers[8] = {14, 7, 3, 12, 9, 11, 6, 2};

    printf("Unsorted Array!\n");
    for(i = 0; i < size; i++)
    {
        printf("%i ", numbers[i]);
    }
    printf("\n");

    merge_sort(numbers, 0, 7);

    printf("Sorted Array!\n");
    for(i = 0; i < size; i++)
    {
        printf("%i ", numbers[i]);
    }
    printf("\n");
    return 0;       // added this //
}

void merge_sort(int array[], int startIndex, int endIndex)
{
// determine size of the array
int size = (endIndex - startIndex) + 1; // updated
int midIndex;    // my compiler is old style C compiler

// if the array has more than 1 element then it needs broken down into smaller arrays
    if(size > 1)
    {
        midIndex = (startIndex + endIndex) / 2;
        merge_sort(array, startIndex, midIndex); // Sort the LEFT side
        merge_sort(array, midIndex + 1, endIndex); // Sort the RIGHT side
        merge(array, startIndex, midIndex, endIndex);
    }
}

void merge(int array[], int startIndex, int midIndex, int endIndex)
{
int leftSize = midIndex - startIndex + 1;
int rightSize = endIndex - midIndex;
int originalArrayIndex = startIndex;   // fixed this line //
//  my compiler doesn't support variable length arrays
//  so allocating from the stack (neither works on large arrays)
int *leftArray  = _alloca(leftSize*sizeof(int));
int *rightArray = _alloca(rightSize*sizeof(int));
// int leftArray[leftSize];
// int rightArray[rightSize];
int currentLeftIndex = 0;
int currentRightIndex = 0;
int i;    // my compiler is old style c compiler

    // fill the leftArray
    for(i = 0; i < leftSize; i++)
    {
        leftArray[i] = array[startIndex+i];   // fixed this line //
        printf("%i ", leftArray[i]);
    }
    printf(" === Left array\n");

    // fill the rightArray
    for(i = 0; i < rightSize; i++)
    {
        rightArray[i] = array[midIndex + 1 + i];  // fixed this line //
        printf("%i ", rightArray[i]);
    }
    printf(" === Right array\n");

    // do the actual merge
    // leftStart < leftSize and rightStart < rightSize
    while((currentLeftIndex < leftSize) && (currentRightIndex < rightSize))
    {
        // if the left array value is smaller than the right array value then that means the left array value goes into the original array[]
        if(leftArray[currentLeftIndex] < rightArray[currentRightIndex])
        {
            array[originalArrayIndex] = leftArray[currentLeftIndex];
            originalArrayIndex++;
            currentLeftIndex++;
        }
        else
        {
            array[originalArrayIndex] = rightArray[currentRightIndex];
            originalArrayIndex++;
            currentRightIndex++;
        }
    }

    // copy any data remaining in leftArray
    while(currentLeftIndex < leftSize)
    {
        array[originalArrayIndex] = leftArray[currentLeftIndex];
        originalArrayIndex++;
        currentLeftIndex++;
    }

    // copy any data remaining in rightArray
    while(currentRightIndex < rightSize)
    {
        array[originalArrayIndex] = rightArray[currentRightIndex];
        originalArrayIndex++;
        currentRightIndex++;
    }

    for(i = 0; i < leftSize; i++)
    {
        printf("%i ", leftArray[i]);
    }
    printf(" ==== left array after sort\n");

    for(i = 0; i < rightSize; i++)
    {
        printf("%i ", rightArray[i]);
    }
    printf(" ==== right array after sort\n");

    for(i = startIndex; i < endIndex + 1; i++)   // fix
    {
        printf("%i ", array[i]);
    }
    printf(" ===== post merge =====\n");
}


text:
Q: Delete and Put. Should they be used? I am watching some videos on ASP.NET Web API and in the video they are using the "Delete" and "Put" command. I never actually used this before and always just used "Post" and "Get" when ever I just used regular ASP.NET MVC and jquery with ajax.
Seeing this is a MS video I wanted to check if that is standard practice to now use them or something MS just decided to do.

A: It's a standard practice for RESTful APIs.
REST utilizes HTTP Verbs and other existing features of HTTP protocol to provide a standardized, discoverable way of using your API.
You can learn more about REST here - http://www.restapitutorial.com/.
And more about HTTP verbs - http://www.restapitutorial.com/lessons/httpmethods.html


text:
Q: Error making ScrollView autoscroll horizontally in react native I am trying to make an image slider that autoscrolls horizontally with react native scrollview, it returns error can't find error _scrollView. Who knows a fix or a better to go about it.
Right I have to manually move between the images.I tried adding a ref to the scrollView, but the ref seems to be giving error.
import React, { Component } from 'react'
import { Animated, View, StyleSheet, Image, Dimensions, ScrollView } from 'react-native'

const deviceWidth = Dimensions.get('window').width
const deviceHeight = Dimensions.get('window').height

const FIXED_BAR_WIDTH = 280
const BAR_SPACE = 10

const images = [
    require("../../assets/images/banner_1.jpg"),
    require("../../assets/images/banner2.jpg")
]

export default class ImgSlider extends Component {

    _scrollView = React.createRef();

    componentDidMount() {
        const numOfBackground = 2;
        let scrollValue = 0, scrolled = 0;
        setInterval(function () {
            scrolled++;
            if(scrolled < numOfBackground)
                scrollValue = scrollValue + deviceWidth;
            else{
                scrollValue = 0;
                scrolled = 0
            }
            _scrollView.scrollTo({ x: scrollValue, animated: false })
        }, 3000);
    }
  numItems = images.length
  itemWidth = (FIXED_BAR_WIDTH / this.numItems) - ((this.numItems - 1) * BAR_SPACE)
  animVal = new Animated.Value(0)

  render() {
    let imageArray = []
    let barArray = []
    images.forEach((image, i) => {
      console.log(image, i)
      const thisImage = (
        <Image
          key={`image${i}`}
          source={image}
          style={{ width: deviceWidth, height: 300 }}
        />
      )
      imageArray.push(thisImage)

      const scrollBarVal = this.animVal.interpolate({
        inputRange: [deviceWidth * (i - 1), deviceWidth * (i + 1)],
        outputRange: [-this.itemWidth, this.itemWidth],
        extrapolate: 'clamp',
      })

      const thisBar = (
        <View
          key={`bar${i}`}
          style={[
            styles.track,
            {
              width: this.itemWidth,
              marginLeft: i === 0 ? 0 : BAR_SPACE,
            },
          ]}
        >
          <Animated.View

            style={[
              styles.bar,
              {
                width: this.itemWidth,
                transform: [
                  { translateX: scrollBarVal },
                ],
              },
            ]}
          />
        </View>
      )
      barArray.push(thisBar)
    })

    return (
      <View
        style={styles.container}
        flex={1}
      >
        <ScrollView
          horizontal
          ref={this._scrollView}
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={10}
          pagingEnabled
        //   ref={(scrollView) => { _scrollView = scrollView }}
          onScroll={
            Animated.event(
              [{ nativeEvent: { contentOffset: { x: this.animVal } } }]
            )
          }
        >

          {imageArray}

        </ScrollView>
        <View
          style={styles.barContainer}
        >
          {barArray}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  barContainer: {
    position: 'absolute',
    zIndex: 2,
    top: 290,
    flexDirection: 'row',
  },
  track: {
    backgroundColor: '#ccc',
    overflow: 'hidden',
    height: 2,
  },
  bar: {
    backgroundColor: '#BB1E18',
    height: 2,
    position: 'absolute',
    left: 0,
    top: 0,
  },
})

A: this._scrollView does not have the function scrollTo try console logging whats init and see whats going on in there.


text:
Q: MySQL and Entity Framework - Application calling a stored procedure returns 0 rows effected but the same procedure works in terminal I recently had to switch from using Microsofts SQL server to using MySQL.
The  application I wrote is using the Entity Framework 4.0. I really like MySQL but the process has been a bit of a pain. Most of the CRUD operations are done with stored procedures so I had fun in my encounter with MySQL bug 55778.
I got over that and manually edited the EDMX file.
Everything worked well until in one scenario I started getting an optimistic concurrency exception.
This is where is happened:
using (var context = new DBEntities())
            {
                context.Requests.AddObject(request);
                context.SaveChanges();

                response.RequestId = request.Id;
                context.Responses.AddObject(response);
                context.SaveChanges();

            }

The request is logged fine. The exception is thrown when I try to save changes on the response. RequestId is the primary key (not auto incremented) of the response table. I tried to use MySQL profiler to see what was happening but it didn't really work. I could only profile queries made through my terminal but not queries made by the application running on my local IIS.
I ended up using Wireshark. I found that when I went to save the response the stored procedure linked to Insert on the response Entity was being called. MySQL returned a response saying 0 rows were effected. This caused the exception. The application then called ROLLBACK removing any changes that should have been made.
If I run that stored procedure in a terminal with the exact same values it works.
So over the wire I see this being called:
CALL `DevDB`.`LogResponse` (1,'2012-03-06 12:30',1,1,'test','test','test','test',false,'test');

Then 0 rows effected being returned and a ROLLBACK being called.
Running the very same command from MySQL workbench works. I have tried this multiple times, dropping the database and starting over. I can't find a reason for this. The request is logged using a similar method and it works.
The application has EXECUTE permissions on both stored routines.
Has anyone come across something like this before?
EDIT:
I also use MySQL handlers to catch any error I could think of and log it to an error log table.
e.g.
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    ROLLBACK;
    INSERT INTO `DevDB`.`tblDatabaseErrorLogs`(ERROR_MESSAGE, ERROR_CODE)
    VALUES(
    'SQL Exception at LogResponse',
    'Unknown'
    );
END;

So far none to the error codes I planned for - SQL Exception, SQL WARNING and a bunch of others - appear to have happened as the error log table is empty.

A: I discovered what was causing the problem but I don't really understand why. If someone gives a good explanation then I will accept that as the answer to this question rather than accepting my own.
This is what appears to have caused the problem.
When using stored procedures to do inserts in the Entity Framework I found that to give the Entity in the application the correct Id at run time I had to return the Id in the stored procedure.
In MySQL I do it like this:
CREATE PROCEDURE LogResponse(IN myVals)
BEGIN
Insert Into `DevDB`.`tblResponses`
(
    someValueNames
)
Values
(
    someValues
);

 SELECT LAST_INSERT_ID() As NewResponseId;
END

The returned SELECT value maps the the PK Id of the Entity which uses this stored procedure as its INSERT function.
It just happened that I didn't use the return value for the response because I didn't need the Id in the application. This was an oversight I guess but it didn't raise any issue when I did a similar thing with SQL Server
i.e.
SELECT SCOPE_IDENTITY() As NewResponseId

All I did to fix the thing is remove the line
SELECT LAST_INSERT_ID() As NewResponseId;

Everything appears to be working as it should now.


text:
Q: gdal2tiles has no attribute 'generate_tiles' I created a new conda environment with python version 3.7
Then installed
conda install -c conda-forge gdal=2.4

Then installed gdal2tiles
pip install gdal2tiles

and then python test.py
#test.py
import gdal2tiles
gdal2tiles.generate_tiles('xyz.tif', 'output_dir')

but I am getting an error
AttributeError: module 'gdal2tiles' has no attribute 'generate_tiles'

It's the same method that I copied from the documentation but doesn't seem to work. https://pypi.org/project/gdal2tiles/

A: Your code seems to be importing the GDAL utility gdal2tiles.py -- probably something to do with your working directory or your path setup.
Try this to display the attributes and methods of the class:
import gdal2tiles
dir(gdal2tiles)

Does it look anything like what you expect from the pypi library ?
https://github.com/tehamalab/gdal2tiles/blob/master/gdal2tiles/gdal2tiles.py
Is there any reason you can't use the GDAL gdal2tiles.py utility without adding the extra python library on top?


text:
Q: Xonix game fill I'm writing a xonix game in c# winforms. There was a problem, I don't know how to fill an area inaccessible to the enemy. I have an array of 500x500 (the size of the playing field), the field frame is filled with 1, and the line drawn by the player is - 2. Thank you for any help!
for (int i = 000; i < 5; i++)
{
    for (int j = 0; j < 500; j++)
    {
        if (i == 0 || j == 0 || i == 500 - 1 || j == 500 - 1)
        {
            for (int a = 0; a < 15; a++)
                for (int b = 0; b < 15; b++)
                {
                    arr[i + a, j + b] = 1;
                    box.SetPixel(i + a, j + b, Color.Blue);
                }
        }
    }
}

This is the way I fill the frame on picturebox


text:
Q: Bash al (alias local) function not found Can I have bash aliases local to directory?
Given such directory structure:
dir1/
  - .
  - ..
  - dir2/
  - file

When I cd dir1 alias eg do not work, but when I cd dir1/dir2/ such alias works. Definition of alsias also should be local, residing in dir1/dir2/
Use case:
I'm programmer with many different companion tools to my projects. I would like to make aliases for some of them, but most of those would be project/directory specific.
I've seen al bash command that would acomplish this, but it's not present in my Ubuntu (14.04).

A: Yes. The simplest approach would be to have a file where your aliases are defined in each directory. So, for example:
$ cat dir1/.alias
alias eg='echo "this is dir1"'
$ cat dir2/.alias
alias eg='echo "this is dir2"'

In the example above, each directory contains a file called .alias where the eg alias is defined. Now, cd into one of them, source the file, and the alias becomes available:
$ cd dir1 && source .alias
$ eg
This is dir1
$ cd ../dir2 && source .alias
$ eg
This is dir2

If you want this done automatically, add this line to your ~/.bashrc:
## Check if an '.alias' file exists and, if it does, source it.
PROMPT_COMMAND='[ -e .alias ] && source .alias'

The PROMPT_COMMAND variable defines a command that is executed before each prompt is shown, so after any command you run. This means that as soon as you more into a directory that contains an .alias file, this file will be sourced.
Notes

*

*This is insecure. Any code within the .alias file will be executed. Use at your own risk. The manual approach is much safer.

*Any aliases defined in the .alias file will still be available after you leave the directory, until they are overwritten by another alias definition with the same name. If that is a problem, you can clear all aliases and then re-load your global ones with:
unalias -a && . /etc/bash.bashrc && . ~/.bashrc && . ~/.bash_aliases

To simplify it, make it a function by adding these lines to your ~/.bashrc:
clear_aliases(){
    unalias -a && . /etc/bash.bashrc && . ~/.bashrc && . ~/.bash_aliases;
}

You will then be able to run clear_aliases to reset your defaults.


text:
Q: VBA Is searching through cells faster with Find method or going through every cell? I've created a VBA macro in Excel that looks for all the instances of specific function in all the worksheets. I've been able to successfully create it, but I'm trying to see what is the best method performance wise give the function I'm searching for could potentially used a large amount of times with a large workbook.
I've used two methods.
Method 1 - Loop through each individual cell and using the "instr" function to see if the cell formula contains thee function.
Method 2 - Use the Find and FindNext methods along with a do loop to only loop through the cells that actually have a function.
I was surprised to find when there are a large number of functions Method 1 is a lot faster (when there are very little method 2 works faster).
Can anyone explain how that could be?
Here's a sample with an example of my code.
On "Sheet1" I've placed a user defined function named "MyFunction" in cells A1:J5000.  Then in cells A5001:J10000 I've left them blank, but have colored them yellow to force the used range to be A1:J10000.
Even though Method 1 is looping through every 100,000 cells it is a lot faster than method 2 which only loops through the 50,000 cells found
Method 1 average run is about 171 ms and Method 2 average run is about 1,531 ms.
Example of my code for Method 1 and Method 2:
Method 1
Private Sub TestMethod1()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim MySheet As Worksheet, MyRange As Range, MyCell As Range
    Dim MyCellAddress As String, MyCellFormula As String, MyFunction As String
    Dim CountTotalCells As Long, CountTotalFunctions As Long

    Dim sw, swEndTime As Long
    Set sw = New StopWatch
    sw.StartTimer

    MyFunction = "=MyFunction("
    CountTotalCells = 0
    CountTotalFunctions = 0

    Set MySheet = Sheets("Forum Question")
    Set MyRange = MySheet.UsedRange

    For Each MyCell In MyRange
        MyCellFormula = MyCell.Formula

        CountTotalCells = CountTotalCells + 1
        If InStr(1, MyCellFormula, MyFunction) > 0 Then
            CountTotalFunctions = CountTotalFunctions + 1
        End If
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

    swEndTime = sw.EndTimer

    MsgBox CountTotalCells & ", " & CountTotalFunctions & ", " & swEndTime & " ms"
End Sub

Method 2
Private Sub TestMethod2()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim MySheet As Worksheet, MyRange As Range, MyCell As Range
    Dim MyCellAddress As String, MyCellFormula As String, MyFunction As String, MyCellFirst As String
    Dim CountTotalCells As Long, CountTotalFunctions As Long

    Dim sw, swEndTime As Long
    Set sw = New StopWatch
    sw.StartTimer

    MyFunction = "=MyFunction("
    CountTotalCells = 0
    CountTotalFunctions = 0

    Set MySheet = Sheets("Forum Question")
    Set MyRange = MySheet.UsedRange

    Set MyCell = MyRange.Cells.Find( _
        What:=MyFunction, _
        After:=[A1], _
        LookIn:=xlFormulas, _
        LookAt:=xlPart, _
        SearchOrder:=xlRows, _
        SearchDirection:=xlNext, _
        MatchCase:=True _
    )

    If Not MyCell Is Nothing Then
        MyCellFirst = MyCell.Address
        Do
            Set MyCell = MyRange.FindNext(After:=MyCell)
            MyCellAddress = MyCell.Address
            MyCellFormula = "z" & MyCell.Formula

            CountTotalCells = CountTotalCells + 1
            If InStr(1, MyCellFormula, MyFunction) > 0 Then
                CountTotalFunctions = CountTotalFunctions + 1
            End If

            If MyCell Is Nothing Or MyCellAddress = MyCellFirst Then
                Exit Do
            End If
        Loop
    End If

    Set MyCell = Nothing

    swEndTime = sw.EndTimer

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

    MsgBox CountTotalCells & ", " & CountTotalFunctions & ", " & swEndTime & " ms"
End Sub

A: Let's break down the code.  Both modules are looping through every cell and testing to see what formula is in the cell.  You only see that in your method 1, but Excel is also check every cell in the target Range when it evaluates the call to .Find.
Let's count the function calls that touch the Worksheet in each loop. Method 1 has exactly 1:
MyCell.Formula

Method 2 has the following:
MyRange.FindNext
MyCell.Address
MyCell.Formula

...plus these comparisons...
MyCell Is Nothing
MyCellAddress = MyCellFirst

...plus this string concatenation:
MyCellFormula = "z" & MyCell.Formula

So let's add up the damage.  I took the liberty of adding profiling code to test the total time spent on each of those lines (with a much larger sample or cells):
Set MyCell = MyRange.Cells.Find: 0 seconds
MyCellFirst = MyCell.Address: 0.421875 seconds
Set MyCell = MyRange.FindNext(After:=MyCell): 4.3125 seconds
MyCellFormula = "z" & MyCell.Formula: 0.34375 seconds
If MyCell Is Nothing Or MyCellAddress = MyCellFirst Then Exit Do: 0.015625 seconds

So, the big performace hog is .FindNext, which isn't surprising.  It's doing a ton of work internally that is flat out skipped in Method 1 (just evaluating the 7 parameters alone...), which does simple retrievals and value string comparisons.


text:
Q: How can I track file in folder already found in .gitignore In file .gitignore there are folder name item....Now I want to track only one file  and ignore the reset of the folder.
and this is the content of my .gitignore
panel
photo
item/*
!item/default.png
jackbox
profile_photo
vid
.htaccess

A: Use negate pattern in .gitignore file:
item/*
!item/default.png

Just edit .gitignore and commit it.
Manual page for gitignore


text:
Q: Where to set Google Cast's custom receiver app ID [Connect SDK] In Google Cast SDK, I am able to specify the custom receiver app ID by calling:
[self.deviceManager launchApplication:kReceiverAppID];

Where in Connect SDK can I do this?

A: Per the Connect SDK documentation:
NSString *webAppId;

if ([_device serviceWithName:@"webOS TV"])
    webAppId = @"5G7328DE";
else if ([_device serviceWithName:@"Chromecast"])
    webAppId = @"3E5106AB";

if (!webAppId)
    return;

[_device.webAppLauncher launchWebApp:webAppId success:^(WebAppSession *webAppSession) {
    NSLog(@"web app launch success");
} failure:^(NSError *error) {
    NSLog(@"web app launch error: %@", error.localizedDescription);
}];


text:
Q: Determinant equality issue Hi I am studying for an exam tomorrow and I have a question, How do I prove that the two determinants are equal ? is there a short way ?
$2abc\left|\begin{array}{ccc}
1 & 1 & 1\\
a & b & c\\
a^{2} & b^{2} & c^{2}
\end{array}\right|$
$
\left|\begin{array}{ccc}
b+c & c+a & a+b\\
b^{2}+c^{2} & c^{2}+a^{2} & a^2+b^2\\
b^{3}+c^{3} & c^{3}+a^{3} & a^{3}+b^{3}
\end{array}\right|
$
Thanks !!!!

A: Use
$$abc\left|\begin{array}{ccc}
1 & 1 & 1\\
a & b & c\\
a^{2} & b^{2} & c^{2}
\end{array}\right| = \left|\begin{array}{ccc}
a & b & c\\
a^2 & b^2 & c^2\\
a^{3} & b^{3} & c^{3}
\end{array}\right| \quad\text{and}\quad
\left|\begin{array}{ccc}
0 & 1 & 1\\
1 & 0 & 1\\
1 & 1 & 0
\end{array}\right| = 2.$$


text:
Q: C++ command line utility input file location changes behaviour I've wrote a command line utility for extracting text from DXF files. My utility is named drawingtotext. Assuming a directory structure like this(Linux OS):
/home/dave/dxfs/

with a bunch of DXF files in the dxfs folder. From that location, assuming a file exists named "P1-1522-YI-WD-0403r1.dxf", running drawingtotext like this fails:
drawingtotext P1-1522-YI-WD-0403r1.dxf

with error: Segmentation fault (core dumped)
running drawingtotext ~/dxfs/P1-1522-YI-WD-0403r1.dxf gives me what I expect plus this at the end:
*** Error in 'drawingtotext': free(): invalid next size (fast): 0x0000000002031170 ***
with a backtrace and huge memory map.
Now, moving that file up a directory (/home/dave/ instead of /home/dave/dxfs/) results in exactly the results I'm looking for with no error. Renaming the file to something else like "mydxf.dxf" and keeping it in /home/dave/dxfs/ fixes the issue as well.
My question is how and why does the location of the file change the behaviour of my program and how do I fix it?
The code is here: http://www.github.com/davidworkman9/drawingtotext/
the main file is called "AutoCADConverter.cpp"

A: For your first error with drawingtotext P1-1522-YI-WD-0403r1.dxf command, are you sure the executable was in the same folder as P1-1522-YI-WD-0403r1.dxf?
The second error occurs when you free memory that has not been allocated. From looking at your code, this error must be occurring on the delete input or delete output lines near the end, seeing as that's the only place you're freeing any memory.  You said

"running this gives me what I expect plus this [error] at the end?"

If the output is created just like you want, and the only thing wrong is this error, then you can account for it by adding:
if (input != null) delete input;
if (output != null) delete output;

to avoid freeing memory that is not allocated. But again this only fixes your problem if the output is correct like you said, this works, but it may be indicative of a larger error.
 You should run the program with Strace so you can see the system calls before the seg fault and free() error.


text:
Q: Magento 2.2.3. Your current session has been expired. How to fix it. I hope this will help someone. I spent a lot of time trying to figure out what is going on.
I updated the php.ini sessions settings, added a row to the core_config_table with session 86400 and it was not helping.
The Solution that worked for me is:
Go to the database into the admin_session table and update the column type updated_at from a TIMESTAMP to CURRENT TIMESTAMP in dropdown.
Thank you,
Cons
Magento 2 Session issue


text:
Q: Ruby/Rails - Convert Unix Timestamp to HH:MM am/pm with Timezone Let's suppose I have the following data:
Unix timestamp: 1388935522
User Timezone: America/Los_Angeles
I currently have the following piece of code,
Time.at(1388935522).strftime("%I:%M %P")

which converts the Unix timestamp.
What is the best way to use the "User Timezone" (currently as a "string") to determine the offset (which would be -8:00) and display the time based upon the user's timezone (7:25 am).
Thanks very much!

A: You have basically two alternatives:

*

*server-side approach

*client-side approach using JavaScript

I explained both in this answer no more than a few days ago.


text:
Q: Issue on Handling button click on samsung Tab-4 I have made an app that is running on all android devices perfectly accept of Samsung Tab-4.
Whenever I click any button my app gets force closed. I am stuck in this problem since many day. Any help will be highly appreciable.
Below is the log-cat message I am getting when I click the button.
sendUserActionEvent() mView == null

A: How did you create a button and call its instance in the activity? There are 2 ways to call a button.

*

*Create an instance of button b in you class.
Button b = (Button)findViewById(R.id.myButton);
Then set a listener on it b.setOnClickListener()...

*Create a button in xml and add onClick with the function name. Example:     android:onClick="handleButton"
In you activity class Then create a method handleButton(View v){
}


text:
Q: Problem involving conditional probability and random variables So, I was asked to solve the following problem:
"A production unit contains two machines functioning independently of each other. Each machine has reliability $p$ over the course of the day, so the probability of it breaking down is equal to $1-p$. In that case, it will be repaired during the night and will be in working order the next day. Only one machine can be repaired at once. Let $X_n$ denote the number of machines broken down at the start of the $n^{\mathrm{th}}$ day, for $n = 1,2,$... Calculate the conditional probability $P(X_{n+1}=0 | X_n=0)$"
Here's my attempt. Since we're dealing with conditional probability, we can simply apply the definition, giving us: $$P(X_{n+1}=0 | X_n=0) = \frac{P(X_{n+1}=0 \ \land \ X_n=0)}{P(X_n = 0)}$$
I'm stuck there. Namely, because I don't know how to find $P(X_n=0)$ (i.e the probability that $0$ machines are broken down at the start of day $n$) because this also depends on what happened on the $n-1^{\mathrm{th}}$ day, and so on.
If you have any tips, or hints, I'd be glad to hear them.

A: The definition is not always the go to tool.   As you observe, it is not a simple matter to find the terms involved here.   They are harder to evaluate.   So don't try that.
Go back to basics and look at what is being asked.   $\mathsf P(X_{n+1}=0\mid X_n=0)$ is the probability that no machines will be broken at the start of day $n+1$ when given that no machines were broken at the start of day $n$.
Such a state transition happens if something or other happens between those times.   Alternatively, if something doesn't happen.   Either way, what is the probability for that?


text:
Q: least value of $3m+n$
If $mx^2+nx+6=0$ does not have two disticnt real
roots. Then least value of $3m+n$ is

Try: Let $3m+n=t,$ Then our equation convert into
$mx^2+(t-3m)x+6=0$
Equation does not have real roots
So we have $(t-3m)^2-24m\leq 0$
$$t^2-6mt+9m^2-24m\geq 0$$
now i am struck here, could some help me how to solve it , Thanks

A: We need $n^2\le24m$
$3m+n\ge\dfrac{ n^2}8+ n=\dfrac{(n+4)^2-16}8\ge-2$


text:
Q: How to prove that $f: ℝ^n → ℝ^m$ is differentiable at $a$ iff each of its components $f_i$ is differentiable at $a$ I don't understand how to prove this, or where to start. Thanks

A: This has nothing to do with differentiation per se. It is a simple consequence of the following basic fact about convergence in ${\mathbb R}^m$:
$${\bf y}\to{\bf 0}\qquad\Longleftrightarrow\qquad y_i\to0\quad (1\leq i\leq m)\ .$$
It follows that
$$\lim_{{\bf X}\to{\bf 0}}{{\bf f}({\bf p}+{\bf X})-{\bf f}({\bf p})-A.{\bf X}\over|{\bf X}|}={\bf 0}$$
iff we have
$$\lim_{{\bf X}\to{\bf 0}}{f_i({\bf p}+{\bf X})-f_i({\bf p})-\sum_{k=1}^n a_{ik}X_k\over|{\bf X}|}=0\qquad(1\leq i\leq m)\ .$$

A:
By definition,
$$
f:\mathbb{R}^n\mapsto\mathbb{R}^m\mbox{ is differentiable at }a\mbox{ if there exists a linear transformation, }\lambda:\mathbb{R}^n\mapsto\mathbb{R}^m,\\ \ \\ \mbox{ such that }\,\,\, \lim\limits_{h\to0}\dfrac{\left\|f(a+h)-f(a)-\lambda h\right\|_{m}}{\left\|h\right\|_{n}}{}={}0\,.
$$

See that the assertion follows, because
$$
\begin{eqnarray*}
\lim\limits_{h\to0}\dfrac{\left\|f(a+h)-f(a)-\lambda h\right\|_{m}}{\left\|h\right\|_{n}}{}={}0&{}\iff{}&\left\|\lim\limits_{h\to0}\dfrac{1}{\left\|h\right\|_{n}}\left(f(a+h)-f(a)-\lambda h\right)\right\|_{m}{}={}0\newline
&&\newline
&{}\iff{}&\left\|\lim\limits_{h\to0}\dfrac{1}{\left\|h\right\|_{n}}\left(g_1,\ldots,g_m\right)\right\|_{m}{}={}0\newline
&&\newline
&{}\iff{}&\left\|\left(\lim\limits_{h\to0}\dfrac{1}{\left\|h\right\|_{n}}g_1,\ldots,\,\lim\limits_{h\to0}\dfrac{1}{\left\|h\right\|_{n}}g_m\right)\right\|_{m}{}={}0\newline
&&\newline
&{}\iff{}&\lim\limits_{h\to0}\dfrac{1}{\left\|h\right\|_{n}}g_i{}={}0,\mbox{ for each }i\newline
&&\newline
&{}\iff{}& \mbox{each }f_i\mbox{ is differentiable at }a\,.\newline
&&\newline
\end{eqnarray*}
$$
Above, for notational convenience, I used $g_i$s which are defined as
$$
g_i{}:={}f_i(a+h)-f_i(a)-(\lambda h)_i\,.
$$

A: General idea: Let $\varphi_1,\ldots,\varphi_m:\mathbb{R}^n\to\mathbb{R}$ be linear functionals. Then one can deduce a linear transformation $\mathbb{R}^n\to\mathbb{R}^m$ by $$v\mapsto(\varphi_1(v),\ldots,\varphi_m(v)).$$In your case, if each component is differentiable, then the differential of each component is a linear functional. The above construction yields the differential of $f$.


text:
Q: SwiftUI - Adding shape at specified position on tap I am trying to create a system where clicking on a point within the screen creates a circle at the specified point.
However, i end up with every tap creating a circle at the same x-axis position all the time with different vertical positions.
Please see gif below for visualization of the current situation.
https://i.stack.imgur.com/KJ9yz.gif
Simplified code below:
import SwiftUI

struct ContentView: View {

    @State var points: [CGPoint] = [CGPoint.zero]
    @State var dragLocation: CGPoint?
    @State var tapLocation: CGPoint?

    var body: some View {
        let tapDetector = TapGesture()
            .onEnded {
                tapLocation = dragLocation
                guard let point = tapLocation else {
                    return
                }
                points.append(point)
            }.simultaneously(with:
            DragGesture(minimumDistance: 0, coordinateSpace: .global).onChanged { value in
                self.dragLocation = value.location
            })

        VStack {
            ForEach(points, id: \.x) {point in
                CreateCircle(location: point)
            }
        }
        .background(Color.black
                        .scaledToFill())
                        .ignoresSafeArea()
                        .gesture(tapDetector)
    }
}

struct CreateCircle: View {

    @State private var currentLocation: CGPoint = CGPoint(x: 100, y: 100)

    init(location: CGPoint) {
        currentLocation = location
    }

    var body: some View {

        return Circle().fill(Color.red)
            .frame(width: 50, height: 50)
            .position(currentLocation)
    }
}

A: Use ZStack and gesture sequenced.
struct ContentView: View {

    @State var points: [CGPoint] = [CGPoint.zero]
    @State var dragLocation: CGPoint?
    @State var tapLocation: CGPoint?

    var body: some View {
        let tapDetector = TapGesture()
            .onEnded {
                tapLocation = dragLocation
                guard let point = tapLocation else {
                    return
                }
                points.append(point)
            }

        let dragGesture = DragGesture(minimumDistance: 0, coordinateSpace: .global)
            .onChanged { value in
                self.dragLocation = value.location
            }

        ZStack { //< Here
            ForEach(points, id: \.x) {point in
                CreateCircle(location: point)
            }
        }
        .background(Color.black
                        .scaledToFill())
        .ignoresSafeArea()
        .gesture(dragGesture.sequenced(before: tapDetector)) //<-- Here
    }
}


text:
Q: How to unlock Smash Flash 2 Characters time and or specific battles I have begun to play SSF2 (Super Smash Flash 2) and am wondering how long it takes to unlock each character via play time, specific fights, etc. If anyone could tell me it would help a ton. The reason I'm asking on here is I cant find a reliable source to find out. Thanks a ton!

A: As far as characters there are only two unlockables - Sandbag and Pichu.
Sandbag is unlocked by winning an online match.
Pichu is unlocked by dealing at or over 172% damage to Pikachu in one stock in a Human v. Human match.
As far as stages go, honestly you can find this on the wiki; just make sure you are looking at the current version of the game. Previous versions (like 0.9b) had different unlock rules.

A: in addition to Brandon_J's answer, you can also unlock Sandbag by completing Classic mode on normal or higher as Random. also a quick way to get Pichu is to win a one stock match with you as Pikachu and the start damage set to 999 (it doesn't necessarily have to be human vs. human, the Pikachu just has to be human controlled.)  if you lose, just do the same thing again until you win.


text:
Q: mysqldump including deleted rows I'm trying to move a database from a Windows2003Server with mysql 5.0.27-community-nt to a new server with CenTOS. When using mysqldump on the database on the windows server, one table (i haven't started checking how widespread the problem is) is being dumped with quite some deleted records in it.
After restoring the dump on the new server, I can easily spot records that exist on the new server but not on the old one. However, when I do a select count(*) both tables show the same record.
The dump is created with --opt, and I also tried dropping the new server's table before a restore. Reading through the dump (I did a table exclusive dump) I can spot the inserts for the records that exist in one database but not the other one.
I also tried doing a flush tables before dumping the table, and tried using SQLyog's export to SQL function, all with the same result.
What can be going on?

A: In case anyone reaches this, and to tag it as finished, the problem was a corrupted index file. MySQL threw the error a couple of hours after and after a REPAIR TABLE it was clear the data was exactly the same.


text:
Q: Update age column in database using php mysqli or pdo How to update age automatically based on its DOB? I'm planning to write a script that fetch DOB column then calculate the age and update it. I started my idea but it still doesn't meet my objective.
Pls. help! Thanks in advance :)

A: Adding an age column when you have already date of birth, is slightly futile. Also, this means you would need to update the value once a year for every record, and at their birth date. That will start to get heavier and heavier. A lot of comments suggested to do the calculation of the age in PHP, this also would get heavy if you wanted to group people by age, you'd have to grab every records of the database and calculate their age. My suggestion is to use MySQL to calculate it, so you can use it in joins, where clauses, group bys and so on...
SELECT YEAR(NOW()) - YEAR(birthdate) - (DATE_FORMAT(NOW(), '%m%d') < DATE_FORMAT(birthdate, '%m%d')) as age FROM table

For more details, this was taken from How to get the difference in years from two different dates? which accounts for leap years.
You could easily create a MySQL function, call it calc_age or something and pass it the birthdate, that would return the current age and would be very easy to use...


text:
Q: How do I find out that a link was seen I'm trying to make a page with some links and when somebody clicks on a link, the score count will go up.
How can I find out the visitor who has really seen the page related to link? But not just click the link and close the page for score...
really seen means: page loads completed.
and my links opens in new window.
any solution?

A: You cant really see pages that aren't in the same domain. Chrome even puts them in a separate thread.
Back in the day you could have used a CSS exploit talked about here: https://developer.mozilla.org/en-US/docs/Web/CSS/Privacy_and_the_:visited_selector
If you really want to make a page with this kind of functionality you will have to make a browser plugin/extension.

A: You can include a nonce token in the link, and post that token to the server, render the page embedding that same token in some javascript and have the javascript post back the token when the page is done rendering. Seems kinda overkill though.

A: The only thing I could thing of is maybe make the link to like a redirect page on your site and then you could control to see if the page was loaded and then like after the page was loaded redirect to the actual webpage to link is intended. This way you know for sure that the user waited to view the webpage.
Other than that I don't think there is any other way for you to go about this.


text:
Q: MongoDB database creation with spring data I am creating a sample web application with spring 3.0 and mongoDB. Following is my root-context.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
    <import resource="classpath:mongo-config.xml"/>

</beans>

and my mongo-config.xml file is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:c="http://www.springframework.org/schema/c"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/data/mongo
            http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util-3.1.xsd">

    <!-- Default bean name is 'mongo'. write concern set to SAFE to ensure unique indexes -->
    <mongo:mongo host="localhost" port="27017" write-concern="SAFE"/>

    <mongo:repositories base-package="com.dashboard.repositories" />

    <bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="DASHBOARD"/>
        <constructor-arg name="credentials" ref="userCredentials"/>
    </bean>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
        <property name="writeResultChecking">
            <util:constant static-field="org.springframework.data.mongodb.core.WriteResultChecking.EXCEPTION" ></util:constant>
        </property>
    </bean>

    <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
        <constructor-arg name="username" value="test"/>
        <constructor-arg name="password" value="abc123"/>
    </bean>

</beans>

when i start the tomcat server, there is no database "Dashboard" created. What is wrong with this code, Kindly help me. Thanks in advance.

A: For making it visible to other viewers i will put my comment into the answer. In Mongo schemas are dynamic and heterogenous so mongo cannot create a fixed schema as RDMS before inserting any data. Here is a more detailed explanation.


text:
Q: How can I generate gettext translations for ecto model field names? I have a usual Ecto.Model and I need to register its fields as translations to move them to .pot file. How can I do that?
UPDATE
I'm using these field names to prepare list of translated errors:
errors = changeset
  |> Ecto.Changeset.traverse_errors(fn {msg, opts} ->
    Enum.reduce(opts, msg, fn {key, value}, _ ->
      String.replace(msg, "%{#{key}}", to_string(value))
    end)
  end)

formatted = for {field, messages} <- errors,
                message <- messages,
                do: "#{field} #{translate_error(message)}" # functionality is here

  defp translate_error(msgid) do
    Gettext.dgettext(MyApp.Gettext, "errors", msgid)
  end

I want to translate not only message, but field too!

A: You can do so with GettextSchemaField package.


text:
Q: Ionic error when pushing to new page I was wondering if someone could help me out, I'm struggling with an error which I can't find any trace of on the internet. it's "_co.auth is undefined" and it is thrown when I setRoot or push to the homepage of my app. Here is the stack trace:
TypeError: _co.auth is undefined
Stack trace:
View_HomePage_0/<@ng:///AppModule/HomePage.ngfactory.js:56:21
debugUpdateDirectives@http://localhost:8100/build/vendor.js:13443:12
checkAndUpdateView@http://localhost:8100/build/vendor.js:12620:5
callViewAction@http://localhost:8100/build/vendor.js:12988:21
execComponentViewsAction@http://localhost:8100/build/vendor.js:12920:13
checkAndUpdateView@http://localhost:8100/build/vendor.js:12626:5
callViewAction@http://localhost:8100/build/vendor.js:12988:21
execEmbeddedViewsAction@http://localhost:8100/build/vendor.js:12946:17
checkAndUpdateView@http://localhost:8100/build/vendor.js:12621:5
callViewAction@http://localhost:8100/build/vendor.js:12988:21
execComponentViewsAction@http://localhost:8100/build/vendor.js:12920:13
checkAndUpdateView@http://localhost:8100/build/vendor.js:12626:5
callViewAction@http://localhost:8100/build/vendor.js:12988:21
execComponentViewsAction@http://localhost:8100/build/vendor.js:12920:13
checkAndUpdateView@http://localhost:8100/build/vendor.js:12626:5
callViewAction@http://localhost:8100/build/vendor.js:12988:21
execEmbeddedViewsAction@http://localhost:8100/build/vendor.js:12946:17
checkAndUpdateView@http://localhost:8100/build/vendor.js:12621:5
callViewAction@http://localhost:8100/build/vendor.js:12988:21
execComponentViewsAction@http://localhost:8100/build/vendor.js:12920:13
checkAndUpdateView@http://localhost:8100/build/vendor.js:12626:5
callWithDebugContext@http://localhost:8100/build/vendor.js:13843:39
debugCheckAndUpdateView@http://localhost:8100/build/vendor.js:13383:12
ViewRef_.prototype.detectChanges@http://localhost:8100/build/vendor.js:10546:9
ApplicationRef_.prototype.tick/<@http://localhost:8100/build/vendor.js:5169:58
ApplicationRef_.prototype.tick@http://localhost:8100/build/vendor.js:5169:13
next/<@http://localhost:8100/build/vendor.js:5041:100
M</l</t.prototype.invoke@http://localhost:8100/build/polyfills.js:3:14354
onInvoke@http://localhost:8100/build/vendor.js:4247:24
M</l</t.prototype.invoke@http://localhost:8100/build/polyfills.js:3:14281
M</c</r.prototype.run@http://localhost:8100/build/polyfills.js:3:9504
NgZone.prototype.run@http://localhost:8100/build/vendor.js:4178:54
next@http://localhost:8100/build/vendor.js:5041:70
EventEmitter.prototype.subscribe/schedulerFn<@http://localhost:8100/build/vendor.js:3992:36
SafeSubscriber.prototype.__tryOrUnsub@http://localhost:8100/build/vendor.js:27705:13
SafeSubscriber.prototype.next@http://localhost:8100/build/vendor.js:27652:17
Subscriber.prototype._next@http://localhost:8100/build/vendor.js:27592:9
Subscriber.prototype.next@http://localhost:8100/build/vendor.js:27556:13
Subject.prototype.next@http://localhost:8100/build/vendor.js:46504:17
EventEmitter.prototype.emit@http://localhost:8100/build/vendor.js:3978:54
checkStable@http://localhost:8100/build/vendor.js:4212:13
onLeave@http://localhost:8100/build/vendor.js:4291:5
onInvokeTask@http://localhost:8100/build/vendor.js:4241:17
M</l</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:14942
M</c</r.prototype.runTask@http://localhost:8100/build/polyfills.js:3:10195
M</h</e.invokeTask@http://localhost:8100/build/polyfills.js:3:16167
e/this.invoke@http://localhost:8100/build/polyfills.js:3:16049
n@http://localhost:8100/build/polyfills.js:2:31385

Here is the function i call it from:
constructor(private toast: ToastController, private fb: FireBaseProvider, public navCtrl: NavController, public navParams: NavParams) {
  }

  createProfile(profile: Profile){
    this.fb.createProfile(profile)
    this.toast.create({
      message: 'Profile information updated',
      duration: 3000
    }).present();
    this.navCtrl.push(HomePage);
  }

and the function at the other end of fb.createProfile is:
profile = {} as Profile;
  user = {} as User;
  constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase) {
  }

  createProfile(profile: Profile){

    this.afAuth.authState.take(1).subscribe(auth => {
      this.afDatabase.list(`profile/${auth.uid}`).push(this.profile);
      });
  }

i really hope someone can help me out with this because I'm completely stumped!
Thanks in Advance!


text:
Q: Running all tests in project using different working directory I need run all tests from my multimodule project using IDE. Like I do it using maven. I can run it by running all tests from specific package. But I need corresponding working directory ($MODULE_DIR$) for tests from each module. How can I do it?

A: Set working directory to $MODULE_DIR$ in the template (Default) run configuration that you are using. All the new configurations of this type will inherit this default setting.


text:
Q: filter JSON object and get a second array as result There is a JSON object and it's structure has shown in the picture. how could i filter this object by a Key named "State" and as result get a second array ??
to make it clear, i need a translated code as equal as this MySQL code : SELECT * FROM data.sepah WHERE state = 'sth'
could anyone help me out solve this problem ?

And My full JSON file is like this :
{

"sepah": [

    {
        "row"   : "1",
        "city"    : "newYork",
        "yegan" : "california",
        "raste" : "tese",
        "clinic" : "+",
        "degree" :  "1",
        "notation" : "empty",
        "kind"  :   "airforce",
        "state" :   "azerbaijan-east"

    },
    {
        "row"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "row"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "row"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    }

],

"naja": [

    {
        "id"   : "1",
        "city"    : "ارتش هرمزگان",
        "far_entz_ostan"    : "۸۲ امام حسین",
        "far_entz_shahr"    : "پدافندی",
        "far_marzbani" : "دارد",
        "hang_marzi" :  "۱",
        "yegan_vije" : "دو مرکز درمانی",
        "clinic"    : "ارتش",
        "hospital"  :   "نیروی هوایی",
        "markaz_amoozeshi"  :   "خراسان رضوی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "ارتش هرمزگان",
        "far_entz_ostan"    : "۸۲ امام حسین",
        "far_entz_shahr"    : "پدافندی",
        "far_marzbani" : "دارد",
        "hang_marzi" :  "۱",
        "yegan_vije" : "دو مرکز درمانی",
        "clinic"    : "ارتش",
        "hospital"  :   "نیروی هوایی",
        "markaz_amoozeshi"  :   "خراسان رضوی",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "ارتش هرمزگان",
        "far_entz_ostan"    : "۸۲ امام حسین",
        "far_entz_shahr"    : "پدافندی",
        "far_marzbani" : "دارد",
        "hang_marzi" :  "۱",
        "yegan_vije" : "دو مرکز درمانی",
        "clinic"    : "ارتش",
        "hospital"  :   "نیروی هوایی",
        "markaz_amoozeshi"  :   "خراسان رضوی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "ارتش هرمزگان",
        "far_entz_ostan"    : "۸۲ امام حسین",
        "far_entz_shahr"    : "پدافندی",
        "far_marzbani" : "دارد",
        "hang_marzi" :  "۱",
        "yegan_vije" : "دو مرکز درمانی",
        "clinic"    : "ارتش",
        "hospital"  :   "نیروی هوایی",
        "markaz_amoozeshi"  :   "خراسان رضوی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    }

],

"aja": [

    {
        "id"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "اصفهان",
        "yegan" : "۸۲ امام حسین",
        "raste" : "پدافندی",
        "clinic" : "دارد",
        "degree" :  "۱",
        "notation" : "دو مرکز درمانی",
        "kind"  :   "نیروی هوایی",
        "state" :   "azerbaijan-east"

    }

],

"setad_kol_sepah": [

    {
        "id"   : "1",
        "city"    : "اصفهان",
        "sepah_ostani"  : "۸۲ امام حسین",
        "nahiye_moghavemat" : "پدافندی",
        "tip_mardom_paye" : "دارد",
        "darmangah" :   "۱",
        "daraje" : "دو مرکز درمانی",
        "markaz_amoozeshi"  : "ارتش",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "اصفهان",
        "sepah_ostani"  : "۸۲ امام حسین",
        "nahiye_moghavemat" : "پدافندی",
        "tip_mardom_paye" : "دارد",
        "darmangah" :   "۱",
        "daraje" : "دو مرکز درمانی",
        "markaz_amoozeshi"  : "ارتش",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "اصفهان",
        "sepah_ostani"  : "۸۲ امام حسین",
        "nahiye_moghavemat" : "پدافندی",
        "tip_mardom_paye" : "دارد",
        "darmangah" :   "۱",
        "daraje" : "دو مرکز درمانی",
        "markaz_amoozeshi"  : "ارتش",
        "state" :   "azerbaijan-east"

    },
    {
        "id"   : "1",
        "city"    : "اصفهان",
        "sepah_ostani"  : "۸۲ امام حسین",
        "nahiye_moghavemat" : "پدافندی",
        "tip_mardom_paye" : "دارد",
        "darmangah" :   "۱",
        "daraje" : "دو مرکز درمانی",
        "markaz_amoozeshi"  : "ارتش",
        "state" :   "azerbaijan-east"

    }

]

}

A: If you wish to filter to match only some specific "state" value, you should do:
var newArr = obj.sepah.filter(function (i) {
  return i.state === 'sth';
});

A: You can simply do map:
const newArray = theArray.map(item => item.state);

or, in Safari and all those browsers that don't yet support ES6,
var newArray = theArray.map(function (item) {
  return item.state;
});

This will return an array that only consists of strings, each taken from state property of every item of the input array.

A: You can use Array#filter for that.
result = data.sepah.filter(function (a) {
    return a.state === 'somevalue';
});

Working example:

var data = { "sepah": [{ "row": "1", "city": "newYork", "yegan": "california", "raste": "tese", "clinic": "+", "degree": "1", "notation": "empty", "kind": "airforce", "state": "azerbaijan-east" }, { "row": "2", "city": "??????", "yegan": "?? ???? ????", "raste": "???????", "clinic": "????", "degree": "?", "notation": "?? ???? ??????", "kind": "????? ?????", "state": "azerbaijan-west" }, ], "naja": [], "setad_kol_sepah": [] },
    result = data.sepah.filter(function (a) {
        return a.state === 'azerbaijan-east';
    });

document.write('
' + JSON.stringify(result, 0, 4) + '
');

With separate function:

function filter(array, key, search) {
    return array.filter(function (a) {
        return a[key] === search;
    });
}

var data = { "sepah": [{ "row": "1", "city": "newYork", "yegan": "california", "raste": "tese", "clinic": "+", "degree": "1", "notation": "empty", "kind": "airforce", "state": "azerbaijan-east" }, { "row": "2", "city": "??????", "yegan": "?? ???? ????", "raste": "???????", "clinic": "????", "degree": "?", "notation": "?? ???? ??????", "kind": "????? ?????", "state": "azerbaijan-west" }, ], "naja": [], "setad_kol_sepah": [] },
    result = filter(data.sepah, 'state', 'azerbaijan-east');

document.write('
' + JSON.stringify(result, 0, 4) + '
');

With more than one value:

function filter(array, key, searchArray) {
    return array.filter(function (a) {
        return ~searchArray.indexOf(a[key]);
    });
}

var data = { "sepah": [{ "row": "1", "city": "newYork", "yegan": "california", "raste": "tese", "clinic": "+", "degree": "1", "notation": "empty", "kind": "airforce", "state": "azerbaijan-east" }, { "row": "2", "city": "??????", "yegan": "?? ???? ????", "raste": "???????", "clinic": "????", "degree": "?", "notation": "?? ???? ??????", "kind": "????? ?????", "state": "azerbaijan-west" }, ], "naja": [], "setad_kol_sepah": [] },
    result = filter(data.sepah, 'state', ['azerbaijan-east', 'azerbaijan-west']);

document.write('
' + JSON.stringify(result, 0, 4) + '
');


text:
Q: Nano: Will it be there for me? I know nano (and Pico!) well on *Nix systems, and don't even know how to get out of vi if it accidentally loads (though on emacs I can get that far. Questions about  my intelligence aside, is it okay to expect that nano will be available on most Linux distributions I encounter?

A: Nope. It isn't.
"vi" on the other hand is quite likely to be there. You may find "pico" if you're lucky.
How to get out of vi:
:q!

Do a regular google search, as well as an image google search, for 'vi cheatsheet'.

A: vi is part of the posix standard, so it will be present on any Unix by definition. nano will be much more iffy. All you really need to know is :q! to get out if it started accidentally, and then man vi to find enough info to figure out how to use it if nothing else is available. Also vim is not vi and you cannot take vim features for granted either.

A: I haven't encountered a popular distro without it. So I think it's save to assume that.


text:
Q: Enumeration Issue NSMutableArray *tempMutableArray = [[NSMutableArray alloc] init];
if (street != NULL) {
[tempMutableArray addObject:(NSString *)street];
}
if (city != NULL) {
[tempMutableArray addObject:(NSString *)city];
}
if (state != NULL) {
[tempMutableArray addObject:(NSString *)state];
}
if (zip != NULL) {
[tempMutableArray addObject:(NSString *)zip];
}
if (country != NULL) {
// Check to see if the country is USA/Canada
NSStringCompareOptions  compareOptions = NSDiacriticInsensitiveSearch;
NSArray* countryIndex = [[NSArray alloc] initWithObjects:@"United States of America", @"United States", @"U.S.A.", @"USA", @"US", @"U.S.", @"Canada", @"CAN", @"CDN", @"CA", nil];

for (NSString* element in countryIndex)
{
NSComparisonResult result = [(NSString *)country compare:element options:compareOptions];
if (NSOrderedSame == result) {
// Do another thing here if they match...
CFRelease(country);
country = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8);
}
else {
// Try something else...
[tempMutableArray addObject:(NSString *)country];
}
}
}
for (NSString* element in tempMutableArray)
{
    syntheticAddress = [syntheticAddress stringByAppendingString:[NSString stringWithFormat:@"%@ ,", element]];
NSLog(@"synthetic address is %@", syntheticAddress);
}

The problem is that the the output is getting excessive entries
2011-07-08 14:42:38.077 TestingApp[3770:ef03] synthetic address is 123 Main Street ,
2011-07-08 14:42:40.673 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,
2011-07-08 14:42:42.510 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,
2011-07-08 14:42:44.136 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,
2011-07-08 14:42:45.637 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States ,
2011-07-08 14:42:49.968 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , ,
2011-07-08 14:42:52.046 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , ,
2011-07-08 14:42:54.306 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , ,
2011-07-08 14:42:55.730 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , , ,
2011-07-08 14:42:58.487 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , , , ,
2011-07-08 14:43:00.035 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , , , , ,
2011-07-08 14:43:01.237 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , , , , , ,
2011-07-08 14:43:06.263 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , , , , , , ,
2011-07-08 14:43:10.537 TestingApp[3770:ef03] Address is 123 Main Street ,SomeCity ,AA ,00000 ,United States , , , , , , , ,

I would like the output to only be
2011-07-08 14:42:38.077 TestingApp[3770:ef03] synthetic address is 123 Main Street ,
2011-07-08 14:42:40.673 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,
2011-07-08 14:42:42.510 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,
2011-07-08 14:42:44.136 TestingApp[3770:ef03] synthetic address is 123 Main Street ,SomeCity ,AA ,00000

A: Your NSLog is inside the for loop.
EDIT :
for (NSString* element in countryIndex)
{
      NSComparisonResult result = [(NSString *)country compare:element options:compareOptions];
      if (NSOrderedSame == result) {
              // Do another thing here if they match...
              CFRelease(country);
              country = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8);
       }
       else {
          // Try something else...
          [tempMutableArray addObject:(NSString *)country];
       }
 }

Look at the code above. Your if condition will only succeed once (I'm assuming ) .. but your else condition will hit for all the other non-matches. And each time it fails, you are adding a country object to your tempMutableArray. Is this what you want?
EDIT 2: This should be the correct way of doing it.
for (NSString* element in countryIndex)
{
      NSComparisonResult result = [(NSString *)country compare:element options:compareOptions];
      if (NSOrderedSame == result) {
          [tempMutableArray addObject:(NSString *)country];
          break;
       }
       else {
          // Try something else...
          // No match. Go on to the next element compare.
       }
 }


text:
Q: Improving PyQGIS distance matrix efficiency I have written a custom processing tool, which I use within a large graphical model in QGIS. I am looking for a way to speed it up.
First step of this processing tool is to connect every point of one input layer to every point of another input layer and measure its line length. This takes quite a while, because usually both layers have more than 10000 points. But I am only interested in point pairs within a given distance to each other. So currently I am going to delete the lines afterwards, which are too long. I think this is quite ineffective, and therefore wanted to ask if there is an easy way to speed up this step, by using a spatial index or something like that. I could create one by using index = QgsSpatialIndex(layer.getFeatures()), but how would I proceed to only connect points I am interested in?
This is a minimal part of my current code:
Memorylayer_VL = QgsVectorLayer(str('LineString?crs=25832')), "tmp_lines", "memory")
Memorylayer_PR = Memorylayer_VL.dataProvider()
maxdistance = 150

# iterate over stop features and create lines
for stop_feat in stop_layer.getFeatures():
    point1 = QgsPoint(stop_feat.geometry().asPoint())
    for source_feat in possibility_layer.getFeatures():
        point2 = QgsPoint(source_feat.geometry().asPoint())
        temp_feat = QgsFeature(fields)
        temp_feat.setGeometry(QgsGeometry.fromPolyline([point1, point2]))
        temp_feat["line_length"] = temp_feat.geometry().length()
        # Only add lines shorter than maxdistance and longer than 1m (Already simplified like this using @BERAs suggestion in comments)
        # However, couldn't using a spatial index even have more effect?
        if (temp_feat.geometry().length() < maxdistance) and (tmp_line_feat.geometry().length() > 1):
            Memorylayer_PR.addFeature(temp_feat)
            Memorylayer_VL.updateFields()
Memorylayer_VL.commitChanges()

# Doing more processing stuff on the just created lines layer....

A: Below the code for select all solution lines between 0 (excluded) and maxdistance (excluded too). All POSSIBILITY features are inserted inside a spatial index (QgsSpatialIndex). A filter, thanks to the spatial index, with a maxdistance square around the feature of the layer STOP is applied for speed the process and select (intersects) only POSSIBILITY features in the square.
If the layer STOP and POSSIBILITY are the same, the code below makes duplicates and isn't not very efficient because of the duplicate.
qgis_project = QgsProject.instance()
layers = {lyr.name(): lyr for lyr in qgis_project.mapLayers().values()}
lyr_from = layers["STOP"]
lyr_to = layers["POSSIBILITY"]
maxdistance = 150

spatial_idx_to = QgsSpatialIndex()
pr_from = lyr_from.dataProvider()
pr_to = lyr_to.dataProvider()
feats_from = pr_from.getFeatures()
feats_to = pr_to.getFeatures()

# insert destination features to the spatial index
spatial_idx_to.addFeatures(feats_to)

result_lines = []
# iterate over origin features
for ft_from in feats_from:
    # find all the nearest feature thanks to the spatial index
    geom_from = ft_from.geometry().asPoint()
    x_from = geom_from.x()
    y_from = geom_from.y()
    # create a rectangle at maxdistance of the from point
    rect = QgsRectangle(
        QgsPointXY(x_from - maxdistance, y_from - maxdistance),
        QgsPointXY(x_from + maxdistance, y_from + maxdistance)
    )
    # get all points in that intersects the rectangle
    distance_ids = spatial_idx_to.intersects(rect)
    for fid in distance_ids:
        geom_to = lyr_to.getFeature(fid).geometry().asPoint()
        # if the distance between origin and destination < maxdistance
        if 0 < geom_from.distance(geom_to) < maxdistance:
            line_feat = QgsFeature()
            # create a PolylineXY from origin and destination PointXY
            line_feat.setGeometry(QgsGeometry.fromPolylineXY([geom_from, geom_to]))
            # append the line feature to the result list
            result_lines.append(line_feat)

# create the memory layer
memlyr = QgsVectorLayer("LineString?crs=epsg:25832", "tmp_lines", "memory")
memlyr_pr = memlyr.dataProvider()
# add all resulting lines features
memlyr_pr.addFeatures(result_lines)
# finally add the line memory layer to the project
qgis_project.addMapLayer(memlyr)


text:
Q: why django-daphne is not working with docker? I have a local & production docker-compose services for my django app, in the local service all be right, but in the production service daphne not work, in the same the redis connection is equals and i'm not using a special network conf for my docker compose services.
local compose:
version: "3"
services:

    app:
        image: app
        build:
            context: .
            dockerfile: ./compose/local/Dockerfile
        environment:
            - DJANGO_SETTINGS_MODULE=psvt.settings.local
        volumes:
            - ".:/django/"
        ports:
            - "8000:8000"
        depends_on:
            - redis
            - db
        links:
            - redis:redis
            - db:postgres

    redis:
        image: redis
        restart: always
        expose:
            - '6379'

    daphne:
        restart: always
        image: "app:latest"
        working_dir: /django/
        command: bash -c "daphne -b 0.0.0.0 -p 8001 psvt.asgi:channel_layer"
        ports:
            - "8001:8001"
        environment:
            - REDIS_HOST=redis
            - DJANGO_SETTINGS_MODULE=psvt.settings.local
        depends_on:
            - redis
        links:
            - redis

    db:
        image: postgres:10.1-alpine
        volumes:
            - postgres_data:/var/lib/postgresql/data/
        expose:
            - "5432"

volumes:
    postgres_data:

production: (here daphne is not working)
version: "3"
services:
    app:
        image: app_production
        build:
            context: .
            dockerfile: ./compose/production/Dockerfile
        #command: bash -c "gunicorn psvt.wsgi:application --bind 0.0.0.0:8000"
        command: bash -c "./manage.py runserver"
        working_dir: /django/
        environment:
            - DJANGO_SETTINGS_MODULE=psvt.settings.production
        volumes:
            - ".:/django/"
            - static_files:/static/
            - media_files:/media/
        ports:
            - "8000:8000"
        depends_on:
            - redis
            - db
        links:
            - redis:redis
            - db:postgres

    daphne:
        restart: always
        image: "app_production:latest"
        working_dir: /django/
        command: bash -c "daphne -b 0.0.0.0 -p 8001 psvt.asgi:channel_layer"
        ports:
            - "8001:8001"
        environment:
            - REDIS_HOST=redis
            - DJANGO_SETTINGS_MODULE=psvt.settings.production
        depends_on:
            - redis
        links:
            - redis

    redis:
        image: redis
        restart: always
        expose:
            - '6379'

    db:
        image: postgres:10.1-alpine
        volumes:
            - postgres_data:/var/lib/postgresql/data/
        expose:
            - "5432"

    nginx:
        build:
            context: ./compose/nginx/
            dockerfile: ./Dockerfile
        ports:
            - 100:80
            - 5000:80
        links:
            - app:app
        volumes:
            - static_files:/static/
            - media_files:/media/
        depends_on:
            - app

volumes:
    postgres_data:
    static_files:
    media_files:

The error is:
Error trying to receive messages: Error -2 connecting to redis:6379. Name or service not known.

A: Try using networks keyword instead of links.
https://docs.docker.com/compose/compose-file/#links

A: fix for me was adjusting working dir in docker-compose
    working_dir: /the_name_of_your_django_project/


text:
Q: C behaving differently for almost same code I have created a program in C to find an integer which is the sum of two semi-prime nos.  The prime nos which are multiplied should be different.  (I have depicted in the output). Here is the code
#include<stdio.h>

main()
{
    int i, j, k, n=0, l=0, c, d, x, y, t, prime[200], a[200], count=0;

    repeat:
    scanf("%d", &t);
    if(t>1 && t<200)
    {
        goto repeat;
    }

    for(i=0; i<t; i++)
    {
        repeat0:
        scanf("%d", &a[i]);
        if(a[i]<1 && a[i]>200)
            goto repeat0;
    }

    for(i=0; i<t; i++)
    {
        for(j=2; j<a[i]; j++)
        {
            for(k=2; k<j; k++)
            {
                if(j%k==0)
                {
                    n++;
                }
            }
            if(n==0)
            {
                prime[l]=j;
                l++;
            }
            n=0;
        }

        for(c=0; c<l; c++)
        {
            for(d=0; d<l; d++)
            {
                for(x=0; x<l; x++)
                {
                    for(y=0; y<l; y++)
                    {
                        if(a[i]==(prime[c]*prime[d])+(prime[x]*prime[y]) && prime[c]!=prime[d] && prime[x]!=prime[y])
                        count++;
                    }
                }
            }
        }

        if(count>0)
            printf("YES\n");
        else printf("NO\n");
        count=0;
    }
}

And now, I give the input
3
30
45
60
The output is
YES
//15+15=3*5(These two nos need to be different, as defined in
  semi-primes i.e 3 and 5, not necessary for 15 and 15)  +  3*5
YES
//5*7  +  2*5
NO
And if I now post
if(a[i]==(prime[c]*prime[d])+(prime[x]*prime[y]) && c!=d && x!=y)
instead of
if(a[i]==(prime[c]*prime[d])+(prime[x]*prime[y]) && prime[c]!=prime[d]
  && prime[x]!=prime[y])
and give the input
3
30
45
62
i get the output
YES
YES
YES

I am not able to understand the different output as the code logic remains the same


text:
Q: Batch Processing Pan sharpening in Erdas Imagine 2015 I am trying to find a way to batch process HPF Resolution Merge in Erdas Imagine 2015. I cannot find the option for running it in batch. Is there a way with python in Spatial modeler? Any help is appreciated.

A: I use this:
 modeler -nq mergeall.pmdl -meter -state "$PAN_FILE" "$MS_FILE_DIR/$MS_FILE_VSK" "$OUT_FILE" Unsigned_16_bit ignore 'Nearest Neighbour' 0 "None" 1,2,3,4


text:
Q: boost.asio error codes on windows are platform-dependent? I am writing a small network client program, it uses boost.asio as
the network layer, this is a function used to cast error codes of
boost.asio to error codes of my program.
Today I found that if my client program starts while the server is
not opened, connect will fails, boost.asio's error code will not be
'asio::error::connection_refused' or 'system::errc::connection_refused'
but 'ERROR_CONNECTION_REFUSED', this is a windows platform-dependent
error code, to deal with this I added a macro to the code, but I think
this is just ugly.
inline ErrorCode::Code cast(const boost::system::error_code& ec, ErrorCode::Code d = ErrorCode::unknownError)
{
    if (ec == boost::asio::error::operation_aborted) {
        return ErrorCode::operationCanceled;
    }
    if (ec == boost::system::errc::connection_refused || ec == boost::asio::error::connection_refused) {
        return ErrorCode::connectionRefused;
    }

    if (ec.category() == boost::system::get_system_category()) {
#if defined(BOOST_ASIO_WINDOWS)
        if (ec.value() == ERROR_CONNECTION_REFUSED) {
            return ErrorCode::connectionRefused;
        }
#endif
    }
    return d;
}

Is there other correct way to deal with this ?

I am confused, default_error_condition's value is still 1225,
on my computer, 'boost::system::errc::connection_refused' is 107,
and 'boost::asio::error::connection_refused' is 10061.
So where is the platform-independent error code ?

A: It looks like you want to use using error_condition instead of error_code here.

Class error_condition
The class error_condition describes an object used to hold values identifying error conditions. [ Note: error_condition values are portable abstractions, while error_code values are implementation specific. --end note ]

Documentation suggests error_code::default_error_condition should work for you.
Also highly interesting is this page: http://en.highscore.de/cpp/boost/errorhandling.html

This chapter introduces two Boost C++ Libraries assisting a developer in leveraging error handling: Boost.System translates operating system specific error codes into platform independent ones
boost::system::error_condition is used just like boost::system::error_code. Both the value() and category() method can be called for the boost::system::error_condition object as shown in the above example.
The reason for having two more or less identical classes is fairly simple: While boost::system::error_code is used for platform dependent error codes, boost::system::error_condition is used to access platform independent error codes instead. By calling the default_error_condition() method, a platform dependent error code is translated into a platform independent error code of type boost::system::error_condition.